hey I need help in coding

 

hello friends, I am trying to code a hedging strategy. I know very little coding. this is what I developed from chatgpt.

This is what I want , when ever I  or another EA places a buy or sell order, the EA should place a hedge order of same lot but one as a limit order and other as a stop order. It should be deployed at a predefined gap. For example: pair :btcusd and current price 55300 , if my initial order is a buy order of 0.03 lot at 55300 and if my predefined pip distance is 10000 then a sell Limit order of 0.03 lot has to be deployed at 55400 and a sell stop order of 0.03 lot has to be deployed at 55200. 

Now if any of these hedges hit that is if either of sell limit or sell stop trigger then all the other pending order to be cancelled

If A is original order and A1 and A2 are its limit and stop order and if either of A1 or A2 triggers then all the remaining pending order gets deleted 

now the code is deploying  limit and stop order as pending order but as soon any one gets deployed, the should cancel but its not happening, please help on this


// Input parameters
input int HedgeDistance = 10000;   // Predefined gap for hedging orders
input double LotSize = 0.03;       // Default lot size for hedge orders
// Structure to track the initial order and its associated pending orders
struct HedgeOrder {
    int initialOrder;  // Original trade order ID
    int pendingOrder1; // First pending order (stop or limit)
    int pendingOrder2; // Second pending order (stop or limit)
};
// Array to store all hedge orders
HedgeOrder hedgeOrders[];
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit() {
   // Initialization code here
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
   // Cleanup code here
}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick() {
   // Check if there are open orders
   for (int i = OrdersTotal() - 1; i >= 0; i--) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
         // Get order details
         int ticket = OrderTicket();
         double orderPrice = OrderOpenPrice();
         int orderType = OrderType();
         string symbol = OrderSymbol();
         // Check if the order is a buy or sell order and not already hedged
         if ((orderType == OP_BUY || orderType == OP_SELL) && !IsOrderHedged(ticket)) {
            // Place the hedge orders once
            PlaceHedgeOrders(ticket, orderType, orderPrice, symbol);
         }
         // Check if any hedge order is triggered and cancel the counterpart
         CheckHedgeOrders();
      }
   }
}
//+------------------------------------------------------------------+
//| Helper function to place hedge orders                            |
//+------------------------------------------------------------------+
void PlaceHedgeOrders(int ticket, int orderType, double orderPrice, string symbol) {
   double hedgeLimitPrice, hedgeStopPrice;
   if (orderType == OP_BUY) { // For buy orders, place Sell Limit above and Sell Stop below
      hedgeLimitPrice = orderPrice + HedgeDistance * Point;  // Sell limit above
      hedgeStopPrice = orderPrice - HedgeDistance * Point;   // Sell stop below
      int sellLimitTicket = PlaceHedgeOrder(symbol, hedgeLimitPrice, LotSize, OP_SELLLIMIT);
      int sellStopTicket = PlaceHedgeOrder(symbol, hedgeStopPrice, LotSize, OP_SELLSTOP);
      // Store hedge order details
      if (sellLimitTicket >= 0 && sellStopTicket >= 0) {
         AddHedgeOrder(ticket, sellLimitTicket, sellStopTicket);
      }
   } else if (orderType == OP_SELL) { // For sell orders, place Buy Limit below and Buy Stop above
      hedgeLimitPrice = orderPrice - HedgeDistance * Point;  // Buy limit below
      hedgeStopPrice = orderPrice + HedgeDistance * Point;   // Buy stop above
      int buyLimitTicket = PlaceHedgeOrder(symbol, hedgeLimitPrice, LotSize, OP_BUYLIMIT);
      int buyStopTicket = PlaceHedgeOrder(symbol, hedgeStopPrice, LotSize, OP_BUYSTOP);
      // Store hedge order details
      if (buyLimitTicket >= 0 && buyStopTicket >= 0) {
         AddHedgeOrder(ticket, buyLimitTicket, buyStopTicket);
      }
   }
}
//+------------------------------------------------------------------+
//| Helper function to place a single hedge order                    |
//+------------------------------------------------------------------+
int PlaceHedgeOrder(string symbol, double price, double lots, int orderType) {
   int slippage = 3;
   double stopLoss = 0, takeProfit = 0;
   // Place the order and return the order ticket
   int orderTicket = OrderSend(symbol, orderType, lots, price, slippage, stopLoss, takeProfit, "Hedge Order", 0, 0, clrRed);
   if (orderTicket < 0) {
      int errorCode = GetLastError();  // Declare errorCode locally here
      Print("Error placing hedge order of type ", orderType, ". Error code: ", errorCode);
   }
   return orderTicket;
}
//+------------------------------------------------------------------+
//| Helper function to check if an order is already hedged            |
//+------------------------------------------------------------------+
bool IsOrderHedged(int ticket) {
   for (int i = 0; i < ArraySize(hedgeOrders); i++) {
      if (hedgeOrders[i].initialOrder == ticket) {
         return true;
      }
   }
   return false;
}
//+------------------------------------------------------------------+
//| Helper function to add hedge order to tracking array             |
//+------------------------------------------------------------------+
void AddHedgeOrder(int ticket, int pendingOrder1, int pendingOrder2) {
   HedgeOrder hedge;
   hedge.initialOrder = ticket;
   hedge.pendingOrder1 = pendingOrder1;
   hedge.pendingOrder2 = pendingOrder2;
   ArrayResize(hedgeOrders, ArraySize(hedgeOrders) + 1);
   hedgeOrders[ArraySize(hedgeOrders) - 1] = hedge;
   Print("Hedge orders placed for ticket: ", ticket, " - Pending Orders: ", pendingOrder1, ", ", pendingOrder2);
}
//+------------------------------------------------------------------+
//| Helper function to check if hedge orders are triggered           |
//+------------------------------------------------------------------+
void CheckHedgeOrders() {
   for (int i = 0; i < ArraySize(hedgeOrders); i++) {
      int ticket1 = hedgeOrders[i].pendingOrder1;
      int ticket2 = hedgeOrders[i].pendingOrder2;
      // Check if the first pending order is triggered
      if (OrderSelect(ticket1, SELECT_BY_TICKET) && OrderCloseTime() > 0) {
         Print("Hedge Order Triggered: ", ticket1);
         CancelPendingOrder(ticket2); // Cancel the counterpart
         RemoveHedgeOrder(i);
         return;
      }
      // Check if the second pending order is triggered
      if (OrderSelect(ticket2, SELECT_BY_TICKET) && OrderCloseTime() > 0) {
         Print("Hedge Order Triggered: ", ticket2);
         CancelPendingOrder(ticket1); // Cancel the counterpart
         RemoveHedgeOrder(i);
         return;
      }
   }
}
//+------------------------------------------------------------------+
//| Helper function to cancel a pending order                        |
//+------------------------------------------------------------------+
void CancelPendingOrder(int ticket) {
   int errorCode;  // Declare errorCode at the top of the function
   if (OrderSelect(ticket, SELECT_BY_TICKET)) {
      // Check if it's a pending order (limit or stop orders)
      int orderType = OrderType();
      if (orderType == OP_BUYLIMIT || orderType == OP_SELLLIMIT || 
          orderType == OP_BUYSTOP || orderType == OP_SELLSTOP) {
         if (OrderDelete(ticket)) {
            Print("Canceled pending order: ", ticket);
         } else {
            errorCode = GetLastError();  // Use the pre-declared errorCode variable
            Print("Error canceling pending order: ", ticket, " Error: ", errorCode);
         }
      } else {
         Print("Order ", ticket, " is not a pending order (limit/stop). Type: ", orderType);
      }
   } else {
      errorCode = GetLastError();  // Use the pre-declared errorCode variable
      Print("Failed to select order: ", ticket, ". Error: ", errorCode);
   }
}
//+------------------------------------------------------------------+
//| Helper function to remove a hedge order from tracking array      |
//+------------------------------------------------------------------+
void RemoveHedgeOrder(int index) {
   for (int i = index; i < ArraySize(hedgeOrders) - 1; i++) {
      hedgeOrders[i] = hedgeOrders[i + 1];
   }
   ArrayResize(hedgeOrders, ArraySize(hedgeOrders) - 1);
   Print("Removed hedge order from tracking.");
}
 
Abhijith K: , I am trying to code a hedging strategy. I know very little coding. this is what I developed from chatgpt.
  1. Help you with what? You haven't stated a problem, you stated even stated a want. Show us your attempt (No attempt) and state the nature of your difficulty (no attempt at debugging).
              No free help (2017)

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

    We're not going to code it for you (although it could happen if you are lucky or the issue is interesting).
              No free help (2017)

  2. 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)

  3. Stop using ChatGPT/Copilot.
              Help needed to debug and fix an AI EA - Trading Systems - MQL5 programming forum #2 (2023)

    ChatGPT (the worst), “Bots Builder”, “EA builder”, “EA Builder Pro”, EATree, “Etasoft forex generator”, “Forex Strategy Builder”, ForexEAdvisor (aka. ForexEAdvisor STRATEGY BUILDER, and Online Forex Expert Advisor Generator), ForexRobotAcademy.com, forexsb, “FX EA Builder”, fxDreema, Forex Generator, FxPro, “LP-MOBI”, Molanis, “Octa-FX Meta Editor”, Strategy Builder FX, “Strategy Quant”, “Visual Trader Studio”, “MQL5 Wizard”, etc., are all the same. You will get something quick, but then you will spend a much longer time trying to get it right, than if you learned the language up front, and then just wrote it.

    Since you haven't learned MQL4/5, therefor 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 yours.

    We are willing to HELP you when you post your attempt (using Code button) and state the nature of your problem, but we are not going to debug your hundreds of lines of code. You are essentially going to be on your own.

    ChatGPT
    1. Even it says do not use it for coding. * 
    2. Mixing MT4 and MT5 code together.
    3. Creating multiple OnCalculate/OnTick functions.
    4. OnCalculate returning a double.
    5. Filling buffers with zero in OnInit (they have no size yet). Setting buffer elements to zero but not setting Empty Value to correspond.
    6. Calling undefined functions.
    7. Calling MT4 functions in MT5 code.
    8. Sometimes, not using strict (MT4 code).
    9. Code that will not compile.
    10. Creating code outside of functions. * 
    11. Creating incomplete code. * 
    12. Initialization of Global variables with non-constants. * 
    13. Assigning a MT5 handle to a double or missing the buffer and bar indexes in a MT4 call. * 
    14. Useing MT4 Trade Functions without first selecting an order. * 
    15. Uses NULL in OrderSend (MT4). * 
    bot builder Creating two OnInit() functions. * 
    EA builder
    1. Counting up while closing multiple orders.
    2. Not useing time in new bar detection.
    3. Not adjusting for 4/5 digit brokers, TP/SL and slippage. * 
    4. Not checking return codes.
    EATree Uses objects on chart to save values — not persistent storage (files or GV+Flush.) No recovery (crash/power failure.)
    ForexEAdvisor
    1. Non-updateing global variables.
    2. Compilation errors.
    3. Not checking return codes.
    4. Not reporting errors.
    FX EA Builder
    1. Not checking return codes.
    2. Loosing open tickets on terminal restart. No recovery (crash/power failure.)
    3. Not adjusting stops for the spread. * 
    4. Using OrdersTotal directly.
    5. Using the old event handlers.

 
