error 0

 

So I have created this it seems to work ok, but I get an error every new bar in the experts tab in mt4    . I suspect I need to check if the condition is true before running,   I only have experience with easylanguage..  Can anyone help?   Is it ok to use the onchart event rather than ontick. 



//+------------------------------------------------------------------+
//|                                                         test.mq4 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
 
//extern string TimeToClose="YYYY.MM.DD HH:MI";
//extern string TimeToOpen="YYYY.MM.DD HH:MI";
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
//////////////TimeLocal() updates each time while code running in OnTimer().//////////
void OnTick()
  {
//---
//





   }
   
  
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---





   {
    double entryPrice = iLow(_Symbol, PERIOD_D1, 1); //0

   double stopLoss = entryPrice - (30 * _Point);  // Example: 3 pips below entry price
   double takeProfit = entryPrice + (20 * _Point);  // Example: 5 pips above entry price
 
int PendingExpiryMinutes=15;
datetime expiry = TimeCurrent() + (PendingExpiryMinutes * 60);
 

 string TimeToOpen="07:05";
 string TimeToClose="07:06";

        if((TimeLocal()>=StrToTime(TimeToOpen))  && (TimeLocal()<=StrToTime(TimeToClose)))


    
{

    int ticket = OrderSend(NULL, OP_BUYLIMIT, 0.1, entryPrice, 0, stopLoss, takeProfit, "Buy at Low of Day",5215,expiry,Blue);
    
    if (ticket > 0)
   
        // Order was placed successfully
        Print("Buy order placed at price: ", entryPrice);
    }
    else
    {
        // Failed to place the order
        Print("Error placing buy order: ", GetLastError());
    }



}
   
   //if((TimeLocal()>=StrToTime("01:05"))
  
  
  
  
  }
  
  
 
Documentation on MQL5: Date and Time / TimeLocal
Documentation on MQL5: Date and Time / TimeLocal
  • www.mql5.com
TimeLocal - Date and Time - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
  • Usually people who cannot code do not receive free help on this forum, although it could happen if you are lucky. Be patient.
  • If you show your attempts and describe your problem clearly, you will most probably receive an answer from the community.
  • If you do not want to learn to code, that is not a problem. You can either look at the Codebase if something free already exists, or in the Market for paid products (also sometimes free).
  • Finally, you also have the option to hire a programmer in the Freelance section.
MQL5 Code Base
MQL5 Code Base
  • www.mql5.com
MQL5 Source Code Library for MetaTrader 5
 

MQL4 and MetaTrader 4, has it's own section on the forum. I have moved your topic to the correct section. Please don't create another topic.

 
  1. Post in the correct place.

  2. Why are you doing this on a chart event? Do you really want to open an order when the chart is scrolled, object created, etc.? Do you really want to not open when Human isn't operating the terminal?

  3.    double stopLoss = entryPrice - (30 * _Point);  // Example: 3 pips below entry price
       double takeProfit = entryPrice + (20 * _Point);  // Example: 5 pips above entry price

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  4.     int ticket = OrderSend(NULL, OP_BUYLIMIT, 0.1, entryPrice, 0, stopLoss, takeProfit, "Buy at Low of Day",5215,expiry,Blue);
    

    Be careful with NULL.

    1. On MT4, you can use NULL in place of _Symbol only in those calls that the documentation specially says you can. iHigh does, iCustom does, MarketInfo does not, OrderSend does not.
    2. Don't use NULL (except for pointers where you explicitly check for it.) Use _Symbol and _Period, that is minimalist as possible and more efficient.
    3. Zero is the same as PERIOD_CURRENT which means _Period. Don't hard code numbers.
    4. MT4: No need for a function call with iHigh(NULL,0,s) just use the predefined arrays, i.e. High[].
      MT5: create them.
    5. Cloud Protector Bug? - MQL4 programming forum (2020)

  5.     double entryPrice = iLow(_Symbol, PERIOD_D1, 1); //0
    

    On MT4: Unless the current chart is that specific symbol(s)/TF(s) referenced, you must handle 4066/4073 errors before accessing candle/indicator values.
              Download history in MQL4 EA - MQL4 programming forum - Page 3 #26.4 (2019)

  6. There is no need to create pending orders in code.

    1. The pending has the slight advantage, A) you are closer to the top of the queue (filled quicker), B) there's no round trip network delay (filled quicker.)

      Don't worry about it unless you're scalping M1 or trading news.

    2. Humans can't watch the screen 24/7, so they use pending orders; EAs can, so no need for pending orders, have it wait until the market reaches the trigger price and just open an order.

  7.  string TimeToOpen="07:05";
     string TimeToClose="07:06";
            if((TimeLocal()>=StrToTime(TimeToOpen))  && (TimeLocal()<=StrToTime(TimeToClose)))

    When dealing with time, a lot of people use strings; they can not be optimized. Using (int) seconds or (double) hours and fraction can be inputs.

    See also Dealing with Time (Part 1): The Basics - MQL5 Articles (2021.10.01)
    Dealing with Time (Part 2): The Functions - MQL5 Articles (2021.10.08)
    MQL5 Programming Basics: Time - MQL5 Articles (2013.04.26)

    What happens when you get multiple events/ticks during that minute?

    Remember to handle the case where start > end (e.g. 2100 … 0200)

 

Thanks,  it is indeed a scalping strategy, ~$50 avg trades but  profit factor>2 but stops are wide and rarely get hit so no slippage

  I backtested on tradestation and use a low spread mt4 broker, so would prefer limit orders . 

So I should move everything from onchartevent to ontick ?    If I use ontick I get an order every tick.  Sorry easylangauge has much simpler structure :)

I can share them with you if you would like to create them.  

  ->" Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes. "

Indeed , I would also need to know how to cancel the stoploss/tgt between 5pm et and 6pm et.

Reason: