Skip to content
TheChatArchiveThe Chat Archive
grok-3-preview-02-24· xAIHugging Face LMArena Human Preference 140K

allow for custom stop loss and take profit in points and in money, plot the pending…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Kimikimi-k2-0711-preview’s answer.
  1. User

    allow for custom stop loss and take profit in points and in money, plot the pending orders as requested

  2. Assistant

    Below is the updated GOLDEN BREAKOUT.mq5 code that includes the following enhancements:

    1. Custom Stop Loss and Take Profit in Points and Money:

      • Added input parameters to allow users to set stop loss and take profit in points or in money (currency).
      • Added logic to calculate stop loss and take profit based on the user's choice (points or money).
    2. Plotting Pending Orders on the Chart:

      • Added functionality to visually represent the pending orders on the chart using horizontal lines for the entry, stop loss, and take profit levels of both buy and sell orders.

    Here is the updated code:

    //+------------------------------------------------------------------+
    //|                                                      GOLDEN BREAKOUT.mq5 |
    //|                        Copyright 2023, YourName                  |
    //|                                                   Version 1.00   |
    //+------------------------------------------------------------------+
    #property strict
    
    // Input parameters
    input double RiskRewardRatio = 2.0; // Risk to Reward Ratio
    input int ATRPeriod = 14;            // ATR Period for Stop Loss
    input double LotSize = 0.1;          // Fixed Lot Size
    input double RiskPercentage = 1.0;   // Risk Percentage of Equity
    input bool UsePercentageLot = false; // Use Percentage of Equity for Lot Size
    input color HighLineColor = clrGreen; // Color for the high line
    input color LowLineColor = clrRed;    // Color for the low line
    input int LineWidth = 2;              // Width of the lines
    
    // Custom Stop Loss and Take Profit Inputs
    input bool UseCustomSLTP = false;     // Use Custom SL/TP (true) or ATR-based (false)
    input bool UsePointsForSLTP = true;   // Use Points for SL/TP (true) or Money (false)
    input double CustomSLPoints = 50;     // Custom Stop Loss in Points
    input double CustomTPPoints = 100;    // Custom Take Profit in Points
    input double CustomSLMoney = 10;      // Custom Stop Loss in Money (Account Currency)
    input double CustomTPMoney = 20;      // Custom Take Profit in Money (Account Currency)
    
    // Global variables
    datetime prevDayTime;
    double prevDayHigh, prevDayLow;
    MqlTradeRequest pendingBuy, pendingSell;
    MqlTradeResult tradeResult;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
      {
       // Initialize previous day's high and low
       prevDayTime = iTime(_Symbol, PERIOD_D1, 1);
       prevDayHigh = iHigh(_Symbol, PERIOD_D1, 1);
       prevDayLow = iLow(_Symbol, PERIOD_D1, 1);
    
       // Draw the previous day's high and low on the chart
       ObjectCreate(0, "PrevDayHigh", OBJ_HLINE, 0, 0, prevDayHigh);
       ObjectSetInteger(0, "PrevDayHigh", OBJPROP_COLOR, HighLineColor);
       ObjectSetInteger(0, "PrevDayHigh", OBJPROP_WIDTH, LineWidth);
    
       ObjectCreate(0, "PrevDayLow", OBJ_HLINE, 0, 0, prevDayLow);
       ObjectSetInteger(0, "PrevDayLow", OBJPROP_COLOR, LowLineColor);
       ObjectSetInteger(0, "PrevDayLow", OBJPROP_WIDTH, LineWidth);
    
       // Prepare pending order structures
       pendingBuy.action = TRADE_ACTION_PENDING;
       pendingBuy.type = ORDER_TYPE_BUY_STOP;
       pendingBuy.price = prevDayHigh;
       pendingBuy.deviation = 20;
       pendingBuy.volume = CalculateLotSize();
       pendingBuy.sl = 0.0; // Will be updated later
       pendingBuy.tp = 0.0; // Will be updated later
    
       pendingSell.action = TRADE_ACTION_PENDING;
       pendingSell.type = ORDER_TYPE_SELL_STOP;
       pendingSell.price = prevDayLow;
       pendingSell.deviation = 20;
       pendingSell.volume = CalculateLotSize();
       pendingSell.sl = 0.0; // Will be updated later
       pendingSell.tp = 0.0; // Will be updated later
    
       return(INIT_SUCCEEDED);
      }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
      {
       // Remove chart objects
       ObjectDelete(0, "PrevDayHigh");
       ObjectDelete(0, "PrevDayLow");
       ObjectDelete(0, "PendingBuyEntry");
       ObjectDelete(0, "PendingBuySL");
       ObjectDelete(0, "PendingBuyTP");
       ObjectDelete(0, "PendingSellEntry");
       ObjectDelete(0, "PendingSellSL");
       ObjectDelete(0, "PendingSellTP");
      }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
      {
       // Check if new day
       datetime currentTime = iTime(_Symbol, PERIOD_CURRENT, 0);
       if(currentTime >= prevDayTime + 86400) // 86400 seconds in a day
         {
          UpdatePrevDayLevels();
         }
    
       // Check if 5-minute candle closed above/below previous day's high/low
       if(CheckBreakoutCondition())
         {
          PlacePendingOrders();
         }
    
       // Manage open trades
       ManageTrades();
      }
    
    //+------------------------------------------------------------------+
    //| Update previous day's high and low                               |
    //+------------------------------------------------------------------+
    void UpdatePrevDayLevels()
      {
       prevDayTime = iTime(_Symbol, PERIOD_D1, 1);
       prevDayHigh = iHigh(_Symbol, PERIOD_D1, 1);
       prevDayLow = iLow(_Symbol, PERIOD_D1, 1);
    
       // Update chart objects
       ObjectSetDouble(0, "PrevDayHigh", OBJPROP_PRICE, prevDayHigh);
       ObjectSetDouble(0, "PrevDayLow", OBJPROP_PRICE, prevDayLow);
      }
    
    //+------------------------------------------------------------------+
    //| Check breakout condition                                         |
    //+------------------------------------------------------------------+
    bool CheckBreakoutCondition()
      {
       double closePrice = iClose(_Symbol, PERIOD_M5, 0);
       if(closePrice > prevDayHigh || closePrice < prevDayLow)
         {
          return true;
         }
       return false;
      }
    
    //+------------------------------------------------------------------+
    //| Place pending orders - ENHANCED FUNCTION                         |
    //+------------------------------------------------------------------+
    void PlacePendingOrders()
      {
       double slBuy, tpBuy, slSell, tpSell;
    
       if(UseCustomSLTP)
         {
          if(UsePointsForSLTP)
            {
             // Use custom SL/TP in points
             slBuy = prevDayHigh - (CustomSLPoints * SymbolInfoDouble(_Symbol, SYMBOL_POINT));
             tpBuy = prevDayHigh + (CustomTPPoints * SymbolInfoDouble(_Symbol, SYMBOL_POINT));
             slSell = prevDayLow + (CustomSLPoints * SymbolInfoDouble(_Symbol, SYMBOL_POINT));
             tpSell = prevDayLow - (CustomTPPoints * SymbolInfoDouble(_Symbol, SYMBOL_POINT));
            }
          else
            {
             // Use custom SL/TP in money
             double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
             double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
             double lotSize = CalculateLotSize();
    
             // Calculate SL and TP in points based on money
             double slPointsBuy = (CustomSLMoney / (lotSize * tickValue)) * tickSize;
             double tpPointsBuy = (CustomTPMoney / (lotSize * tickValue)) * tickSize;
             double slPointsSell = (CustomSLMoney / (lotSize * tickValue)) * tickSize;
             double tpPointsSell = (CustomTPMoney / (lotSize * tickValue)) * tickSize;
    
             slBuy = prevDayHigh - slPointsBuy;
             tpBuy = prevDayHigh + tpPointsBuy;
             slSell = prevDayLow + slPointsSell;
             tpSell = prevDayLow - tpPointsSell;
            }
         }
       else
         {
          // Use ATR-based SL/TP
          int atrHandle = iATR(_Symbol, PERIOD_H1, ATRPeriod);
          if (atrHandle == INVALID_HANDLE)
            {
             Print("Failed to get ATR handle");
             return;
            }
    
          double atrArray[];
          if (CopyBuffer(atrHandle, 0, 0, 1, atrArray) <= 0)
            {
             Print("Failed to copy ATR data");
             return;
            }
    
          double atr = atrArray[0];
    
          slBuy = prevDayHigh - atr;
          tpBuy = prevDayHigh + (RiskRewardRatio * (prevDayHigh - slBuy));
          slSell = prevDayLow + atr;
          tpSell = prevDayLow - (RiskRewardRatio * (slSell - prevDayLow));
         }
    
       // Update pending order structures
       pendingBuy.sl = slBuy;
       pendingBuy.tp = tpBuy;
       pendingSell.sl = slSell;
       pendingSell.tp = tpSell;
    
       // Place pending orders
       if(!OrderSend(pendingBuy, tradeResult))
         {
          Print("Failed to place pending BUY order: ", tradeResult.retcode);
         }
       else
         {
          // Plot pending buy order on chart
          PlotPendingOrder("PendingBuy", pendingBuy.price, pendingBuy.sl, pendingBuy.tp, clrBlue);
         }
    
       if(!OrderSend(pendingSell, tradeResult))
         {
          Print("Failed to place pending SELL order: ", tradeResult.retcode);
         }
       else
         {
          // Plot pending sell order on chart
          PlotPendingOrder("PendingSell", pendingSell.price, pendingSell.sl, pendingSell.tp, clrRed);
         }
      }
    
    //+------------------------------------------------------------------+
    //| Plot pending order on chart                                      |
    //+------------------------------------------------------------------+
    void PlotPendingOrder(string prefix, double entry, double sl, double tp, color lineColor)
      {
       // Plot entry line
       ObjectCreate(0, prefix + "Entry", OBJ_HLINE, 0, 0, entry);
       ObjectSetInteger(0, prefix + "Entry", OBJPROP_COLOR, lineColor);
       ObjectSetInteger(0, prefix + "Entry", OBJPROP_WIDTH, 1);
       ObjectSetInteger(0, prefix + "Entry", OBJPROP_STYLE, STYLE_DASH);
    
       // Plot stop loss line
       ObjectCreate(0, prefix + "SL", OBJ_HLINE, 0, 0, sl);
       ObjectSetInteger(0, prefix + "SL", OBJPROP_COLOR, lineColor);
       ObjectSetInteger(0, prefix + "SL", OBJPROP_WIDTH, 1);
       ObjectSetInteger(0, prefix + "SL", OBJPROP_STYLE, STYLE_DOT);
    
       // Plot take profit line
       ObjectCreate(0, prefix + "TP", OBJ_HLINE, 0, 0, tp);
       ObjectSetInteger(0, prefix + "TP", OBJPROP_COLOR, lineColor);
       ObjectSetInteger(0, prefix + "TP", OBJPROP_WIDTH, 1);
       ObjectSetInteger(0, prefix + "TP", OBJPROP_STYLE, STYLE_DOT);
      }
    
    //+------------------------------------------------------------------+
    //| Calculate lot size based on inputs                               |
    //+------------------------------------------------------------------+
    double CalculateLotSize()
      {
       if(UsePercentageLot)
         {
          double equity = AccountInfoDouble(ACCOUNT_EQUITY);
          double riskAmount = equity * (RiskPercentage / 100);
          double pointValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
          double stopLossInPoints = (prevDayHigh - prevDayLow) / SymbolInfoDouble(_Symbol, SYMBOL_POINT);
          if (stopLossInPoints == 0) return 0.01; // Avoid division by zero
          double lotSize = riskAmount / (stopLossInPoints * pointValue);
          return MathMax(lotSize, SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN));
         }
       else
         {
          return LotSize;
         }
      }
    
    //+------------------------------------------------------------------+
    //| Manage open trades                                               |
    //+------------------------------------------------------------------+
    void ManageTrades()
      {
       // Implement trade management logic here (e.g., trailing stop, etc.)
       // ...
      }
    //+------------------------------------------------------------------+
    

    Explanation of Additions

    1. Custom Stop Loss and Take Profit:

      • Input Parameters:
        • UseCustomSLTP: If true, uses custom SL/TP values; if false, uses ATR-based SL/TP.
        • UsePointsForSLTP: If true, uses points for SL/TP; if false, uses money (account currency).
        • CustomSLPoints and CustomTPPoints: Custom stop loss and take profit in points.
        • CustomSLMoney and CustomTPMoney: Custom stop loss and take profit in money (account currency).
      • Logic in PlacePendingOrders:
        • If UseCustomSLTP is true, the EA calculates SL/TP based on either points or money.
        • For points, it directly converts the input points to price levels using SymbolInfoDouble(_Symbol, SYMBOL_POINT).
        • For money, it calculates the equivalent points based on the lot size, tick size, and tick value, then converts to price levels.
    2. Plotting Pending Orders on the Chart:

      • New Function PlotPendingOrder:
        • This function creates three horizontal lines for each pending order: entry, stop loss, and take profit.
        • The lines are styled differently (dashed for entry, dotted for SL/TP) and use different colors for buy (blue) and sell (red) orders.
      • Integration in PlacePendingOrders:
        • After successfully placing a pending order, the PlotPendingOrder function is called to draw the lines on the chart.
      • Cleanup in OnDeinit:
        • Added ObjectDelete calls to remove the pending order lines when the EA is removed from the chart.

    Notes

    • Testing: Always test the EA in a demo account before using it in live trading to ensure it behaves as expected.
    • Customization: You can adjust the colors, line styles, and widths of the plotted lines by modifying the PlotPendingOrder function or adding more input parameters.
    • Error Handling: The current code includes basic error handling for order placement. You may want to add more robust error handling, especially for chart object creation and deletion.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.