Dinesh Tarte Dinesh is software Engineer by profession and a trader in equity and commodity markets. He does research with various technical analysis and loves to develop strategies in amibroker. Remarkably he is a student of Marketcalls and does freelancing for creating custom indicators in Amibroker

Backtestable Open Range Breakout ( ORB ) Study for Amibroker

5 min read

The main challenge with the classic ORB Study for Amibroker is that it generates too many signals on the intraday charts and backtesting is not possible with such a study. This problem has been overcome by Mr Dinesh Tarte by fine tuning ORB study makes the code backtestable

Dinesh is software Engineer by profession and a trader in equity and commodity markets. He does research with various technical analysis and loves to develop strategies in amibroker. Remarkably he is a student of Marketcalls.

ORB Trading rules
1)Buy after 11.15a.m if the market crosses above ORBH ( ORB-High) and exit logs at 150pts profit in case of banknifty or exit around 3.30p.m or if the stoploss ORBL ( ORB-Low) hits.

2)Short after 11:15a.m if the market crosses below ORBL ( ORB-Low) and exit shorts at 150pts profit in case of banknifty or exit around 3.30p.m or if the stoploss ORBH ( ORB- High) hits

Backtestable ORB

[wp_ad_camp_5]

 
What does this code do?
Sample ORB strategy is shown above over Bank Nifty April Futures Charts. Where the Green and Red arrows indicates Buy and Sell Signals Respectively. And the Green and Red Star indicates Buy Exit and Sell Exit Respectively.

The ORB Study calculates the high (ORBH) and low (ORBL) between the first two hours i.e. from 9.15a.m to 11.15a.m .It takes the signal descision when the market cross the range on or either side after 11:15a.m. The below parameter in the code mentions the market open, close time and signal breakout time. Here signal breakout will occur only if the ORBH and ORBL break out after 11:15a.m.

Market_Start_Time=091500;
Market_Open_Brakeout=111500;
Market_end_time=151500;

The code has been optimized for Bank Nifty and it also exits at profit (say 150 points in case of Bank Nifty). However you can change the values according to your favorite stock/index. The following code decide the target point

target_point=Optimize(“target_point”,150,20,200,1);

Stop Loss Hits in Case of Two Conditions

1) If the 1st signal is active and market breaches the stoploss i.e ORBL is the stop loss in case of active buy signal
and ORBH is the stoploss in case of active sell signal

2)The position will be closed at the end of the day .

This system is purely optimized for bank nifty and consider the lot size of 50 (2 lots) in case of Bank Nifty. This code can be used with high beta stocks like SBI and others and fine tuned with the break out time like first 1 hr or ½ hr depending upon your analysis and experience with ORB study.

Amibroker Settings

The following settings is mandatory for this code to work properly.

Goto->Tools->Preferences->Intraday and Set time of first inside tick bar as shown below

Preferences

Download Backtestable ORB code for AmibrokerBackTestable ORB

Amibroker Code

// Developed by Dinesh R Tarte
_SECTION_BEGIN("Backtestable ORB");
SetBarsRequired(100000,0);
GraphXSpace = 15;
SetChartOptions(0,chartShowArrows|chartShowDates);
SetChartBkColor(ParamColor("bkcolor",ColorRGB(0,0, 0)));
GfxSetBkMode(0); 
GfxSetOverlayMode(1);
SetBarFillColor(IIf(C>O,ParamColor("Candle UP Color", colorGreen),IIf(C<=O,ParamColor("Candle Down Color", colorRed),colorLightGrey)));
Plot(C,"nPrice",IIf(C>O,ParamColor("Wick UP Color", colorDarkGreen),IIf(C<=O,ParamColor("Wick Down Color", colorDarkRed),colorLightGrey)),64,0,0,0,0);

_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));

Market_Start_Time=091500;
Market_Open_Brakeout=111500; 
Market_end_time=151500; 
 
//need to consider 60 min insted of 100 //Market_Signal_time=Market_end_time - Market_Open_Brakeout;
Market_Signal_time=033000;
Min_in_signal_time=2190;                

Bars_in_Signal=210/5;
Total_No_Of_Every_Day_Bar=72;


