how trade when a condition triggers mid-bar

 

Hi to all,

I have a few questions to ask help because i didn't find clear answer in forum...

I am trying to finish my EA in MT5  unsing some indicators , specifically :iMA, iATR, iMACD 

also I set the timeframe to H4 for the pair XAUUSD and for indicators.

1 ) FIRST 

the logic is that when I receive the tick event i update the data insicators , check if data indicators give me the values expected and then trade a position.

Reading here in forum I also understood about isNewBar() behavior to make sure that the analysis is made just one time per bar and so i put this  method  just after OnTick() event like :

if ( !IsNewBar ) return;

The problem is that when I launched the EA in backtest( showing chart)  i noted the the indicator gives a good signal to trade when I was i a middle of a bar so this is confusing me because  this signal is skipped by isNewbar test. 

Some one could help me understand witch is the good behavior  to manage this situation ?  i mean  Is corretct to operate with IsNewbar()  test or whatever and in witch situation ??

2) SECOND 

Due to the fact  there are tons of ticks between timeframe ...  is corect to put a trailing stop  before isNewbar() test ? 
this question is because I noted that the trades i put are always  closed ( loss/profit) at the market price, no matter what timframe you have set. so seems correct also to put a SetTrailingStop(); before  isNewbar() .

3) THIRD
Is correct to set also the new Takeprofit value in   SetTrailingStop(); method.?  ( also because  the market price  doesn't wait you timeframe ).

 
  1. You decide whether you are going to look at the completed bar or the forming one. In the latter, you risk entering and then having the signal vanish.
  2. You decide, what bar your trailing method will be using.
  3. Why did you not set your take profit when you opened? Do you really mean “new take profit?” What is new about it?
  4. Until you can state your requirements in concrete terms, it can not be coded.

 

Hi William ,

Thanks for replay.

I know that i have to decide  to enter at the complete bar or in the forming one. But what does it mean " you risk entering and then having the signal vanish ?  the problem , at least for what i have understood , is that indicators values is indipendent form your timeframe  or put in onother way what is the relation between  IMA.. etc...timeframe and candle  timeframe.. ( what I see on the chart  ) ?


I was asking what is your experience about that ? or what do you think is better ?

for about takeprofit , yes I set it when I open a trade, but it's correct to change it in meanwhile i change the stoploss vaue ?? , also what is your experience ? 
about the code nothing of special , something like this :

        double Bid = SymbolInfoDouble(symbol, SYMBOL_BID);              // 
        double Ask = SymbolInfoDouble(symbol, SYMBOL_ASK);              //            
        ::        
              openprice = PositionGetDouble(POSITION_PRICE_OPEN);
              openSL = PositionGetDouble(POSITION_SL);
              openTP = PositionGetDouble(POSITION_TP);      

         if ( posType == POSITION_TYPE_BUY)
         {
            trailingStopLevel = openprice + pips;
            newSL = Bid - pips;
            if (Bid - trailingStopLevel > 0 && Bid - openSL > pips)
                                trade.PositionModify(ticket, newSL, openTP);   <--  something of NewTP
        ::

for the first question see the picture below.

Files:
 
  1. jossnet #: is that indicators values is indipendent form your timeframe  or put in onother way what is the relation between  IMA.. etc...timeframe and candle  timeframe.. ( what I see on the chart  ) ?

    It is dependent on the timeframe the indicator is running at. A 200 SMA on the M1 only indicates the last three hours, vs the D1 the last year.

  2. jossnet #: But what does it mean " you risk entering and then having the signal vanish ?  

    Assuming your signal is the cross of the MA. What happens if the high of a bar is above, but the close is below. You had a signal, but not at the end of the bar.

  3. jossnet #: I was asking what is your experience about that ? or what do you think is better ?

    I don't think at all. I run the optimizer and find out.

 

thank you William,

OK now is more clear. thanks.


About the  new Takeprofit question , you are talking about backtester isn't it ? not in live account ?...

I have also another question about drawdown calculation. I was asked to calculate  the daily drawdown every day and check when  and if  the DD value is more then a X%  ( considering all the trades of that day as if they are "equity" )  applaying this formula 
dailydrawdown = (balance -equity) /balance *100.0;
 
  where  balance  = banlance at start of that day

     equity = all trades of that day ( including the ones of type  DEAL_ENTRY_IN  and DEAL_ENTRY_OUT)

and then if the resulting percentage is more than X% value stop to trade.

I didn't see anything here in forum. Am I out of the world or this request has a sense ? 
About the code  I thing something like this 

OnTick()
{
        ::
        double balance = AccountInfoDouble(ACCOUNT_BALANCE);
        
        double dailyEquity =  DailyProfit();
        balance = balance - dailyEquity;		// set balance at the start of the day
        
        double dailyDrawdown = dailyEquity / balance * 100;	// calc Drawdown %

        if ( dailyDrawdown > MaxDailyDrawdown ) return;
        ::
}

double DailyProfit(  )
{
   double   profit=0, TotProfit=0;
   datetime time,StartTtime,EndTime;
   ulong    ticket=0;
   long     id,type,entry;
   string   symbolps;
   
   string symbol = ChartSymbol(ID);
   EndTime = TimeLocal();                       

   StartTtime = EndTime -PeriodSeconds(PERIOD_D1);              // diminuisce di 1GG
        
   HistorySelect(StartTtime, EndTime );
        
   int i, hstTotal = HistoryDealsTotal();
        
        for ( i=0; i < hstTotal; i++)
        {
                if ( ticket = HistoryDealGetTicket(i) > 0 ) 
                {
                    symbolps = HistoryDealGetString(ticket,DEAL_SYMBOL);
                    entry = HistoryDealGetInteger(ticket,DEAL_ENTRY);
                        
                    if ( symbol == symbolps && ( entry == DEAL_ENTRY_OUT || entry ==DEAL_ENTRY_INOUT || entry ==DEAL_ENTRY_IN ) )
                    {
                         //--- get deals properties
                         id    = HistoryDealGetInteger(ticket,DEAL_POSITION_ID);
                         price = HistoryDealGetDouble(ticket,DEAL_PRICE);
                         time  = (datetime)HistoryDealGetInteger(ticket,DEAL_TIME);
                         type  = HistoryDealGetInteger(ticket,DEAL_TYPE);
                         profit= HistoryDealGetDouble(ticket,DEAL_PROFIT);
                 
                         TotProfit += profit;  ( positive & negative value )
                    }                   
                }
        }       
        
}

if this code is correct I also want to be sure that  the entry of type = DEAL_ENTRY_IN ( open trade)  is present in   HistorySelect

Can you give a light on this ??


EDIT : 22-04-23 21-44

Hi William ,
After fighting  with calculating drawdown for every whole DAY  in a correct way, may be i found the correct way and I want to put here my solution :

The general logic is to read data from two separate origin , Specifically :

1. read daily profit for order already executed  with : 

HistorySelect(StartTtime, EndTime ); // you must specify the startin date from D'2023.XX.YY 00:00:01'  to  D'2023.XX.YY 23:59:59' of current day

hstTotal = HistoryDealsTotal();
::
dayProfit += profit;

2. read current profit for the order(s) still not executed ( in witch every tick can change value ) with:

hstTotal = PositionsTotal();

for( int z = hstTotal; z >= 0; z--) {

ulong ticket = PositionGetTicket(z);
::::

  openProfit += profit;

dailyProfit = dayProfit +openProfit;

double dailyDrawdown = dailyProfit  / balance * 100; // this is the daily drawdown  

// then you can apply the logic to close current order if your  dailyDrawdown is negative and  is bigger then
if (  dailyDrawdown < 0  && MathAbs( dailyDrawdown  )  >maxdailyDrawdown  ) 

::::

// from this point one can also calc the monthly  drawdown   , i think...

Can you confirm the correctness of this logic so that could be useful for others..

thank you

Reason: