63

AFL of the week: Intraday Opening Range Breakout system

Opening Range Breakout (ORB) is probably the most popular intraday trading system. It takes into account the volatility of first few minutes of trading hours, and any breakout above or below the price range of this period is considered as a possible trade. The credit behind this system goes to Sir Tony Crabel who published a book in 1990 to explain this strategy in detail.

How to trade Opening Range Breakout?

First of all you have to decide a specific period in the intraday chart which would be called as Opening range period. This period may vary depending on the security you are trading. The high made during this period is called Opening Range High and the low is called Opening Range Low. The system gives Buy signal when price crosses above Opening range while it gives Sell signal when price crosses below Opening range. Aggressive traders may take the trade as soon as breakout happens while conservative traders may wait for a specific period or price move before entering. The time range between which the trade can be taken is called Trade Start time and Trade End time. There can be pre-defined targets and stoploss depending on your risk management but all positions should be necessarily squared of at the end of day. Below are the parameters for the AFL we are going to discuss below:

  • Opening Range Period: 5 Minutes
  • Trade Start Time: 55 minutes after Market Open
  • Trade End Time: 70 minutes afte Market Open

Please note that this AFL is available in its raw form in most of the online forums and communities. We have just optimized it for Nifty Futures and made it backtestable.

Please visit Trading Tuitions Academy to learn AFL coding and create your own Trading systems.

AFL Overview

Paramter Value
Preferred Timeframe Intraday 5 minute
Indicators Used None
Buy Condition
  • Current candle high is greater than Opening range High.
  • Between 55 to 70 minutes of Market Open time.
Short Condition
  • Current candle low is less than Opening range Low.
  • Between 55 to 70 minutes of Market Open time.
Sell Condition
  • Stop Loss hit
  • Target Met
  • End of Day
Cover Condition
  • Stop Loss hit
  • Target Met
  • End of Day
Stop Loss 0.5%
Targets 3%
Position Size 150 (fixed)
Initial Equity 200000
Brokerage 50 per order
Margin 10%

AFL Code

//------------------------------------------------------
//
//  Formula Name:    Intraday Opening Range Breakout system
//  Author/Uploader: Trading Tuitions
//  E-mail:          support@tradingtuitions.com
//  Website:         www.tradingtuitions.com
//------------------------------------------------------


function ParamOptimize( pname, defaultval, minv, maxv, step ) 
{ 
return Optimize( pname, 
Param( pname, defaultval, minv, maxv, step ), 
minv, maxv, step ); 
} 
 
_SECTION_BEGIN("Intraday Opening Range Breakout system");  

SetOption( "InitialEquity", 200000);
SetOption("FuturesMode" ,True);
SetOption("MinShares",1);
SetOption("CommissionMode",2);
SetOption("CommissionAmount",50);
SetOption("AccountMargin",10);
SetOption("RefreshWhenCompleted",True);
SetPositionSize(150,spsShares);
SetOption( "AllowPositionShrinking", True );
 
//--Intraday time frame  
TimeFrameSet(in5Minute); 
TimeFrameInMinutes = 5; 
 
//--Define all params  
EntryBufferPct = ParamOptimize("Entry Buffer %", 0, 0, 2, 0.1); 
SLPct = ParamOptimize("SL %", 0.5, 0.5, 2, 0.5); 
TargetPct = ParamOptimize("Target %", 3, 0, 3, 0.5); 
MaxTarget = 100; 
TargetPct = IIf(TargetPct == 0, MaxTarget, TargetPct);  
EntryTimeStart = ParamOptimize("Entry Time Start (Minutes)", 55, 5, 120, 5); 
EntryBarStart = floor(EntryTimeStart/TimeFrameInMinutes) - 1; 
EntryTimeEnd = ParamOptimize("Entry Time End (Minutes)", 70, 10, 300, 10); 
EntryBarEnd = floor(EntryTimeEnd/TimeFrameInMinutes) - 1; 
EntryBarEnd = IIf(EntryBarEnd < EntryBarStart, EntryBarStart, EntryBarEnd);   
 
