mt4-fbs-crypto/TON_USD_FBS_Robot.mq4
2025-07-31 07:51:37 -03:00

335 lines
No EOL
12 KiB
MQL4

//+------------------------------------------------------------------+
//| TON_USD_FBS_Robot.mq4 |
//| Expert Advisor para FBS Crypto |
//| TON/USD Trading Robot |
//+------------------------------------------------------------------+
#property copyright "FBS Crypto TON/USD Robot"
#property link ""
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Parâmetros de Entrada |
//+------------------------------------------------------------------+
input double LotSize = 0.01; // Tamanho do lote
input double StopLoss = 50; // Stop Loss em pips
input double TakeProfit = 100; // Take Profit em pips
input double MaxSpread = 2.0; // Spread máximo permitido (pips)
input int MagicNumber = 12345; // Número mágico
input double RiskPercent = 2.0; // Risco por operação (%)
input bool UseMoneyManagement = true; // Usar gestão de capital
input int RSI_Period = 14; // Período do RSI
input int RSI_Oversold = 30; // RSI sobrevenda
input int RSI_Overbought = 70; // RSI sobrecompra
input int MA_Fast = 21; // Média móvel rápida
input int MA_Slow = 50; // Média móvel lenta
input int MaxOrders = 1; // Máximo de ordens simultâneas
input bool TradingEnabled = true; // Habilitar negociação
input int StartHour = 0; // Hora de início (servidor)
input int EndHour = 23; // Hora de fim (servidor)
//+------------------------------------------------------------------+
//| Variáveis Globais |
//+------------------------------------------------------------------+
double spread;
double point;
int slippage = 3;
//+------------------------------------------------------------------+
//| Função de Inicialização |
//+------------------------------------------------------------------+
int OnInit()
{
Print("=== TON/USD FBS Crypto Robot Iniciado ===");
Print("Corretora: FBS | Conta: Crypto | Par: TON/USD");
Print("Spread flutuante a partir de 0.7 pip | Alavancagem: 50x");
Print("Moeda da conta: USDT");
// Verificar se o símbolo está disponível
if(Symbol() != "TONUSD" && Symbol() != "TON/USD" && Symbol() != "TONUSDT")
{
Alert("ATENÇÃO: Verifique se o símbolo TON/USD está correto!");
Print("Símbolo atual: ", Symbol());
}
// Configurar variáveis
point = Point;
if(Digits == 5 || Digits == 3)
point = Point * 10;
Print("Configurações carregadas com sucesso!");
Print("Lote: ", LotSize, " | SL: ", StopLoss, " | TP: ", TakeProfit);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Função de Desinicialização |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("=== TON/USD FBS Robot Finalizado ===");
Print("Motivo: ", reason);
}
//+------------------------------------------------------------------+
//| Função Principal de Tick |
//+------------------------------------------------------------------+
void OnTick()
{
// Verificar se a negociação está habilitada
if(!TradingEnabled)
return;
// Verificar horário de negociação
if(!IsTimeToTrade())
return;
// Verificar spread
spread = (Ask - Bid) / point;
if(spread > MaxSpread)
{
Comment("Spread muito alto: ", DoubleToStr(spread, 1), " pips");
return;
}
// Contar ordens abertas
int totalOrders = CountOrders();
if(totalOrders >= MaxOrders)
return;
// Análise técnica e sinais
if(GetBuySignal())
{
OpenBuyOrder();
}
else if(GetSellSignal())
{
OpenSellOrder();
}
// Atualizar comentário
UpdateComment();
}
//+------------------------------------------------------------------+
//| Verificar se é hora de negociar |
//+------------------------------------------------------------------+
bool IsTimeToTrade()
{
int currentHour = Hour();
return (currentHour >= StartHour && currentHour <= EndHour);
}
//+------------------------------------------------------------------+
//| Sinal de Compra |
//+------------------------------------------------------------------+
bool GetBuySignal()
{
double rsi = iRSI(Symbol(), 0, RSI_Period, PRICE_CLOSE, 1);
double maFast = iMA(Symbol(), 0, MA_Fast, 0, MODE_SMA, PRICE_CLOSE, 1);
double maSlow = iMA(Symbol(), 0, MA_Slow, 0, MODE_SMA, PRICE_CLOSE, 1);
// Condições para compra
bool rsiCondition = rsi < RSI_Oversold;
bool maCondition = maFast > maSlow;
bool priceAboveMA = Close[1] > maFast;
return (rsiCondition && maCondition && priceAboveMA);
}
//+------------------------------------------------------------------+
//| Sinal de Venda |
//+------------------------------------------------------------------+
bool GetSellSignal()
{
double rsi = iRSI(Symbol(), 0, RSI_Period, PRICE_CLOSE, 1);
double maFast = iMA(Symbol(), 0, MA_Fast, 0, MODE_SMA, PRICE_CLOSE, 1);
double maSlow = iMA(Symbol(), 0, MA_Slow, 0, MODE_SMA, PRICE_CLOSE, 1);
// Condições para venda
bool rsiCondition = rsi > RSI_Overbought;
bool maCondition = maFast < maSlow;
bool priceBelowMA = Close[1] < maFast;
return (rsiCondition && maCondition && priceBelowMA);
}
//+------------------------------------------------------------------+
//| Abrir Ordem de Compra |
//+------------------------------------------------------------------+
void OpenBuyOrder()
{
double lotSize = CalculateLotSize();
double sl = 0, tp = 0;
if(StopLoss > 0)
sl = Ask - (StopLoss * point);
if(TakeProfit > 0)
tp = Ask + (TakeProfit * point);
int ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, slippage, sl, tp,
"TON/USD Buy - FBS Crypto", MagicNumber, 0, clrGreen);
if(ticket > 0)
{
Print("Ordem de COMPRA aberta - Ticket: ", ticket, " | Lote: ", lotSize, " | Preço: ", Ask);
}
else
{
Print("Erro ao abrir ordem de COMPRA: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Abrir Ordem de Venda |
//+------------------------------------------------------------------+
void OpenSellOrder()
{
double lotSize = CalculateLotSize();
double sl = 0, tp = 0;
if(StopLoss > 0)
sl = Bid + (StopLoss * point);
if(TakeProfit > 0)
tp = Bid - (TakeProfit * point);
int ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, slippage, sl, tp,
"TON/USD Sell - FBS Crypto", MagicNumber, 0, clrRed);
if(ticket > 0)
{
Print("Ordem de VENDA aberta - Ticket: ", ticket, " | Lote: ", lotSize, " | Preço: ", Bid);
}
else
{
Print("Erro ao abrir ordem de VENDA: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Calcular Tamanho do Lote |
//+------------------------------------------------------------------+
double CalculateLotSize()
{
if(!UseMoneyManagement)
return LotSize;
double balance = AccountBalance();
double riskAmount = balance * (RiskPercent / 100.0);
double stopLossPoints = StopLoss * point;
double tickValue = MarketInfo(Symbol(), MODE_TICKVALUE);
if(stopLossPoints > 0 && tickValue > 0)
{
double lotSize = riskAmount / (stopLossPoints / Point * tickValue);
// Aplicar limites mínimos e máximos
double minLot = MarketInfo(Symbol(), MODE_MINLOT);
double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
lotSize = MathMax(minLot, MathMin(maxLot, lotSize));
lotSize = NormalizeDouble(lotSize / lotStep, 0) * lotStep;
return lotSize;
}
return LotSize;
}
//+------------------------------------------------------------------+
//| Contar Ordens Abertas |
//+------------------------------------------------------------------+
int CountOrders()
{
int count = 0;
for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
count++;
}
}
return count;
}
//+------------------------------------------------------------------+
//| Atualizar Comentário |
//+------------------------------------------------------------------+
void UpdateComment()
{
string comment = "";
comment += "=== TON/USD FBS Crypto Robot ===\n";
comment += "Spread: " + DoubleToStr(spread, 1) + " pips\n";
comment += "Ordens Ativas: " + IntegerToString(CountOrders()) + "/" + IntegerToString(MaxOrders) + "\n";
comment += "Saldo: $" + DoubleToStr(AccountBalance(), 2) + " USDT\n";
comment += "Equity: $" + DoubleToStr(AccountEquity(), 2) + " USDT\n";
comment += "Margem Livre: $" + DoubleToStr(AccountFreeMargin(), 2) + " USDT\n";
comment += "Status: " + (TradingEnabled ? "ATIVO" : "PAUSADO") + "\n";
double rsi = iRSI(Symbol(), 0, RSI_Period, PRICE_CLOSE, 1);
comment += "RSI: " + DoubleToStr(rsi, 1) + "\n";
Comment(comment);
}
//+------------------------------------------------------------------+
//| Função de Gestão de Risco |
//+------------------------------------------------------------------+
bool CheckRiskManagement()
{
double equity = AccountEquity();
double balance = AccountBalance();
double freeMargin = AccountFreeMargin();
// Verificar margem livre
if(freeMargin < (balance * 0.1)) // Menos de 10% de margem livre
{
Print("AVISO: Margem livre baixa - ", DoubleToStr(freeMargin, 2));
return false;
}
// Verificar drawdown
double drawdown = ((balance - equity) / balance) * 100;
if(drawdown > 20) // Drawdown maior que 20%
{
Print("AVISO: Drawdown alto - ", DoubleToStr(drawdown, 2), "%");
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Função de Trailing Stop |
//+------------------------------------------------------------------+
void TrailingStop()
{
for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
{
if(OrderType() == OP_BUY)
{
double newSL = Bid - (StopLoss * point);
if(newSL > OrderStopLoss() && newSL < Bid)
{
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrBlue);
}
}
else if(OrderType() == OP_SELL)
{
double newSL = Ask + (StopLoss * point);
if((newSL < OrderStopLoss() || OrderStopLoss() == 0) && newSL > Ask)
{
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrBlue);
}
}
}
}
}
}