NR7 Trading Strategy: Low Risk High Reward

Narrow Range trading strategy or NR7 Trading strategy is a breakout based method which assumes that the price of a security trends up or down after a brief consolidation in a narrow range. The default look back period of this strategy is 7 days which means that if the price range of any particular days is lowest as compared to last 7 days, then that day is termed as NR7 day. Here the range is calculated as the difference between High and Low of the particular day. The day following NR7 day acts as a confirming factor on where the price will move further. Breakout of the High of NR7 candle with high volumes indicates bullishness, while breakout of Low of NR7 candle indicates bearishness. The philosophy behind the pattern is similar to the Bollinger Band Squeeze: a volatility contraction is often followed by a volatility expansion. Narrow range days mark price contractions that often precede price expansions. See the below chart for visual explanation:


Image Source:

Further in this article we’ll go through an Amibroker trading system based on NR7 strategy. This strategy seems to work very well in indexes especially Nifty and Banknifty. It takes very few trades in the year, but still happens to catch big moves. This is the reason we named it low risk high reward strategy

Read our article on AFL tutorial here.

NR7 Trading Strategy Overview

Paramter Value
Preferred Timeframe Daily
Indicators Used None
Buy Condition Previous candle is NR7 candle, and current candle has a Gap-Up opening.
Short Condition Previous candle is NR7 candle, and current candle has a Gap-Down opening.
Sell Condition Based on Target and Stop Loss
Cover Condition Based on Target and Stop Loss
Stop Loss 1% (fixed)
Targets 4% (fixed)
Position Size 50% of Equity
Initial Equity 200000
Brokerage 100 per order
Margin 10%

AFL Code

//  Formula Name:    NR7 Trading Strategy
//  Author/Uploader: Trading Tuitions
//  E-mail:
//  Website:

_SECTION_BEGIN("NR7 Trading Strategy");

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

//Initial Parameters
SetTradeDelays( 0,0,0, 0 );
SetOption( "InitialEquity", 200000);
SetOption("FuturesMode" ,True);
SetOption( "AllowPositionShrinking", True );

Plot( Close, "Price", colorWhite, styleCandle );

range = H-L;
Condition0 = range<Ref(range,-1) AND range<Ref(range,-2) AND range<Ref(range,-3)AND range<Ref(range,-4)AND range<Ref(range,-5)AND range<Ref(range,-6);
NR7 = IIf(Condition0,True, False);

printf("\nNR7 : " + NR7 );  


TGT= Param("Target Percent",4,1,20,1);
SL= Param("SL Percent",1,1,5,1);

Buy=Ref(NR7,-1) AND GapUp();
Short=Ref(NR7,-1) AND GapDown();

Sell= H>=BuyTgt OR L<=BuySL;

Cover=  L<=ShortTgt OR H>=ShortSL;

SellPrice = IIf(Sell, IIf(H>=BuyTgt, BuyTgt, BuySL), Null);  
CoverPrice = IIf(Cover, IIf(L<=ShortTgt, ShortTgt, ShortSL), Null);  

Buy = ExRem(Buy,Sell);
Sell =ExRem(Sell,Buy);

printf("\nBuy : " + Buy );   
printf("\nSell : " + Sell );  
printf("\nShort : " + Short );  
printf("\nCover : " + Cover );  
printf("\nBuyPrice : " + BuyPrice );
printf("\nShortPrice : " + ShortPrice ); 
printf("\nSellPrice : " + SellPrice ); 
printf("\nCoverPrice : " + CoverPrice ); 
printf("\nBuyTgt : " + BuyTgt );  
printf("\nBuySL : " + BuySL ); 
printf("\nShortTgt : " + ShortTgt );  
printf("\nShortSL : " + ShortSL ); 

/* 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(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),colorWhite, 0, H, Offset=25);
PlotShapes(IIf(Cover, shapeStar, shapeNone),colorWhite, 0,L, Offset=-25);


NR7 Trading Strategy: AFL Screenshot

NR7 Trading Strategy

Backtest Report

See the backtest report of NR7 Trading strategy on two major Indices listed in NSE.

Paramter Value
Nifty Bank Nifty
Initial Capital 200000 200000
Final Capital 1482002.22 1691748.00
Backtest Period 01-Jan-2010 to 30-Sep-2016 01-Jan-2012 to 30-Sep-2016
Net Profit % 641.00% 745.87%
Annual Return % 34.59% 56.79%
Number of Trades 33 28
Winning Trade % 54.55% 53.57%
Average holding Period 8.24 periods 4.96 periods
Max consecutive losses 4 3
Max system % drawdown -25.83% -18.52%
Max Trade % drawdown -34.61% -31.09%

Download the detailed backtest report here.

Equity Curve

The NR7 Trading strategy has a close to linear equity curve.



Bank Nifty:


Additional Amibroker settings for backtesting

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

Symbol Info


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


  1. @Admin: What will be the result is “Current Candle” is not gap up/ gap down candle?
    If current candle opens in price range between body of NR7 candle & then goes above NR7 candle high (for long)
    OR goes down below NR7 candle low (for short)
    Does it still qualify the parameter of entry candle?
    Pls clarify.
    Thanks & Regards,

    • Hi Gautam,

      We tested that way but the result was not that great. So we recommend to take positions only during occurrence of gap-up/gap-down.

  2. “Reposted”
    Admin if possible please provide the afl code for the below mentioned strategy along with back test result on crude oil and nse futures.

    Chart Setup
    Time Frame: Intraday Chart 1 Hour
    Technical Indicator: 3EMA (Open)


    Buy Setup:
    1). We look for 1 Hr Candle to Open above 3EMA (Open) and Close above 3EMA (Open).
    2). If the above condition is met place then trigger Buy order on last candle’s high price + 0.10% to avoid immediate price reversal.
    3). SL is Low of the Trigger Candle
    4). Target: Minimum 1% from buy level

    Sell Setup
    1). We look for 1 Hr Candle to Open below 3EMA (Open) and Close below 3EMA (Open).
    2). If the above condition is met place trigger Sell order on the Low price of the last candle – 0.10% to avoid immediate price reversal.
    3). SL is High of the Trigger Candle
    4). Target: Minimum 1% from sell level

    Please give options to
    1. Place SL at 0.50% against buy/sell trigger levels.
    2. Change Intraday Chart from 1 hour to 30 min / 15 min / 5 min etc.

    Thanks in advance

  3. Hii Admin,

    Excellent code…Have you tried testing NR4/NR7 with Inside day ?? Also if you trade a basket of highly liquid front line stocks, how would it work out??

    • Hi Hardik,

      Inside day filter definitely produces good results but reduces the number of trades drastically. So we cannot conclude on the performance of system based on such low trades. And yes it works good for al liquid and high beta stocks.

      • Hi Admin,
        Thanks for the excellent code .Backtested using 5min and hourly timeframes, it shows good performance , but some wrong cover signals , can you add the box at the bottom which shows a buy price and stoploss price. It helps us in visualizing the correct buy/sell price.

      • Thanks for the response…Could you tell me what changes should I make in the existing code if;
        1 I want to test it on basket of liquid stocks,i.e Nifty 50.
        2 Also test it with/without NR4 or ID variations.
        3 Test other exit strategies for example same day exit by EOD.
        You are doing great job by providing the information about trading systems. Why don’t you provide Amibroker training ?? It will be a great help for people with no programming background.

        • Hi Hardik,

          Please go through the other AFL’s posted in this website. You would definitely get answers to these questions. If you fail somewhere, we are there to help. And yes we would plan for Amibroker sessions soon.

  4. A big thanks for this strategy. I have few questions:
    1. Since we have to go long on gap up it means we have to sit in front of our system every day at 09:15 hrs. Will it be possible to get list of NR7 candle formed stocks a day before?
    2. I want to trade in equity and want some settings like always by stock with Rs 1 Lac capital. Don’t add or deduct the profit or loss in next trade. Then simulate the afl for net profit on yearly basis.
    Please guide me.

    • 1) Yes it is definitely possible. A small exploration code would do it. See the NR7 variable and add it to the exploration code.
      2) Replace “SetPositionSize(50,spsPercentOfEquity)” with “SetPositionSize(100000,spsValue)”

    • Yes, daily a NR7 futures stock list will be published by causticnews on twitter.

  5. How can I use trailing stop loss feature rather than using fixed target in NR7 afl. Please guide.

  6. The definition GapUp() or GapDown() is
    “when yesterdays high/low/ is grater/lower/ than todays low/high/”
    At price OPEN /Buy or Short/ You do not know yet whether the condition /Gap/ is met .
    So backtest is a failure

  7. Admin afl is incorrect, look in to the future beware, definition of gapup and gapdown need the completation of bar and you enter at open yes next day of nr7 but same day of gap, so correct is: Buy=Ref(NR7,-1) AND ref(GapUp(),-1);
    Short=Ref(NR7,-1) AND ref(GapDown(),-1); and so results are poor

    • Hi Frank,

      Determining Gaps doesn’t need completion of bar as it is based on Open price that does not change. The strategy is to buy/sell when Gap occurs after NR7 day, which is coded correctly in the AFL. Please let me know if you have any more queries.

  8. Peraphs your definition of gapup or gapdown with investopedia is correct but anyway amibroker take gap only at the end of candle so the correct formula is that i’ve posted or you must define gap like open outside yesterday candle with a declaration

  9. It’s common error.
    You buing OPEN with the gap day but gap /second condition met/ finalize at the End of the Day when High stays above previous High.
    Buy Open but second condition met at the end of the day , so AB selectively shows only those cases when at the end of the day gap stays open.
    Your code NOT SEE those trades when during the day gap is closed and in reality you must do this trades or wait to second condition met but only at Close or next day OPEN after gap day.

  10. Hi ADMIN its me VinDiCode here again

    I had made several backtests with the AFL provided and found then correctly coded and working perfectly.

    I have one query when I use “trailing stoploss with percentage of profit” option in “Backtester Setting” I get different number of total trades.
    Total Trades Trailing SL with percentage of profit
    254 0
    266 10
    268 20
    267 30

    How is this possible? Please explain

  11. Hi admin i repeat your code is wrog, this is how amibroker intend gap and is not like investopedia: FUNCTION from amibroker library: A gap up occurs if yesterday’s high is less than today’s low.

    So the correct code is that i’ve posted:Buy=Ref(NR7,-1) AND ref(GapUp(),-1);
    Short=Ref(NR7,-1) AND ref(GapDown(),-1); Thanks

    • Frank
      Buy=Ref(NR7,-2) AND ref(GapUp(),-1);
      Short=Ref(NR7,-2) AND ref(GapDown(),-1)


      Stop loss price must be
      SellPrice = IIf(Sell, IIf(H>=BuyTgt, BuyTgt, Min(Open,BuySL)), Null);

      in case when open price is less than stop loss target.

  12. Frank/Pit,
    I see what you are saying and thanks for bringing this up. Amibroker has a very goofed up definition for gaps which caused this confusion. Setting trade delays to 1 will solve the issue without any code change.

    • SetTradeDelays( buydelay, selldelay, shortdelay, coverdelay )
      settradedelays( 1, 1, 1, 1 ) or settradedelays( 1, 1, 0, 0 ) or settradedelays( 1, 1, 1, 1 )

      Please clarify.

  13. Pit thanks for your clarification, i’m working for other patterns like nr4 id & others

  14. Hi,
    Is it possible to create a similar excel for all NSE future stocks? I’m looking for an excel which scans previous trading day’s ranges and provides the list of NR7 and NR21 stocks.

  15. Hello Admin,
    I have few queries and few solutions for this NR7 system.
    1) Entry price mentioned is on open price, which in practical would be difficult to enter.
    2) As Frank and PIT mentioned, and I too agree that, the system reference into future, as anyday if the gap gets filled, the software wont show up any trade, whereas in practical we had already traded.
    1) how about we keep entry price as some percentage above/below the previous high/low.?
    2) if the system has to go with the GAP theory for entry, than how about we code buy = ref(NR7,-1) and open > ref(High,-1);
    short = ref(NR7,-1) and open < ref(Low,-1); in this way if the gap gets closed by eod, still the trade will remain.

    • Hi CARL,

      For buy = ref(NR7,-1) and open > ref(High,-1) and short = ref(NR7,-1) and open < ref(Low,-1) I had checked and back tested the AFL. The result was very poor.
      With the actual AFL the result was so great that I thought I got a jackpot but as you mentioned key error with the existing AFL "as anyday if the gap gets filled, the software wont show up any trade, whereas in practical we had already traded".
      Even the result was very poor for setting trade delay by 1.

  16. Can we trade it with 1hr timeframe , it gives excellent backtest results for some stocks in f&o. Has anyone tried it?

    • Hi Srinivas,

      If possible, please mention the stock names in which you have tested. It would benefit everyone.

  17. Nr7 backtested by me 15 stocks for last one month. Not getting the expected result

    • Hi Sarasan,

      Yes unfortunately this system does not work for all the stocks It works only for liquid and volatile ones.

  18. Its working good for bank nifty with 1 hour time frame , i backtested it from july 2009 to current date. I tested on axisbank with limited data 1 hr time frame.

    • Yes you definitely can. But please perform paper trading for few days before going live.

  19. Respected sir, i need your help, without c++ how can we find a specific range bound candle’s high, low and name of that candle, example:-

    for( i = BarCount-2; i <= BarCount-1; i++ )
    H1=H[i];// HIGH of that candle
    L1=L[i] ;//LOW of that candle
    H1bar=i;// name of that candle


    BUT I WANTS THIS IN SIMPLE LANGUAGE.WITHOUT USING (for),(i),(BARCOUNT),I mean without loop Example :-

    MASK= ParamStyle("MASK",styleBar| styleThick , maskAll);
    BARCOLOR = IIf(RANGE,colorTurquoise,colorGrey50);
    Plot( C, "Close", BARCOLOR,MASK);

    please plot this in your system and guide me and help me to find name, high, low of Turquoise colour (LATEST -1) candle in simple afl language

Leave a Reply

Your email address will not be published. Required fields are marked *