//+------------------------------------------------------------------+
//| Scalping Robot Enhanced with Neural Network                     |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.01"

#include <Trade/Trade.mqh> 

#define NumNodes 10
CTrade trade;
CPositionInfo pos;
COrderInfo ord;

// Trading Parameters
input double LotSize = 0.01;                // Lot size for trading
input int Tppoints = 800;                   // Take Profit (10 points = 1 pip)
input int Slpoints = 800;                   // Stoploss 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";    // Trade comment
input int MaxSpread = 100;                  // Maximum spread allowed (in points)
input int Slippage = 50;                    // Slippage in points
input int MaxOrders = 2;                    // Maximum simultaneous orders

input int BarsN = 5;                        // Bars to analyze
input int ExpirationBars = 100;             // Order expiration based on bars
input int OrderDistPoints = 100;            // Distance in points from price

// Neural Network Parameters
input double Coefficient = 0.1;
input double BuyTargetOutput = 0.3;
input double SellTargetOutput = -0.3;
input double LearningRate = 0.1;

double Weight[];
double RSIBuffer[NumNodes];
double NormalizedInputs[NumNodes];
double NNOutPut = 0;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   trade.SetExpertMagicNumber(InpMagic);
   ChartSetInteger(0, CHART_SHOW_GRID, false);

   // Initialize Neural Network Weights
   ArrayResize(Weight, NumNodes);
   for (int i = 0; i < NumNodes; i++)
      Weight[i] = 0.5;

   return (INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // Run TrailStop logic
   TrailStop();

   // Check for new bar and exit if not
   if (!IsNewBar())
      return;

   // Check spread
   double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
   if (spread > MaxSpread)
      return;

   // Count open orders
   int BuyTotal = 0, SellTotal = 0;
   for (int i = PositionsTotal() - 1; i >= 0; i--)
   {
      pos.SelectByIndex(i);
      if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol)
      {
         if (pos.PositionType() == POSITION_TYPE_BUY)
            BuyTotal++;
         if (pos.PositionType() == POSITION_TYPE_SELL)
            SellTotal++;
      }
   }

   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      ord.SelectByIndex(i);
      if (ord.Magic() == InpMagic && ord.Symbol() == _Symbol)
      {
         if (ord.OrderType() == ORDER_TYPE_BUY_STOP)
            BuyTotal++;
         if (ord.OrderType() == ORDER_TYPE_SELL_STOP)
            SellTotal++;
      }
   }

   // Ensure order limit
   int TotalOrders = BuyTotal + SellTotal;
   if (TotalOrders >= MaxOrders)
      return;

   // Neural network prediction
   NormalizingInputs();
   OutPutLayerCalculation();

   // Determine Buy and Sell Signals
   bool buySignal = (BuyTotal == 0 && NNOutPut > 0); // Neural Buy Signal
   bool sellSignal = (SellTotal == 0 && NNOutPut < 0); // Neural Sell Signal

   if (buySignal)
   {
      double high = findHigh();
      if (high > 0)
         SendBuyOrder(high);
   }

   if (sellSignal)
   {
      double low = findLow();
      if (low > 0)
         SendSellOrder(low);
   }
}

//+------------------------------------------------------------------+
//| High and Low Search                                              |
//+------------------------------------------------------------------+
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;
}


//+------------------------------------------------------------------+
//| Order Sending Logic                                              |
//+------------------------------------------------------------------+
void SendBuyOrder(double entry)
{
    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    if (ask > entry - OrderDistPoints * _Point)
        return;

    double tp = entry + Tppoints * _Point;
    double sl = entry - Slpoints * _Point;

    trade.BuyStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, iTime(_Symbol, Timeframe, 0) + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
}

void SendSellOrder(double entry)
{
    double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    if (bid < entry + OrderDistPoints * _Point)
        return;

    double tp = entry - Tppoints * _Point;
    double sl = entry + Slpoints * _Point;

    trade.SellStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, iTime(_Symbol, Timeframe, 0) + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
}

//+------------------------------------------------------------------+
//| Neural Network Functions                                         |
//+------------------------------------------------------------------+
void NormalizingInputs()
{
    double LowerNormRange = -1;
    double UpperNormRange = 1;

    for (int i = 0; i < NumNodes; i++)
    {
        NormalizedInputs[i] = (((RSIBuffer[i] - 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))));
}

//+------------------------------------------------------------------+
//| Is New Bar Function                                              |
//+------------------------------------------------------------------+
bool IsNewBar()
{
    static datetime previousTime = 0;
    datetime currentTime = iTime(_Symbol, Timeframe, 0);
    if (previousTime != currentTime)
    {
        previousTime = currentTime;
        return true;
    }
    return false;
}

//+------------------------------------------------------------------+
//| 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);
                }
            }
        }
    }
}

use de exemplo a rede neural desse codigo e implemente do meu codigo abaixo para melhorar a assertividade, nao adicione outras estrategias de RSI etc apenas mantenha a estrategia do meu codigo original e apenas adicione a rede neural e me entregue o codigo completo com as atualizações:

