Help debug EA code - basic pullback strategy

 

Hi Guys 

 I am trader with no coding experience. In the spirit GenAI I was attempting to automate a strategy I am working on into an EA using GPT. However whenever I compile it I run into trouble with the code due SL and TP variable declarations or something along those line. I am a novice trying to work this out. Can anyone tell me what is wrong with this code.

// Constants and Global Variables

double riskPercent = 1.0; // Risk 1% of the account balance

double slippage = 3;

int magicNumber = 123456;


// Entry and Exit Conditions

void OnTick()

{

    // Calculate risk amount based on account balance and risk percentage

    double riskAmount = AccountBalance() * (riskPercent / 100.0);


    // Check open positions and manage exits

    ManageOpenPositions();


    // Calculate position size based on risk amount and stop loss distance

    double atr = iATR(Symbol(), 0, 14, 0);

    double stopLossDistance = atr; // Setting stop loss distance to 1 times ATR

    double totalLotSize = riskAmount / stopLossDistance / MarketInfo(Symbol(), MODE_MARGINREQUIRED);

    double lotSize = totalLotSize / 2; // Split lot size between two positions


    // Trend identification: Determine if we're in an uptrend or downtrend

    double ma50 = iMA(Symbol(), 0, 50, 0, MODE_SMA, PRICE_CLOSE, 0);

    double ma20 = iMA(Symbol(), 0, 20, 0, MODE_SMA, PRICE_CLOSE, 0);

    bool uptrend = ma20 > ma50;

    bool downtrend = ma20 < ma50;


    // Pullback and confirmation conditions

    double rsi = iRSI(Symbol(), 0, 14, PRICE_CLOSE, 0);

    bool rsiLongCondition = rsi < 50 && rsi > 20; // RSI below 50 but not oversold

    bool rsiShortCondition = rsi > 50 && rsi < 80; // RSI above 50 but not overbought


    // Entry condition for long trade

    if (uptrend && Low[1] > ma20 && Low[0] < ma20 && rsiLongCondition)

    {

        // Place two buy orders with calculated lot size

        PlaceBuyOrder(lotSize, true, 3 * atr);  // With take profit

        PlaceBuyOrder(lotSize, false, 0); // Without take profit

    }


    // Entry condition for short trade

    if (downtrend && High[1] < ma20 && High[0] > ma20 && rsiShortCondition)

    {

        // Place two sell orders with calculated lot size

        PlaceSellOrder(lotSize, true, 3 * atr);  // With take profit

        PlaceSellOrder(lotSize, false, 0); // Without take profit

    }

}


// Function to manage open positions and exit conditions

void ManageOpenPositions()

{

    for (int i = OrdersTotal() - 1; i >= 0; i--)

    {

        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

        {

            if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicNumber)

            {

                // Check for long trade exit conditions

                if (OrderType() == OP_BUY)

                {

                    double stopLoss = OrderStopLoss();

                    double takeProfit = OrderTakeProfit();

                    // Close trade if stop loss or take profit is hit

                    if (Close[0] <= stopLoss || (takeProfit > 0 && Close[0] >= takeProfit))

                    {

                        if (OrderClose(OrderTicket(), OrderLots(), Bid, slippage, Red) == false)

                        {

                            Print("Error closing buy order: ", GetLastError());

                        }

                    }

                }

                // Check for short trade exit conditions

                else if (OrderType() == OP_SELL)

                {

                    double stopLoss = OrderStopLoss();

                    double takeProfit = OrderTakeProfit();

                    // Close trade if stop loss or take profit is hit

                    if (Close[0] >= stopLoss || (takeProfit > 0 && Close[0] <= takeProfit))

                    {

                        if (OrderClose(OrderTicket(), OrderLots(), Ask, slippage, Green) == false)

                        {

                            Print("Error closing sell order: ", GetLastError());

                        }

                    }

                }

            }

        }

    }

}


// Function to place a buy order

