Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

Supertrend V4.0 – Amibroker AFL Code

6 min read

Compared to Supertrend 3.0 with the new version two interesting features have been added. One is a simple EMA filter rule is added to Buy and Short Conditions and changes in the dashboard (including target levels in Supertrend Dashboard for discrete traders). And the performance of the Trading system is really interesting when comes to backtesting with Nifty and Bank Nifty Futures. Recorded Webinar of Supertrend and Filters posted down below.

Supertrend V4


Trading Rules

Buy – if suptrend shows a buy signal and candle above 200 EMA (Green Arrow)
Exit Buy – if supertrend shows an exit signal (Yellow Star)

Short – if suptrend shows a sell signal and candle below 200 EMA (Red Arrow)
Exit Short – if supertrend shows a exit signal (Yellow Star)

Trades are Executed on the close of the Candle.

Supertrend Interactive Charts

Apply Supertrend V4.0 indicator in Interactive NSE Futues and Options 5min Charts

Add Supertrend and Moving Average 200EMA over the candlestick and for trading system rules follow the above mentioned.

Visit here To know more about the basic version of supertrend and concepts

Trailing Stops : Green lines are trailing stop lines for Buy Signal and Red lines are trailing stop lines for Sell Signal.

Features

1)Buy, Short and Exit Signals
2)Trading Dashboard which tracks the Trade executed price, Trailing stoploss and P/L for current running trade
3)Time left feature to identify bar completion time
4)Dashboard indicates no trade zone when there are no trades happening.
5)200 EMA line – Filter Condition.
6)Target Achievement Indication in the Dashboard for current Signals.
7)Exploration

Webinar on Supertrend V4.0 with Filters



If you like the video do subscribe to our youtube video to receive updates on trading system, trading strategies and lot more on trading concepts.

Presentation on Supertrend and Filters

Steps to Install in your Amibroker
1)Download Supertrend v4.0 – Amibroker AFL Code. If you are not comfortable in running Backtesting and Optimization try with the following code Supertrend V4.0 Backtest and Optimize
2)Unzip Supertrend V4.0 afl to local folder
3)Copy Supertrend V4.0.afl file to \\program files\\amibroker\\formula\\basic folder\\
5)Open Amibroker and Open a New Blank Chart
6)Goto Charts->Basic Charts and apply/drag-and-drop the Supertrend v4.0 code into the blank chart
7)Bingo you are done. Now you will be able to see the Supertrend v4.0 Trading System indicator with Buy and Sell signals.

Supertrend V4.0 Backtested Results for Nifty futures with Fixed lot size of 100 shares. Backtested with 1min historical data since Jan 2008 to July 2014

Supertrend V4.0 – Amibroker AFL code

/* Done by    Rajandran R  */
/* Author of www.marketcalls.in  */

function GetSecondNum()
{
    Time = Now( 4 );
    Seconds = int( Time % 100 );
    Minutes = int( Time / 100 % 100 );
    Hours = int( Time / 10000 % 100 );
    SecondNum = int( Hours * 60 * 60 + Minutes * 60 + Seconds );
    return SecondNum;
}


_SECTION_BEGIN("SuperTrend Ver 4");

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




SetPositionSize(1*RoundLotSize,spsShares);

sig = 0;
bars =0; 
tar1 =0;
tar2 = 0;
tar3=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 ) ) ));



Factor=optimize("Factor",3,1,3,1);

Pd=optimize("ATR Periods",10,1,100,1);


Up=(H+L)/2+(Factor*ATR(Pd));

Dn=(H+L)/2-(Factor*ATR(Pd));

iATR=ATR(Pd);

TrendUp=TrendDown=Null;

trend[0]=1;

changeOfTrend=0;

flag=flagh=0;



for (i = 1; i <BarCount; i++) {

      TrendUp[i] = Null;

      TrendDown[i] = Null;

     

      trend[i]=1;

   

      

      if (Close[i]>Up[i-1]) {

         trend[i]=1;

         if (trend[i-1] == -1) changeOfTrend = 1;

         

      }

      else if (Close[i]<Dn[i-1]) {

         trend[i]=-1;

         if (trend[i-1] == 1) changeOfTrend = 1;

      }

      else if (trend[i-1]==1) {

         trend[i]=1;

         changeOfTrend = 0;       

      }

      else if (trend[i-1]==-1) {

         trend[i]=-1;

         changeOfTrend = 0;

      }



      if (trend[i]<0 && trend[i-1]>0) {

         flag=1;

      }

      else {

         flag=0;

      }

      

      if (trend[i]>0 && trend[i-1]<0) {

         flagh=1;

      }

      else {

         flagh=0;

      }

      

      if (trend[i]>0 && Dn[i]<Dn[i-1]){

         Dn[i]=Dn[i-1];

		}

      

      if (trend[i]<0 && Up[i]>Up[i-1])

        { Up[i]=Up[i-1];

		}

      

      if (flag==1)

       {  Up[i]=(H[i]+L[i])/2+(Factor*iATR[i]);;

        } 

      if (flagh==1)

        { Dn[i]=(H[i]+L[i])/2-(Factor*iATR[i]);;

         }

      if (trend[i]==1) {

         TrendUp[i]=Dn[i];

         if (changeOfTrend == 1) {

            TrendUp[i-1] = TrendDown[i-1];

            changeOfTrend = 0;

         }

      }

      else if (trend[i]==-1) {

         TrendDown[i]=Up[i];

         if (changeOfTrend == 1) {

            TrendDown[i-1] = TrendUp[i-1];

            changeOfTrend = 0;

         }

      }

   } 



Plot(TrendUp,"Trend",colorGreen);

Plot(TrendDown,"Down",colorRed);

Length =200;//Optimize("HMA",100,10,300,1);

emafilter = Ref(EMA(Close,length),-1);

Buy = trend==1 AND c>emafilter;
Sell=trend==-1 ;

Short=trend==-1  and C<emafilter;
Cover=trend==1;

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

short=ExRem(short,cover);
cover=ExRem(cover,short);

Long=Flip(Buy,Sell); 
Shrt=Flip(Short,Cover); 
Relax = NOT Long AND NOT Buy AND NOT shrt AND NOT Sell AND NOT Sell AND NOT Cover; 

BarsSincebuy = BarsSince( Buy ); 
BarsSinceshort = BarsSince( Short ); 
LastSignal = IIf( BarsSincebuy < BarsSinceshort, 1, -1 ); 

SetTradeDelays(0,0,0,0);

Buy = Ref(Buy,-1);
Sell = Ref(Sell,-1);
Short = Ref(Short,-1);
Cover = Ref(Cover,-1);

BuyPrice=ValueWhen(Buy,open);
SellPrice=ValueWhen(Sell,open);
ShortPrice=ValueWhen(Short,open);
CoverPrice=ValueWhen(Cover,open);

Title = EncodeColor(colorWhite)+ "Super Trend AFL code from www.marketcalls.in" + " - " +  Name() + " - " + EncodeColor(colorRed)+ Interval(2) + EncodeColor(colorWhite) +

 "  - " + Date() +" - "+"\n" +EncodeColor(colorRed) +"Op-"+O+"  "+"Hi-"+H+"  "+"Lo-"+L+"  "+

"Cl-"+C+"  "+ "Vol= "+ WriteVal(V)+"\n"+ 

EncodeColor(colorLime)+

WriteIf (Buy , " GO LONG / Reverse Signal at "+C+"  ","")+

WriteIf (Sell , " EXIT LONG / Reverse Signal at "+C+"  ","")+"\n"+EncodeColor(colorYellow)+

WriteIf(Sell , "Total Profit/Loss for the Last Trade Rs."+(C-BuyPrice)+"","")+

WriteIf(Buy  , "Total Profit/Loss for the Last trade Rs."+(SellPrice-C)+"","");



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),colorGold, 0, L, Offset=-15); 
PlotShapes(IIf(Cover, shapeStar, shapeNone),colorGold, 0,L, Offset=-15); 





TrendSL=IIf(trend==1,TrendUp,TrendDown);

sig=0;


for(i=BarCount-1;i>1;i--)

{

if(Buy[i] == 1)

{

entry = C[i];

sig = 1;

sl = TrendSL[i];

tar1 = entry + (entry * .0050);

tar2 = entry + (entry * .0092);

tar3 = entry + (entry * .0179);

 

bars = i;

i = 0;

}

if(Short[i] == 1)

{

sig = -1;

entry = C[i];

sl = TrendSL[i];

tar1 = entry - (entry * .0050);

tar2 = entry - (entry * .0112);

tar3 = entry - (entry * .0212);

 

 

bars = i;

i = 0;

}

}

Offset = 20;

SellSL=ValueWhen(Short,Ref(TrendSL,-1),1); 
BuySL=ValueWhen(Buy,Ref(TrendSL,-1),1); 



Clr = IIf(sig ==1, colorLime, colorRed);

ssl = IIf(bars == BarCount-1, TrendSL[BarCount-1], Ref(TrendSL, -1));

sl = ssl[BarCount-1];





Plot(LineArray(bars-Offset, tar1, BarCount, tar1,1), "", Clr, styleLine|styleDots, Null, Null, Offset);

Plot(LineArray(bars-Offset, tar2, BarCount, tar2,1), "", Clr, styleLine|styleDots, Null, Null, Offset);

Plot(LineArray(bars-Offset, tar3, BarCount, tar3,1), "", Clr, styleLine|styleDots, Null, Null, Offset);






buyach1 = IIf((Buy OR Long AND NOT Relax AND NOT Cover AND NOT Short AND NOT Shrt), H > tar1, 0); 
buyach2 = IIf((Buy OR Long AND NOT Relax AND NOT Cover AND NOT Short AND NOT Shrt), H > tar2, 0); 
buyach3 = IIf((Buy OR Long AND NOT Relax AND NOT Cover AND NOT Short AND NOT Shrt), H > tar3, 0); 

sellach1 = IIf((Short OR Shrt AND NOT Relax AND NOT Sell AND NOT Buy AND NOT Long), L < tar1, 0); 
sellach2 = IIf((Short OR Shrt AND NOT Relax AND NOT Sell AND NOT Buy AND NOT Long), L < tar2, 0); 
sellach3 = IIf((Short OR Shrt AND NOT Relax AND NOT Sell AND NOT Buy AND NOT Long), L < tar3, 0); 


// Message Board ----------------- 
GfxSelectFont( "Tahoma", 13, 100 ); 

GfxSetBkMode( 1 ); 

GfxSetTextColor 
( colorWhite ); 

if ( SelectedValue( LastSignal ) == 1 ) 
    { 
        GfxSelectSolidBrush( colordarkGreen ); 
    } 
    else 
    { 
        GfxSelectSolidBrush( colorRed ); 
        } 


pxHeight = Status( "pxchartheight" ) ; 

xx = Status( "pxchartwidth"); 

Left = 1100; 

width = 310; 

x = 5; 

x2 = 290; 

y = pxHeight; 

GfxSelectPen 
( colorLightBlue, 1); // border color 

GfxRoundRect 
( x, y - 155, x2, y , 7, 7 ) ; 


GfxTextOut( ( "Marketcalls - Supertrend V4.0"),13,y-130);

GfxTextOut 
( ("" + WriteIf(Buy, "Go Long At "+C+" - SL " +Ref(TrendSL,-1),"")), 13, y-105); 

GfxTextOut 
( ("" + WriteIf (Short, "Go Short At "+C+" - SL " +Ref(TrendSL,-1),"")), 13, y-105); 


GfxTextOut 
( ("" + WriteIf (Sell AND NOT Short, "Exit Long At "+C,"")), 13, y-115); 

GfxTextOut 
( ("" + WriteIf (Cover AND NOT Buy, "Exit Short At "+C,"")), 13, y-115); 


GfxTextOut 
( ("" + WriteIf (Long AND NOT Buy, "Long At "+(BuyPrice)+" - TSL " + Ref(TrendSL,-1)+ "","")), 13, y-105); 

GfxTextOut 
( ("" + WriteIf (shrt AND NOT Short, "Short At "+(ShortPrice)+" - TSL " + Ref(TrendSL,-1)+ "","")), 13, y-105); 

GfxTextOut 
( ("" + WriteIf (Relax, "No Trade Zone - Wait","")), 13, y-105); 

GfxTextOut 
( ("" + WriteIf (Long AND NOT Buy, "Current P/L: "+(C-BuyPrice)+" Points","")), 13, y-85); 

GfxTextOut 
( ("" + WriteIf (shrt AND NOT Short, "Current P/L: "+(ShortPrice-C)+" Points","")), 13, y-85); 

GfxTextOut 
( ("" + WriteIf (Long OR Buy OR Shrt OR Short, "Target 1: "+tar1,"")), 13, y-65); 

GfxTextOut 
( ("" + WriteIf (Long OR Buy OR Shrt OR Short, "Target 2: "+tar2,"")), 13, y-45); 

GfxTextOut 
( ("" + WriteIf (Long OR Buy OR Shrt OR Short, "Target 3: "+tar3,"")), 13, y-25); 

GfxTextOut 
( ("" + WriteIf (buyach1, "Target 1: "+tar1+" :: Achiecheved","")), 13, y-65); 

GfxTextOut 
( ("" + WriteIf (sellach1, "Target 1: "+tar1+" :: Achiecheved","")), 13, y-65); 

GfxTextOut 
( ("" + WriteIf (buyach2, "Target 2: "+tar2+" :: Achiecheved","")), 13, y-45); 

GfxTextOut 
( ("" + WriteIf (sellach2, "Target 2: "+tar2+" :: Achiecheved","")), 13, y-45); 

GfxTextOut 
( ("" + WriteIf (buyach3, "Target 3: "+tar3+" :: Achiecheved","")), 13, y-25); 

GfxTextOut 
( ("" + WriteIf (sellach3, "Target 3: "+tar3+" :: Achiecheved","")), 13, y-25); 



Filter=Buy OR Short; 
AddColumn( IIf( Buy, 66 , 83 ), "Signal", formatChar, colorDefault, IIf( Buy , colorGreen, colorRed ) ); 
AddColumn(Close,"Entry Price",1.4, colorDefault, IIf( Buy , colorGreen, colorRed )); 
AddColumn(Ref(TrendSL,-1),"Stop Loss",1.4, colorDefault, IIf( Buy , colorGreen, colorRed )); 
AddColumn(tar1,"Target 1",1.4, colorDefault, IIf( Buy , colorGreen, colorRed )); 
AddColumn(tar2,"Target 2",1.4, colorDefault, IIf( Buy , colorGreen, colorRed )); 
AddColumn(tar3,"Target 3",1.4, colorDefault, IIf( Buy , colorGreen, colorRed )); 
AddColumn(Volume,"Volume",1.0, colorDefault, IIf ((Volume > 1.25 * EMA( Volume, 34 )),colorBlue,colorYellow)); 

_SECTION_END();

_SECTION_BEGIN("EMA1");
P = ParamField("Price field",-1);
Periods = Param("Periods", 200, 2, 300, 1, 10 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") ); 
_SECTION_END();

_SECTION_BEGIN("Time Left");

RequestTimedRefresh( 1 );

TimeFrame = Interval();

SecNumber = GetSecondNum();

Newperiod = SecNumber % TimeFrame == 0;

SecsLeft = SecNumber - int( SecNumber / TimeFrame ) * TimeFrame;

SecsToGo = TimeFrame - SecsLeft;



x=Param("xposn",50,0,1000,1);

y=Param("yposn",380,0,1000,1);



GfxSelectSolidBrush( ColorRGB( 230, 230, 230 ) );

GfxSelectPen( ColorRGB( 230, 230, 230 ), 2 );

if ( NewPeriod )

{

GfxSelectSolidBrush( colorYellow );

GfxSelectPen( colorYellow, 2 );

Say( "New period" );

}

//GfxRoundRect( x+45, y+40, x-3, y-2, 0, 0 );

//GfxSetBkMode(1);

GfxSelectFont( "Arial", 14, 700, False );

GfxSetTextColor( colorRed );

GfxTextOut( "Time Left :"+SecsToGo+"", x, y );

_SECTION_END(); 


Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

[Webinar] Understanding and Mitigating Curve Fitting in System Trading

"Understanding and Mitigating Curve Fitting in System Trading"! This dynamic session aims to equip novice to intermediate traders, quantitative analysts, and financial engineers with...
Rajandran R
1 min read

P-Signal Strategy Long Only Strategy – Amibroker AFL Code

This tutorial provides an overview of the P-Signal reversal strategy, a quantitative trading strategy that utilizes statistical parameters and error functions to generate probabilistic...
Rajandran R
2 min read

130 Replies to “Supertrend V4.0 – Amibroker AFL Code”

      1. sir can we do intraday in nifty and bank nifty using super trend v4.0. If yes how can we do.

  1. Hello sir,
    Very nice webinar for supertrend V4.0

    Let me ask one question to confirm if i understand the system properly.
    For banknifty the trailing sl is 18820.8 and 200 ema is 18794.4. So if a 5min candle close below sl i should simply exit longs. And wait if it close below 200ema will short with sl of that time trailing sl value right?, in other case if banknifty resume uptrend and buy comes will long again.
    I hope i understand it properly.

    And what if 200,ema became totally flat like from 6th april!!!???

    Thanks in advance.

  2. Sir,
    I am using Ami 5.30 ; It shows :
    Ultimate :
    Clr = IIf(sig == ”
    —————^
    Error 1.
    Operation not allowed. Operator/operand type mismatch

    what wrong with my system
    regards,

    umesh

  3. Sir,
    looks like there was some problem in the sheet, when dropped to other Sheet its working fine.
    Thanks,

    umesh

  4. Hello Rajendran,

    Fantastic work on the AFL i have a suggestion to the existing setup which i will mail you. I also wanted to let you know that im unable to run Optimization on the code. Can you please assist with the same ?

    Currently if i click on Optimize i get the following :

    Clr = IIf(sig == ”
    —————–^

    Error 1.
    Operation not allowed. Operator/operand type mismatch.

  5. Problem is, it doesn’t make money. Back-test it on any index of any country, and it has about 33% winning trades, and loses money big time. Any ideas on how you would make this a winning system?

    1. You cannot expect a trading system to work universally across all the markets and produce universal results. Do try with Nifty futures and Bank Nifty futures or even the spot.

    2. I found the system working nicely with TCS and other nifty stocks. Use 15 min or 60 min as time frame.

  6. If I want to try with different EMA like 100 or 150 please let me know which line I need to change, its rather confusing. Thanks

      1. I am trying with 5 or 15 dma but the no trade zones are not appearing… All signals appear as is. Is there some issue or other change to be done?

          1. Yes I understood, I edited the AFL code and saved it, replacing 200 with the new number as you said but it is not changing the signals. For dma 100 I see some changes in signals compared to default 200 but below that somehow the signals are not changing. Any ideas?

  7. Thanks a lot Rajan for the valuable session,wanted to know do you or does anyone provide algo bridge to compatible to odin and amibroker.
    Thanks and regards
    Umesh

    1. We are not proving algo bridge for ODIN. Moreover ODIN itself so far havent introduced any API for their traders to send algo orders. There is no legal solution as of now as long as ODIN open API to their trading clients.

  8. Unable to run the scan- Give error -Operation not allowed. Operator/operand type mismatch.

    What graphical element i have to remove form this code as you suggested above ?

      1. Dear Sir,

        Wonderful work and exploration for reducing noise and SL for market

        I have following query can you please elaborate in detail as not technical guy.

        1) For scanning , back testing all you said to remove code after buy sell ….. Pls tell line no from line no to end line no.

        2) Can you pls write a code that all transactions are closed Intraday what can be the profit / loss or back testing ? As we always do back-testing for 6 months or 10 years but 70 % of traders closes position daily so bookish examples are not achieved in actual s

        3) I have seen parameters settings in Trend Blaster
        a) Show Volume , Show SL , Show Today H/L , Show Prevous Days H/L,
        b) Switch to Aggressive mode or Close market positions EOD or Carry over.

        Your exploration and Tech knowledge is wonderful.

        Thanks in advance

  9. HI Sir,
    Thank you for the Super Update to Supertrend System.

    Sir need few solutions, I’m using AMIBROKER 5.60.2 . Problem is it does not display Message Board, Magnified Price, no trade zone and Time Remaining utility on the chart. Have kept everything as default as the original codding in the file.

    Another problem is that Backtesting is not working. No results are displayed however im not getting any error message as some other users have mentioned above.

    Kindly Suggest

    Regards,
    Rahul

  10. Thanks for this. Can you apply neural network to optimize the result? Can you shed some light on that? Thanking you in anticipation.

  11. Hi Sir
    I have successfully installed AFL as per your instructions. Only problem is Target in message board shows Target achived in Buy Trade But accurate in Sell trade. How to solve this problem.

    Thanks.

      1. Thankyou for the reply, is there any other software where this is possible, and if we would like to use different time frame filter like daily ma 20 is it possible in supertrend for back test?

        Regards

        Yasharth

        1. Yeh you can backtest with different timeframe filter. Not necesary that you have to use only 200EMA. Its just one good example otherwise Sky is the limit!

  12. Sir I have been trying to backtest the same for CRUDE_OIL but no trades are being generated. Could u point me where I should check??

  13. Dear Rajendran,

    i could’nt get time frame window ( ami 5.6) in supertrend v4, plz advice

  14. Dear Rajendran,

    I could’nt get time fame window in supertrend v4 ( AMI 5.6), Kindly advice

  15. I have tried backtesting using the new code u have provided. Still no trades are being generated. I tried using both 1hr and 30m timeframe…..

  16. Dear Rajandran,

    A very good afl. Thanks for sharing. It is not changing the target when subsequent trades are generated for same direction. For example if a short call has been triggered & closed with star mark, & a fresh short trade before long trade is giving the same target lines of 1st short trade. Can you kindly help us in getting new target lines for each new trades generated.

    Thanks in advance.
    Regards,
    Manjunath

  17. hi sir!

    its excellent ST4 and webninar!

    sir how to change the stop loss of the code….i mean i want to add more condition in stop loss like ema crossing or other indicator value like ema 200…….suppose we buy with our condition st4 + ema 200 and market moves against us and goes below 200 ema our Stop loss should hit instead of waitining till that green or red line…….

    filter sl as well …is it possible?

    thanks for your help.

  18. April2015 has been the toughest month for supertrend followers, the highest number of stoplosses in banknifty. Months like this is when the true discipline and conviction of the traders is tested. In such months of volatility , if we have backtested results, its very helpful to keep on continuing with our system.

    1. Yeh incurred a drawdown of 36% in case of ST v4.0 (for BankNifty). Bank Nifty was trading in a highly compressed fashion compared to Nifty

  19. Sir, For making this Supertrend V.4 most effective, which is the time frame we have to use for Nifty Index, and for other stock futures.

  20. hi,Mr.Rajandaran

    right now i am using Trade Tiger charting is there any afl code of supertrend for trade tiger
    and how to plot in trade tiger
    kindly help me in that

      1. thanks for the reply sir

        which parameter i should use for nifty futures for 60 min. charts
        in your interactive charts you have set the parameters (4,10) for 5 min.time frame
        is it also applicable for the (15 min) and (60 min) or daily time frame ?

        if there is any other parameters for big time frame could you please share
        i am using trade tiger please tell me accordingly

  21. Sir,

    Just a suggestion……How about introducing ADX indicator into SuperTrend V4.0….This would probably reduce trend-less loss-making trades and would probably increase profitability per trade.

  22. Dear Sir,

    Whole of last week, I did run optimization on 5-min tick chart of Nifty and of Bank Nifty with SuperTrend V4.0 AFL Code

    5-min tick chart of Nifty for the period 05-Nov-2007 and 08-May-2015

    5-min tick chart of Bank Nifty for the period 03-Jan-2011 and 08-May-2015

    Factor= Optimize(“Factor”,Param(“Factor”,10,1,50,0.1),1,50,0.1);

    Pd= Optimize(“ATR Periods”,Param(“ATR Periods”,7,1,500,1),1,500,1);

    Length = Optimize(“HMA”,Param(“HMA”,200,100,600,1),100,600,1);

    I tried almost all possible permutation and combination of Factor, Pd and Length

    Yet, I did not find any particular parameter combination giving output back-testing report with Profit Factor and Sharpe Ratio above 2.00

    Kindly requesting you to suggest me particular parameter combination giving output back-testing report with Profit Factor and Sharpe Ratio above 2.00

    1. Thats tru, the market dynamucs change, as of now (6 month) it is give great profit in 15 min factor 3 without any filter. I can tell u a method to decide the scrupt and the best timeframe and foctor for it but the again it wont be forever due to change in markets nature, so keep probabilty on ur side and with a little luck u can get great profit.

  23. what are the ways to enter, add in and exit capital into the system?

    As said, System should tell u when to add or exit. Based on the premise moneymanagement rules would look like,

    Enter :-Enter when drawdown reaches its average low. for nifty when 500 points loss is incurred.

    Add in capital:- same as enter.

    Exit:- Any ideas?

  24. Dear Sir,

    Wonderful work and exploration for reducing noise and SL for market

    I have following query can you please elaborate in detail as not technical guy.

    1) For scanning , back testing all you said to remove code after buy sell ….. Pls tell line no from line no to end line no.

    2) Can you pls write a code that all transactions are closed Intraday what can be the profit / loss or back testing ? As we always do back-testing for 6 months or 10 years but 70 % of traders closes position daily so bookish examples are not achieved in actual s

    3) I have seen parameters settings in Trend Blaster
    a) Show Volume , Show SL , Show Today H/L , Show Prevous Days H/L,
    b) Switch to Aggressive mode or Close market positions EOD or Carry over.

    Your exploration and Tech knowledge is wonderful.

  25. I have observed that around 250 trades are coming per year with ST 4.

    With higher number of trades brokerage and slippage take a lot more impact. Calculating them ahead is important.

    Percentage brokerage with any where from .03% doesnt leave a lot for us.
    The system is better with discount brokerages , i found that we need to subtract 25% profits with 1 lot for 1 lac employed .

    I am trying to figure out what is the slippage and its impact.

    Any one who is trading can suggest what is slippage for NIFTY and BankNifty. Assuming that i would be placing a market order as soon as i get a signal.?

    1. I have been trading it actively and there is not much slippage as the time is fixed and while you backtest you make the trade at next bar open.

      1. good to hear that .
        Regarding trading does any one do automating trading.

        i have amazon cloud account, installed zerodha trader, amibroker and RTD. so data comes free into amibroker and generates signals.

        i am working on sending signals to PI platform. and automate the acceptance part.
        if its doesnt work than need to setup things with symphony.

          1. Yes , only semi automated is supported currently.
            the manual part is clicking on a buy button, typing in the trading password and clicking couple of ok button.

            These all can be managed by autoit coding.

            However, current form of PI is very basic it would be really practical only when it can send open positions ( size, scripts, quantity) data to Amibroker. Zerodha is working on the same , and they said only then PI will come out of BETA .

          2. rajandran sir,

            i m getting very good result with supertrend after some optimization and modification, I m doing it on crude, i wanted to know , as i really need to automate it thru Pi platform of zerodha, but after a huge time devotion though, i m still unable to send signal from amibroker to Pi, using supertrend formula, it ll be really helpful for me if u can guide the logic to send the signals to Pi for automation…

            thank u

            waiting your reply

  26. I tried your signal to fetch result in an EA in MT4. However the results were erroneous. It never matched the values in data window. Do you have an EA for this indicator or can you please clarify whats wrong.
    Looking forward.
    Thx
    ——
    double val0 = iCustom(_Symbol, timePd, “SuperTrend(NR2)”, 0, posn);
    double val1 = iCustom(_Symbol, timePd, “SuperTrend(NR2)”, 1, posn);
    double val2 = iCustom(_Symbol, timePd, “SuperTrend(NR2)”, 2, posn);
    double val3 = iCustom(_Symbol, timePd, “SuperTrend(NR2)”, 3, posn);
    (Note: removed all extern int and replaced with int, inorder to avoid passing parameter to iCustom)

  27. sir can you please tell about the settings of super trend for trading in intraday like 15 to 30 min charts ?

  28. Your AFL is great!

    I am bit confused for Long Targets! check this image
    http://postimg.org/image/guxfrl6rb/

    As you can see, it says, “Go Long At 18511, Target 1: 18434, Target 2: 18319” How can be the target will be in negative points, by taking long positions?

    1. Make sure non of the candles are selected if yes you will see a blue vertical line which make the dashboard to show wrong values. Remove the blue line by just double click over the lines so that the dashboard show wrong values and ensure you are not selecting any candles with your cursor.

  29. Still I didn’t get the right targets, check this new image http://postimg.org/image/dcvjjktn5/

    The top one is ‘Non Repainting Super Trend Indicator’ and the below one is SuperTrend V4.0

    As you can see the above chart shows the target correctly, but not it SuperTrend V4.0 chart! The problem only with long position targets, the short position target shows correctly!

    (As you said, I didn’t select any bar or with cursor)

    Thanks for your time!

    1. Try using bar replay future it will show current values. Dont scroll to the past and check the dashboard value. Coz currently the dashbord is not confiured to run that way. It always with respect to the ltp price or the selected value.

  30. Supertrend has given two bad months consecutively, april and may. weak and amateur traders will exit this system. only those having conviction will be able to survive

    1. dear friend

      supertrend need periodical optimization, u sud thnk to mr rajandran , who has provided the life boat in the middle of the sea, now its your duty to curve and cut it according to your fit, we sud not expect a system like universally fitted, …….market is dynamic……..best part of super trend is, the trailing stop is inbuilt

  31. sir when buy signal generated next candle open was buy .(in this afl) .but i want to buy above the previous candle high (buy signal genarated candle ) .

  32. There is a delay set so as to execute the order at the open of the next bar, that is, the open of the bar after the signal bar – SetTradeDelays(1, 1, 1, 1). However the BuyPrice and ShortPrice values are set at the close of the signal bar itself (not the next bar). Shouldn’t the BuyPrice and ShortPrice be equal to the open of the bar after signal bar?

  33. hi sir
    thanks for yr work and support
    yr artical helps a lot
    sir i neend yr help i am luking for sun an application through which i cal place place buy sell order from chart to odin and nest manully without time delay with the help of buy sell button
    so plz guide me or help me i get it
    thnks

      1. 15 trades in crude oil with 2 lots since i installed this new version abt a month ago…and i got 14 successful trades…ty again fr this wonderful indicator…now i am even getting those much required tea break also….

  34. well i can’t thank you much ,sir you have been great help to me for so many years . today was in a doubt hence would like to ask you something.

    sir is it possible to create an afl in amibroker that can generate an alert when ever the difference between the price and the swing line is less than 1/2 percentage .

    i mean if you see the super trend image at the top , in the extreme right it shows price is 8805 and suppose swing says for example 8777.
    now the indicator should generate an alert as soon as their difference in less than 1/2 percentage between the two value irrespective of the closing of the candle as soon as the level is breached the alert has to be generated..
    the alert need not be a buy or sell but it should be a general alert like “watch nse” with that particular scrip name time and the swing value,

  35. Hello Sir,

    Thanks a lot for a new version with more conviction. Please incorporate sentiments dashboard in supertrend 4.0 as it was shown in your live signals of nifty & mcx gold

  36. Dear Sir,

    I want 200 EMA value in title bar ..what changes i have to made in afl

  37. Dear Sir,
    I am new to AFL and AMIBROKER but learning new things only through your guidance. I tried to apply supertrend 4.0 on all charts, but values of last five trade results is ‘0’ in all five columns. whereas it is available supertrend 3.0, kindly guide , Regards.

  38. Sir, very good afl
    I want to scan the stocks trading above the trend line (i.e., buying mode) is it possible.
    thanks in advance and waiting for ur reply

  39. SIR Supertrend Indicator for 15 minutes just shows all the trends at 9:19:19 a.m, not a single signal thereafter on any of index or stock or anything,

    please help

  40. sir pls suggest me how to use supertrend v4.0 with ambibroker terminal..what i have to do?

  41. on backtesting above supertrend afl .. following error is comming plz help … there some barcount array error. error no 10.

    1. Make sure you have enough number of bars or possibly you are trying to backtest for All Symbols where some of the charts dont have data.
      Use Current symbol for backtesting or use filters

      1. Thanks it worked.

        I some queries.

        1- When call are generated we get 3 targets. If i want to place exit at 3 target every trade as most of time price touches 3 rd target and correction is generated and loss is booked. How to do that.

        2 – I also used your super tend intraday afl, it is good. if we want to ignore previous day call at the time of opening and just trade only on fresh calls generated in particular day.

        3 – I have been programming for acceleration candle trading strategy. But i am stuck. as i got time counter and price change but not able to evaluate the 5 min candle for first 1 min for price acceleration. can you tell how to code for same.

  42. Hi,
    I have been trading on algo basis for the past year and have seen that using cash market data (nifty & bank nifty) for generating signals and placing orders in futures gives better results. My understanding is that this primae facie due to there being lesser noise in cash market compared to future markets.

    I wanted to know if you have run any such analysis and what were your views on generating trades on cash market and executing them on futures market. As even your indicators on back testing gives better results for cash markets than on futures market.

    I also wanted to know what is the commissions and slippage that you take into account for backtesting of supertrend.

  43. i get this error when scanning or explore and it stops.

    Clr = IIf(sig == ”
    —————–^

    Error 1.
    Operation not allowed. Operator/operand type mismatch.

    1. I’ve fixed this issue.

      at the line which is initializing sig,.. use sig = “”; that is double quote double quote– null string.

  44. Statistics | Charts | Trades | Formula | Settings | Symbols
    Trade list
    Trades
    Ticker Trade Entry Exit % change Profit Shares Pos. value Cum. profit # bars Profit/bar MAE/MFE Scale In/Out
    DISHMAN Long 6/21/2012
    58.6
    1/21/2013
    103.55 76.71% 4495.00
    76.71% 100 5860.00 4495.00 145 31.00 0.00%
    112.37% 0/0
    DISHMAN Long 11/1/2013
    69
    1/28/2014
    87.85 27.32% 1885.00
    27.32% 100 6900.00 6380.00 60 31.42 0.00%
    59.93% 0/0
    DISHMAN Long 6/5/2014
    101.5
    10/20/2014
    152.7 50.44% 5120.00
    50.44% 100 10150.00 11500.00 91 56.26 0.00%
    93.99% 0/0
    DISHMAN Long 1/5/2015
    143.25
    4/28/2015
    145.25 1.40% 200.00
    1.40% 100 14325.00 11700.00 76 2.63 -12.01%
    33.93% 0/0
    DISHMAN Long 6/25/2015
    160.6
    11/18/2015
    327.5 103.92% 16690.00
    103.92% 100 16060.00 28390.00 100 166.90 -8.03%
    161.39% 0/0
    Supertrend V4.0 Backtest and Optimize – Backtest Report Page 1 of 1
    file://C:\Program Files\AmiBroker\Reports\Supertrend V4.0 Backtest and Optimize-2015… 12/28/2015

    Statistics | Charts | Trades | Formula | Settings | Symbols
    Statistics
    All trades Long trades Short trades
    Initial capital 10000.00 10000.00 10000.00
    Ending capital 38390.00 38390.00 10000.00
    Net Profit 28390.00 28390.00 0.00
    Net Profit % 283.90 % 283.90 % 0.00 %
    Exposure % 33.44 % 33.44 % 0.00 %
    Net Risk Adjusted Return % 849.02 % 849.02 % N/A
    Annual Return % 40.43 % 40.43 % 0.00 %
    Risk Adjusted Return % 120.92 % 120.92 % N/A
    Total transaction costs 0.00 0.00 0.00
    All trades 5 5 (100.00 %) 0 (0.00 %)
    Avg. Profit/Loss 5678.00 5678.00 N/A
    Avg. Profit/Loss % 51.96 % 51.96 % N/A
    Avg. Bars Held 94.40 94.40 N/A
    Winners 5 (100.00 %) 5 (100.00 %) 0 (0.00 %)
    Total Profit 28390.00 28390.00 0.00
    Avg. Profit 5678.00 5678.00 N/A
    Avg. Profit % 51.96 % 51.96 % N/A
    Avg. Bars Held 94.40 94.40 N/A
    Max. Consecutive 5 5 0
    Largest win 16690.00 16690.00 0.00
    # bars in largest win 100 100 0
    Losers 0 (0.00 %) 0 (0.00 %) 0 (0.00 %)
    Total Loss 0.00 0.00 0.00
    Avg. Loss N/A N/A N/A
    Avg. Loss % N/A N/A N/A
    Avg. Bars Held N/A N/A N/A
    Max. Consecutive 0 0 0
    Largest loss 0.00 0.00 0.00
    # bars in largest loss 0 0 0
    Max. trade drawdown -8705.00 -8705.00 0.00
    Max. trade % drawdown -21.15 % -21.15 % 0.00 %
    Max. system drawdown -8705.00 -8705.00 0.00
    Max. system % drawdown -21.23 % -21.23 % 0.00 %
    Recovery Factor 3.26 3.26 N/A
    CAR/MaxDD 1.90 1.90 N/A
    RAR/MaxDD 5.70 5.70 N/A
    Profit Factor N/A N/A N/A
    Payoff Ratio N/A N/A N/A
    Standard Error 3752.45 3752.45 0.00
    Risk-Reward Ratio 1.46 1.46 N/A
    Ulcer Index 9.06 9.06 0.00
    Ulcer Performance Index 3.87 3.87 N/A
    Sharpe Ratio of trades 2.25 2.25 0.00
    K-Ratio 0.0534 0.0534 N/A
    Supertrend V4.0 Backtest and Optimize – Backtest Report Page 1 of 1
    file://C:\Program Files\AmiBroker\Reports\Supertrend V4.0 Backtest and Optimize-2015… 12/28/2015

  45. hello sir i am regular reader and follower of your AFL and POSTs lot of thanks

    sir my humble Request sir please prepaire to this AFL in to MULTI TIME FRAME ( Not MTF DashBoard ) means when we select 5 min chart but indicator play like 15 min s Data based , and 15 min chart like 60 min …………,
    sir i found like this supertrend in MQ4 but not in Amibroker so please ……………prepaire this
    AFL ( SUPERTREND V4-0 ….. Indicator) in MTF i hope response possitively thankyou sir

    Sir below link is SUPERTREND MTF MT4

    As said in previous post if possible please modify –SUPERTREND V4-0…………….. IN TO MULTI TIME FRAME.
    Thank you sir

    http://www.wisestocktrader.com/indicatorpasties/1566-supertrend-multi-time-frame-for-mt4&lc=en-IN&s=1&m=269&ts=1451714952&sig=ALL1Aj5CX0PgTHW3_URFhSivSQtsJNkhaA

  46. Hi,

    I am not able to apply the Supertrend v4.0 afl , and getting the following error codes. please help me to resolve this issue.

    PlaySound(“c:\\windows\\media\\ding.wav”);

    ln :22, Col:18 Error 30. Syntax Error

    Clr = IIf(sig == “BUY”, colorLime, colorRed);
    ln :366, Col:18 Error 1. Operation not allowed. Operator/ Operand type mismatch

  47. Hi,

    I am new to AFL coding and trying to learn. Just one question, can this ALF be used for stocks?

    Thanks,
    Peter

  48. DEAR RAJANDRAN

    Greetings of the day..! Keep Goin with all your efforts..!

    I got this code through my friend, since am not good in computers, not able to rectify the problem in that code. Plz help

    _SECTION_BEGIN ( “Chart Display Theme” );
    ChartDisplayTheme = ParamList ( “Chart Display Theme”, “White background with B/W candles|Black background with R/G candles”, 1 );
    param_ShowSystemTitle = ParamToggle ( “Show System Title ?”, “No|Yes”, 1 );
    _SECTION_END ();
    TA_ChartDisplayTheme (ChartDisplayTheme);
    //============================End of Chart Display Style=============================//
    //============================Take User Inputs=============================//
    _SECTION_BEGIN ( “Alerts” );
    Param_AudioAlert = ParamToggle ( “Audio / text Alert?”, “No|Yes”, 1 );
    Param_ShowValuesBox = ParamToggle ( “Display values in Box?”, “No|Yes”, 1 );
    Param_BoxLocation = ParamList ( “Box Location?”, “Left Top|Left Bottom|Right Top|Right Bottom”, 0 );
    Param_BoxBackgroundColour = ParamColor ( “Box background colour?”,colorDarkGrey);
    Param_HideBoxBehindChart = ParamToggle ( “Hide Box behind Chart?”, “No|Yes” );
    _SECTION_END ();
    _SECTION_BEGIN ( “Money Management” );
    Param_Show_Equity = ParamToggle ( “Show Equity ?(Enter correct INITIAL EQUITY in AA Settings)”, “No|Yes” );
    Param_Margin = Param ( “Margin required (used for backtesting only)”, 15, 0.001, 100, 0.001 );
    Param_LotSize = Param ( “Lot Size – DO NOT CHANGE”, 50, 5, 5000, 5 );
    Param_NoOfLots = Param ( “No of lots normally traded (used for backtesting only)”, 2, 1, 10000, 1 );
    Param_drawdown= ParamList ( “Trailing Stoploss Method – DO NOT CHANGE”, “% of total trade value|Fixed amount per share” );
    Param_Stoploss_percent = Param ( “Stoploss % per trade”, 0.7, 0.01, 5, 0.01 );
    Param_Stoploss_amount = Param ( “Stoploss Amount per share”, 15, 0.01, 50000, 0.01 );
    _SECTION_END ();
    //============================End of User Inputs=============================//
    //==========================Start of Show Resistance and Support Lines===============================//
    _SECTION_BEGIN ( “Support-Resistance” );
    Param_ShowResSup = ParamToggle ( “Show Resistance / Support ?”, “No|Yes” );
    Param_HowManyRS = Param ( “How many Support / Resistance to show ?”, 2, 0, 10, 1 );
    Param_ResSupVolatility = Param ( “Support / Resistance Volatility “, 0.1, 0.1, 100, 0.1 );
    Param_SupLineColor = ParamColor ( “Support Line Color”,colorBrightGreen);
    Param_SupLineStyle = ParamStyle ( “Support Line Style”, styleLine|styleNoTitle);
    Param_ResLineColor = ParamColor ( “Resistance Line Color”,colorRed);
    Param_ResLineStyle = ParamStyle ( “Resistance Line Style”, styleLine|styleNoTitle);
    if(Param_ShowResSup AND Param_HowManyRS> 0 ) TA_ShowSupportResistance (Param_HowManyRS,Param_ResSupVolatility,Param_SupLineColor,Param_ResLineColor,Param_SupLineStyle,Param_ResLineStyle);
    _SECTION_END ();
    //===========End of Resistance and Support Lines===========//
    _SECTION_BEGIN ( “Trading System” );
    //====================Show Reversals ?====================//
    Param_ShowReversals = ParamToggle ( “Show possible reversals ?”, “No|Yes” );
    if(Param_ShowReversals) TA_ShowReversals ();
    //====================End of Show Reversals ?====================//
    //====================Start of Trading System====================//
    Param_ShowArrows = ParamToggle ( “Show Buy/Sell/Short/Cover Arrows ?”, “No|Yes”, 1 );
    firstBarEntryExit = ParamToggle ( “First bar trade entry / exit ?”, “No|Yes” );
    A = Param ( “A – 14, 2, 25, 1 );
    B = Param ( “B – 5, 2, 25, 1 );
    CC = Param ( “C – 5, 1, 25, 1 );
    D = Param ( “D – 5, 1, 25, 1 );
    E = Param ( “E – 18, 1, 20, 1 );
    TA_TradingSystemCheckEntry (A,B,CC,D,E,firstBarEntryExit);
    _SECTION_END ();
    //Settings for Backtester
    //SetOption(“InitialEquity”, 100000);
    SetOption ( “AllowSameBarExit”, False);
    SetOption ( “AllowPositionShrinking”, True);
    SetOption ( “FuturesMode”, True);
    SetOption ( “InterestRate”, 0 );
    SetOption ( “MaxOpenPositions”, 1 );
    RoundLotSize = Param_LotSize;
    SetOption ( “MinShares”,RoundLotSize);
    SetOption ( “PriceBoundChecking”,False);
    //SetOption(“CommissionMode”,3);
    //SetOption(“CommissionAmount”,12.5/RoundLotSize);
    SetOption ( “AccountMargin”,Param_Margin);
    SetOption ( “ReverseSignalForcesExit”,True);
    SetOption ( “UsePrevBarEquityForPosSizing”,True);
    SetOption ( “GenerateReport”, 1 );
    SetOption ( “MaxOpenLong”, 1 );
    SetOption ( “MaxOpenShort”, 1 );
    PositionSize = C*RoundLotSize*Param_NoOfLots;
    SetTradeDelays ( 1, 1, 1, 1 );
    BuyPrice = Open;
    SetOption ( “RefreshWhenCompleted”,True);
    //End of Settings for Backtester
    TA_TradingSystemCheckExit (Param_drawdown,Param_NoOfLots,Param_Stoploss_Percent,Param_Stoploss_amount,Param_LotSize,firstBarEntryExit);
    //====================End of Trading System====================//
    //==================Plot Equity, Arrows, AudioAlerts and box containing values================//
    TA_PlotEquityArrowsAlertsValueBox (Param_BoxLocation, Param_Show_Equity,Param_ShowArrows,Param_AudioAlert,param_ShowSystemTitle,Param_ShowValuesBox, Param_HideBoxBehindChart,Param_BoxBackgroundColour);
    //=================== End of Plot Arrows, AudioAlerts and box containing values================//
    //=================== Start of Volume Display================//
    _SECTION_BEGIN ( “Volume Selector” );
    showVolume = ParamToggle ( “Show Volume ?”, “No|Yes”, 1 );
    displayStyle = ParamList ( “Volume Display Mode”, “Normal Volume|Coloured Volume|Volume at Price|Volume at Price (grouped)|Volume at Price + Volume|Volume at Price + Coloured Volume|Volume at Price (grouped) + Volume|Volume at Price (grouped) + Coloured Volume|Customised VAP / candles|Customised VAP / candles + Volume|Customised VAP / candles + Coloured Volume” );
    Param_NormalVolumeColor = ParamColor ( “Normal Volume Colour”, colorDarkBlue);
    Param_NormalVolumeStyle = ParamStyle ( “Normal Volume Style”, styleHistogram | styleOwnScale | styleNoLabel, maskHistogram );
    Param_UpVolumeColor = ParamColor ( “Up Volume Colour”, colorGreen);
    Param_DownVolumeColor = ParamColor ( “Down Volume Colour”, colorRed);
    Param_ColouredVolumeStyle = ParamStyle ( “Coloured Volume Style”, styleHistogram | styleOwnScale | styleNoLabel, maskHistogram);
    Param_VAPLinesCount = Param ( “VAP Lines Count”, 100, 5, 1000, 1 );
    Param_VAPLinesWidth = Param ( “VAP Lines Width”, 40, 1, 100, 1 );
    Param_VAPVolumeColor = ParamColor ( “VAP Color”, colorGold);
    Param_VAPSide = ParamToggle ( “VAP Side”, “Left|Right” );
    Param_VAPOverlay = 4 * ParamToggle ( “VAP Z-order”, “On top|Behind”, 1 );
    Param_VAPStyle = 2 * ParamToggle ( “VAP(grouped) Style”, “Fill|Lines”, 1 );
    Param_Segment = Param ( “No. of candles for Customized VAP”, 10, 2, 1000, 1 );
    if(showVolume)
    {
    segmentValue = IIf ( Interval () O, Param_UpVolumeColor,Param_DownVolumeColor), Param_ColouredVolumeStyle, 2 );
    }
    else if (displayStyle == “Volume at Price” )
    {
    PlotVAPOverlay ( Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide | Param_VAPOverlay );
    }
    else if (displayStyle== “Volume at Price (grouped)” )
    {
    PlotVAPOverlayA (segmentValue, Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide | Param_VAPStyle | Param_VAPOverlay);
    }
    else if (displayStyle == “Volume at Price + Volume” )
    {
    Plot ( Volume, “Vol “, Param_NormalVolumeColor, Param_NormalVolumeStyle, 2 );
    PlotVAPOverlay ( Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide | Param_VAPOverlay );
    }
    else if (displayStyle == “Volume at Price + Coloured Volume” )
    {
    Plot ( Volume, “Vol “, IIf ( C > O, Param_UpVolumeColor,Param_DownVolumeColor), Param_ColouredVolumeStyle, 2 );
    PlotVAPOverlay ( Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide | Param_VAPOverlay );
    }
    else if (displayStyle== “Volume at Price (grouped) + Volume” )
    {
    Plot ( Volume, “Vol “, Param_NormalVolumeColor, Param_NormalVolumeStyle, 2 );
    PlotVAPOverlayA (segmentValue, Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide | Param_VAPStyle | Param_VAPOverlay);
    }
    else if (displayStyle== “Volume at Price (grouped) + Coloured Volume” )
    {
    Plot ( Volume, “Vol “, IIf ( C > O, Param_UpVolumeColor,Param_DownVolumeColor), Param_ColouredVolumeStyle, 2 );
    PlotVAPOverlayA (segmentValue, Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide | Param_VAPStyle | Param_VAPOverlay);
    }
    else if(displayStyle== “Customised VAP / candles” ) TA_ShowCustomizedVAP (Param_Segment,Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide,Param_VAPStyle,Param_VAPOverlay);
    else if(displayStyle== “Customised VAP / candles + Volume” )
    {
    Plot ( Volume, “Vol “, Param_NormalVolumeColor, Param_NormalVolumeStyle, 2 );
    TA_ShowCustomizedVAP (Param_Segment,Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide,Param_VAPStyle,Param_VAPOverlay);
    }
    else if(displayStyle== “Customised VAP / candles + Coloured Volume” )
    {
    Plot ( Volume, “Vol “, IIf ( C > O, Param_UpVolumeColor,Param_DownVolumeColor), Param_ColouredVolumeStyle, 2 );
    TA_ShowCustomizedVAP (Param_Segment,Param_VAPLinesCount, Param_VAPLinesWidth, Param_VAPVolumeColor, Param_VAPSide,Param_VAPStyle,Param_VAPOverlay);
    }
    _SECTION_END ();
    }
    //=================== End of Volume Display================//

  49. How have you considered contract expiry days for Nifty Futures? Did you use adjusted Nifty Futures data for series rollover? In other words, were the prices continuous/adjusted at rollovers?

  50. Thanks for the reply. There are various ways to adjust data to make the contracts continuous. Some people calculate the difference between closing prices on expiry day of two consecutive contracts and then then do backward adjustment. Some calculate the ratio of closing prices on expiry day and then do adjustment. Some do forward adjustment.

    Just waned to understand, which methodology did you follow to manually adjust the data to make continuous?

  51. Hello Sir,

    Thanks for your efforts.
    Noticing small error. in Supertrend ver 4. on 16 Feb 2016 Reliance F&O shows sell signal at 949 in MTF (in red box left down corner) . Where as the sell signal actually came at 943.

    am I using wrong supertrend Is it possible to share the link for Original Super trend ver 4. PLs recheck at your end.

  52. Sir please help me as per super trend if sell signal came at 10:15 and candle are above 200 ema now 10:45 candle closes below 200 ema so how much time should i wait or signal should come on both simultaneosly

  53. Sir,

    Please suggest to whom we should consider more reliable while taking tarde break up/below super trend or break with super trend and ema combined

  54. Hi sir, Thanks for this good work you are giving to us.
    1. I have used auto trading nest now control. Orders are generated but not going into now terminal. I have Nest plus subscription also. That Nest plus 2.7 application is running in now terminal. Is it the same which you calling nest API or Nest API is different than nest plus 2.7 app running with now terminal? I have also going through your latest blogs and With your website only I understood technical analysis importance and now I am learning it also.
    2. I also started algo trading with symphony. Integrated supertrend 4 with presto and used it for paper trading. Signals are generating fine and working like miracle. Thanks for such good AFL.
    3. I also want to know can we give orders using supertrend 4 as buy call option for nifty when supertrend generate buy signal and when supertrend generate sell signal for nifty then order should place to buy put option for nifty. Please help me to create that afl. If it work then it will help lots of people who are loosing money trading with options. Thanks a lot again.

  55. Hi Rajandran,

    While using the verify syntax after pasting the code. I am getting error “Warning 506. You have specified precision that exceeds IEEE standard. Numbers are only accurate upto the 7th significant digit” in 2 places.

    line nos in your code: 265 & 531

    “Cl-“+C+” “+ “Vol= “+ WriteVal(V)+”\n”+

    “Cl-“+C+” “+ “Vol= “+ WriteVal(V)+”\n”+ EncodeColor(colorYellow)+ “\n\n\nLast 5 Trade Results\n” +

    I have just downloaded the version 6.0 of amibroker, should be because of that. Which version did you use for coding and any idea what should the syntax be in these 2 lines

    thanks,

  56. I want to learn this system .what is the procedure .

    online training is available. if ye send me the details.

  57. Rajendra Sir, Do you have the Supertrend AFL for LIntra, if you can share that for Ami.
    regards // Gururaj

  58. sir,
    i am intraday trader, i use super trend and volume for the same, i want exploration of super trend and increase volume on the same tick ,, same exploration, pls do needful

  59. Sir,

    Drawdown of 20% means INR 20,000 if initial capital is 1 Lac. But we require a margin of only 15% for buying Nifty lot.

    So does that mean, that the actual drawdown is 20%/15% = 133% ??

    Kindly clarify.

  60. Rajendra Sir,
    i need your help. Please help me.
    On going through the web, i came across a nice indicator of Meta-trader 4 named as “Megafxprofit”.Since i am using Amibroker and Metastock, I sincerely request you to convert this indicator coding suitable for Amibroker and Metastock.
    With regards
    Pradip

  61. Hi how to make this generate the buy/sell signal in the same candle and not in the open of the next candle? I changed settradedelays to 0 but it did not work. Please help Rajandran!!!!

  62. How to make this strategy work in same candle instead of open of next candle? I tried to change settradedelays to 0 but it did not work. Please help me Rajandran sir!!

  63. This code is not suited for timeframe like 30 min and 1 hour because it takes trade in the next candle.. How to make it take trade in the same candle? I don’t want to buy a stock at 12:31 if the supertrend was crossed sometime at 11:54. I want the signal to be generated at 11:54 itself.

Leave a Reply

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