AFL of the week: Intraday Trading Strategy for Nifty

This week we are going to share an excellent Intraday trading strategy for Nifty. This strategy uses RSI and ADX combination to find Buy/Sell opportunities. As a general rule, when RSI crosses an upper limit it indicates a Sell signal, while if it crosses lower limit it indicates Buy signal. But in this strategy, we are going to do the opposite i.e. Buy when RSI crosses upper limit and Sell when RSI crosses lower limit. ADX would be used as a trend identifier while taking Buy/Sell decisions. All the positions would be squared off at the end of day

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

AFL Overview

Paramter Value
Preferred Timeframe Intraday 1 minute
Indicators Used RSI(17), ADX(14)
Buy Condition RSI(17)>=75 AND ADX(14)>25
Short Condition RSI(17)<=25 AND ADX(14)>25
Sell Condition Same as Short Condition OR Time>=03:15 PM
Cover Condition Same as Cover Condition OR Time>=03:15 PM
Stop Loss 0.5%
Targets No fixed target, Stop and reverse when AFL gives opposite signal
Position Size 150 (fixed) or 80% of equity (as per your risk appetite)
Initial Equity 200000
Brokerage 50 per order
Margin 10%

AFL Code

//  Formula Name:    Nifty Intraday Strategy using RSI and ADX
//  Author/Uploader: Trading Tuitions
//  E-mail:          support@tradingtuitions.com
//  Website:         www.tradingtuitions.com

_SECTION_BEGIN("Nifty Intraday Strategy");

SetTradeDelays( 1, 1, 1, 1 );
SetOption( "InitialEquity", 200000);
SetOption("FuturesMode" ,True);
SetPositionSize(150,spsShares); //Use this for fixed position size
//SetPositionSize(80,spsPercentOfEquity); //Use this for position size as a percent of Equity
SetOption( "AllowPositionShrinking", True );

_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 );


Buy=RSI(RSIPeriods)>=75 AND ADX(ADXPeriods)>25;
Short=RSI(RSIPeriods)<=25 AND ADX(ADXPeriods)>25 ;


Sell=Short OR TimeNum()==151500;
Cover=Buy OR TimeNum()==151500;


Plot( RSI(RSIPeriods), "RSI", color=colorBlue, ParamStyle( "Style", styleOwnScale) );
Plot( ADX(ADXPeriods), "ADX", color=colorRed, ParamStyle( "Style", styleOwnScale) );

/* 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);


AFL Screenshot

Nifty Intraday Strategy

Backtest Report

Below is the backtest report for two different variations of this strategy. One is using fixed position size of 150. Another is position size as a percentage of Equity. You can clearly see that the second one outperforms the first due to Power of Compounding.

Can you count Final capital for the second one? Just give it a try 🙂

Moral of the Story: Your strategy need not to be complex and lengthy to be extremely profitable,

 Paramter Value
  Fixed Position Size  Position Size=80% of Equity
Initial Capital  200000 200000
Final Capital 1439280.45  11219716562.40
Backtest Period 01-Jan-2008 to 22-03-2016 01-Jan-2008 to 22-03-2016
Timeframe 1 Minute 1 Minute
Net Profit % 619.64% 5609758.28%
Annual Return % 27.10% 277.59%
Number of Trades 1913 1913
Winning Trade % 43.49%  43.49%
Average holding Period 128.08 periods  128.08 periods
Max consecutive losses 12 12
Max system % drawdown -18.14% -31.51%
Max Trade % drawdown -31.51% -44.43%

Download the detailed backtest report here.

Equity Curve

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

Equity Curve_Nifty Intraday

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


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


  1. Sir
    I am trying to use Robo system and i tried also.This Afl gives buy order correctly and it is missing fresh Sell order.
    Will u please add sell command in the afl
    Thanks in advance

  2. Dear Sir,

    Thank you so much for sharing this non-repainting strategy. I have a big doubt on the results of your second backtest report where the position size equals 80% of the equity. In my opinion, correct me if I am wrong, there is an error in the backtest report since you have assumed Rs 50 towards brokerage or transaction cost per leg.

    Practically it is impossible to trade by just paying a total transaction fee of Rs 50 per leg for large volumes. I understand that brokerage fee a may remain fixed at or below Rs 20 regardless of the volume size. However, other exchange costs like STT, stamp duty, turnover charges, service tax, SEBI charges tend to increase with increase in volume. So, if you consider these costs into account, the profitability of the strategy will largely decline.

    Most retail traders that have trading account with discount brokerage firms incur total transaction costs of 0.1% per leg.

    You may want to republish this report if you think point is correct


    • Hi Nasrudeen,
      You are absolutely right. But second backtest report is just an indicative of how much profit you can earn if you allow compounding. It may be practically impossible though considering the slippage, transaction charges and market limits for the number of lots. But even if the overall profits decline by 50% after taking into account these factors, this strategy is successful enough. Appreciate your comment!

  3. Hello Sir,

    In this AFL, you used spsShares this for fixed position size and
    spsPercentOfEquity for position size as a percent of Equity; but what if I want to create position size for a fixed amount? For example, I will buy shares for 5 lakhs per trade. Could you please tell me what should be the AFL command?
    Thanks a lot.


    • Hi Karan,
      Just follow the Buy/Sell signals in Chart. Let us know if you have any specific question regarding this AFL.



    • Hi Karan,
      Trading cannot be done through performance sheet. You just have to follow the buy/sell signals from the AFL provided and bet 80% of your capital on every trade. See backtest report for trade log.

  7. Sir , u have mentioned ENTRY price as OPEN…………Buy / Sell condition may vary ( not stable) before that candle closes….so is it correct..or we should modify as CLOSE price…..Raja

    • Hi Raja,
      SetTradeDelay is set to 1, so the position would be taken at next candle open. Hope that clarifies

      • In the above code, it is already set by 1 bar delay, as I see in Bar-replay.
        SetTradeDelays( 1, 1, 1, 1 );
        Please let me know, what I have to change to make it as close of the candle or next candle opening for the existing code in back testing.

        • Hi Rama,

          1 bar delay is set to Buy/Sell at the open of next candle once the signal is generated.

  8. Sir,Iam very much interested in stock market.My trading account collapsed due to follow up stock tips.Hence,I dont know how to become an expert in stock selection,because of ultimate goal is that.So,please be help me.Thank YOU.

    • Hi Bhasskar,

      I am sad for your loss. This is the perfect example why we should avoid believing in tipsters. I would recommend you to subscribe to this blog and read each and every post carefully. It will help you to select stocks based on Technical analysis. You can also contact us at support@tradingtuitions.com for any specific query.

  9. can you please let me know how to optimize the code for bank nifty , plz add optimize parameter in the code.

  10. Hi Sir,
    Is this the Intraday or positional trade , when i back test it shows me some positional trades.

  11. Hi Sir,
    Is this the Intraday or positional trade , when i back test with 1 min timeframe it shows me some positional trades.

    • It is purely Intraday Strategy. Are u able to see Sell/Cover arrows at EOD?


  13. Dear Admin,

    I really appreciate you for your selfless work
    can you please modify the code such that…after entering the trade number of points to be booked can be defined…ie buy price + 1 point is sell and sell price -1 point is cover…It would be great if it done

  14. HI,
    How can I use this code in other trading platforms such as Zerodha Pi ,
    Is there a way we can use this strategy there?
    and Thank you for your wonderful contribution , If we find on the whole web most of the trading strategies are less suitable for Indian Markets and are mostly foreigner, it is difficult to find strategies focused on Indian perspective you are doing a great job.

  15. Hi Admin,
    Sorry if i sound like learner. In your afl,,it has been defined that Buy signal when RSI >=75 and vice versa Sell if =75 AND ADX(ADXPeriods)>25; (nrmally it should sell when RSI is more than or equal to 75).
    Short=RSI(RSIPeriods)25 ;(nrmally it should buy when RSI is less than or equal to 25).

    As I have noticed few signal where, we have missed just beacuse of this.

    • Hi Manish,

      Yes, your point is valid. But since it’s a Trend following strategy we are using RSI in a different way. I have backtested it both ways, and this is most profitable.

  16. Hello Admin,
    I am thankful for this site. I need a small favour from you. As I am a small trader and can’t buy Amibroker. I am requesting you to provide the backtest results for Crude oil with Supertrend indicator on 5 minute charts. As I tested 3 months data it is given good results but I require minimum 1 year backtest results. Can you please provide it. It will be available for lot of small traders like me.

  17. Dear Admin,

    Wonderful work by YOU & your team.

    Can u add alert in this so that we can see which other stocks fulfilling this criteria.

    Secondly Pls check am i going something wrong…. For 1 min time frame from Feb 2016 till 09 Aug only 16 TraDES ?

    Pls check and confirm

    • i am a day trader.I want to give you one humble suggestion,that don’t get confused with so many AFL’s and running here and there.
      If you are a day trader or a positional trader,simply find out a AFL which gives you consistent result and enjoy earning.

      There are so many reputed web sites / blogs etc are there and offering wounderfull collection of AFL’s select the correct AFL (after proper back testing)
      and enjoy your trading.
      That I have learned after dashing my head(many times and lost money too in many cases) here and there.

      Take care.

  18. Dear sir I am not aware of amibroker. I use falcon. When I give many of your strategy to develop they could not even develop a single strategy correctly. Please let me know how I can I work on amibroker. Any vendor or any person who can help me in this regard. I also want to automate this strategy. Please help.

    • Hi Rahul,

      Yes, it can be. But I would recommend to do paper trading before making it live. Actual results can slightly differ from backtested results.

  19. why there are 3 statement for each plotshape? buy, sell, short and cover? I can only see color and offset is little different.

    • Hi Amit,

      The 3 statements plot square and arrow combination to make it look more realistic and visible.

  20. hi
    it is puerly intraday or positional
    why i m asking bcoz you said it is Intraday then how you backtest it
    when market open on next day and signal generated then you take entry calculation and exit calculation on 3.15
    or something different calculation signal to signal

      • hi Admin sir,

        you mention on afl time frame one minute , then what is meaning to backtest it on 5 min chart

        • Hello Admin

          Pls clatify as yo whether this has to be implied on 1 min or 5 min charts??? As you have mentioned 1 min in the strategy details whereas you refer the backtesting on 5 min TF…

          • Hi Chintan,

            It works well for both the timeframes. In 5 min you would see lesser number of whipsaws.

  21. Hi Admin,
    Please guide me would this strategy really help. My ultimate target is to earn only 1000-2000 Rs. in a day. I am new to this market. I could manage to put Rs. 1000000.
    Please guide if this strategy really works, so, I could purchase AFL software. And would this be automated as you have mentioned many formulas? This is just my query.

  22. Thanks for ur reply.
    Dear sir,
    I have just opened demat account in Hdfc sec. Bought new PC and downloaded amibroker software. How should I start if I want to use intraday niffty trading statergy as you have given here.please help.

  23. Thanks for ur reply.
    Dear sir,
    I have just opened demat account in Hdfc sec. Bought new PC and downloaded amibroker software. How should I start if I want to use intraday niffty trading statergy as you have given here. I am bigginer.

        • Dear Dipak,
          Lack of trading experience can evaporate ones tradung capital. There are good trading strategies that work very well, but only in the long run you be able to make income consistently. All strategies suffer drawdown which is very hard to stomach for most traders. So stay away from trading activities. My sincere advice is to invest money in well managed mutual funds for short term benefits and begin SIP for long term wealth creation. And to save costs on brokerage you make have a brokerage account with discount brokers like Zerodha whose service is excellent and zero beokerage for delivery based equity transactions.

          • Hi Nasrudeen,

            We appreciate your advice but do not completely agree to it. Trading Tuitions aims to enable and educate people on profitable trading concepts. I agree there is drawdowns involved in trading, but it doesn’t not mean that people should refrain from trading because of that, mutual funds too have drawdowns. Even retail traders with low capital can do wonders if they are disciplined and follow risk management. Technology has brought everything at our finger tips, it depends on us how we use it. Lastly, we do not promote advertising the tips providing service, so your comment has been edited.

          • Hello Admin,

            The work of Trading Tuitions is astounding, it is unquestionable. But, no one can deny the fact that there is a fundamental difference between a drawdown in trading strategies and well-managed mutual funds. A matured mutual fund investor would view drawdowns as an opportunity in the event of a systemic risk. While a matured trader would begin to doubt and try to tweak his strategy which would mostly be more harm than good.

            In my opinion, any trading strategy is highly risky for retail traders who has minimum capital. A wild blow can not only cause capital erosion but also cause deeper psychological dent.

            Thank you,

          • I agree and I am not against mutual funds or any other systematic investment plans. Mutual funds definitely lowers your risk but then the rewards are also limited. Trading definitely has higher risk, but offers unlimited reward. It’s upto you how you can control your risk and survive this game. And that’s where quantitative trading strategies pitch in where your trading decisions are non discretionary and governed by algorithms. These strategies are backtested over years of data and so you already know the average drawdown, hence the probability of surprises are low. And I bet most of the mutual funds and hedge funds use these quantitative strategies. I hope I made my point.

    • Hi Dipak,

      Glad to know that you are interested in trading and setup a demat account already. We suggest you to learn for the first six months and start paper trading. Don’t directly jump into applying the strategies we have posted. You should follow a step by step approach and find the strategy that suits you. Refer the below article as a starting point:

  24. Thank u adminji,
    I will not give up.I will learn and apply my knowledge with discipline.

  25. Hello Sir,
    What is the cost of Amibroker software and can I linked it to Zerodha PI. As I believe this is an automated trade strategy. Please confirm. What should be the capital required to trade in one lot of Nifty.

  26. Thank you for this post. Are there any brokers who can automate these kind of trades? I don’t have amibroker and would like to go with some who can automate these kind of strategy from account. Thank You.

  27. What is the significance of RSI period 17 instead of default 14 ?

    • Hi Vidyadhar,

      The system has been optimized for RSI period 17. The default period does not work always in modern day technical analysis.

  28. Dear Admin, I am not getting exit trade signal in amibrokar 5.60.2. Pls help

  29. Hello team,
    Can i get the excel report for this AFL coding ?I mean the excel report should contain how many stocks in that condition (RSI>75 and ADX> 25) instead of auto buy .?

  30. If we consider brokerage + taxes is around 200-250 per lot of 75shares so it will b 400rs for 150 quantity… And for total 1913 trades it will be around 8lakhs rs. So 8+2lacs initial fund.. =10 lakhs
    So i think one can earn only 4-5 lakhs..

  31. After a certain upper limit, compunding doesn’t make sense. e.g. can you imagine your last trade getting executed in your favour with the capital in 100s of crores ? for that there should be equal amount of selling activity should happen when you buy and buying when you sell.

    • Hi Vidydhar,

      Yes, that is true. But the backtest results are just for illustration that how the strategy works.

  32. Has anyone tried this out in real life ?

    Just let us know what was the practical profitability

  33. Dear Sir,
    You site has gem of information for new trader who wants to learn AFL. Thank you for your selfless effort.
    I am facing issue while backtesting, Trades are not closed on same day. I have sent detailed email regarding same. Please reply.

  34. User would never get entry at signal price for most of successful trades. Bcoz of below condition.
    SetTradeDelays( 1, 1, 1, 1 );
    It shold be BuyPrice =Close;
    and with close price backtest result is negative.

    • Hi Mitesh,
      For the reasons you have mentioned, SetTradDelays is set to 1. I agree there would be some slippages though.

  35. Hi,

    Thanks for sharing the formula.

    When I try to use I get the following error:
    “Error 61: The number of format specifier(s) (%) does not match the number of arguments passed.”
    It’s got something to do with the code on Line 28, Col 21. Can you please help me resolve this?

    • Hi Mayank,

      Please comment out line 61. It doesn’t work in some versions of Amibroker

  36. Hi Admin,
    Thanks for your strategy
    This is a stop & reverse strategy, so for a buy order a sell condition closes the trade and for a sell order a buy condition closes the trade so where does the stop loss of 0.5% come into the picture?

  37. This is cheating strategy. You are entering the trade in Opening price which is not possible in real trade. Don’t waste your time

    • Hi Raju,

      The trade delay is set to 1 which means you need to enter on next day’s open price

  38. Dear admin

    Can you help with stop loss criteria, is it 0.5% of nifty value ?

Leave a Reply

Your email address will not be published.