// 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];
adicionando o estochastico em comfluencia com os indicadores RSI e com a rede neural pode aumentar a assertividade ?se sim atualize e me entregue o codigo completo
Adicionar o Estocástico junto ao RSI na estratégia pode aumentar a assertividade, especialmente se utilizado como uma confirmação adicional para os sinais dados pela rede neural. Por exemplo, a estratégia pode buscar momentos onde o RSI e o Estocástico estejam indicando possíveis reversões ou tendências, usando isso como uma segunda camada de filtro para as decisões de compra ou venda da rede neural.
Aqui está o código atualizado com a inclusão do Estocástico, usado como um filtro adicional à lógica existente:
Código Atualizado com o Estocástico
mql4
//+------------------------------------------------------------------+
//| Scalping Robot |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.02"
#include <Trade/Trade.mqh>
#define NumNodes 10 // Number of network nodes
CTrade trade;
CPositionInfo pos;
COrderInfo ord;
// Neural Network Parameters
input double Coefficient = 0.1;
input double LearningRate = 0.1;
double Weight[NumNodes]; // Neural network node weights
double NormalizedInputs[NumNodes];
double NNOutput = 0;
//+------------------------------------------------------------------+
//| Inputs and Settings |
//+------------------------------------------------------------------+
input group "*** Trading Inputs ***"
input double LotSize = 0.01; // Lot size for trading
input int Tppoints = 800; // Take Profit (10 points = 1 pip)
input int Slpoints = 800; // Stop Loss Points (10 points = 1 pip)
input int TslTriggerPoints = 35; // Points in profit before Trailing SL is activated (10 points = 1 pip)
input int TslPoints = 10; // Trailing Stoploss (10 points = 1 pip)
input ENUM_TIMEFRAMES Timeframe = PERIOD_CURRENT; // Time frame to run
input int InpMagic = 891245; // EA identification no
input string TradeComment = "Wendel Cassiano";
input int MaxSpread = 100; // Maximum spread allowed (in points)
input int Slippage = 50; // Slippage in points
input int MaxOrders = 2; // Max simultaneous orders
int BarsN = 5;
int ExpirationBars = 100;
int OrderDistPoints = 100;
//+------------------------------------------------------------------+
//| Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
trade.SetExpertMagicNumber(InpMagic);
ChartSetInteger(0, CHART_SHOW_GRID, false);
// Initialize Neural Network Weights
for (int i = 0; i < NumNodes; i++)
Weight[i] = 0.5; // Arbitrary initial weights for the neural network
return (INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert Tick Function |
//+------------------------------------------------------------------+
void OnTick()
{
// Apply trailing stop logic
TrailStop();
// 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();
// Get RSI and Stochastic values as additional filter
double rsiValue = RSIValue(0);
double stoK, stoD;
if (!GetStochasticValues(0, stoK, stoD)) return;
// Confirm Buy and Sell Signals with Stochastic
bool buySignal = (BuyTotal == 0 && NNOutput > 0 && rsiValue < 30 && stoK < 20 && stoK < stoD);
bool sellSignal = (SellTotal == 0 && NNOutput < 0 && rsiValue > 70 && stoK > 80 && stoK > stoD);
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;
}
//+------------------------------------------------------------------+
//| Retrieve RSI Value |
//+------------------------------------------------------------------+
double RSIValue(int shift)
{
int rsiPeriod = 14;
double rsi[];
int rsiHandle = iRSI(_Symbol, Timeframe, rsiPeriod, PRICE_CLOSE);
if (rsiHandle == INVALID_HANDLE)
{
Print("Error creating RSI!");
return 0.0;
}
if (CopyBuffer(rsiHandle, 0, shift, 1, rsi) <= 0)
{
Print("Error copying RSI values!");
return 0.0;
}
IndicatorRelease(rsiHandle);
return rsi[0];
}
//+------------------------------------------------------------------+
//| Retrieve Stochastic Values |
//+------------------------------------------------------------------+
bool GetStochasticValues(int shift, double &stoK, double &stoD)
{
int stochPeriodK = 5, stochPeriodD = 3, slowing = 3;
double kBuffer[], dBuffer[];
int stochHandle = iStochastic(_Symbol, Timeframe, stochPeriodK, slowing, stochPeriodD, MODE_SMA, PRICE_CLOSE);
if (stochHandle == INVALID_HANDLE)
{
Print("Error creating Stochastic!");
return false;
}
if (CopyBuffer(stochHandle, 0, shift, 1, kBuffer) <= 0 || CopyBuffer(stochHandle, 1, shift, 1, dBuffer) <= 0)
{
Print("Error copying Stochastic values!");
return false;
}
IndicatorRelease(stochHandle);
stoK = kBuffer[0];
stoD = dBuffer[0];
return true;
}
//+------------------------------------------------------------------+
//| Trailing Stop |
//+------------------------------------------------------------------+
void TrailStop()
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (pos.SelectByIndex(i) && pos.Magic() == InpMagic && pos.Symbol() == _Symbol)
{
double sl = 0;
double tp = pos.TakeProfit();
if (pos.PositionType() == POSITION_TYPE_BUY)
{
if (bid - pos.PriceOpen() >= TslTriggerPoints * _Point)
{
sl = bid - TslPoints * _Point;
if (sl > pos.StopLoss() || pos.StopLoss() == 0)
trade.PositionModify(pos.Ticket(), sl, tp);
}
}
if (pos.PositionType() == POSITION_TYPE_SELL)
{
if (pos.PriceOpen() - ask >= TslTriggerPoints * _Point)
{
sl = ask + TslPoints * _Point;
if (sl < pos.StopLoss() || pos.StopLoss() == 0)
trade.PositionModify(pos.Ticket(), sl, tp);
}
}
}
}
}
//+------------------------------------------------------------------+
//| Detect New Bar |
//+------------------------------------------------------------------+
bool IsNewBar()
{
static datetime previousTime = 0;
datetime currentTime = iTime(_Symbol, Timeframe, 0);
if (previousTime != currentTime)
{
previousTime = currentTime;
return true;
}
return false;
}
Alterações Realizadas:
Incluído Estocástico: Foi adicionado o uso do indicador estocástico (iStochastic), que calcula os valores %K e %D.
Confluência dos Indicadores: A decisão de compra/venda agora depende do sinal da rede neural em conjunto com o RSI e o Estocástico.
Compra: RSI < 30, %K < 20 e %K < %D (Estocástico em sobrevenda).
Venda: RSI > 70, %K > 80 e %K > %D (Estocástico em sobrecompra).
Filtros Adicionais: Agora a estratégia é mais restrita em suas condições de entrada, prevenindo operações impulsivas.
Agora a estratégia está utilizando múltiplos critérios para melhorar a assertividade. Teste em conta demo para ajustes e otimização!
o codigo naoe sta 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];
Aqui você tem o código completo do robô de scalping atualizado com a inclusão do indicador Estocástico, adicionando-o como uma confluência ao RSI e à lógica de rede neural. A detecção de sinais de compra e venda leva em consideração tanto o RSI quanto os valores do Estocástico (%K, %D) como parte dos critérios de decisão.
Segue o código completo atualizado:
mql4
//+------------------------------------------------------------------+
//| Scalping Robot |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.02"
#include <Trade/Trade.mqh>
#define NumNodes 10 // Number of network nodes
CTrade trade;
CPositionInfo pos;
COrderInfo ord;
// Neural Network Parameters
input double Coefficient = 0.1;
input double LearningRate = 0.1;
double Weight[NumNodes]; // Neural network node weights
double NormalizedInputs[NumNodes];
double NNOutput = 0;
//+------------------------------------------------------------------+
//| Inputs and Settings |
//+------------------------------------------------------------------+
input group "*** Trading Inputs ***"
input double LotSize = 0.01; // Lot size for trading
input int Tppoints = 800; // Take Profit (10 points = 1 pip)
input int Slpoints = 800; // Stop Loss Points (10 points = 1 pip)
input int TslTriggerPoints = 35; // Points in profit before Trailing SL is activated (10 points = 1 pip)
input int TslPoints = 10; // Trailing Stoploss (10 points = 1 pip)
input ENUM_TIMEFRAMES Timeframe = PERIOD_CURRENT; // Time frame to run
input int InpMagic = 891245; // EA identification no
input string TradeComment = "Wendel Cassiano";
input int MaxSpread = 100; // Maximum spread allowed (in points)
input int Slippage = 50; // Slippage in points
input int MaxOrders = 2; // Max simultaneous orders
int BarsN = 5;
int ExpirationBars = 100;
int OrderDistPoints = 100;
//+------------------------------------------------------------------+
//| Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
trade.SetExpertMagicNumber(InpMagic);
ChartSetInteger(0, CHART_SHOW_GRID, false);
// Initialize Neural Network Weights
for (int i = 0; i < NumNodes; i++)
Weight[i] = 0.5; // Arbitrary initial weights for the neural network
return (INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert Tick Function |
//+------------------------------------------------------------------+
void OnTick()
{
// Apply trailing stop logic
TrailStop();
// 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();
// Get RSI and Stochastic values
double rsiValue = RSIValue(0);
double stoK, stoD;
if (!GetStochasticValues(0, stoK, stoD)) return;
// Confirm signals with Stochastic and RSI
bool buySignal = (BuyTotal == 0 && NNOutput > 0 && rsiValue < 30 && stoK < 20 && stoK < stoD);
bool sellSignal = (SellTotal == 0 && NNOutput < 0 && rsiValue > 70 && stoK > 80 && stoK > stoD);
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;
double rsi[];
int rsiHandle = iRSI(_Symbol, Timeframe, rsiPeriod, PRICE_CLOSE);
if (rsiHandle == INVALID_HANDLE)
return 0.0;
if (CopyBuffer(rsiHandle, 0, shift, 1, rsi) <= 0)
return 0.0;
IndicatorRelease(rsiHandle);
return rsi[0];
}
//+------------------------------------------------------------------+
//| Get Stochastic Values |
//+------------------------------------------------------------------+
bool GetStochasticValues(int shift, double &stoK, double &stoD)
{
int stochPeriodK = 5, stochPeriodD = 3, slowing = 3;
double kBuffer[], dBuffer[];
int stochHandle = iStochastic(_Symbol, Timeframe, stochPeriodK, slowing, stochPeriodD, MODE_SMA, PRICE_CLOSE);
if (stochHandle == INVALID_HANDLE)
return false;
if (CopyBuffer(stochHandle, 0, shift, 1, kBuffer) <= 0 || CopyBuffer(stochHandle, 1, shift, 1, dBuffer) <= 0)
return false;
stoK = kBuffer[0];
stoD = dBuffer[0];
IndicatorRelease(stochHandle);
return true;
}
//+------------------------------------------------------------------+
//| Neural Network Implementation |
//+------------------------------------------------------------------+
void NormalizingInputs()
{
double LowerNormRange = -1;
double UpperNormRange = 1;
for (int i = 0; i < NumNodes; i++)
{
double currentRSI = RSIValue(i);
NormalizedInputs[i] = (((currentRSI - 0) * (UpperNormRange - LowerNormRange)) / (100 - 0)) + LowerNormRange;
}
}
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)));
}
//+------------------------------------------------------------------+
//| Place Orders |
//+------------------------------------------------------------------+
void SendBuyOrder(double entry)
{
double tp = entry + Tppoints * _Point;
double sl = entry - Slpoints * _Point;
trade.BuyStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, TimeCurrent() + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
}
void SendSellOrder(double entry)
{
double tp = entry - Tppoints * _Point;
double sl = entry + Slpoints * _Point;
trade.SellStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, TimeCurrent() + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
}
//+------------------------------------------------------------------+
//| Trailing Stop |
//+------------------------------------------------------------------+
void TrailStop()
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (pos.SelectByIndex(i) && pos.Magic() == InpMagic && pos.Symbol() == _Symbol)
{
double sl = 0;
double tp = pos.TakeProfit();
if (pos.PositionType() == POSITION_TYPE_BUY)
{
if (bid - pos.PriceOpen() >= TslTriggerPoints * _Point)
{
sl = bid - TslPoints * _Point;
if (sl > pos.StopLoss() || pos.StopLoss() == 0)
trade.PositionModify(pos.Ticket(), sl, tp);
}
}
if (pos.PositionType() == POSITION_TYPE_SELL)
{
if (pos.PriceOpen() - ask >= TslTriggerPoints * _Point)
{
sl = ask + TslPoints * _Point;
if (sl < pos.StopLoss() || pos.StopLoss() == 0)
trade.PositionModify(pos.Ticket(), sl, tp);
}
}
}
}
}
//+------------------------------------------------------------------+
//| Detect New Bar |
//+------------------------------------------------------------------+
bool IsNewBar()
{
static datetime previousTime = 0;
datetime currentTime = iTime(_Symbol, Timeframe, 0);
if (previousTime != currentTime)
{
previousTime = currentTime;
return true;
}
return false;
}
Alterações:
Estocástico:
Agora é utilizado como critério adicional junto com o RSI.
Um sinal de compra é gerado se o %K estiver abaixo de 20 e %K < %D (sobrevenda).
Um sinal de venda é gerado se o %K estiver acima de 80 e %K > %D (sobrecompra).
Filtro com RSI e Estocástico:
As decisões de compra/venda são confirmadas somente quando o RSI e Estocástico indicam confluência com a saída da rede neural.
Correção de IndicatorRelease no RSI e Estocástico para liberar os recursos alocados dos indicadores.
Este código depende de indicadores como o RSI e Estocástico. Portanto, realize testes com SymbolTester para otimizar os parâmetros (como períodos do RSI ou limiares do Estocástico). Ajuste a rede neural também para melhor convergência.
A mensagem de erro indica que houve um problema na passagem do tipo de preço (PRICE_CLOSE) para a função iStochastic(). No MQL5, a função iStochastic() não aceita diretamente PRICE_CLOSE como argumento, mas sim uma combinação de tipos de preços, representada pelo enumerador ENUM_STO_PRICE (como STO_LOWHIGH ou STO_LOWCLOSE).
Vamos corrigir isso no código. Em vez de PRICE_CLOSE, usaremos STO_LOWHIGH, que é o valor padrão para o cálculo do Estocástico, ou STO_LOWCLOSE, que pode ser utilizado dependendo da necessidade.
Aqui está o trecho corrigido do código com a utilização apropriada de ENUM_STO_PRICE:
Código Atualizado
mql5
//+------------------------------------------------------------------+
//| Get Stochastic Values |
//+------------------------------------------------------------------+
bool GetStochasticValues(int shift, double &stoK, double &stoD)
{
int stochPeriodK = 5; // Período do %K
int stochSlowing = 3; // Slowing do Estocástico
int stochPeriodD = 3; // Período do %D
ENUM_MA_METHOD maMethod = MODE_SMA; // Método de média
ENUM_STO_PRICE priceField = STO_LOWHIGH; // Tipo de preço (LOW/HIGH padrão)
// Buffer para %K e %D
double kBuffer[];
double dBuffer[];
// Handle para o Estocástico
int stochHandle = iStochastic(_Symbol, Timeframe, stochPeriodK, stochSlowing, stochPeriodD, maMethod, priceField);
if (stochHandle == INVALID_HANDLE)
{
Print("Erro ao criar o indicador Estocástico!");
return false;
}
// Copiar os valores do Estocástico para os buffers
if (CopyBuffer(stochHandle, 0, shift, 1, kBuffer) <= 0 || CopyBuffer(stochHandle, 1, shift, 1, dBuffer) <= 0)
{
Print("Erro ao copiar os valores do Estocástico!");
IndicatorRelease(stochHandle);
return false;
}
// Recolher os valores do Estocástico
stoK = kBuffer[0];
stoD = dBuffer[0];
// Liberar o handle do indicador
IndicatorRelease(stochHandle);
return true;
}
Explicação das Alterações:
ENUM_STO_PRICE:
Substituí PRICE_CLOSE por STO_LOWHIGH como argumento na função iStochastic(). Você também pode usar STO_LOWCLOSE caso prefira calcular com base em CLOSE em vez de HIGH/LOW.
Correção dos parâmetros do Estocástico:
stochPeriodK: Período do %K.
stochSlowing: Slowing do Estocástico (suavização).
stochPeriodD: Período da média do %D.
maMethod: Método da média móvel (default: MODE_SMA).
priceField: Tipo de preço para o cálculo do Estocástico (usei STO_LOWHIGH como padrão).
Teste o Código
Com as alterações acima, este problema deve ser resolvido. Certifique-se de testar o robô em modo de depuração ou em uma conta demo para garantir que ele está se comportando conforme esperado. Se precisar de mais ajuda, estou à disposição!
Aqui está o código atualizado e completo do robô de Scalping com rede neural, RSI e Estocástico, corrigindo os problemas previamente descritos:
mql5
//+------------------------------------------------------------------+
//| Scalping Robot |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.02"
#include <Trade/Trade.mqh>
#define NumNodes 10 // Número de nós na rede neural
CTrade trade;
CPositionInfo pos;
COrderInfo ord;
// Parâmetros da Rede Neural
input double Coefficient = 0.1;
input double LearningRate = 0.1;
double Weight[NumNodes]; // Pesos dos nós da rede neural
double NormalizedInputs[NumNodes];
double NNOutput = 0;
//+------------------------------------------------------------------+
//| Entradas e Configs |
//+------------------------------------------------------------------+
input group "*** Configurações de Operação ***"
input double LotSize = 0.01; // Tamanho do lote
input int Tppoints = 800; // Take Profit
input int Slpoints = 800; // Stop Loss
input int TslTriggerPoints = 35; // Pontos até ativar Trailing Stop
input int TslPoints = 10; // Trailing Stoploss
input ENUM_TIMEFRAMES Timeframe = PERIOD_CURRENT; // Timeframe usado
input int InpMagic = 891245; // Identificador único do EA
input string TradeComment = "Wendel Cassiano"; // Comentário das ordens
input int MaxSpread = 100; // Spread máximo permitido
input int Slippage = 50; // Slippage em pontos
input int MaxOrders = 2; // Máximo de ordens simultâneas
int BarsN = 5;
int ExpirationBars = 100;
int OrderDistPoints = 50;
//+------------------------------------------------------------------+
//| Inicialização |
//+------------------------------------------------------------------+
int OnInit()
{
trade.SetExpertMagicNumber(InpMagic);
ChartSetInteger(0, CHART_SHOW_GRID, false);
// Inicializar os pesos da Rede Neural
for (int i = 0; i < NumNodes; i++)
Weight[i] = 0.5; // Pesos arbitrários para iniciar
return (INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Função principal (Tick) |
//+------------------------------------------------------------------+
void OnTick()
{
// Aplicar o trailing stop
TrailStop();
// Verificar se há candle novo
if (!IsNewBar()) return;
// Checar spread
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
if (spread > MaxSpread) return;
// Contar ordens ativas de compra/venda
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++;
}
// Limitar número máximo de ordens
if ((BuyTotal + SellTotal) >= MaxOrders) return;
// Saída da rede neural
NormalizingInputs();
OutputLayerCalculation();
// Obter valores do RSI e Estocástico
double rsiValue = RSIValue(0);
double stoK, stoD;
if (!GetStochasticValues(0, stoK, stoD)) return;
// Confirmar sinais de compra/venda com RSI e Estocástico
bool buySignal = (BuyTotal == 0 && NNOutput > 0 && rsiValue < 30 && stoK < 20 && stoK < stoD);
bool sellSignal = (SellTotal == 0 && NNOutput < 0 && rsiValue > 70 && stoK > 80 && stoK > stoD);
if (buySignal)
{
double high = findHigh();
if (high > 0)
SendBuyOrder(high);
}
if (sellSignal)
{
double low = findLow();
if (low > 0)
SendSellOrder(low);
}
}
//+------------------------------------------------------------------+
//| Funções Auxiliares |
//+------------------------------------------------------------------+
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;
}
//+------------------------------------------------------------------+
//| Obtém valor do RSI |
//+------------------------------------------------------------------+
double RSIValue(int shift)
{
int rsiPeriod = 14;
double rsi[];
int rsiHandle = iRSI(_Symbol, Timeframe, rsiPeriod, PRICE_CLOSE);
if (rsiHandle == INVALID_HANDLE) return 0.0;
if (CopyBuffer(rsiHandle, 0, shift, 1, rsi) <= 0)
{
IndicatorRelease(rsiHandle);
return 0.0;
}
IndicatorRelease(rsiHandle);
return rsi[0];
}
//+------------------------------------------------------------------+
//| Obtém valores do Estocástico |
//+------------------------------------------------------------------+
bool GetStochasticValues(int shift, double &stoK, double &stoD)
{
int stochPeriodK = 5; // Período do %K
int stochSlowing = 3; // Slowing
int stochPeriodD = 3; // Período do %D
ENUM_MA_METHOD maMethod = MODE_SMA; // Método da média
ENUM_STO_PRICE priceField = STO_LOWHIGH; // Tipo de preço
double kBuffer[];
double dBuffer[];
int stochHandle = iStochastic(_Symbol, Timeframe, stochPeriodK, stochSlowing, stochPeriodD, maMethod, priceField);
if (stochHandle == INVALID_HANDLE)
{
Print("Erro ao criar o Estocástico!");
return false;
}
if (CopyBuffer(stochHandle, 0, shift, 1, kBuffer) <= 0 || CopyBuffer(stochHandle, 1, shift, 1, dBuffer) <= 0)
{
IndicatorRelease(stochHandle);
return false;
}
stoK = kBuffer[0];
stoD = dBuffer[0];
IndicatorRelease(stochHandle);
return true;
}
//+------------------------------------------------------------------+
//| Implementação da Rede Neural |
//+------------------------------------------------------------------+
void NormalizingInputs()
{
double LowerNormRange = -1;
double UpperNormRange = 1;
for (int i = 0; i < NumNodes; i++)
{
double currentRSI = RSIValue(i);
NormalizedInputs[i] = (((currentRSI - 0) * (UpperNormRange - LowerNormRange)) / (100 - 0)) + LowerNormRange;
}
}
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)));
}
//+------------------------------------------------------------------+
//| Envia ordens de Compra e Venda |
//+------------------------------------------------------------------+
void SendBuyOrder(double entry)
{
double tp = entry + Tppoints * _Point;
double sl = entry - Slpoints * _Point;
trade.BuyStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, TimeCurrent() + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
}
void SendSellOrder(double entry)
{
double tp = entry - Tppoints * _Point;
double sl = entry + Slpoints * _Point;
trade.SellStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, TimeCurrent() + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
}
//+------------------------------------------------------------------+
//| Aplica o Trailing Stop |
//+------------------------------------------------------------------+
void TrailStop()
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (pos.SelectByIndex(i) && pos.Magic() == InpMagic && pos.Symbol() == _Symbol)
{
double sl = 0;
double tp = pos.TakeProfit();
if (pos.PositionType() == POSITION_TYPE_BUY)
{
if (bid - pos.PriceOpen() >= TslTriggerPoints * _Point)
{
sl = bid - TslPoints * _Point;
if (sl > pos.StopLoss() || pos.StopLoss() == 0)
trade.PositionModify(pos.Ticket(), sl, tp);
}
}
if (pos.PositionType() == POSITION_TYPE_SELL)
{
if (pos.PriceOpen() - ask >= TslTriggerPoints * _Point)
{
sl = ask + TslPoints * _Point;
if (sl < pos.StopLoss() || pos.StopLoss() == 0)
trade.PositionModify(pos.Ticket(), sl, tp);
}
}
}
}
}
//+------------------------------------------------------------------+
//| Detecta novo candle |
//+------------------------------------------------------------------+
bool IsNewBar()
{
static datetime previousTime = 0;
datetime currentTime = iTime(_Symbol, Timeframe, 0);
if (previousTime != currentTime)
{
previousTime = currentTime;
return true;
}
return false;
}
Resumo
Este código está corrigido para funcionar com o indicador Estocástico e RSI como confluências em uma estratégia orientada por rede neural.
Principais Componentes:
RSI e Estocástico:
RSIValue calcula o RSI.
GetStochasticValues retorna os valores %K e %D.
Neural Network:
A rede analisa inputs normalizados (NormalizedInputs) e gera uma previsão de compra/venda.
Condições de Compra/Venda:
Consideram a saída da rede neural, valores do RSI e o Estocástico como confirmação.
Teste
Certifique-se de testar o código em uma conta demo antes de usá-lo em cenários de trading real e ajuste os períodos dos indicadores para sua estratégia.