EA to trade on the current candle

 

Hi,

Lets say I want to write an EA to trade SMA 21 as a baseline on a daily chart, whenever the price crosses the baseline, I want to open a position. I could easily create a Boolean condition and open a position based on that:

   bool buyCondition = (PriceInfo[1].close > BufferMA[1]) && (PriceInfo[2].close < BufferMA[2]);
   bool sellCondition = (PriceInfo[1].close < BufferMA[1]) && (PriceInfo[2].close > BufferMA[2]);

 But according to this, for a trade that happens today, I am making a decision on what happened yesterday and the day before, but what i actually want, is to trade if the cross happens today, the problem is, for today or the current candle, since the market isn't closed yet, the value of the SMA is not finalized and is constantly updating. There might be workaround this, since our local market opens at 9:00 AM and closes at 12:30 PM (only 3 and a half hours a day!), if I read the SMA value 5 minutes before the market closing, it would be fairly close to the actual closing SMA of the current candle. In order to do this, I have this simple snippet which also ensures i trade only once per candle: 

bool NewBar() {
   
   int Minutes_to_Close = 5

   static datetime prevTime = 0;
   datetime currentTime = iTime(_Symbol, _Period, 0) + (750 - Minutes_to_Close)*60;
   if (currentTime != prevTime) {
      prevTime = currentTime;
      return(true);
   }
   return(false);

The iTime, registers at 00:00:00 , so I added the time difference to the closing of the market to it, and passed it as a Boolean to the OnTick() function and I also changed the baseline condition to use the current candle value and only compare it to yesterday value:

void OnTick() {

   if(!NewBar()) return;

   ArraySetAsSeries(BufferMA,true);
   ArraySetAsSeries(PriceInfo,true);
   
   
   CopyBuffer(Handle_cma, sma_Index, 0, 3, BufferMA) ;
   CopyRates(_Symbol, _Period, 0, 3, PriceInfo);

   bool buyCondition = (PriceInfo[0].close > BufferMA[0]) && (PriceInfo[1].close < BufferMA[1]);
   bool sellCondition = (PriceInfo[0].close < BufferMA[0]) && (PriceInfo[1].close > BufferMA[1]);
   
   
   if (buyCondition) {
      OrderOpen(ORDER_TYPE_BUY);
   }
   
   else if (sellCondition) {
      OrderOpen(ORDER_TYPE_SELL);
   }
   return;
}

and my OrderOpen() function goes like this:

bool OrderOpen(ENUM_ORDER_TYPE orderType) {

   double price;
   double stopLossPrice;
   double takeProfitPrice;
   
   int volume = 10000;
   StopLoss = ATR_Multiplier * BufferATR[0];
   TakeProfit =  ATR_Multiplier * BufferATR[0]; 
   
   
   if (orderType == ORDER_TYPE_BUY) {
      price = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
      stopLossPrice = NormalizeDouble(price - StopLoss, _Digits);
      takeProfitPrice = NormalizeDouble(price + TakeProfit, _Digits);
   }
   else if (orderType == ORDER_TYPE_SELL){
      price = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);
      stopLossPrice = NormalizeDouble(price + StopLoss, Digits());
      takeProfitPrice = NormalizeDouble(price - TakeProfit, _Digits);
   }
   else return(false);
   
   
   Trade.PositionOpen(_Symbol, orderType, volume, price, stopLossPrice, takeProfitPrice, InpTradeComment);
   return(true);

}


I have couple of question in regard to my approach here.

1. From logical point of view, is it wise to compare the current candle price as a signal to trade ?

2. Does my  NewBar() function make sure to populate the BufferMA[0] with SMA of the current candle at 12:25:00?

3. In the OnThick() function, if my NewBar() condition is met, why in the backtesting history, all my trades are happening on the current day, but at 9:00:00 when the market opens, shouldn't my trade take place at 12:25:00? 

 

Comment:

 ORDER_TYPE_BUY 

Learn the help - there are no ORDERS! There is a deal and a POSITION.

 
Vladimir Karputov:

Comment:

Learn the help - there are no ORDERS! There is a deal and a POSITION.

I didn't understand your point, you mean i should not use this?

Trade.PositionOpen(_Symbol, orderType, volume, price, stopLossPrice, takeProfitPrice, InpTradeComment);

or should i add more steps to it ?

 

3. In the OnThick() function, if my NewBar() condition is met, why in the backtesting history, all my trades are happening on the current day, but at 9:00:00 when the market opens, shouldn't my trade take place at 12:25:00? 

Everything is okay . But :

bool NewBar() {
   
   int Minutes_to_Close = 5;

   static datetime prevTime = 0;
   datetime currentTime = iTime(_Symbol, _Period, 0) + (750 - Minutes_to_Close)*60;
   if (currentTime != prevTime) {
      prevTime = currentTime;
      return(true);
   }
   return(false);
}
/*
First run : currentTime = 12:25:00 (on current day ,theres more to the timestamp),prevtime =0 , they are different so NewBar Fires on open of market
Second run : currentTime = 12:25:00 (today 12:25:00),prevtime is yesterday 12:25:00 , they are different so NewBar Fires on open of market
essentially the new bar were telling it to execute if the limit time was different than the previous limit time ,which is always true
*/
//i did not test this yet : let me know 
bool AllowOnNewBar(){
int MTC=5;//minutes to close 
static datetime barStamp=0;
datetime now=TimeCurrent();
datetime limit=(datetime)(iTime(_Symbol,_Period,0)+(750-MTC)*60);
if(now>=limit&&limit!=barStamp){
barStamp=limit;
return(true);
}
return(false);
}
 
