how to open trade on open trade of new candle

 

Hi I'd like to open trade on the open candle, to do that I use this code to detect new bar formed from earnforex:

datetime NewCandleTime = TimeCurrent();
bool IsNewCandle()
  {
   if(NewCandleTime == iTime(Symbol(), 0, 0))
      return false;
   else
     {
      NewCandleTime = iTime(Symbol(), 0, 0);
      return true;
     }
  }

for open the trade I use this code:

slippage = 0;
if(logic == 1)
   {
        OpenCandle = iOpen(Symbol(),PERIOD_CURRENT,0);
        double openPriceBuy    = OpenCandle;
        double stoplossBuy     = OpenCandle - stoploss;
        double takeProfitBuy   = OpenCandle + takeprofit;
        double lotsizeBuy      = 0.01;
        int    ticket          = OrderSend(Symbol(),OP_BUY,lotSizeBuy,openPriceBuy,slippage,stoplossBuy,takeProfitBuy,"BUY",MagicNumber);
   }

if(logic == 2)
   {
        OpenCandle = iOpen(Symbol(),PERIOD_CURRENT,0);
        double openPriceSell    = OpenCandle;
        double stoplossSell     = OpenCandle - stoploss;
        double takeProfitSell   = OpenCandle + takeprofit;
        double lotsizeSell      = 0.01;
        int    ticket          = OrderSend(Symbol(),OP_BUY,lotSizeSell,openPriceSell,slippage,stoplossSell,takeProfitSell,"BUY",MagicNumber);
   }

using these code I can open trade when new bar formed but the entry price is not the open price of new candle sometimes it can open near the close candle of new candle. Is there a way to make it open on the open price of new candle?

 
Luandre Ezra:

Hi I'd like to open trade on the open candle, to do that I use this code to detect new bar formed from earnforex:

for open the trade I use this code:

using these code I can open trade when new bar formed but the entry price is not the open price of new candle sometimes it can open near the close candle of new candle. Is there a way to make it open on the open price of new candle?

Yes, use the 

IsNewCandle()

function.

 
Keith Watford #:

Yes, use the 

function.

I already used that code but when I backtest any strategy the entry price isn't the open candle. Sometimes it open near close candle. Do you know why this happened?
 
Luandre Ezra #:
I already used that code but when I backtest any strategy the entry price isn't the open candle. Sometimes it open near close candle. Do you know why this happened?

You don't use that code. Here is the code from your first post.

slippage = 0;
if(logic == 1)
   {
        OpenCandle = iOpen(Symbol(),PERIOD_CURRENT,0);
        double openPriceBuy    = OpenCandle;
        double stoplossBuy     = OpenCandle - stoploss;
        double takeProfitBuy   = OpenCandle + takeprofit;
        double lotsizeBuy      = 0.01;
        int    ticket          = OrderSend(Symbol(),OP_BUY,lotSizeBuy,openPriceBuy,slippage,stoplossBuy,takeProfitBuy,"BUY",MagicNumber);
   }

if(logic == 2)
   {
        OpenCandle = iOpen(Symbol(),PERIOD_CURRENT,0);
        double openPriceSell    = OpenCandle;
        double stoplossSell     = OpenCandle - stoploss;
        double takeProfitSell   = OpenCandle + takeprofit;
        double lotsizeSell      = 0.01;
        int    ticket          = OrderSend(Symbol(),OP_BUY,lotSizeSell,openPriceSell,slippage,stoplossSell,takeProfitSell,"BUY",MagicNumber);
   }

There is no code to check for a new candle.

 
Keith Watford #:

You don't use that code. Here is the code from your first post.

There is no code to check for a new candle.

Sorry my bad, the code that I posted is nested on IsNewCandle() function from earnforex website. But I still found that ea open trade near close price.
 
Luandre Ezra #:
Sorry my bad, the code that I posted is nested on IsNewCandle() function from earnforex website. But I still found that ea open trade near close price.

There is a better way to structure your code for a new bar detection. Please read the following ...

Code Base

Detecting the start of a new bar or candle

Fernando Carreiro, 2022.04.24 00:46

Detecting the start of a new bar or candle, in the OnTick() event handler of an expert advisor.
 
Luandre Ezra #:
Sorry my bad, the code that I posted is nested on IsNewCandle() function from earnforex website. But I still found that ea open trade near close price.

As you have not posted the actual code that you are using, how do you expect anyone to help?
Post your actual code.

 
here the full code. Using moving average crossover will result the same problem.
Files:
 
  1. Luandre Ezra #: here the full code.

    That code will not even compile; missing IsNewCandle() and CalculateLotSize() definitions.

  2. double openPriceBuy  = Ask;
    double stoplossBuy   = NormalizeDouble(openPriceBuy - Stoploss*Point(),Digits);
    double takeProfitBuy        = NormalizeDouble(openPriceBuy + Take_profit*Point(),Digits);

    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 to 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, but average maximum spread = 134 (your broker will be similar).

  3. double lotSizeBuy = CalculateLotSize(Risk_Per_Trade,stoplossBuy)/100;

    No idea how you think you can calculate lotsize with a single price.

    Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin and leverage. No SL means you have infinite risk (on leveraged symbols). Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce, the stop goes below the support.

    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/PIP, but it takes account of the exchange rates of the pair vs. your account currency.)

    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum (2017)
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum (2018)
                Lot value calculation off by a factor of 100 - MQL5 programming forum (2019)

    4. You must normalize lots properly and check against min and max.

    5. You must also check Free Margin to avoid stop out

    6. For MT5, see 'Money Fixed Risk' - MQL5 Code Base (2017)

    Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

 
  1. William Roeder #That code will not even compile; missing IsNewCandle() and CalculateLotSize() definitions.
    I forgot that I use an include file for those function. I already add both function in this new file.

  2. double openPriceBuy  = Ask;
    double stoplossBuy   = NormalizeDouble(openPriceBuy - Stoploss*Point(),Digits);
    double takeProfitBuy = NormalizeDouble(openPriceBuy + Take_profit*Point(),Digits);
    
    the whole problem is indeed on the openPriceBuy.  I want to enter the trade on the open price of new candle. I thought the problem would be on the indicator but when I tried to use moving average crossover, EA would still open trade near or on the close price instead of open price. 

    I tried to change the 
    openPriceBuy into open = iOpen(Symbol(),PERIOD_CURRENT,0), but it returns error 138. If any is there a way to put specified price such as open candle as entry price?


  3. Don't you want the specified amount used in either direction?

    the idea of openPriceBuy for SL and TP to referred to. It is would not be equal because spread doesn't include in the calculation. The EA is still on working that's why I don't add much in the calculation. One thing though, from your link to MODE_SPREAD, you said that
    for a short position you must use an average spread
    may I know do I must use average spread on short position?
Files:
 
 An open candle only has the Open price which is the last candle's Close price in most of the cases(forex/xauusd). So in the open candle, you only have 3 properties Open price which is Close[1], Ask price and Bid price.  Maybe the language cannot return a candle for you unless it has all components, open,close, high, low. There's another work around is that you set a time interval and wait for that time interval after Close[1] if it's a stock CFD, or use a much smaller timeframe to get the most recent iClose().