target_point=Optimize("target_point",150,20,200,1);
SetPositionSize(1,spsShares);

//Total_No_Of_Every_Day_Bar=(Market_end_time-Market_Start_Time)/5(Time in Min)
printf("n Bars in the signal is =>" + Bars_in_Signal);
//(for 5 Min Chart divide by 5 AND for 15 Min Charts divide by 15 (Min))
printf("n market singal Time=>"+Market_Signal_time);
SetTradeDelays(1,1,1,1);
ST=MArket_start_time=091500;
BT=brake_out_time=111500; 
Currtime =TimeNum(); 
Currentdate=DateNum(); 
afterbreakout0 = Cross(TimeNum(),BT); 
printf("n Todays date is +" +NumToStr((Currentdate),formatDateTime )); 
Curren_Dae=Day(); 
SetPositionSize(1,spsShares);   
 
//--New Day & Time. End Day & Time . End Day & Time is null till end of day 1 
  //IT will check the condition of the each bar .
NewDay = Day()!= Ref(Day(), -1); 
printf("n Day+starttime  : " + Day() ); 
EndDay = (Day()!= Ref(Day(), 1)); 

printf("n newday Value is=>"+NewDay);
printf("n End day value is =>"+EndDay); 




printf("n EndDay  : " + EndDay ); 
starttime = Cross(TimeNum(),ST);
TimeNum()>ST; 
//it will caluclate the highest and lowest array from the start time 
//.its go on calculating entire array till next Day 
 Exit_Time = TimeNum() > Market_end_time; 

Highest_science = HighestSince(starttime,H,1); 
Lowest_science =LowestSince(starttime,L,1); 
 
WriteIf (IsNan(Highest_science) , "higest_scinece value is = 
"+Highest_science+"  ","")+"n"+ 
 
 
//it will calculate the high and low value of the BT time 
 
ORBH = ValueWhen(afterbreakout0,Highest_science,1); 
ORBL = ValueWhen(afterbreakout0,Lowest_science,1); 
 
 
//Plots ORB High and Low Line 
Plot(ORBH,"",colorGreen,styleDots); 
Plot(ORBL,"",colorBlue,styleDots); 
Buy=IIf(Cross(C,ORBH) AND (Currtime>BT) ,True,Null); 
Short =IIf((Cross(ORBL,C) AND (Currtime>BT)) ,True,Null); 
Shortflag=-99;
BarsToday = 1 + BarsSince( Day() != Ref(Day(), -1));
Buy_Bar_count=ValueWhen(Buy,BarsToday,1);
Short_bar_Count=ValueWhen(Short,BarsToday,1);

printf("n Buy signal coming at the bar => "+Buy_Bar_count);

printf ("n Today's date is =>"+ Date()); 
printf ("Bar is =>"+BarsToday); 


ReminingBarinDay=ReminingBarinDay_short=60;

Buy=ExRemSpan(Buy,ReminingBarinDay);
Short=ExRemSpan(Short,ReminingBarinDay_short) ;

//this is for when buy is active and short signal is coming
sellflag_short=IIf(Short==1,   True,0);
//Shortflag=Buyflag=IIf(NewDay == 1 ,2,Null);

//this is for when short is active and Buy signal is coming

Coverflag_buy=IIf(Buy==1,True,0);

// to set the flag when buy condition is true

 IIf(Buy==1,Buyflag=1,0);

BuyPrice1=ValueWhen(Buy,C,1);
SellPrice1=BuyPrice1+target_point; 

printf("n before sell signal coming SellPrice:-" +SellPrice1);
Sell_Cond=Cross(H,SellPrice1);
//Sell_Cond=IIf(H >=SellPrice1,True,False);
printf("n DD->Sell  Cond Value is =>"+Sell_Cond);

//short flag is used to close the condition when buy condition is active at the same time short is also active (in short when the buy signal is active short signal is coming so closing the position of buy @short price);

printf("n Buy flag value is =>"+BuyFlag);
printf("n Sell_flag_short value is =>"+Sellflag_short);


//Shortflag=Close the existing position when Short Signal arrived
//End Day:-close the open position at the end of the day 
    Sell=IIf(((BuyFlag==1) AND  ((Sell_Cond==1) OR (EndDay==1))),True ,Null);

//this is for when buy is active and short signal is coming
       Sell=IIf(((BuyFlag==1) AND (Sellflag_short==1 ) ),True ,Sell);






Shortflag=Buyflag=IIf(NewDay == 1  ,2,Null);

Sell=ExRem(Sell,Buy);



printf("n Buy Verible value is =>"+Buy);
printf("n Sell Verible value is =>"+Sell);

SellPrice=ValueWhen(Sell,H,1);
printf("n  sellsell price is :-" +SellPrice); 

ShortPrice=ValueWhen(Short,C,1); 

//Setting the flag when short condition is active

 IIf(Short==1,Shortflag=1,0);
 
printf("Short flag value is =>"+Shortflag);

printf("n short sell flag value is =>" +Sellflag_short);

ShortPrice1=ValueWhen(Short,C,1);

//Cover the Condition Of the Lower point

CoverPrice1=ShortPrice1-target_point;

printf ("Short price is for price1 is =>"+ ShortPrice1);
printf ("CoverPrice is for price1 is =>"+ CoverPrice1);
 
Cover_cond= IIf(L<=CoverPrice1,True,False); 
printf("n Cover Cond Value is =>"+Cover_Cond);

//Cover the position when Short is active AND Current price(L) is Less then Condition price OR Close the position end Of the Day  

Cover=IIf((ShortFlag==1) AND (Cover_Cond==1 OR EndDay==1),True,Null) ;

//this is for covering the position when buy signal is appering when short signal is active .clsoing the existing short position

Cover=IIf((ShortFlag==1) AND (Coverflag_buy==1),True,Cover);

printf("n Cover value is =>"+Cover);

CoverPrice=ValueWhen(Cover,C,1);

printf("n Cover price is ->"+CoverPrice);

Cover=ExRem(Cover,Short);

PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40); 
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50); 
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50); 
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45); 
PlotShapes(IIf(Sell, shapeStar, shapeNone),colorGreen, 0, H, Offset=-70); 
PlotShapes(IIf(Cover, shapeStar, shapeNone),colorBlue , 0, L, Offset=-70);