Pouria_mzn :

I didn't understand your point, you mean i should not use this?

or should i add more steps to it ?

Use the Buy and Sell methods.

Buy

Opens a long position with specified parameters

Sell

Opens a short position with specified parameters

Documentation on MQL5: Standard Library / Trade Classes / CTrade / Buy
Documentation on MQL5: Standard Library / Trade Classes / CTrade / Buy
  • www.mql5.com
Successful completion of the Buy(...) method does not always mean successful execution of the trade operation. It is necessary to check the result of trade request (trade server return code) using ResultRetcode() and value returned by ResultDeal().
 
Lorentzos Roussos:

Everything is okay . But :

It worked like a charm, thanks a lot. 

 
Pouria_mzn:

It worked like a charm, thanks a lot. 

Great 

 
Vladimir Karputov:

Use the Buy and Sell methods.

Buy

Opens a long position with specified parameters

Sell

Opens a short position with specified parameters

Thanks, I updated my code to use Sell and Buy:

bool OrderOpen(ENUM_ORDER_TYPE orderType) {

   double price;
   double stopLossPrice;
   double takeProfitPrice;
   
   int volume = 10000;
   StopLoss = ATR_Multiplier * BufferATR[0];
   TakeProfit =  ATR_Multiplier * BufferATR[0]; 
   
   
   if (orderType == ORDER_TYPE_BUY) {
      price = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits);
      stopLossPrice = NormalizeDouble(price - StopLoss, _Digits);
      takeProfitPrice = NormalizeDouble(price + TakeProfit, _Digits);
      Trade.Buy(volume, _Symbol, price, stopLossPrice, takeProfitPrice, NULL);
   }
   else if (orderType == ORDER_TYPE_SELL){
      price = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), _Digits);
      stopLossPrice = NormalizeDouble(price + StopLoss, Digits());
      takeProfitPrice = NormalizeDouble(price - TakeProfit, _Digits);
      Trade.Sell(volume, _Symbol, price, stopLossPrice, takeProfitPrice, NULL);
   }
   else return(false);
   
   
   //Trade.PositionOpen(_Symbol, orderType, volume, price, stopLossPrice, takeProfitPrice, InpTradeComment);
   return(true);

}

But honestly after all my readings, i didn't find any the difference between PositionOpen() and Buy(), even after I changed my code to use Buy() function, it still performs the same, with the same number of trades and the same amount of profit!! Even I've found this post on the forum, which your answer to it was " PositionOpen is a more general function - you can open both Buy and Sell and expose a pending order. Whereas the Buy function only opens a long position"

PositionOpen Vs Buy?
PositionOpen Vs Buy?
  • 2017.07.18
  • www.mql5.com
Hello, Im trying to understand trade function in the Ctrade class...
 
Pouria_mzn :

Thanks, I updated my code to use Sell and Buy:

But honestly after all my readings, i didn't find any the difference between PositionOpen() and Buy(), even after I changed my code to use Buy() function, it still performs the same, with the same number of trades and the same amount of profit!! Even I've found this post on the forum, which your answer to it was " PositionOpen  is a more general function - you can open both Buy and Sell and expose a pending order. Whereas the  Buy  function only opens  a long position"

As long as YOU will operate with the word "order" - you will make many stupid mistakes. Once you start using "position", your brain will start generating the correct code.

Look at your code - until you remove any mention of "order" - you start writing efficient code.

 
Pouria_mzn :

***

3. In the OnThick() function, if my NewBar() condition is met, why in the backtesting history, all my trades are happening on the current day, but at 9:00:00 when the market opens, shouldn't my trade take place at 12:25:00? 

You need to get the timing right.

Let's say you want to open a POSITION in the last five minutes of trading. Bidding ends at '12:30 ', which means you need (this is the easiest way) to set the start time '12:25' in the input parameters. And check in the advisor - if the current time is less than '12:25 '- do not search for a signal, and only if the time is '12:25' (or more), search for a signal.

In this case (if there is a signal), the POSITION will be opened at '12:25 '(either online or in the strategy tester). Naturally, in the strategy tester, you need to select the tick generation type 'every tick' or 'every tick based on real ticks'.

 
Vladimir Karputov:

As long as YOU will operate with the word "order" - you will make many stupid mistakes. Once you start using "position", your brain will start generating the correct code.

Look at your code - until you remove any mention of "order" - you start writing efficient code.

I was reading on how MQL4 and MQL5 are different on sending Orders, and how on MQL5 we have Deals and Trades and everything is translated into Positions, which on MQL4 it's all combined in Orders. So i think it would be wise not to use Orders to avoid confusions. Thanks for your help 

Reason: