//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Signal MQL5 Robot started successfully.");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("Signal MQL5 Robot stopped.");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Certificando-se de que não há outra posição aberta antes de executar a lógica de sinais
if (PositionsTotal() == 0)
{
RunSignalLogic();
}
else
{
Print("Já existe uma ordem aberta. Aguardando.");
}
}
//+------------------------------------------------------------------+
//| Signal logic function |
//+------------------------------------------------------------------+
void RunSignalLogic()
{
// Capturando os parâmetros do gráfico atual (últimos 3 candles)
MqlRates prices[];
ArraySetAsSeries(prices, true); // Inverte a ordem (candle 0 é o mais recente)
if (CopyRates(Symbol(), Period(), 0, 3, prices) <= 0)
{
Print("Erro ao copiar os preços: ", GetLastError());
return;
}
// Variáveis para os candles atuais e anteriores
double openPrice0 = prices[1].open;
double closePrice0 = prices[1].close;
double highPrice0 = prices[1].high;
double lowPrice0 = prices[1].low;
// Preenchendo a estrutura de solicitação
ZeroMemory(request);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lots;
request.price = price;
request.sl = NormalizeDouble(stopLoss, _Digits);
request.tp = NormalizeDouble(takeProfit, _Digits);
request.type = ORDER_TYPE_SELL;
request.type_filling = ORDER_FILLING_IOC;
request.deviation = 10;
// Enviando a ordem
if (!OrderSend(request, result))
Print("Erro ao enviar ordem de venda: ", GetLastError());
else
Print("Ordem de venda enviada com sucesso!");
}
}
coloque no codigo acima o trailing stop e TP com as mesmas configuraçoes , deacordo com o do codigo abaixo de exemplo: adicione maximo de spread permitido tambem e um TP e SL fixo
//+------------------------------------------------------------------+
//| Scalping Robot |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.01"
#include <Trade/Trade.mqh>
#define NumNodes 20 // Number of network nodes
CTrade trade;
CPositionInfo pos;
COrderInfo ord;
// Check if the new bar is available
if (!IsNewBar()) return;
// Check spread
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
if (spread > MaxSpread) return;
// Count active Buy and Sell positions/orders
int BuyTotal = 0, SellTotal = 0;
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
pos.SelectByIndex(i);
if (pos.PositionType() == POSITION_TYPE_BUY && pos.Symbol() == _Symbol && pos.Magic() == InpMagic)
BuyTotal++;
if (pos.PositionType() == POSITION_TYPE_SELL && pos.Symbol() == _Symbol && pos.Magic() == InpMagic)
SellTotal++;
}
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
ord.SelectByIndex(i);
if (ord.OrderType() == ORDER_TYPE_BUY_STOP && ord.Symbol() == _Symbol && ord.Magic() == InpMagic)
BuyTotal++;
if (ord.OrderType() == ORDER_TYPE_SELL_STOP && ord.Symbol() == _Symbol && ord.Magic() == InpMagic)
SellTotal++;
}
// Limit maximum orders
int TotalOrders = BuyTotal + SellTotal;
if (TotalOrders >= MaxOrders) return;
// Neural network prediction
NormalizingInputs();
OutputLayerCalculation();
// Determine Buy and Sell Signals from Neural Network
bool buySignal = (BuyTotal == 0 && NNOutput > 0);
bool sellSignal = (SellTotal == 0 && NNOutput < 0);
if (buySignal)
{
double high = findHigh();
if (high > 0)
SendBuyOrder(high);
}
if (sellSignal)
{
double low = findLow();
if (low > 0)
SendSellOrder(low);
}
}
//+------------------------------------------------------------------+
//| Helper Functionality |
//+------------------------------------------------------------------+
double findHigh()
{
double highestHigh = 0;
for (int i = 0; i < 200; i++)
{
double high = iHigh(_Symbol, Timeframe, i);
if (i > BarsN && iHighest(_Symbol, Timeframe, MODE_HIGH, BarsN * 2 + 1, i - BarsN) == i)
{
if (high > highestHigh) return high;
}
highestHigh = MathMax(high, highestHigh);
}
return -1;
}
double findLow()
{
double lowestLow = DBL_MAX;
for (int i = 0; i < 200; i++)
{
double low = iLow(_Symbol, Timeframe, i);
if (i > BarsN && iLowest(_Symbol, Timeframe, MODE_LOW, BarsN * 2 + 1, i - BarsN) == i)
{
if (low < lowestLow) return low;
}
}
return -1;
}
//+------------------------------------------------------------------+
//| Calculate RSI Value |
//+------------------------------------------------------------------+
double RSIValue(int shift)
{
int rsiPeriod = 14; // Período padrão do RSI
double rsi[]; // Array para armazenar os valores do RSI
code
// Handle do indicador RSI
int rsiHandle = iRSI(_Symbol, Timeframe, rsiPeriod, PRICE_CLOSE);
// Verifique se o handle foi criado corretamente
if (rsiHandle == INVALID_HANDLE)
{
Print("Erro ao criar o indicador RSI!");
return 0.0;
}
// Copiar os valores do RSI para o array a partir do buffer
if (CopyBuffer(rsiHandle, 0, shift, 1, rsi) <= 0)
{
Print("Erro ao copiar os valores do RSI!");
return 0.0;
}
// Liberar recursos do handle do indicador
IndicatorRelease(rsiHandle);
// Retornar o valor do RSI desejado
return rsi[0];
Para adicionar o trailing stop, o limite de spread permitido e o uso de Stop Loss (SL) e Take Profit (TP) fixos ao primeiro código, você pode ajustar a estrutura da função ExecuteSignal e adicionar a lógica de trailing stop semelhante ao exemplo fornecido. Aqui está o código ajustado:
Código Final:
mql5
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Signal MQL5 Robot started successfully.");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("Signal MQL5 Robot stopped.");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Certificando-se de que não há outra posição aberta antes de executar a lógica de sinais
if (PositionsTotal() == 0)
{
RunSignalLogic();
}
else
{
Print("Já existe uma ordem aberta. Aguardando.");
TrailStop(); // Aplica o trailing stop em atuais posições abertas
}
}
//+------------------------------------------------------------------+
//| Signal logic function |
//+------------------------------------------------------------------+
void RunSignalLogic()
{
// Capturando os parâmetros do gráfico atual (últimos 3 candles)
MqlRates prices[];
ArraySetAsSeries(prices, true); // Inverte a ordem (candle 0 é o mais recente)
if (CopyRates(Symbol(), Period(), 0, 3, prices) <= 0)
{
Print("Erro ao copiar os preços: ", GetLastError());
return;
}
// Verifica o spread atual
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
int MaxSpread = 100; // Spread máximo permitido em pontos
if (spread > MaxSpread)
{
Print("Spread atual (", spread, ") excede o máximo permitido (", MaxSpread, ").");
return;
}
// Variáveis para os candles atuais e anteriores
double openPrice0 = prices[1].open;
double closePrice0 = prices[1].close;
double highPrice0 = prices[1].high;
double lowPrice0 = prices[1].low;
double highPrev = prices[2].high;
double lowPrev = prices[2].low;
double closePrev = prices[2].close;
// Sinal: Nenhum (0), Compra (2), Venda (1)
int signalType = 0;
// --- Condições de Compra ---
bool c0 = openPrice0 > closePrice0; // Candle vermelho
bool c1 = highPrice0 > highPrev; // Máxima atual maior que a anterior
bool c2 = lowPrice0 < lowPrev; // Mínima atual menor que a anterior
bool c3 = closePrice0 < lowPrev; // Fechamento está abaixo da mínima anterior
if (c0 && c1 && c2 && c3)
signalType = 2;
// --- Condições de Venda ---
c0 = openPrice0 < closePrice0; // Candle verde
c1 = lowPrice0 < lowPrev;
c2 = highPrice0 > highPrev;
c3 = closePrice0 > highPrev;
if (c0 && c1 && c2 && c3)
signalType = 1;
// Executando o sinal detectado
if (signalType != 0)
ExecuteSignal(signalType);
}
//+------------------------------------------------------------------+
//| Função para executar os sinais detectados |
//+------------------------------------------------------------------+
void ExecuteSignal(int signalType)
{
MqlTradeRequest request;
MqlTradeResult result;
// Valores fixos
double lots = 0.1;
double slPoints = 200 * _Point; // Exemplo: 20 pips
double tpPoints = 400 * _Point; // Exemplo: 40 pips
double tslTriggerPoints = 350 * _Point; // Trailing Stop ativado cerca de 35 pips
double tslPoints = 100 * _Point; // Trailing Stop ajusta com distância de 10 pips
double price = 0.0;
double stopLoss = 0.0;
double takeProfit = 0.0;
if (signalType == 2) // Compra
{
price = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
stopLoss = price - slPoints;
takeProfit = price + tpPoints;
// Preenchendo a estrutura de solicitação
ZeroMemory(request);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lots;
request.price = price;
request.sl = NormalizeDouble(stopLoss, _Digits);
request.tp = NormalizeDouble(takeProfit, _Digits);
request.type = ORDER_TYPE_BUY;
request.type_filling = ORDER_FILLING_IOC;
request.deviation = 10;
if (!OrderSend(request, result))
Print("Erro ao enviar ordem de compra: ", GetLastError());
else
Print("Ordem de compra enviada com sucesso!");
}
if (signalType == 1) // Venda
{
price = SymbolInfoDouble(Symbol(), SYMBOL_BID);
stopLoss = price + slPoints;
takeProfit = price - tpPoints;
// Preenchendo a estrutura de solicitação
ZeroMemory(request);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lots;
request.price = price;
request.sl = NormalizeDouble(stopLoss, _Digits);
request.tp = NormalizeDouble(takeProfit, _Digits);
request.type = ORDER_TYPE_SELL;
request.type_filling = ORDER_FILLING_IOC;
request.deviation = 10;
if (!OrderSend(request, result))
Print("Erro ao enviar ordem de venda: ", GetLastError());
else
Print("Ordem de venda enviada com sucesso!");
}
}
//+------------------------------------------------------------------+
//| Trailing Stop |
//+------------------------------------------------------------------+
void TrailStop()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (SelectPosition(i))
{
double sl = 0;
double tp = PositionGetDouble(POSITION_TP);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
double currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
if (currentPrice - openPrice >= tslTriggerPoints)
{
sl = currentPrice - tslPoints;
if (sl > PositionGetDouble(POSITION_SL))
ModifyPosition(PositionGetTicket(), sl, tp);
}
}
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
double currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
if (openPrice - currentPrice >= tslTriggerPoints)
{
sl = currentPrice + tslPoints;
if (sl < PositionGetDouble(POSITION_SL))
ModifyPosition(PositionGetTicket(), sl, tp);
}
}
}
}
}
//+------------------------------------------------------------------+
//| Helpers |
//+------------------------------------------------------------------+
bool SelectPosition(int index)
{
return (PositionSelectByIndex(index) && PositionGetString(POSITION_SYMBOL) == Symbol());
}
bool ModifyPosition(ulong ticket, double newSl, double newTp)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
request.action = TRADE_ACTION_SLTP;
request.symbol = Symbol();
request.sl = NormalizeDouble(newSl, _Digits);
request.tp = NormalizeDouble(newTp, _Digits);
request.position = ticket;
return OrderSend(request, result);
}
Modificações realizadas:
Trailing Stop integrado na função TrailStop(), verificando o gatilho (tslTriggerPoints) e ajustando o SL dinamicamente.
Limite de spread permitido para evitar execução de ordens com spreads altos.
SL e TP fixos adicionados direto nas posições durante a criação da ordem.
Organização da lógica de sinais e execução mantendo a compatibilidade com Stop Loss e Take Profit automáticos.
Esses ajustes garantem que o robô verifique o spread, utilize trailing stop e aplique SL/TP corretamente durante a criação/gerenciamento de posições.
Pelos erros apresentados, parece que há inconsistências no código em relação à declaração de variáveis, chamadas de funções e parametrizações. Vou ajustar o código e explicar os ajustes para eliminar os erros e torná-lo funcional.
Causas dos Erros:
tslTriggerPoints e tslPoints:
Essas variáveis precisam ser declaradas no escopo global ou passadas como parâmetros para serem reconhecidas nas funções que fazem uso delas.
PositionGetTicket():
A função PositionGetTicket() não existe. O correto é usar PositionGetInteger(POSITION_TICKET) para obter o ticket de uma posição aberta.
PositionSelectByIndex():
O método correto é PositionSelect(), mas ele deve ser utilizado com o nome do símbolo ou índice.
Outros erros de parsing (ex: index ou ==):
Isso ocorre devido a erros de sintaxe ou uso inadequado de funções.
Código Corrigido
Segue o código corrigido com as alterações necessárias:
mql5
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Signal MQL5 Robot started successfully.");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("Signal MQL5 Robot stopped.");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Certificando-se de que não há outra posição aberta antes de executar a lógica de sinais
if (PositionsTotal() == 0)
{
RunSignalLogic();
}
else
{
Print("Já existe uma ordem aberta. Aguardando.");
TrailStop(); // Aplica o trailing stop em atuais posições abertas
}
}
//+------------------------------------------------------------------+
//| Signal logic function |
//+------------------------------------------------------------------+
void RunSignalLogic()
{
// Capturando os parâmetros do gráfico atual (últimos 3 candles)
MqlRates prices[];
ArraySetAsSeries(prices, true); // Inverte a ordem (candle 0 é o mais recente)
if (CopyRates(Symbol(), Period(), 0, 3, prices) <= 0)
{
Print("Erro ao copiar os preços: ", GetLastError());
return;
}
// Verifica o spread atual
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
int MaxSpread = 100; // Spread máximo permitido em pontos
if (spread > MaxSpread)
{
Print("Spread atual (", spread, ") excede o máximo permitido (", MaxSpread, ").");
return;
}
// Variáveis para os candles atuais e anteriores
double openPrice0 = prices[1].open;
double closePrice0 = prices[1].close;
double highPrice0 = prices[1].high;
double lowPrice0 = prices[1].low;
double highPrev = prices[2].high;
double lowPrev = prices[2].low;
double closePrev = prices[2].close;
// Sinal: Nenhum (0), Compra (2), Venda (1)
int signalType = 0;
// --- Condições de Compra ---
bool c0 = openPrice0 > closePrice0; // Candle vermelho
bool c1 = highPrice0 > highPrev; // Máxima atual maior que a anterior
bool c2 = lowPrice0 < lowPrev; // Mínima atual menor que a anterior
bool c3 = closePrice0 < lowPrev; // Fechamento está abaixo da mínima anterior
if (c0 && c1 && c2 && c3)
signalType = 2;
// --- Condições de Venda ---
c0 = openPrice0 < closePrice0; // Candle verde
c1 = lowPrice0 < lowPrev;
c2 = highPrice0 > highPrev;
c3 = closePrice0 > highPrev;
if (c0 && c1 && c2 && c3)
signalType = 1;
// Executando o sinal detectado
if (signalType != 0)
ExecuteSignal(signalType);
}
//+------------------------------------------------------------------+
//| Função para executar os sinais detectados |
//+------------------------------------------------------------------+
void ExecuteSignal(int signalType)
{
MqlTradeRequest request;
MqlTradeResult result;
// Valores fixos
double lots = 0.1;
double slPoints = 200 * _Point; // Exemplo: 20 pips
double tpPoints = 400 * _Point; // Exemplo: 40 pips
double price = 0.0;
double stopLoss = 0.0;
double takeProfit = 0.0;
if (signalType == 2) // Compra
{
price = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
stopLoss = price - slPoints;
takeProfit = price + tpPoints;
// Preenchendo a estrutura de solicitação
ZeroMemory(request);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lots;
request.price = price;
request.sl = NormalizeDouble(stopLoss, _Digits);
request.tp = NormalizeDouble(takeProfit, _Digits);
request.type = ORDER_TYPE_BUY;
request.type_filling = ORDER_FILLING_IOC;
request.deviation = 10;
if (!OrderSend(request, result))
Print("Erro ao enviar ordem de compra: ", GetLastError());
else
Print("Ordem de compra enviada com sucesso!");
}
if (signalType == 1) // Venda
{
price = SymbolInfoDouble(Symbol(), SYMBOL_BID);
stopLoss = price + slPoints;
takeProfit = price - tpPoints;
// Preenchendo a estrutura de solicitação
ZeroMemory(request);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lots;
request.price = price;
request.sl = NormalizeDouble(stopLoss, _Digits);
request.tp = NormalizeDouble(takeProfit, _Digits);
request.type = ORDER_TYPE_SELL;
request.type_filling = ORDER_FILLING_IOC;
request.deviation = 10;
if (!OrderSend(request, result))
Print("Erro ao enviar ordem de venda: ", GetLastError());
else
Print("Ordem de venda enviada com sucesso!");
}
}
//+------------------------------------------------------------------+
//| Trailing Stop |
//+------------------------------------------------------------------+
void TrailStop()
{
double tslTriggerPoints = 35 * _Point; // Exemplo: Trailing Stop ativo com 35 pips de lucro
double tslPoints = 10 * _Point; // Stop move 10 pips atrás do preço atual
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionSelect(Symbol())) // Seleciona a posição do símbolo atual
{
double sl = 0;
double tp = PositionGetDouble(POSITION_TP);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
double currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_BID);
if (currentPrice - openPrice >= tslTriggerPoints)
{
sl = currentPrice - tslPoints;
if (sl > PositionGetDouble(POSITION_SL))
ModifyPosition(PositionGetInteger(POSITION_TICKET), sl, tp);
}
}
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
double currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
if (openPrice - currentPrice >= tslTriggerPoints)
{
sl = currentPrice + tslPoints;
if (sl < PositionGetDouble(POSITION_SL))
ModifyPosition(PositionGetInteger(POSITION_TICKET), sl, tp);
}
}
}
}
}
bool ModifyPosition(ulong ticket, double newSl, double newTp)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
request.action = TRADE_ACTION_SLTP;
request.symbol = Symbol();
request.sl = NormalizeDouble(newSl, _Digits);
request.tp = NormalizeDouble(newTp, _Digits);
request.position = ticket;
return OrderSend(request, result);
}
Correções Realizadas:
Declarei variáveis tslTriggerPoints e tslPoints explicitamente na função TrailStop.
Corrigi o uso de PositionGetInteger(POSITION_TICKET) em vez de PositionGetTicket().
Usei a função correta PositionSelect(Symbol()) para selecionar posições abertas pelo símbolo atual.
Ajustei a lógica e a sintaxe geral para evitar erros de parsing.
Agora, o código está corrigido. Por favor, teste e compartilhe caso encontre algo mais!
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Signal MQL5 Robot started successfully.");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("Signal MQL5 Robot stopped.");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Certificando-se de que não há outra posição aberta antes de executar a lógica de sinais
if (PositionsTotal() == 0)
{
RunSignalLogic();
}
else
{
Print("Já existe uma ordem aberta. Aguardando.");
TrailStop(); // Aplica o trailing stop em atuais posições abertas
}
}
//+------------------------------------------------------------------+
//| Signal logic function |
//+------------------------------------------------------------------+
void RunSignalLogic()
{
// Capturando os parâmetros do gráfico atual (últimos 3 candles)
MqlRates prices[];
ArraySetAsSeries(prices, true); // Inverte a ordem (candle 0 é o mais recente)
code
if (CopyRates(Symbol(), Period(), 0, 3, prices) <= 0)
{
Print("Erro ao copiar os preços: ", GetLastError());
return;
}
// Verifica o spread atual
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
int MaxSpread = 100; // Spread máximo permitido em pontos
if (spread > MaxSpread)
{
Print("Spread atual (", spread, ") excede o máximo permitido (", MaxSpread, ").");
return;
}
// Variáveis para os candles atuais e anteriores
double openPrice0 = prices[1].open;
double closePrice0 = prices[1].close;
double highPrice0 = prices[1].high;
double lowPrice0 = prices[1].low;
double highPrev = prices[2].high;
double lowPrev = prices[2].low;
double closePrev = prices[2].close;
// Sinal: Nenhum (0), Compra (2), Venda (1)
int signalType = 0;
// --- Condições de Compra ---
bool c0 = openPrice0 > closePrice0; // Candle vermelho
bool c1 = highPrice0 > highPrev; // Máxima atual maior que a anterior
bool c2 = lowPrice0 < lowPrev; // Mínima atual menor que a anterior
bool c3 = closePrice0 < lowPrev; // Fechamento está abaixo da mínima anterior
if (c0 && c1 && c2 && c3)
signalType = 2;
// --- Condições de Venda ---
c0 = openPrice0 < closePrice0; // Candle verde
c1 = lowPrice0 < lowPrev;
c2 = highPrice0 > highPrev;
c3 = closePrice0 > highPrev;
if (c0 && c1 && c2 && c3)
signalType = 1;
// Executando o sinal detectado
if (signalType != 0)
ExecuteSignal(signalType);
}
//+------------------------------------------------------------------+
//| Função para executar os sinais detectados |
//+------------------------------------------------------------------+
void ExecuteSignal(int signalType)
{
MqlTradeRequest request;
MqlTradeResult result;
adicione no meu codigo acima rede neural como a do codigo abaixo para melhorar a assertividade da estrategia do codigo acima e me entregue o codigo completo:
//+------------------------------------------------------------------+
//| Scalping Robot |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.01"
#include <Trade/Trade.mqh>
#define NumNodes 10 // Number of network nodes
CTrade trade;
CPositionInfo pos;
COrderInfo ord;
// Check if the new bar is available
if (!IsNewBar()) return;
// Check spread
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
if (spread > MaxSpread) return;
// Count active Buy and Sell positions/orders
int BuyTotal = 0, SellTotal = 0;
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
pos.SelectByIndex(i);
if (pos.PositionType() == POSITION_TYPE_BUY && pos.Symbol() == _Symbol && pos.Magic() == InpMagic)
BuyTotal++;
if (pos.PositionType() == POSITION_TYPE_SELL && pos.Symbol() == _Symbol && pos.Magic() == InpMagic)
SellTotal++;
}
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
ord.SelectByIndex(i);
if (ord.OrderType() == ORDER_TYPE_BUY_STOP && ord.Symbol() == _Symbol && ord.Magic() == InpMagic)
BuyTotal++;
if (ord.OrderType() == ORDER_TYPE_SELL_STOP && ord.Symbol() == _Symbol && ord.Magic() == InpMagic)
SellTotal++;
}
// Limit maximum orders
int TotalOrders = BuyTotal + SellTotal;
if (TotalOrders >= MaxOrders) return;
// Neural network prediction
NormalizingInputs();
OutputLayerCalculation();
// Determine Buy and Sell Signals from Neural Network
bool buySignal = (BuyTotal == 0 && NNOutput > 0);
bool sellSignal = (SellTotal == 0 && NNOutput < 0);
if (buySignal)
{
double high = findHigh();
if (high > 0)
SendBuyOrder(high);
}
if (sellSignal)
{
double low = findLow();
if (low > 0)
SendSellOrder(low);
}
}
//+------------------------------------------------------------------+
//| Helper Functionality |
//+------------------------------------------------------------------+
double findHigh()
{
double highestHigh = 0;
for (int i = 0; i < 200; i++)
{
double high = iHigh(_Symbol, Timeframe, i);
if (i > BarsN && iHighest(_Symbol, Timeframe, MODE_HIGH, BarsN * 2 + 1, i - BarsN) == i)
{
if (high > highestHigh) return high;
}
highestHigh = MathMax(high, highestHigh);
}
return -1;
}
double findLow()
{
double lowestLow = DBL_MAX;
for (int i = 0; i < 200; i++)
{
double low = iLow(_Symbol, Timeframe, i);
if (i > BarsN && iLowest(_Symbol, Timeframe, MODE_LOW, BarsN * 2 + 1, i - BarsN) == i)
{
if (low < lowestLow) return low;
}
}
return -1;
}
//+------------------------------------------------------------------+
//| Calculate RSI Value |
//+------------------------------------------------------------------+
double RSIValue(int shift)
{
int rsiPeriod = 14; // Período padrão do RSI
double rsi[]; // Array para armazenar os valores do RSI
code
// Handle do indicador RSI
int rsiHandle = iRSI(_Symbol, Timeframe, rsiPeriod, PRICE_CLOSE);
// Verifique se o handle foi criado corretamente
if (rsiHandle == INVALID_HANDLE)
{
Print("Erro ao criar o indicador RSI!");
return 0.0;
}
// Copiar os valores do RSI para o array a partir do buffer
if (CopyBuffer(rsiHandle, 0, shift, 1, rsi) <= 0)
{
Print("Erro ao copiar os valores do RSI!");
return 0.0;
}
// Liberar recursos do handle do indicador
IndicatorRelease(rsiHandle);
// Retornar o valor do RSI desejado
return rsi[0];
Adicionar uma rede neural ao seu código principal para melhorar a assertividade é um excelente passo para criar sistemas mais inteligentes e adaptativos. No caso, a estrutura da rede neural do segundo código será incorporada ao seu código existente. Como a lógica da rede neural já está bem organizada no segundo código, será integrada no seu código original.
Abaixo está o código completo com a integração da rede neural:
Código Final com Rede Neural Integrada
mql5
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.01"
#include <Trade/Trade.mqh>
// Parâmetros do Neural Network
#define NumNodes 10 // Número de nós da rede neural
input double Coefficient = 0.1; // Coeficiente para transformação dos dados na rede
input double LearningRate = 0.1; // Taxa de aprendizado da rede
// Funções Comerciais
CTrade trade;
// Declaração de variáveis da rede neural
double Weight[NumNodes]; // Pesos dos nós da rede
double NormalizedInputs[NumNodes]; // Entradas normalizadas para a rede
double NNOutput = 0; // Saída final da rede neural
// Outros parâmetros fixos para trading
input double LotSize = 0.1; // Tamanho de lote para ordens
input int Tppoints = 400; // Points para Take Profit
input int Slpoints = 200; // Points para Stop Loss
input int TslTriggerPoints = 35; // Pontos antes de ativar Trailing Stop
input int TslPoints = 10; // Ajuste do Trailing Stop
input int MaxSpread = 100; // Spread máximo permitido
input int InpMagic = 123456; // Magic Number das ordens
//+------------------------------------------------------------------+
//| Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Signal MQL5 Robot with Neural Network started successfully.");
// Inicializa os pesos da rede neural
for (int i = 0; i < NumNodes; i++)
Weight[i] = 0.5; // Inicializando pesos com valores arbitrários
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("Signal MQL5 Robot stopped.");
}
//+------------------------------------------------------------------+
//| Expert Tick Function |
//+------------------------------------------------------------------+
void OnTick()
{
// Certifique-se de que não há outra posição antes de operar
if (PositionsTotal() == 0)
{
RunSignalLogic();
}
else
{
Print("Já existe uma posição aberta. Verificando trailing stop.");
TrailStop(); // Aplica o trailing stop às posições atuais
}
}
//+------------------------------------------------------------------+
//| Função RunSignalLogic com rede neural |
//+------------------------------------------------------------------+
void RunSignalLogic()
{
// Verifica o spread atual
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
if (spread > MaxSpread)
{
Print("Spread atual excede o limite permitido. Ignorando sinal.");
return;
}
// Configure a entrada normalizada para a Rede Neural
NormalizingInputs();
// Calcula a saída da rede neural
OutputLayerCalculation();
// Determina o tipo de sinal com base na saída da rede
if (NNOutput > 0) // Condição neural indicando compra
{
ExecuteSignal(ORDER_TYPE_BUY);
}
else if (NNOutput < 0) // Condição neural indicando venda
{
ExecuteSignal(ORDER_TYPE_SELL);
}
}
//+------------------------------------------------------------------+
//| Executa sinal (compra ou venda) |
//+------------------------------------------------------------------+
void ExecuteSignal(int signalType)
{
MqlTradeRequest request;
MqlTradeResult result;
double price, stopLoss, takeProfit;
// Define os preços relevantes
if (signalType == ORDER_TYPE_BUY)
{
price = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
stopLoss = price - (Slpoints * _Point);
takeProfit = price + (Tppoints * _Point);
}
else if (signalType == ORDER_TYPE_SELL)
{
price = SymbolInfoDouble(Symbol(), SYMBOL_BID);
stopLoss = price + (Slpoints * _Point);
takeProfit = price - (Tppoints * _Point);
}
// Preenche as informações da requisição
ZeroMemory(request);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = LotSize;
request.price = price;
request.sl = NormalizeDouble(stopLoss, _Digits);
request.tp = NormalizeDouble(takeProfit, _Digits);
request.type = signalType;
request.type_filling = ORDER_FILLING_IOC;
request.magic = InpMagic;
request.deviation = 10;
// Envia a ordem
if (!OrderSend(request, result))
Print("Erro ao enviar ordem: ", GetLastError());
else
Print("Ordem enviada com sucesso: ", signalType == ORDER_TYPE_BUY ? "Compra" : "Venda");
}
//+------------------------------------------------------------------+
//| Trail Stop para posições abertas |
//+------------------------------------------------------------------+
void TrailStop()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionSelect(Symbol()))
{
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ?
SymbolInfoDouble(Symbol(), SYMBOL_BID) :
SymbolInfoDouble(Symbol(), SYMBOL_ASK);
double sl;
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY &&
(currentPrice - openPrice) >= (TslTriggerPoints * _Point))
{
sl = currentPrice - (TslPoints * _Point);
if (sl > PositionGetDouble(POSITION_SL))
PositionModify(PositionGetInteger(POSITION_TICKET), sl, PositionGetDouble(POSITION_TP));
}
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL &&
(openPrice - currentPrice) >= (TslTriggerPoints * _Point))
{
sl = currentPrice + (TslPoints * _Point);
if (sl < PositionGetDouble(POSITION_SL))
PositionModify(PositionGetInteger(POSITION_TICKET), sl, PositionGetDouble(POSITION_TP));
}
}
}
}
//+------------------------------------------------------------------+
//| Normalização das entradas para a rede neural |
//+------------------------------------------------------------------+
void NormalizingInputs()
{
double LowerNormRange = -1, UpperNormRange = 1;
for (int i = 0; i < NumNodes; i++)
{
double currentRSI = RSIValue(i);
NormalizedInputs[i] = (((currentRSI - 0) * (UpperNormRange - LowerNormRange)) / (100 - 0)) + LowerNormRange;
}
}
//+------------------------------------------------------------------+
//| Cálculo da saída da rede neural |
//+------------------------------------------------------------------+
void OutputLayerCalculation()
{
NNOutput = HiddenLayerCalculation(NormalizedInputs, Weight);
}
double HiddenLayerCalculation(double &inputs[], double &Weights[])
{
double TotalWeightedInputs = 0.0;
for (int i = 0; i < ArraySize(inputs); i++)
TotalWeightedInputs += inputs[i] * Weights[i];
TotalWeightedInputs *= Coefficient;
return TanHActivationFunction(TotalWeightedInputs);
}
double TanHActivationFunction(double WeightedInputs)
{
return (exp(WeightedInputs) - exp(-WeightedInputs)) / (exp(WeightedInputs) + exp(-WeightedInputs));
}
//+------------------------------------------------------------------+
//| Calculo do RSI |
//+------------------------------------------------------------------+
double RSIValue(int shift)
{
int rsiPeriod = 14;
double rsi[];
int rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, rsiPeriod, PRICE_CLOSE);
if (rsiHandle == INVALID_HANDLE)
{
Print("Erro ao inicializar RSI.");
return 0.0;
}
if (CopyBuffer(rsiHandle, 0, shift, 1, rsi) <= 0)
{
Print("Erro ao capturar buffer do RSI.");
return 0.0;
}
IndicatorRelease(rsiHandle);
return rsi[0];
}
//+------------------------------------------------------------------+
O que foi feito:
Rede Neural Adicionada:
Integrei a normalização de entradas e o cálculo da rede neural.
A lógica da saída da rede (compra/venda) substitui os critérios anteriores.
Trailing Stop e Proteções:
Trailing Stop foi revisado e integrado.
Execução de Ordens:
Toma decisões com base nas saídas da rede neural.
RSI para Entradas:
RSI é usado como entrada para os nós da rede.
Teste e Validação:
Execute o código em ambiente de backtest utilizando diferentes pares de moedas e períodos para ajustar os pesos da rede neural (treinamento não implementado nesse modelo). Poste dúvidas caso surjam durante os testes!
Os erros apresentados sugerem que o código possui algumas falhas no uso de variáveis, operações e funções relacionadas à manipulação de posições e ordens no MetaTrader 5.
Vamos revisar e corrigir os erros apresentados:
1. possible use of uninitialized variable (price, stopLoss, takeProfit)
Esse erro ocorre porque as variáveis price, stopLoss e takeProfit não têm valores atribuídos antes de serem usadas. Isso ocorre na função ExecuteSignal.
Correção:
Garante-se que as variáveis são inicializadas de acordo com o tipo de ordem (compra ou venda).
2. implicit enum conversion para valores como ORDER_TYPE_BUY e ORDER_TYPE_SELL
Esse erro ocorre devido à falta de conversão explícita ou manipulação correta de ENUM_ORDER_TYPE.
Correção:
Os valores devem ser usados diretamente sem conversões, já que os enums estão bem definidos no contexto.
3. Erro em PositionModify - identificador não declarado
A função PositionModify não existe diretamente no MQL5. Para modificar uma posição, deve-se utilizar trade.PositionModify da biblioteca CTrade.
Correção:
Usar o objeto CTrade trade para modificar posições. Certifique-se de que o Ticket da posição também é corrigido para o contexto.
Código Revisado e Corrigido:
Aqui está o código ajustado com todas as correções dos erros relatados:
mql5
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.01"
#include <Trade/Trade.mqh>
// Neural Network Parameters
#define NumNodes 10 // Número de nós da rede neural
input double Coefficient = 0.1; // Coeficiente para transformação dos dados na rede
input double LearningRate = 0.1; // Taxa de aprendizado da rede
// Input Trading Parameters
input double LotSize = 0.1; // Tamanho de lote para ordens
input int Tppoints = 400; // Points para Take Profit
input int Slpoints = 200; // Points para Stop Loss
input int TslTriggerPoints = 35; // Pontos antes de ativar Trailing Stop
input int TslPoints = 10; // Ajuste do Trailing Stop
input int MaxSpread = 100; // Spread máximo permitido
input int InpMagic = 123456; // Magic Number das ordens
CTrade trade; // Objeto para manipulação de ordens
// Variáveis da Rede Neural
double Weight[NumNodes]; // Pesos dos nós da rede neural
double NormalizedInputs[NumNodes]; // Entradas normalizadas para a rede
double NNOutput = 0; // Resultado da rede neural
//+------------------------------------------------------------------+
//| Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Signal MQL5 Robot with Neural Network started successfully.");
for (int i = 0; i < NumNodes; i++)
Weight[i] = 0.5; // Inicializando pesos com valores arbitrários
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("Signal MQL5 Robot stopped.");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if (PositionsTotal() == 0) // Verifica posições abertas
{
RunSignalLogic();
}
else
{
Print("Já existe uma posição aberta. Verificando trailing stop.");
TrailStop(); // Aplica trailing stop nas posições abertas
}
}
//+------------------------------------------------------------------+
//| Sinal baseado na Rede Neural |
//+------------------------------------------------------------------+
void RunSignalLogic()
{
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
if (spread > MaxSpread)
{
Print("Spread atual excede o limite permitido. Ignorando sinais.");
return;
}
// Normaliza as entradas e calcula a saída da rede neural
NormalizingInputs();
OutputLayerCalculation();
// Compra ou venda com base na saída da rede neural
if (NNOutput > 0)
{
ExecuteSignal(ORDER_TYPE_BUY);
}
else if (NNOutput < 0)
{
ExecuteSignal(ORDER_TYPE_SELL);
}
}
//+------------------------------------------------------------------+
//| Envio de Ordens com base nos Sinais |
//+------------------------------------------------------------------+
void ExecuteSignal(int signalType)
{
double price = 0.0, stopLoss = 0.0, takeProfit = 0.0;
// Configurando os valores para cada tipo de ordem (compra/venda)
if (signalType == ORDER_TYPE_BUY)
{
price = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
stopLoss = price - (Slpoints * _Point);
takeProfit = price + (Tppoints * _Point);
}
else if (signalType == ORDER_TYPE_SELL)
{
price = SymbolInfoDouble(Symbol(), SYMBOL_BID);
stopLoss = price + (Slpoints * _Point);
takeProfit = price - (Tppoints * _Point);
}
// Envio da Ordem
if (!trade.PositionOpen(_Symbol, signalType == ORDER_TYPE_BUY ? OP_BUY : OP_SELL,
LotSize, price, stopLoss, takeProfit, ""))
{
Print("Erro ao enviar ordem: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Função de Trailing Stop |
//+------------------------------------------------------------------+
void TrailStop()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (!PositionSelect(Symbol()))
continue; // Seleciona a posição atual no símbolo
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ?
SymbolInfoDouble(Symbol(), SYMBOL_BID) :
SymbolInfoDouble(Symbol(), SYMBOL_ASK);
double sl;
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY &&
(currentPrice - openPrice) >= (TslTriggerPoints * _Point))
{
sl = currentPrice - (TslPoints * _Point);
if (sl > PositionGetDouble(POSITION_SL))
trade.PositionModify(PositionGetInteger(POSITION_TICKET), sl, PositionGetDouble(POSITION_TP));
}
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL &&
(openPrice - currentPrice) >= (TslTriggerPoints * _Point))
{
sl = currentPrice + (TslPoints * _Point);
if (sl < PositionGetDouble(POSITION_SL))
trade.PositionModify(PositionGetInteger(POSITION_TICKET), sl, PositionGetDouble(POSITION_TP));
}
}
}
//+------------------------------------------------------------------+
//| Normalização de Entradas |
//+------------------------------------------------------------------+
void NormalizingInputs()
{
double LowerNormRange = -1, UpperNormRange = 1;
for (int i = 0; i < NumNodes; i++)
{
double currentRSI = RSIValue(i);
NormalizedInputs[i] = (((currentRSI - 0) * (UpperNormRange - LowerNormRange)) / (100 - 0)) + LowerNormRange;
}
}
//+------------------------------------------------------------------+
//| Saída da Rede Neural |
//+------------------------------------------------------------------+
void OutputLayerCalculation()
{
NNOutput = HiddenLayerCalculation(NormalizedInputs, Weight);
}
double HiddenLayerCalculation(double &inputs[], double &Weights[])
{
double TotalWeightedInputs = 0.0;
for (int i = 0; i < ArraySize(inputs); i++)
TotalWeightedInputs += inputs[i] * Weights[i];
TotalWeightedInputs *= Coefficient;
return TanHActivationFunction(TotalWeightedInputs);
}
double TanHActivationFunction(double WeightedInputs)
{
return (exp(WeightedInputs) - exp(-WeightedInputs)) / (exp(WeightedInputs) + exp(-WeightedInputs));
}
//+------------------------------------------------------------------+
//| RSI utilizado como entrada |
//+------------------------------------------------------------------+
double RSIValue(int shift)
{
int rsiPeriod = 14;
double rsi[];
int rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, rsiPeriod, PRICE_CLOSE);
if (rsiHandle == INVALID_HANDLE)
{
Print("Erro ao inicializar RSI.");
return 0.0;
}
if (CopyBuffer(rsiHandle, 0, shift, 1, rsi) <= 0)
{
Print("Erro ao capturar buffer do RSI.");
return 0.0;
}
IndicatorRelease(rsiHandle);
return rsi[0];
}
//+------------------------------------------------------------------+
Alterações:
Variáveis como price, stopLoss e takeProfit foram inicializadas antes de seu uso.
trade.PositionModify substituiu o método PositionModify.
Ajustes para enums claros nas opções ORDER_TYPE_BUY e ORDER_TYPE_SELL.
Revisado Trailing Stop e integrado corretamente.
Execute este código corrigido e compartilhe resultados!
Os identificadores OP_BUY e OP_SELL pertencem ao MQL4 e não existem no MQL5. No MQL5, você deve usar os enums ORDER_TYPE_BUY e ORDER_TYPE_SELL diretamente, pois eles fazem parte das definições padrão para abertura de posições. Além disso, tentamos usar o ternário (?) para decidir entre compra e venda, o que também resultou em erro porque o tipo esperado não combinava com os parâmetros do MQL5.
Corrigirei os trechos do código onde esses erros ocorreram:
Solução:
No lugar de OP_BUY e OP_SELL, você usará os enums ORDER_TYPE_BUY e ORDER_TYPE_SELL diretamente no método trade.PositionOpen. Além disso, removeremos o uso do operador ternário (?) para garantir a compatibilidade.
O método de abertura de posições no objeto CTrade deve ser utilizado corretamente.
Código Final Corrigido:
mql5
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property version "1.01"
#include <Trade/Trade.mqh>
// Neural Network Parameters
#define NumNodes 10 // Número de nós da rede neural
input double Coefficient = 0.1; // Coeficiente para transformação dos dados na rede
input double LearningRate = 0.1; // Taxa de aprendizado da rede
// Input Trading Parameters
input double LotSize = 0.1; // Tamanho de lote para ordens
input int Tppoints = 400; // Points para Take Profit
input int Slpoints = 200; // Points para Stop Loss
input int TslTriggerPoints = 35; // Pontos antes de ativar Trailing Stop
input int TslPoints = 10; // Ajuste do Trailing Stop
input int MaxSpread = 100; // Spread máximo permitido
input int InpMagic = 123456; // Magic Number das ordens
CTrade trade; // Objeto para manipulação de ordens
// Variáveis da Rede Neural
double Weight[NumNodes]; // Pesos dos nós da rede neural
double NormalizedInputs[NumNodes]; // Entradas normalizadas para a rede
double NNOutput = 0; // Resultado da rede neural
//+------------------------------------------------------------------+
//| Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Signal MQL5 Robot with Neural Network started successfully.");
for (int i = 0; i < NumNodes; i++)
Weight[i] = 0.5; // Inicializando pesos com valores arbitrários
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("Signal MQL5 Robot stopped.");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if (PositionsTotal() == 0) // Verifica posições abertas
{
RunSignalLogic();
}
else
{
Print("Já existe uma posição aberta. Verificando trailing stop.");
TrailStop(); // Aplica trailing stop nas posições abertas
}
}
//+------------------------------------------------------------------+
//| Sinal baseado na Rede Neural |
//+------------------------------------------------------------------+
void RunSignalLogic()
{
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
if (spread > MaxSpread)
{
Print("Spread atual excede o limite permitido. Ignorando sinais.");
return;
}
// Normaliza as entradas e calcula a saída da rede neural
NormalizingInputs();
OutputLayerCalculation();
// Compra ou venda com base na saída da rede neural
if (NNOutput > 0)
{
ExecuteSignal(ORDER_TYPE_BUY);
}
else if (NNOutput < 0)
{
ExecuteSignal(ORDER_TYPE_SELL);
}
}
//+------------------------------------------------------------------+
//| Envio de Ordens com base nos Sinais |
//+------------------------------------------------------------------+
void ExecuteSignal(ENUM_ORDER_TYPE signalType)
{
double price = 0.0, stopLoss = 0.0, takeProfit = 0.0;
// Configurando os valores para cada tipo de ordem (compra/venda)
if (signalType == ORDER_TYPE_BUY)
{
price = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
stopLoss = price - (Slpoints * _Point);
takeProfit = price + (Tppoints * _Point);
}
else if (signalType == ORDER_TYPE_SELL)
{
price = SymbolInfoDouble(Symbol(), SYMBOL_BID);
stopLoss = price + (Slpoints * _Point);
takeProfit = price - (Tppoints * _Point);
}
// Envio da Ordem
if (!trade.PositionOpen(Symbol(), signalType, LotSize, price, stopLoss, takeProfit, "Neural Signal"))
{
Print("Erro ao enviar ordem: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Função de Trailing Stop |
//+------------------------------------------------------------------+
void TrailStop()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (!PositionSelect(Symbol()))
continue; // Seleciona a posição atual no símbolo
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ?
SymbolInfoDouble(Symbol(), SYMBOL_BID) :
SymbolInfoDouble(Symbol(), SYMBOL_ASK);
double sl;
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY &&
(currentPrice - openPrice) >= (TslTriggerPoints * _Point))
{
sl = currentPrice - (TslPoints * _Point);
if (sl > PositionGetDouble(POSITION_SL))
trade.PositionModify(PositionGetInteger(POSITION_TICKET), sl, PositionGetDouble(POSITION_TP));
}
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL &&
(openPrice - currentPrice) >= (TslTriggerPoints * _Point))
{
sl = currentPrice + (TslPoints * _Point);
if (sl < PositionGetDouble(POSITION_SL))
trade.PositionModify(PositionGetInteger(POSITION_TICKET), sl, PositionGetDouble(POSITION_TP));
}
}
}
//+------------------------------------------------------------------+
//| Normalização de Entradas |
//+------------------------------------------------------------------+
void NormalizingInputs()
{
double LowerNormRange = -1, UpperNormRange = 1;
for (int i = 0; i < NumNodes; i++)
{
double currentRSI = RSIValue(i);
NormalizedInputs[i] = (((currentRSI - 0) * (UpperNormRange - LowerNormRange)) / (100 - 0)) + LowerNormRange;
}
}
//+------------------------------------------------------------------+
//| Saída da Rede Neural |
//+------------------------------------------------------------------+
void OutputLayerCalculation()
{
NNOutput = HiddenLayerCalculation(NormalizedInputs, Weight);
}
double HiddenLayerCalculation(double &inputs[], double &Weights[])
{
double TotalWeightedInputs = 0.0;
for (int i = 0; i < ArraySize(inputs); i++)
TotalWeightedInputs += inputs[i] * Weights[i];
TotalWeightedInputs *= Coefficient;
return TanHActivationFunction(TotalWeightedInputs);
}
double TanHActivationFunction(double WeightedInputs)
{
return (exp(WeightedInputs) - exp(-WeightedInputs)) / (exp(WeightedInputs) + exp(-WeightedInputs));
}
//+------------------------------------------------------------------+
//| RSI utilizado como entrada |
//+------------------------------------------------------------------+
double RSIValue(int shift)
{
int rsiPeriod = 14;
double rsi[];
int rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, rsiPeriod, PRICE_CLOSE);
if (rsiHandle == INVALID_HANDLE)
{
Print("Erro ao inicializar RSI.");
return 0.0;
}
if (CopyBuffer(rsiHandle, 0, shift, 1, rsi) <= 0)
{
Print("Erro ao capturar buffer do RSI.");
return 0.0;
}
IndicatorRelease(rsiHandle);
return rsi[0];
}
//+------------------------------------------------------------------+
Alterações Específicas:
OP_BUY e OP_SELL substituídos por ORDER_TYPE_BUY e ORDER_TYPE_SELL.
No MQL5, esses enums são diretamente suportados.
Uso correto de trade.PositionOpen.
Correção para evitar conflitos de tipos ao trabalhar com enums em OrderSend.
Esse código agora deve ser compilado sem erros no MetaEditor. Teste em seu ambiente e veja se ele atende às suas expectativas. Caso mais problemas surjam, não hesite em perguntar! 🚀