void PlaceBuyOrder(double lotSize, bool withTakeProfit, double takeProfitDistance)

{

    double price = Ask;

    int ticket;


    double stopLoss = price - iATR(Symbol(), 0, 14, 0);

    double takeProfit = withTakeProfit ? price + takeProfitDistance : 0; // 1:3 risk-reward ratio


    ticket = OrderSend(Symbol(), OP_BUY, lotSize, price, slippage, stopLoss, takeProfit, "", magicNumber, 0, Blue);


    if (ticket < 0)

    {

        Print("Error opening buy order: ", GetLastError());

    }

}


// Function to place a sell order

void PlaceSellOrder(double lotSize, bool withTakeProfit, double takeProfitDistance)

{

    double price = Bid;

    int ticket;


    double stopLoss = price + iATR(Symbol(), 0, 14, 0);

    double takeProfit = withTakeProfit ? price - takeProfitDistance : 0; // 1:3 risk-reward ratio


    ticket = OrderSend(Symbol(), OP_SELL, lotSize, price, slippage, stopLoss, takeProfit, "", magicNumber, 0, Red);


    if (ticket < 0)

    {

        Print("Error opening sell order: ", GetLastError());

    }

}

Files:
Midas_1.mq4  5 kb
 
Fredrick Maboko:

Hi Guys 

 I am trader with no coding experience. In the spirit GenAI I was attempting to automate a strategy I am working on into an EA using GPT. However whenever I compile it I run into trouble with the code due SL and TP variable declarations or something along those line. I am a novice trying to work this out. Can anyone tell me what is wrong with this code.

// Constants and Global Variables

double riskPercent = 1.0; // Risk 1% of the account balance

double slippage = 3;

int magicNumber = 123456;


// Entry and Exit Conditions

void OnTick()

{

    // Calculate risk amount based on account balance and risk percentage

    double riskAmount = AccountBalance() * (riskPercent / 100.0);


    // Check open positions and manage exits

    ManageOpenPositions();


    // Calculate position size based on risk amount and stop loss distance

    double atr = iATR(Symbol(), 0, 14, 0);

    double stopLossDistance = atr; // Setting stop loss distance to 1 times ATR

    double totalLotSize = riskAmount / stopLossDistance / MarketInfo(Symbol(), MODE_MARGINREQUIRED);

    double lotSize = totalLotSize / 2; // Split lot size between two positions


    // Trend identification: Determine if we're in an uptrend or downtrend

    double ma50 = iMA(Symbol(), 0, 50, 0, MODE_SMA, PRICE_CLOSE, 0);

    double ma20 = iMA(Symbol(), 0, 20, 0, MODE_SMA, PRICE_CLOSE, 0);

    bool uptrend = ma20 > ma50;

    bool downtrend = ma20 < ma50;


    // Pullback and confirmation conditions

    double rsi = iRSI(Symbol(), 0, 14, PRICE_CLOSE, 0);

    bool rsiLongCondition = rsi < 50 && rsi > 20; // RSI below 50 but not oversold

    bool rsiShortCondition = rsi > 50 && rsi < 80; // RSI above 50 but not overbought


    // Entry condition for long trade

    if (uptrend && Low[1] > ma20 && Low[0] < ma20 && rsiLongCondition)

    {

        // Place two buy orders with calculated lot size

        PlaceBuyOrder(lotSize, true, 3 * atr);  // With take profit

        PlaceBuyOrder(lotSize, false, 0); // Without take profit

    }


    // Entry condition for short trade

    if (downtrend && High[1] < ma20 && High[0] > ma20 && rsiShortCondition)

    {

        // Place two sell orders with calculated lot size

        PlaceSellOrder(lotSize, true, 3 * atr);  // With take profit

        PlaceSellOrder(lotSize, false, 0); // Without take profit

    }

}


// Function to manage open positions and exit conditions

void ManageOpenPositions()