//+------------------------------------------------------------------+
//|                                            AI RSI BB SCALPER.mq5 |
//|                                                           Alfr5d |
//|                                       https://www.49design.co.za |
//+------------------------------------------------------------------+

#property copyright   "Copyright 2023, Alfred Mandala. "
#property description "www.billionairebulls.co.za\n"
#property version     "1.5"
#property description "RSI GRID SCALPING EA com Stochastic\n"

// Incluindo bibliotecas necessárias
#include <Trade/Trade.mqh>

// ---- INPUTS ----
input group "--- Trading Inputs ---";
input double Lots                    = 0.01;           // Tamanho do Lote
input int TpPoints                   = 50;             // Take Profit em pontos [m5-50p, h1-200p]
input int StopLossPoints             = 500;             // Stop Loss em pontos [Ex: 20 pontos]
input ENUM_TIMEFRAMES RsiTimeFrame   = PERIOD_CURRENT; // Timeframe

input group "--- RSI Inputs ---";
input int RsiPeriods                 = 18;             // Periodo do RSI
input ENUM_APPLIED_PRICE RsiAppPrice = PRICE_CLOSE;   // Preço aplicado pelo RSI
input double RsiSellTrigger          = 70;             // Zona de Venda do RSI
input double RsiBuyTrigger           = 30;             // Zona de Compra do RSI

input group "--- Bollinger Bands Inputs ---";
input int         BbPeriods          = 23;             // Períodos das BB
input double      BbDeviation        = 2.0;            // Desvio
input double      BbShift            = 0;              // Deslocamento

input group "--- Stochastic Inputs ---";
input int StochKPeriod               = 5;              // Período K do Stoch
input int StochDPeriod               = 3;              // Período D do Stoch
input int StochSlowing               = 3;              // Atraso do Stoch
input double StochOverbought         = 80.0;           // Nível de sobrecompra
input double StochOversold           = 20.0;           // Nível de sobrevenda

// ---- GLOBAL VARIABLES ----
int handleRsi, handleBb, handleStochastic;
double rsi[], bbUpper[], bbLower[], stochMain[];

// Instanciar classe de trade
CTrade trade;

// ---- EXPERT INIT ----
int OnInit()
{
   handleRsi      = iRSI(_Symbol, RsiTimeFrame, RsiPeriods, RsiAppPrice);
   handleBb       = iBands(_Symbol, PERIOD_CURRENT, BbPeriods, BbShift, BbDeviation, PRICE_CLOSE);
   handleStochastic = iStochastic(_Symbol, PERIOD_CURRENT, StochKPeriod, StochDPeriod, StochSlowing, MODE_SMA, STO_LOWHIGH);

   return (INIT_SUCCEEDED);
}

// ---- EXPERT DEINIT ----
void OnDeinit(const int reason)
{
   IndicatorRelease(handleBb);
   IndicatorRelease(handleRsi);
   IndicatorRelease(handleStochastic);
}

// ---- ON TICK FUNCTION ----
void OnTick()
{
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   CopyBuffer(handleBb, 1, 0, 1, bbUpper);
   CopyBuffer(handleBb, 2, 0, 1, bbLower);
   CopyBuffer(handleRsi, 0, 0, 2, rsi);
   CopyBuffer(handleStochastic, 0, 0, 2, stochMain);

   // Febrero para evitar múltiplas ordens (apenas uma por vez)
   if (PositionsTotal() == 0) // Verifica se não há posições abertas
   {
      // Condição de venda usando RSI e Stochastic
      if (rsi[1] > RsiSellTrigger && rsi[0] < RsiSellTrigger && stochMain[0] > StochOverbought)
      {
         if (bid >= bbUpper[0])
         {
            Print(__FUNCTION__, " > SELL Signal...");
            trade.Sell(Lots, _Symbol, bid, bid + StopLossPoints * _Point, bid - TpPoints * _Point);
         }
      }
      // Condição de compra usando RSI e Stochastic
      else if (rsi[1] < RsiBuyTrigger && rsi[0] > RsiBuyTrigger && stochMain[0] < StochOversold)
      {
         if (bid <= bbLower[0])
         {
            Print(__FUNCTION__, " > BUY Signal...");
            trade.Buy(Lots, _Symbol, bid, bid - StopLossPoints * _Point, bid + TpPoints * _Point);
         }
      }
   }
   
   // Lógica para fechamento de posições
   ManagePositions();
   Comment("\nRSI[0]: ", DoubleToString(rsi[0], 5),
           "\nRSI[1]: ", DoubleToString(rsi[1], 5),
           "\nStochastic: ", DoubleToString(stochMain[0], 2));
}

// --- Função para gerenciar posições abertas ---
void ManagePositions()
{
   for (int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong posTicket = PositionGetTicket(i);
      if (PositionSelectByTicket(posTicket))
      {
         ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE) PositionGetInteger(POSITION_TYPE);
         double posOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
         double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         int points = (posType == POSITION_TYPE_BUY) ? (int)((bid - posOpenPrice) / _Point) : (int)((posOpenPrice - SymbolInfoDouble(_Symbol, SYMBOL_ASK)) / _Point);

         if (points > TpPoints)
         {
            trade.PositionClose(posTicket);
         }
      }
   }
}