//+------------------------------------------------------------------+
//| RedFairy v1.5.mq5 |
//| Integrando RSI, MACD e MOM com Redes Neurais |
//| Joy D Moyo |
//| www.latvianfts.com |
//+------------------------------------------------------------------+
#property copyright "Joy D Moyo"
#property link "www.latvianfts.com"
#property version "1.5"
#include <Trade\Trade.mqh>
#define NumNodes 15 // Atualizado para incluir MOM como terceiro indicador
CTrade *Trade;
CPositionInfo PositionInfo;
input group "GENERAL INPUTS"
input string SymbolTraded = "EURUSD";
input ENUM_TIMEFRAMES PeriodTraded = PERIOD_M5;
input int EAMagic = 76755544;
input int MaxSlippage = 1;
input group "RSI INPUTS"
input int RSIPeriod = 14;
input ENUM_APPLIED_PRICE RSIAppliedPrice = PRICE_CLOSE;
input int OSLevel = 30; // Zona sobrevendida
input int OBLevel = 70; // Zona sobrecomprada
input int BuyCloseLevel = 60; // Fechar trades de compra acima desse nível
input int SellCloseLevel = 40; // Fechar trades de venda abaixo desse nível
input group "MACD INPUTS"
input int FastEMA = 12; // Período da EMA rápida
input int SlowEMA = 26; // Período da EMA lenta
input int SignalSMA = 9; // Período da linha de sinal
input ENUM_APPLIED_PRICE MACDAppliedPrice = PRICE_CLOSE;
input group "MOMENTUM INPUTS"
input int MOMPeriod = 14; // Período do indicador de Momentum
input group "TRADE MANAGEMENT INPUTS"
input bool UseCostAveraging = false;
input double LotMultiplier = 2;
input double GridDistance = 20;
input group "RISK INPUTS"
input double BalanceIncrease = 200;
input double VolumeIncrease = 0.01;
input group "NEURAL NETWORK INPUTS"
input double Coefficient = 0.1;
input double BuyTargetOutput = 0.3;
input double SellTargetOutput = -0.3;
input double LearningRate = 0.1;
int RSIHandle, MACDHandle, MOMHandle, OldNumBars = 0, MyDigits;
double RSIBuffer[], MACDBuffer[], SignalBuffer[], MOMBuffer[], MyPoint, NormalizedInputs[NumNodes], NNOutPut, NextBuyPrice = 0, NextSellPrice = 0, NextBuyLot = 0, NextSellLot = 0, GridDistancePoints;
double Weight[];
int DataUsed = NumNodes;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configuração do gráfico
ChartSetInteger(0, CHART_SHOW_GRID, false);
ChartSetInteger(0, CHART_MODE, CHART_CANDLES);
ChartSetInteger(0, CHART_COLOR_BACKGROUND, clrBlack);
ChartSetInteger(0, CHART_COLOR_FOREGROUND, clrWhite);
ChartSetInteger(0, CHART_COLOR_CANDLE_BULL, clrWhite);
ChartSetInteger(0, CHART_COLOR_CANDLE_BEAR, clrRed);
// Inicializa a classe de negociação
Trade = new CTrade;
ulong MaxSlippagePoints = MaxSlippage * 10;
Trade.SetDeviationInPoints(MaxSlippagePoints);
Trade.SetExpertMagicNumber(EAMagic);
// Configura os pesos iniciais da rede neural
ArrayResize(Weight, NumNodes);
for (int i = 0; i < NumNodes; i++)
Weight[i] = 0.5;
// Configura o ativo e os pontos
MyPoint = SymbolInfoDouble(SymbolTraded, SYMBOL_POINT);
MyDigits = (int)SymbolInfoInteger(SymbolTraded, SYMBOL_DIGITS);
GridDistancePoints = GridDistance * 10 * MyPoint;
// Inicializa os indicadores
RSIHandle = iRSI(SymbolTraded, PeriodTraded, RSIPeriod, RSIAppliedPrice);
MACDHandle = iMACD(SymbolTraded, PeriodTraded, FastEMA, SlowEMA, SignalSMA, MACDAppliedPrice);
MOMHandle = iMomentum(SymbolTraded, PeriodTraded, MOMPeriod, PRICE_CLOSE);
ArraySetAsSeries(RSIBuffer, true);
ArraySetAsSeries(MACDBuffer, true);
ArraySetAsSeries(SignalBuffer, true);
ArraySetAsSeries(MOMBuffer, true);
return (INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
IndicatorRelease(RSIHandle);
IndicatorRelease(MACDHandle);
IndicatorRelease(MOMHandle);
delete Trade;
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if (!NewBarPresent()) return;
// Atualiza os dados dos indicadores
CopyBuffer(RSIHandle, 0, 0, DataUsed, RSIBuffer);
if (CopyBuffer(MACDHandle, 0, 0, DataUsed, MACDBuffer) <= 0 ||
CopyBuffer(MACDHandle, 1, 0, DataUsed, SignalBuffer) <= 0)
{
Print("Erro ao carregar buffers do MACD: ", GetLastError());
return;
}
if (CopyBuffer(MOMHandle, 0, 0, DataUsed, MOMBuffer) <= 0)
{
Print("Erro ao carregar buffers do Momentum: ", GetLastError());
return;
}
// Normaliza os inputs para uso na rede neural
NormalizingInputs();
OutPutLayerCalculation();
double TargetOutPut = 0;
// Definição do output alvo
if (RSIBuffer[1] >= 50)
TargetOutPut = BuyTargetOutput;
else if (RSIBuffer[1] < 50)
TargetOutPut = SellTargetOutput;
// Treinamento da rede neural usando BackPropagation
BackPropagation(NormalizedInputs, Weight, NNOutPut, TargetOutPut, LearningRate);
// Realiza operações de compra e venda com base nos indicadores
if (BuySignal())
Buy();
if (SellSignal())
Sell();
if (UseCostAveraging)
{
GridBuy();
GridSell();
}
// Fecha trades desatualizados
CloseMatureTrades();
}
//+------------------------------------------------------------------+
//| Implementação do normalizador de inputs |
//+------------------------------------------------------------------+
void NormalizingInputs()
{
double LowerNormRange = -1.0; // Faixa mínima de normalização
double UpperNormRange = 1.0; // Faixa máxima de normalização
double MinRSI = RSIBuffer[ArrayMinimum(RSIBuffer)];
double MaxRSI = RSIBuffer[ArrayMaximum(RSIBuffer)];
double MinMACD = MACDBuffer[ArrayMinimum(MACDBuffer)];
double MaxMACD = MACDBuffer[ArrayMaximum(MACDBuffer)];
double MinSignal = SignalBuffer[ArrayMinimum(SignalBuffer)];
double MaxSignal = SignalBuffer[ArrayMaximum(SignalBuffer)];
double MinMOM = MOMBuffer[ArrayMinimum(MOMBuffer)];
double MaxMOM = MOMBuffer[ArrayMaximum(MOMBuffer)];
// Normaliza RSI
for (int i = 0; i < DataUsed / 3; i++)
{
NormalizedInputs[i] = (((RSIBuffer[i] - MinRSI) * (UpperNormRange - LowerNormRange)) / (MaxRSI - MinRSI)) + LowerNormRange;
}
// Normaliza MACD
for (int i = DataUsed / 3; i < 2 * DataUsed / 3; i++)
{
NormalizedInputs[i] = (((MACDBuffer[i - DataUsed / 3] - MinMACD) * (UpperNormRange - LowerNormRange)) / (MaxMACD - MinMACD)) + LowerNormRange;
}
// Normaliza Momentum
for (int i = 2 * DataUsed / 3; i < DataUsed; i++)
{
NormalizedInputs[i] = (((MOMBuffer[i - 2 * DataUsed / 3] - MinMOM) * (UpperNormRange - LowerNormRange)) / (MaxMOM - MinMOM)) + LowerNormRange;
}
}
//+------------------------------------------------------------------+
//| Funções auxiliares para a rede neural |
//+------------------------------------------------------------------+
double HiddenLayerCalculation(double &inputs[], double &Weights[])
{
double TotalWeightedInputs = 0.0; // Soma dos inputs ponderados por seus pesos
for (int i = 0; i < ArraySize(inputs); i++)
TotalWeightedInputs += inputs[i] * Weights[i];
TotalWeightedInputs *= Coefficient; // Multiplica pelo coeficiente ajustável
return TanHActivationFunction(TotalWeightedInputs);
}
//+------------------------------------------------------------------+
//| Função de ativação Tangente Hiperbólica |
//+------------------------------------------------------------------+
double TanHActivationFunction(double WeightedInputs)
{
// Aplicação da função Tangente Hiperbólica
return ((exp(WeightedInputs) - exp(-WeightedInputs)) / (exp(WeightedInputs) + exp(-WeightedInputs)));
}
//+------------------------------------------------------------------+
//| Calcula a saída da rede neural usando os inputs normalizados |
//+------------------------------------------------------------------+
void OutPutLayerCalculation()
{
// Saída da rede neural baseada em um cálculo de camada oculta
NNOutPut = HiddenLayerCalculation(NormalizedInputs, Weight);
}
//+------------------------------------------------------------------+
//| BackPropagation - Atualiza os pesos na rede neural |
//+------------------------------------------------------------------+
void BackPropagation(double &Inputs[], double &Weights[], double &Outputs, double TargetOutputs, double LearningRates)
{
double error = TargetOutputs - Outputs; // Erro (diferença entre esperado e obtido)
double derivative = 1 - MathPow(Outputs, 2); // Derivada da função Tangente Hiperbólica
for (int i = 0; i < ArraySize(Inputs); i++)
{
double gradient = error * derivative * Inputs[i];
Weights[i] += LearningRates * gradient; // Atualiza os pesos da rede
}
}
//+------------------------------------------------------------------+
//| Funções de Sinais - Compra e Venda |
//+------------------------------------------------------------------+
bool BuySignal()
{
if (RSIBuffer[1] >= OSLevel && // RSI em zona de sobrecompra
RSIBuffer[2] < OSLevel && // RSI estava abaixo na barra anterior
MACDBuffer[1] > SignalBuffer[1] && // Linha MACD cruzando acima da linha de sinal
MOMBuffer[1] > MOMBuffer[2] && // Momentum subindo
NNOutPut > 0) // Confirmação pela rede neural (positivo)
return true;
return false;
}
bool SellSignal()
{
if (RSIBuffer[1] <= OBLevel && // RSI em zona de sobrevenda
RSIBuffer[2] > OBLevel && // RSI estava acima na barra anterior
MACDBuffer[1] < SignalBuffer[1] && // Linha MACD cruzando abaixo da linha de sinal
MOMBuffer[1] < MOMBuffer[2] && // Momentum caindo
NNOutPut < 0) // Confirmação pela rede neural (negativo)
return true;
return false;
}
//+------------------------------------------------------------------+
//| Verifica se há uma nova barra |
//+------------------------------------------------------------------+
bool NewBarPresent()
{
static datetime PreviousTime = 0; // Mantém o horário da última barra processada
datetime CurrentTime = iTime(SymbolTraded, PeriodTraded, 0); // Horário da nova barra
if (CurrentTime != PreviousTime) // Se a nova barra tiver outro horário
{
PreviousTime = CurrentTime; // Atualiza o tempo da última barra
return true; // Há uma nova barra
}
return false; // Caso contrário, não há nova barra
}
//+------------------------------------------------------------------+
//| Funções de Compra e Venda |
//+------------------------------------------------------------------+
void Buy()
{
if (!BuySignal()) // Se o sinal de compra não estiver presente, retorna
return;
double LotUsed = LotSize();
double ASK = SymbolInfoDouble(SymbolTraded, SYMBOL_ASK);
// Tenta abrir uma ordem de compra
if (!Trade.Buy(LotUsed, SymbolTraded, ASK, 0, 0, "FirstBuy"))
{
Print("Erro ao abrir ordem de Compra: ", GetLastError());
}
else
{
NextBuyLot = NormalizeDouble(LotUsed * LotMultiplier, 2);
NextBuyPrice = NormalizeDouble(ASK - GridDistancePoints, MyDigits);
}
}
void Sell()
{
if (!SellSignal()) // Se o sinal de venda não estiver presente, retorna
return;
double LotUsed = LotSize();
double BID = SymbolInfoDouble(SymbolTraded, SYMBOL_BID);
// Tenta abrir uma ordem de venda
if (!Trade.Sell(LotUsed, SymbolTraded, BID, 0, 0, "FirstSell"))
{
Print("Erro ao abrir ordem de Venda: ", GetLastError());
}
else
{
NextSellLot = NormalizeDouble(LotUsed * LotMultiplier, 2);
NextSellPrice = NormalizeDouble(BID + GridDistancePoints, MyDigits);
}
}
//+------------------------------------------------------------------+
//| Estratégia de Cost Averaging (Grade de Ordens) |
//+------------------------------------------------------------------+
void GridBuy()
{
if (!BuySignal()) // Verifica se ainda há sinais de compra válidos
return;
double ASK = SymbolInfoDouble(SymbolTraded, SYMBOL_ASK);
if (ASK < NextBuyPrice) // Condição para próxima compra na grade
{
if (!Trade.Buy(NextBuyLot, SymbolTraded, ASK, 0, 0, "GridBuy"))
{
Print("Erro ao abrir Grade de Compras: ", GetLastError());
}
else
{
NextBuyLot = NormalizeDouble(NextBuyLot * LotMultiplier, 2);
NextBuyPrice = NormalizeDouble(ASK - GridDistancePoints, MyDigits);
}
}
}
void GridSell()
{
if (!SellSignal()) // Verifica se ainda há sinais de venda válidos
return;
double BID = SymbolInfoDouble(SymbolTraded, SYMBOL_BID);
if (BID > NextSellPrice) // Condição para próxima venda na grade
{
if (!Trade.Sell(NextSellLot, SymbolTraded, BID, 0, 0, "GridSell"))
{
Print("Erro ao abrir Grade de Vendas: ", GetLastError());
}
else
{
NextSellLot = NormalizeDouble(NextSellLot * LotMultiplier, 2);
NextSellPrice = NormalizeDouble(BID + GridDistancePoints, MyDigits);
}
}
}
//+------------------------------------------------------------------+
//| Fechar posições maduras |
//+------------------------------------------------------------------+
void CloseMatureTrades()
{
if (NumOfBuy() > 0 && RSIBuffer[1] > BuyCloseLevel && RSIBuffer[2] < BuyCloseLevel)
{
CloseAllBuys();
NextBuyPrice = 0;
NextBuyLot = 0;
}
if (NumOfSell() > 0 && RSIBuffer[1] < SellCloseLevel && RSIBuffer[2] > SellCloseLevel)
{
CloseAllSells();
NextSellPrice = 0;
NextSellLot = 0;
}
}
//+------------------------------------------------------------------+
//| Fechar todas as posições de compra |
//+------------------------------------------------------------------+
void CloseAllBuys()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (!PositionInfo.SelectByIndex(i))
continue;
if (PositionInfo.Magic() != EAMagic)
continue;
if (PositionInfo.Symbol() != SymbolTraded)
continue;
if (PositionInfo.PositionType() != POSITION_TYPE_BUY)
continue;
if (!Trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
Print("Erro ao fechar posição de Compra: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Fechar todas as posições de venda |
//+------------------------------------------------------------------+
void CloseAllSells()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (!PositionInfo.SelectByIndex(i))
continue;
if (PositionInfo.Magic() != EAMagic)
continue;
if (PositionInfo.Symbol() != SymbolTraded)
continue;
if (PositionInfo.PositionType() != POSITION_TYPE_SELL)
continue;
if (!Trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
Print("Erro ao fechar posição de Venda: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Cálculo do tamanho do lote |
//+------------------------------------------------------------------+
double LotSize()
{
double Lot = NormalizeDouble(VolumeIncrease * AccountInfoDouble(ACCOUNT_BALANCE) / BalanceIncrease, 2);
if (Lot > SymbolInfoDouble(SymbolTraded, SYMBOL_VOLUME_MAX))
Lot = SymbolInfoDouble(SymbolTraded, SYMBOL_VOLUME_MAX);
if (Lot < SymbolInfoDouble(SymbolTraded, SYMBOL_VOLUME_MIN))
Lot = SymbolInfoDouble(SymbolTraded, SYMBOL_VOLUME_MIN);
return Lot;
}
//+------------------------------------------------------------------+
//| Contagem de posições atuais (Compra e Venda) |
//+------------------------------------------------------------------+
int NumOfBuy()
{
int Num = 0;
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (!PositionInfo.SelectByIndex(i))
continue;
if (PositionInfo.Magic() != EAMagic || PositionInfo.Symbol() != SymbolTraded)
continue;
if (PositionInfo.PositionType() == POSITION_TYPE_BUY)
Num++;
}
return Num;
}
int NumOfSell()
{
int Num = 0;
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (!PositionInfo.SelectByIndex(i))
continue;
if (PositionInfo.Magic() != EAMagic || PositionInfo.Symbol() != SymbolTraded)
continue;
if (PositionInfo.PositionType() == POSITION_TYPE_SELL)
Num++;
}
return Num;
}
esse codigo precisa sometne abrir ordens quando todos indicadores estao em confluencia caso contrario deve ignorar caso algum esteja em conflito , é isso que esta acontecendo no codigio atualmente?