//--Plot Price Candle Chart 
SetChartOptions(0,chartShowArrows|chartShowDates); 
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) )); 
Plot( Close, "Price", colorWhite, styleCandle );
 
//--New Day & Time. End Day & Time . End Day & Time is null till end of day 1   
NewDay = (Day()!= Ref(Day(), -1)) OR BarIndex() == 0;  
printf("\n NewDay  : " + NewDay );  
EndDay = (Day()!= Ref(Day(), 1));  
printf("\n EndDay  : " + EndDay ); 
FirstBarTime = ValueWhen(NewDay,TimeNum(),1);  
EndTime = ValueWhen(EndDay,TimeNum(),1); 
SquareOffTime = EndTime; 
 
//--Calculate ORB, and SL 
HighestOfDay = HighestSince(NewDay,H,1);  
LowestOfDay = LowestSince(NewDay,L,1);  
ORBH = ValueWhen(NewDay,HighestOfDay ,1) * (1 + (EntryBufferPct/100));  
ORBL = ValueWhen(NewDay,LowestOfDay ,1) * (1 - (EntryBufferPct/100));  

 
//--Find Buy, Sell, Short & Cover Signals 
BarsSinceNewDay = BarsSince(NewDay);  
BuySignal = (H >= ORBH) AND (BarsSinceNewDay  > EntryBarStart);  
printf("\nBuySignal : " + BuySignal );  
ShortSignal = (L <= ORBL) AND (BarsSinceNewDay  > EntryBarStart) ;  
printf("\nShortSignal  : " + ShortSignal );  
BarsSinceLastBuySignal = (BarsSince(Ref(BuySignal,-1)) + 1); 
BarsSinceLastShortSignal = (BarsSince(Ref(ShortSignal,-1)) + 1); 
BarsSinceLastEntrySignal = Min(BarsSinceLastBuySignal, BarsSinceLastShortSignal); 
BothEntrySignalsNull = IsNull(BarsSinceLastBuySignal) AND IsNull(BarsSinceLastShortSignal); //true for start of Day 1 
printf("\n\nBarsSinceNewDay : " + BarsSinceNewDay );  
printf("\nBarsSinceLastBuySignal : " + BarsSinceLastBuySignal );  
printf("\nBarsSinceLastShortSignal : " + BarsSinceLastShortSignal );  
printf("\n BarsSinceLastEntrySignal : " + BarsSinceLastEntrySignal);  
Buy = (H >= ORBH) AND (BarsSinceNewDay  > EntryBarStart) AND (BarsSinceNewDay <= EntryBarEnd) AND ((BarsSinceNewDay < BarsSinceLastEntrySignal) OR BothEntrySignalsNull );  
Short = (L <= ORBL) AND (BarsSinceNewDay  > EntryBarStart) AND (BarsSinceNewDay <= EntryBarEnd) AND ((BarsSinceNewDay < BarsSinceLastEntrySignal) OR BothEntrySignalsNull );  
BuyPrice = IIf(Buy, Max(ORBH,O), Null);  
ShortPrice = IIf(Short, Min(ORBL,Open), Null);  

ORBHSL = ValueWhen(BuyPrice,BuyPrice) * (1-(SLPct/100));   
ORBLSL = ValueWhen(ShortPrice,ShortPrice) * (1+(SLPct/100)); 
ORBHTarget = ValueWhen(BuyPrice,BuyPrice) * (1+(TargetPct/100)); 
ORBLTarget = ValueWhen(ShortPrice,ShortPrice) * (1-(TargetPct/100)); 

Sell = (L <= ORBHSL) OR (H >= ORBHTarget) OR (TimeNum() > SquareOffTime-1) AND (BarsSinceNewDay > BarsSinceLastBuySignal);  
Cover = (H >= ORBLSL) OR (L <= ORBLTarget) OR (TimeNum() > SquareOffTime-1) AND (BarsSinceNewDay > BarsSinceLastShortSignal);  

SellPrice = IIf(Sell, IIf(H >= ORBHTarget, ORBHTarget, Max(ORBHSL, L)), Null);  
CoverPrice = IIf(Cover, IIf(L <= ORBLTarget, ORBLTarget, Min(ORBLSL, H)), Null);  

printf("\nBuy : " + Buy );  
printf("\nSell : " + Sell );  
printf("\nShort : " + Short );  
printf("\nCover : " + Cover );  

printf("\nORBH : " + ORBH );  
printf("\nORBL : " + ORBL );  
printf("\nBuyPrice : " + BuyPrice );  
printf("\nShortPrice : " + ShortPrice );  

printf("\nORBHSL : " + ORBHSL );  
printf("\nORBLSL : " + ORBLSL );  
printf("\nORBHTarget : " + ORBHTarget );  
printf("\nORBLTarget : " + ORBLTarget );  
 
//--Handle if ORB broken both sides on same bar 
//--And remove duplicate Sell & Cover signals, since ExRem did not work as needed when Buy & Sell on same bar 
orbBothSides = IIf(Buy AND Short, 1, 0);  
Buy = IIf(orbBothSides AND C <= O, 0, Buy);  
Short = IIf(orbBothSides AND C > O, 0, Short);  
Sell = IIf(orbBothSides AND C > O AND (L <= ORBHSL), 1, Sell);  
Sell = IIf((BarsSince(Buy) < (BarsSince(Ref(Sell,-1))+1)) OR (BarsSince(Buy) AND IsNull(BarsSince(Ref(Sell,-1)))),Sell,0); 
Cover = IIf(orbBothSides AND C <= O AND (H >= ORBLSL), 1, Cover);  
Cover = IIf((BarsSince(Short) < (BarsSince(Ref(Cover,-1))+1)) OR (BarsSince(Short) AND IsNull(BarsSince(Ref(Cover,-1)))),Cover,0); 


//Plot(IIf(BarsSinceNewDay > BarsSinceLastBuySignal,ORBHSL,NULL),"BuyStopLoss",colorRed,styleDashed); 
//Plot(IIf(BarsSinceNewDay > BarsSinceLastShortSignal,ORBLSL,NULL),"SellStopLoss",colorRed,styleDashed);  
Plot(ORBH,"",colorBlue,styleDots);
Plot(ORBL,"",colorBlue,styleDots);


/* Plot Buy and Sell Signal Arrows */
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(Cover, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Cover, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, 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);

 
//--Restore time frame  
TimeFrameRestore();  
_SECTION_END();

AFL Screenshot

The blue dotted line shows the Opening Range.

Intraday ORB

Backtest Report

 Paramter Value
  Fixed Position Size
Initial Capital  200000
Final Capital 662679.55
Backtest Period 01-Jan-2015 to 22-03-2016
Timeframe 5 Minutes
Net Profit % 231.34%
Annual Return % 165.97%
Number of Trades 259
Winning Trade % 54.44%
Average holding Period 55.46 periods
Max consecutive losses 13
Max system % drawdown -20.02%
Max Trade % drawdown -12.83%

Download the detailed backtest report here.

Equity Curve

This strategy has a very smooth and linear equity curve with minimum drawdowns. Check it out.

Intraday_ORB_EquityCurve

Additional Amibroker settings for backtesting

Goto Symbol–>Information, and specify the lot size and margin requirement. The below screenshot shows lot size of 75 and margin requirement of 10% for NSE Nifty:

Symbol Info_Nifty

Disclaimer:

All the AFL’s posted in this section are for learning purpose. Trading Tuitions does not necessarily own these AFL’s and we don’t have any intellectual property rights on them. We might copy useful AFL’s from public forums and post it in this section in a presentable format. The intent is not to copy anybody’s work but to share knowledge. If you find any misleading or non-reproducible content then please inform us at support@tradingtuitions.com

Related Posts

63 Comments

  1. SIR, BROKERAGE RS.50/- FOR 2 LOT OF NIFTY INCLUDING TAXES IS VERY LESS

    • Hi Karan,
      I agree that this brokerage is extremely low. You may adjust it from the AFL itself.

  2. SIR, KINDLY POST THE PERFORMANCE OF YOUR BREAKOUT AFL FOR THE PERIOD 1/1/2013 TO 31/12/2013 AND 1/1/2014 TO 31/12/2014, I WOULD BE OBLIGED

  3. Hello Sir, Is it Possible for you to Provide the Results for 15 mins and 30 mins of this ORB System, I guess Winning Percentage of Trades would be higher

    • Hi Rohit,
      For Nifty, the profitability is highest in 5 minutes ORB. I haven’t tried for other stocks. You may change it yourself from AFL and compare the results. Let me know if you face any issues.

      • It seems the results are too good to believe! Has anyone really run this in real time and tested it? What about whipsaws?

        Also can this be used to auto trigger buy/sell orders, I mean does it take care of profit booking SL points properly without manual intervention?

  4. SIR, WAITING FOR THE PERFORMANCE SHEET OF YOUR BREAKOUT AFL FOR THE PERIOD 1/1/2013 TO 31/12/2013 AND 1/1/2014 TO 31/12/2014. THANKS & REGARDS

  5. SIR, WAITING FOR THE PERFORMANCE SHEET OF YOUR BREAKOUT AFL FOR THE PERIOD 1/1/2013 TO TO 31/12/2014. THANKS & REGARDS

  6. SIR, KINDLY PROVIDE THE PERFORMANCE SHEET OF YOUR BREAKOUT AFL FOR THE PERIOD 1/1/2013 TO TO 31/12/2014. I DO NOT HAVE DATA FROM 1/1/2013 TO 31/12/2014. I WOULD BE OBLIGED.
    THANKS & REGARDS

  7. Sir
    Will you please post the similar strategy for bank Nifty also. I will be very thankful. May I know your contact number please

  8. Sir u are doing a great job by providing such nice strategies. But please provide back tested data for longer time like 4-5 years. Because it will be beneficial to the readers as in this duration market looks all the phases. That will give a fair idea about the strategy. You have already given some back test report for even 15 years duration. Sir please give back test report for 5 years for this and intraday high low strategy. I will be very thankful. Regards
    Ramendra singh

    • Hi Ramendra,

      We would keep that in mind whenever we post any Intraday strategy in future. Thanks for the kind suggestion!

  9. SIR, HUMBLE REQUEST, KINDLY PROVIDE THE PERFORMANCE SHEET OF YOUR BREAKOUT AFL FOR THE PERIOD 1/1/2013 TO 6/7/2016.
    I WOULD BE OBLIGED.

  10. i need some clarity on at what rate to initiate the trade a situation where 5 minutes high is 8455 and and at 10.10 it is trading at 8475 should the long be initiated and in opposite case if it is trading below 20 points from the low is ths short trade on

  11. SIR, I HAVE REQUESTED MANY TIMES TO KINDLY PROVIDE THE PERFORMANCE SHEET OF YOUR BREAKOUT AFL FOR THE PERIOD 1/1/2013 TO 8/7/2016.KINDLY HELP AND PROVIDE THE REQUESTED PERFORMANCE SHEET.
    I WOULD BE OBLIGED.

  12. Sir I have one query. As in the backrest report the max trade drawdown is approx 35000. Sir when sl is fixed at .5% & quantity at 150 and trade is intraday then how a single trade can make a drawdown of 35000. Please clarify

    • Hi Ramendra,

      Drawdown is the max difference in peak to trough capital. It cannot be necessarily from one trade. 35000 Drawdown could have happened due to multiple consecutive losing trades.

  13. Thanks for sharing the afl, Sir.
    Very well done with the backtesting. None of the trade took positional.
    I have backtested this with NIFTY with 15m TF from the year 2008 and i got 42% winning trade and annual returns of 10.28% that is bit less!
    Anyway a purely intraday strategy with minimum profit guarantee.

  14. in intraday trading 3 % target almost never achievable… so how it shows 54.44% winning trade please solve my query

  15. Dear Sir,
    Can you explain entry,exit ,stoploss, target with example
    Please sir

  16. Sometimes the Nifty/Bank Nifty can make a big move during the first 55 minutes so my question is why wait for 55 mins,what is the significance of this 55 mins.
    Why can’t we trade once a candle closes above or below the first candle range?

  17. A small query
    I am not getting Blue line plotted by you in screen shot…can u please rectify code and update ? A just display matter.
    Secondly
    Default parameters already there in AFL coding still in amibroker settings we have to mention 200000 to get backtesting results match with your displayed results here ?

    Thanks & update

  18. Sir, Gr8 Work, Can I have download Link, Copy and Paste not working 🙁

    • Hi Chanakya,

      That is strange! We haven’t restricted copy-paste for any AFL code

  19. I suggest to please make it more Autostylish like robots do. Please add if possible 3 more things. Take Profit option in points which should show in charts like target 1 and target 2 and Colour volumes on bottom also. Also if you can add boxes or dots which will show 15 mins and 30 mins trend green or red also….thanks

  20. sir, thanks for this incredible code.
    My question is ,if I want to change entry time window from 55 to 70 to say for example, 30-45, then where I’m the code should I change that

    • Hi Sachin,

      You would need to change in the below two lines:

      EntryTimeStart = ParamOptimize(“Entry Time Start (Minutes)”, 55, 5, 120, 5);
      EntryTimeEnd = ParamOptimize(“Entry Time End (Minutes)”, 70, 10, 300, 10);

  21. Would you mind doing the backtest (or add backtest feature for any Harmonic Pattern AFL out there)?

    • Hi Hari,

      Definitely, can you explain the Harmonic strategy you are talking about?

  22. Thanks for the post and the AFL.
    Few queries: 1. Max trade DD as u have explained is largest peak to valley decline experienced in any single trade. so if the largest trade loss is 6821/-then how come max trade DD is 33849. 2. The target is 3% of what , the opening range ? or what

  23. Sir its to complicated
    sir please write a code for simple orb buy and sell signal

    • Hi Thej,

      Please let me know the part you did not understand. I will try to simplify it for you 🙂

  24. Hi,
    I have Amibroker installed. Can anyone please suggest a good, reliable NSE IntraDay Real Time Data supplier ? Sorry, couldnt find a relevant post to put this question.

  25. Sir, your afl is so good and if u add popup alert when buy sell signal came to this afl it is more helpfull …..
    thank you.

  26. Hi
    I am using Amibroker 6.00.2.
    I have applied the required settings as mentioned above.
    I could see the graph well, but trades are not getting fetched in Backtest report. Trade List after backtest comes as blank.
    Please could you help?
    Thank You!

  27. Hello, Great work.. Appreciate if you can let me know the same strategy can be applied to Bank nifty as well… ” The formula seems that the formula references FUTURE quotes.
    If you backtest this system you may receive outstanding results
    that CAN NOT be reproduced in real trading “. I have read that it should not refer to future quotes.. Pls do give me your valuable feed back.

  28. How can we do autotrading using this formula, sorry i am new to algo trading

  29. Please clarify why the ORB shows 14.15 as the time. To clarify,
    Open high and low is set at market open or 55 mts after market open?

  30. hi
    i want to print buyprice and other prices.
    i am using below code but it is not printing the price.

    dist = 1.5*ATR(10); for( i = 0; i < BarCount; i++ )
    { if( Buy[i] ) PlotText( "Buy\n"+ " @" + BuyPrice, i, L[ i ]-dist[i], colorGreen, colorYellow );
    if( Short[i] ) PlotText( "Short\n" + " @" + ShortPrice, i, H[ i ]+dist[i], colorRed, colorYellow );
    i dont want to print close price of the candle. i want to print my entry price and my exit price as per the system.

  31. Hi
    I am using Amibroker 6.00.2.
    I have applied the required settings as mentioned above.
    I could see the graph well, but trades are not getting fetched in Backtest report. Trade List after backtest comes as blank.
    Please could you help?
    Thank You!

    • Hi Pushpak,

      Something to do with your backtester settings. By any chance have you specified incorrect timeframe in your backtest settings?

      • I also think thatr this has to do something with the settings. In backtest, the periodicity is set to default “Daily”. In the main window as well, the periodicity is set to Daily. Since the periodicity timeframe is set in the code, i thought this wont influence.

  32. I have tested your code with Nifty futures, but result is just opposite to yours. I don’t know why…. It’s copy pasted and then backtested. Can you provide your backtested pdf?

Leave a Reply

Your email address will not be published.