Note : Code tested with Amibroker 5.60 version
Bank_nifty_ORB – Backtest Report_April (1)

Dinesh Tarte Dinesh is software Engineer by profession and a trader in equity and commodity markets. He does research with various technical analysis and loves to develop strategies in amibroker. Remarkably he is a student of Marketcalls and does freelancing for creating custom indicators in Amibroker

Fisher Transform – Amibroker AFL Code

The Fisher Transform is a technical analysis indicator developed by John F. Ehlers, designed to identify potential turning points in the price movements of...
Rajandran R
2 min read

My Experience Converting SSL Hybrid from PineScript to Amibroker…

As a trader and coding enthusiast, I often find myself needing to translate trading indicators from one programming language to another. Recently, I embarked...
Rajandran R
8 min read

Line Trading – OpenAlgo Automation Module for Amibroker Users

The line Trading Automation tool is designed for Manual traders who want to perform level-based trade execution faster and also bring some advanced trade...
Rajandran R
59 sec read

29 Replies to “Backtestable Open Range Breakout ( ORB ) Study for…”

  1. I am using Amibroker 5.30. This code is not working for me. can you mention any changes in the code to make it work.
    Thanks in advance.

    1. Rajan,
      You need to do changes as mentioned in the Amibroker Settings section .Please refer it

  2. Respected Sir,
    LeMan System Indicator which is MT4 CODE, which is using EURO/USD
    is this same code like ORB
    (ostryforex)

    Warms Regards
    Chinmay

  3. Dear Rajan,
    am using amibroker 5.5 ,this afl I can load but it is a plain price chart without any buy/sell & exit arrows ,please help

  4. hello sir, this is not working i m change amibroker setting also but plan price chart display only plz help me

  5. I just uploaded above AFL to my amibroker and it works fine as well. Only one problem, even after making preference changes, I cannot see buy/sell arrows as shown in pic. Any specific reason? Please guide.

  6. Hello friend,
    Would like to know, the candle time which needs to be set in for this code to work well.
    I trade only on Bank Nifty and would appreciate your response.
    Regards,
    Abhinav

  7. Dear Sir
    1.The back test report is of how many days?
    2.As per attached back test report ,Risk to reward ratio is 70.30. Does this mean that risk is 70% & Reward is only 30% or it is opposite?
    Pl. reply
    Regards

  8. hello

    i am very much thankful for this code ..sir please help me ..every thing is perfect i am using this for nse future .so please tell me that instead of setting traget profit interms of point just by percentage .means 1 %, 2 % so that when the signal gives buy or sell signal it shows the profit target by percentage set by any user…

    1. dear sir
      first lot you book at 50 points in nifty future when you book the second lot?

  9. HELLO SIR,
    I WANT AUTO-TRADE IN NSE .I AM MANUALY TRADING WITH RKSV SECURITIES .{DISCOUNT BROKER} .CAN YOU ME PROVIDE AUTO-TRADING S/W AND ALONG WITH STRATEGIES. I CAN GIVE YOUR FEES. REPLY ME. THANK YOU.

  10. Hi Sir,
    i am trying to import this into amibroker but its showing some error is:

    Error 32.
    Syntax error, unexpected IDENTIFIER. Is there semicolon missing at the end of the previous line?

    Use ‘Edit Formula’ to correct error”

    could u help out
    Thanking u

  11. Hi,
    Only candlestick bars are showing but buy/sell signals and ORBL AND ORBH lines are not showing solution please,, i changed setting as per u but still its not showing.
    Thank u

  12. I know im a little late in looking into this strategy so if someone is still looking into this thread do pitch in..
    I wanted to integrate this with a custom strategy of my own so wanted to understand the parameters pointed to below :

    Market_Start_Time=091500; <<< ———————- Opening of the Market.
    Market_Open_Brakeout=111500; <<< ———————- Duration upto which you would like to identify the breakout Range.
    Market_end_time=151500; <<< ———————- End of Market for Intraday players i believe.

    //need to consider 60 min insted of 100 //Market_Signal_time=Market_end_time – Market_Open_Brakeout;
    Market_Signal_time=033000; <<< ———————- What is this for ? Does this need to be changed. Why do you reference 100 here ? I did not understand how you came up with the value 033000 and what it means.
    Min_in_signal_time=2190; <<< ———————- No idea on this as well.

    Bars_in_Signal=210/5;
    Total_No_Of_Every_Day_Bar=72;

    I am asking the above questions because im unable to interpret what needs to be changed if i change the breakout duration. Also the backtest does not produce any results, i use AB 5.6.

  13. End of day is finding out based on next bar date. So next bar will come only in the next day. So what will happen is exit signal will show in the days end bar only when the next day is started.

    Code
    EndDay = (Day()!= Ref(Day(), 1));

    Instead we can make a time based exit. That will work correctly I hope.

    Replace the above code with

    EndDay = (TimeNum() >= ParamTime(“Exit Time”, “11:15:00 PM”));

    This will exit the position at 11:15 PM.

    1. I optimized for Mcx Its Working Great Change Market opening 10 And Breakout on 10:15 Crude Target 10 points Zinc 50 paisa Ng 80 paisa Copper 2 rs lead 50 Allu 40 paisa Gold 28 point Silver 100 All Trade Ends on 12 clock Awesome

      The editor Thanks

      1. Appu, Please explain how did you change the time, Buy order entry / sell order entry and fix target..pl explain

  14. Hi
    I am using Amibroker 6.00.2.
    I have applied the required settings as mention in above code.
    I could see the grapgh well, but trades are not getting fetched in Backtest report.
    Please could you help?
    Thank You!

  15. Note : Code tested with Amibroker 5.60 version
    Bank_nifty_ORB – Backtest Report_April (1)

    Kind Attention: Mr. Dinesh Tarte/ Rajandaran,

    With reference to above, sir would like to point out that your candle signal for Buy is executing at the “High” parameter instead of “Open” of the next candle. And vice-versa for short/sell.

    Can you please correct this code and upload the corrected version.

    Thanks

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More