{

    for (int i = OrdersTotal() - 1; i >= 0; i--)

    {

        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

        {

            if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicNumber)

            {

                // Check for long trade exit conditions

                if (OrderType() == OP_BUY)

                {

                    double stopLoss = OrderStopLoss();

                    double takeProfit = OrderTakeProfit();

                    // Close trade if stop loss or take profit is hit

                    if (Close[0] <= stopLoss || (takeProfit > 0 && Close[0] >= takeProfit))

                    {

                        if (OrderClose(OrderTicket(), OrderLots(), Bid, slippage, Red) == false)

                        {

                            Print("Error closing buy order: ", GetLastError());

                        }

                    }

                }

                // Check for short trade exit conditions

                else if (OrderType() == OP_SELL)

                {

                    double stopLoss = OrderStopLoss();

                    double takeProfit = OrderTakeProfit();

                    // Close trade if stop loss or take profit is hit

                    if (Close[0] >= stopLoss || (takeProfit > 0 && Close[0] <= takeProfit))

                    {

                        if (OrderClose(OrderTicket(), OrderLots(), Ask, slippage, Green) == false)

                        {

                            Print("Error closing sell order: ", GetLastError());

                        }

                    }

                }

            }

        }

    }

}


// Function to place a buy order

void PlaceBuyOrder(double lotSize, bool withTakeProfit, double takeProfitDistance)

{

    double price = Ask;

    int ticket;


    double stopLoss = price - iATR(Symbol(), 0, 14, 0);

    double takeProfit = withTakeProfit ? price + takeProfitDistance : 0; // 1:3 risk-reward ratio


    ticket = OrderSend(Symbol(), OP_BUY, lotSize, price, slippage, stopLoss, takeProfit, "", magicNumber, 0, Blue);


    if (ticket < 0)

    {

        Print("Error opening buy order: ", GetLastError());

    }

}


// Function to place a sell order

void PlaceSellOrder(double lotSize, bool withTakeProfit, double takeProfitDistance)

{

    double price = Bid;

    int ticket;


    double stopLoss = price + iATR(Symbol(), 0, 14, 0);

    double takeProfit = withTakeProfit ? price - takeProfitDistance : 0; // 1:3 risk-reward ratio


    ticket = OrderSend(Symbol(), OP_SELL, lotSize, price, slippage, stopLoss, takeProfit, "", magicNumber, 0, Red);


    if (ticket < 0)

    {

        Print("Error opening sell order: ", GetLastError());

    }

}


You should pay a job at freelance section more than ask gpt. 
 
  1. Why did you post your MT4 question in the MT5 General section instead of the MQL4 section, (bottom of the Root page)?
              General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
    Next time, post in the correct place.

  2. I have edited your (original) post with the CODE button (or Alt+S)!
          General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
              Messages Editor
          Forum rules and recommendations - General - MQL5 programming forum (2023)

  3. Fredrick Maboko I am trader with no coding experience

    You have only four choices:

    1. Search for it (CodeBase or Market). Do you expect us to do your research for you?

    2. Try asking at:

    3. MT4: Learn to code it.
      MT5: Begin learning to code it.

      If you don't learn MQL4/5, there is no common language for us to communicate. If we tell you what you need, you can't code it. If we give you the code, you don't know how to integrate it into your code.
                I need HEEEELP, please, it's URGENT...really ! - General - MQL5 programming forum (2017)

    4. Or pay (Freelance) someone to code it. Top of every page is the link Freelance.
                Hiring to write script - General - MQL5 programming forum (2019)

    We're not going to code it for you (although it could happen if you are lucky or the problem is interesting.) We are willing to help you when you post your attempt (using CODE button) and state the nature of your problem.
              No free help (2017)

 

Hi

I don’t recommend using AI directly – there are too many flops of the “logic” yet. You should probably check how the EA behaves and make a lot of tests to check 8f EA works according to your idea, but to make this code compile just add:

#property strict

At the top of your script and it will compile.

Have a nice weekend