Skip to content
The Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

#include <Trade\Trade.mqh> #define NumNodes 10 CTrade trade; CPositionInfo pos;…

  1. User

    #include <Trade\Trade.mqh>

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

    // Trading Parameters input double LotSize = 0.01; // Lot size for trading double initialLotSize; // Tamanho inicial do lote 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[NumNodes]; double RSIBuffer[NumNodes]; double NormalizedInputs[NumNodes]; double NNOutPut = 0;

    // Aumento de tamanho do lote input double profitThreshold = 50.0; // Limite de lucro para aumentar o lote input double lotIncreaseFactor = 2.0; // Fator de aumento do lote

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

    // Inicializar o tamanho inicial do lote initialLotSize = LotSize;

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

    return (INIT_SUCCEEDED); }

    //+------------------------------------------------------------------+ //| Função para calcular o tamanho do lote baseado em lucro | //+------------------------------------------------------------------+ double CalculateLotSize() { double currentProfit = 0.0;

    // Calcular o lucro total das posições abertas
    for (int i = 0; i < PositionsTotal(); i++)
    {
        if (pos.SelectByIndex(i) && pos.Magic() == InpMagic)
        {
            currentProfit += pos.Profit(); // Somando lucros
        }
    }
    
    // Ajuste do tamanho do lote
    double newLotSize = initialLotSize;
    if (currentProfit >= profitThreshold)
    {
        newLotSize *= lotIncreaseFactor; // Aumento do lote
        Print("Aumento no tamanho do lote para: ", newLotSize);
    }
    
    return newLotSize;
    

    }

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

    // 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

    // Calcular o novo tamanho do lote antes de enviar a ordem LotSize = CalculateLotSize();

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

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

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

    }

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

    //+------------------------------------------------------------------+ //| Parameter Update Functions | //+------------------------------------------------------------------+ // Function to check if the trading parameters have been updated bool CheckForParameterUpdates() { static double prevLotSize = LotSize; static int prevTppoints = Tppoints; static int prevSlpoints = Slpoints;

    if (prevLotSize != LotSize || prevTppoints != Tppoints || prevSlpoints != Slpoints)
    {
        prevLotSize = LotSize;
        prevTppoints = Tppoints;
        prevSlpoints = Slpoints;
        return true;
    }
    return false;
    

    }

    // Function to adjust points of negotiation when parameters are updated void AdjustPointsOfNegotiation() { // Recalcular e reatribuir valores que dependem dos parâmetros atualizados // Por exemplo, ajustando trailing stop ou atualizando parâmetros de ordens

    for (int i = 0; i < NumNodes; i++)
    {
        // Recalcular pesos ou outros parâmetros, se necessário
        Weight[i] = 0.5 * Coefficient; // Exemplo de ajuste, pode ser personalizado
    }
    
    // Imprimir mensagem no log para indicar que os parâmetros foram ajustados
    Print("Parâmetros atualizados e pontos de negociação ajustados.");
    

    } erros:

    'LotSize' - constant cannot be modified Scalping_GOLD__012_NEURAL_Lots_.mq5 131 4 implicit conversion from 'number' to 'string' Scalping_GOLD__012_NEURAL_Lots_.mq5 160 148 implicit conversion from 'number' to 'string' Scalping_GOLD__012_NEURAL_Lots_.mq5 172 149

  2. Assistant

    The errors you are encountering in your MQL5 code can be resolved with a few adjustments. Let’s go through the issues one by one:

    1. 'LotSize' - constant cannot be modified

      • The variable LotSize is declared as an input, which makes it a constant input parameter. You cannot modify it in your code after it has been set. Instead of attempting to modify LotSize, you should use a different variable to keep track of the current lot size.
    2. Implicit conversion from 'number' to 'string'

      • The errors related to implicit conversion indicate that you are trying to concatenate or use numeric values with strings without explicitly converting them to strings using the DoubleToString() function or similar.

    Revised Code

    Here’s a modified version of your code with the necessary fixes applied:

    #include <Trade\Trade.mqh> 
    
    #define NumNodes 10
    CTrade trade;
    CPositionInfo pos;
    COrderInfo ord;
    
    // Trading Parameters
    input double LotSize = 0.01;                // Lot size for trading
    double initialLotSize;                       // Initial lot size
    double currentLotSize;                       // Variable to hold the current lot size
    
    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[NumNodes];
    double RSIBuffer[NumNodes];
    double NormalizedInputs[NumNodes];
    double NNOutPut = 0;
    
    // Increase lot size settings
    input double profitThreshold = 50.0;        // Profit limit to increase lot size
    input double lotIncreaseFactor = 2.0;       // Lot size increase factor
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
       trade.SetExpertMagicNumber(InpMagic);
       ChartSetInteger(0, CHART_SHOW_GRID, false);
    
       // Initialize the initial lot size
       initialLotSize = LotSize;
       currentLotSize = LotSize; // Set current lot size to initial lot size
    
       // Initialize Neural Network Weights
       for (int i = 0; i < NumNodes; i++)
          Weight[i] = 0.5;
    
       return (INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Function to calculate the lot size based on profit             |
    //+------------------------------------------------------------------+
    double CalculateLotSize()
    {
        double currentProfit = 0.0;
    
        // Calculate total profit of open positions
        for (int i = 0; i < PositionsTotal(); i++)
        {
            if (pos.SelectByIndex(i) && pos.Magic() == InpMagic)
            {
                currentProfit += pos.Profit(); // Summing profits
            }
        }
    
        // Adjust lot size
        double newLotSize = initialLotSize;
        if (currentProfit >= profitThreshold)
        {
            newLotSize *= lotIncreaseFactor; // Increase lot size
            Print("Increased lot size to: ", DoubleToString(newLotSize, 2));
        }
    
        return newLotSize;
    }
    
    //+------------------------------------------------------------------+
    //| 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++;
          }
       }
    
       // 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
    
       // Calculate the new lot size before sending the order
       currentLotSize = CalculateLotSize(); // Update current lot size
    
       if (buySignal)
       {
          double high = findHigh();
          if (high > 0)
             SendBuyOrder(high);
       }
    
       if (sellSignal)
       {
          double low = findLow();
          if (low > 0)
             SendSellOrder(low);
       }
    }
    
    //+------------------------------------------------------------------+
    //| 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(currentLotSize, 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(currentLotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, iTime(_Symbol, Timeframe, 0) + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
    }
    
    // Continuation of the rest of the code...
    

    Key Changes:

    1. Added currentLotSize: A variable to dynamically hold the current lot size, which can be modified based on the profit condition.
    2. Replaced LotSize with currentLotSize: Updated the function that sends orders to use currentLotSize.
    3. Used DoubleToString() for logging: Ensured proper conversion of numbers to strings for printing/logging.

    With these modifications, your code should compile without the specified errors. Make sure to test the updated code in a controlled environment before applying it in a live trading scenario.

  3. User

    me entregue o codigo completo

  4. Assistant

    Aqui está o código completo e corrigido do seu Expert Advisor em MQL5. As alterações feitas foram para permitir a modificação do tamanho do lote com base no lucro atual, além de corrigir os erros relacionados à conversão implícita de números para strings.

    #include <Trade\Trade.mqh> 
    
    #define NumNodes 10
    CTrade trade;
    CPositionInfo pos;
    COrderInfo ord;
    
    // Trading Parameters
    input double LotSize = 0.01;                // Lot size for trading
    double initialLotSize;                       // Initial lot size
    double currentLotSize;                       // Variable to hold the current lot size
    
    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[NumNodes];
    double RSIBuffer[NumNodes];
    double NormalizedInputs[NumNodes];
    double NNOutPut = 0;
    
    // Increase lot size settings
    input double profitThreshold = 50.0;        // Profit limit to increase lot size
    input double lotIncreaseFactor = 2.0;       // Lot size increase factor
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        trade.SetExpertMagicNumber(InpMagic);
        ChartSetInteger(0, CHART_SHOW_GRID, false);
    
        // Initialize the initial lot size
        initialLotSize = LotSize;
        currentLotSize = LotSize; // Set current lot size to initial lot size
    
        // Initialize Neural Network Weights
        for (int i = 0; i < NumNodes; i++)
            Weight[i] = 0.5;
    
        return (INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Function to calculate the lot size based on profit             |
    //+------------------------------------------------------------------+
    double CalculateLotSize()
    {
        double currentProfit = 0.0;
    
        // Calculate total profit of open positions
        for (int i = 0; i < PositionsTotal(); i++)
        {
            if (pos.SelectByIndex(i) && pos.Magic() == InpMagic)
            {
                currentProfit += pos.Profit(); // Summing profits
            }
        }
    
        // Adjust lot size
        double newLotSize = initialLotSize;
        if (currentProfit >= profitThreshold)
        {
            newLotSize *= lotIncreaseFactor; // Increase lot size
            Print("Increased lot size to: ", DoubleToString(newLotSize, 2));
        }
    
        return newLotSize;
    }
    
    //+------------------------------------------------------------------+
    //| 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++;
            }
        }
    
        // 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
    
        // Calculate the new lot size before sending the order
        currentLotSize = CalculateLotSize(); // Update current lot size
    
        if (buySignal)
        {
            double high = findHigh();
            if (high > 0)
                SendBuyOrder(high);
        }
    
        if (sellSignal)
        {
            double low = findLow();
            if (low > 0)
                SendSellOrder(low);
        }
    }
    
    //+------------------------------------------------------------------+
    //| 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(currentLotSize, 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(currentLotSize, 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);
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| 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;
    }
    
    //+------------------------------------------------------------------+
    //| Parameter Update Functions                                       |
    //+------------------------------------------------------------------+
    // Function to check if the trading parameters have been updated
    bool CheckForParameterUpdates()
    {
        static double prevLotSize = LotSize;
        static int prevTppoints = Tppoints;
        static int prevSlpoints = Slpoints;
        
        if (prevLotSize != LotSize || prevTppoints != Tppoints || prevSlpoints != Slpoints)
        {
            prevLotSize = LotSize;
            prevTppoints = Tppoints;
            prevSlpoints = Slpoints;
            return true;
        }
        return false;
    }
    
    // Function to adjust points of negotiation when parameters are updated
    void AdjustPointsOfNegotiation()
    {
        // Recalculate and reassign values dependent on the updated parameters
        for (int i = 0; i < NumNodes; i++)
        {
            // Recalculate weights or other parameters if necessary
            Weight[i] = 0.5 * Coefficient; // Example adjustment, can be customized
        }
    
        // Print message to log to indicate parameters have been adjusted
        Print("Parameters updated and negotiation points adjusted.");
    }
    

    Principais Modificações:

    • Adicionei currentLotSize para permitir a modificação do tamanho do lote com base no lucro acumulado sem interferir na variável de entrada de configuração LotSize.
    • Corrigi os trechos onde os números estavam sendo convertidos para string, usando DoubleToString() nas mensagens de log.
    • Mantive a estrutura e lógica do seu algoritmo, incluindo a implementação da rede neural, então ele deve funcionar como esperado para o que você planejou.

    Observação

    Por favor, teste este código em um ambiente de demonstração antes de usá-lo em uma conta real. Certifique-se de que todas as variáveis e condições funcionam como esperado para suas estratégias comerciais.