William Roeder #:
  1. Help you with what? You haven't stated a problem, you stated even stated a want. Show us your attempt (No attempt) and state the nature of your difficulty (no attempt at debugging).
              No free help (2017)

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

    We're not going to code it for you (although it could happen if you are lucky or the issue is interesting).
              No free help (2017)

  2. 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)

  3. Stop using ChatGPT/Copilot.
              Help needed to debug and fix an AI EA - Trading Systems - MQL5 programming forum #2 (2023)

    ChatGPT (the worst), “Bots Builder”, “EA builder”, “EA Builder Pro”, EATree, “Etasoft forex generator”, “Forex Strategy Builder”, ForexEAdvisor (aka. ForexEAdvisor STRATEGY BUILDER, and Online Forex Expert Advisor Generator), ForexRobotAcademy.com, forexsb, “FX EA Builder”, fxDreema, Forex Generator, FxPro, “LP-MOBI”, Molanis, “Octa-FX Meta Editor”, Strategy Builder FX, “Strategy Quant”, “Visual Trader Studio”, “MQL5 Wizard”, etc., are all the same. You will get something quick, but then you will spend a much longer time trying to get it right, than if you learned the language up front, and then just wrote it.

    Since you haven't learned MQL4/5, therefor 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 yours.

    We are willing to HELP you when you post your attempt (using Code button) and state the nature of your problem, but we are not going to debug your hundreds of lines of code. You are essentially going to be on your own.

    ChatGPT
    1. Even it says do not use it for coding. * 
    2. Mixing MT4 and MT5 code together.
    3. Creating multiple OnCalculate/OnTick functions.
    4. OnCalculate returning a double.
    5. Filling buffers with zero in OnInit (they have no size yet). Setting buffer elements to zero but not setting Empty Value to correspond.
    6. Calling undefined functions.
    7. Calling MT4 functions in MT5 code.
    8. Sometimes, not using strict (MT4 code).
    9. Code that will not compile.
    10. Creating code outside of functions. * 
    11. Creating incomplete code. * 
    12. Initialization of Global variables with non-constants. * 
    13. Assigning a MT5 handle to a double or missing the buffer and bar indexes in a MT4 call. * 
    14. Useing MT4 Trade Functions without first selecting an order. * 
    15. Uses NULL in OrderSend (MT4). * 
    bot builder Creating two OnInit() functions. * 
    EA builder
    1. Counting up while closing multiple orders.
    2. Not useing time in new bar detection.
    3. Not adjusting for 4/5 digit brokers, TP/SL and slippage. * 
    4. Not checking return codes.
    EATree Uses objects on chart to save values — not persistent storage (files or GV+Flush.) No recovery (crash/power failure.)
    ForexEAdvisor
    1. Non-updateing global variables.
    2. Compilation errors.
    3. Not checking return codes.
    4. Not reporting errors.
    FX EA Builder
    1. Not checking return codes.
    2. Loosing open tickets on terminal restart. No recovery (crash/power failure.)
    3. Not adjusting stops for the spread. * 
    4. Using OrdersTotal directly.
    5. Using the old event handlers.


thanks I l hire someone who knows stuff well.