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 V3.0 AFL code with Buy and Sell Alerts

5 min read

Supertrend V3.0 is the upgraded version of Supertrend Indicator. The trading logic remains the same however a lot of bugs got removed and few features added in the current version. Multiple Consecutive Sound and Popup alert issues got resolved. Now you will be getting only one sound and popup alert whenever there is a buy or sell signal occurrence.

Features Added
1)Scan Based Popup and Sound Alerts in Amibroker as shown below. If you enabled real-time Scanning now you should see a popup coming for the matched scanned scrips.

Realtime Scan Alert

 

2)Supertrend Indicator with Last 5 Trades Dashboard
Nifty Supertrend V3.0

Other Existing Features
1)Trading Dashboard.
2) Non-Repainting Indicator.
3)Time left feature which alerts the end of the current running candle.

Supertrend V3.0 Amibroker AFL code

If you are very new to trading follow this video to know more about super trend

/* Done by    Rajandran R  */
/* Author of www.marketcalls.in  */
/* Date : 10th Dec 2019 */

_SECTION_BEGIN("New Supertrend V3.0");

global trend, TrendUp, TrendDown;

function supertrend(Factor, Pd)
{

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



iATR=ATR(Pd);

TrendUp=TrendDown=Null;  //Final Trailingstop array for both Buy and Short Signal

trend[0]=1; // 1 - buy continuing and (-1) short is continuing

changeOfTrend=0; //transition from buy to sell or sell to buy

flag=flagh=0;


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

      TrendUp[i] = Null;

      TrendDown[i] = Null;

      trend[i]=1;
      
      
         if (Close[i]>Up[i-1]) {  // if close is breaking the upper channel

         trend[i]=1; //positive trend started or ongoing

         if (trend[i-1] == -1) changeOfTrend = 1;  //change in trend from negative to positive

         

      }//if loop closed
      
      
      else if (Close[i]<Dn[i-1]) { //if the candle is closing below the down channel

         trend[i]=-1; //negative trend started or ongoing

         if (trend[i-1] == 1) changeOfTrend = 1; //change in trend from positive to negative

      }
      
       else if (trend[i-1]==1) {  // buy continues

         trend[i]=1;

         changeOfTrend = 0;    //existing trend continues   

      }

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

         trend[i]=-1;

         changeOfTrend = 0; //existing trend continues  

      }
      
      
      if (trend[i]<0 && trend[i-1]>0) {  //transition from buy to sell

         flag=1; //signal just changed from buy to sell signal

      }

      else {

         flag=0;

      }

      

      if (trend[i]>0 && trend[i-1]<0) {  //transition froms sell to buy

         flagh=1; //signal just changed from sell to buy signal

      }

      else {

         flagh=0;

      }

 
 
 //remodifying my channel so that it behaves like a stoploss     

      if (trend[i]>0 && Dn[i]<Dn[i-1]){ //if current trend is positive down channel is my trailing stoploss

         Dn[i]=Dn[i-1]; // keeping the downchannel flat whenver down channel is going down. Here want to trail the downchannel only if the down channel value increases compared to prev downchannel

		}

      

      if (trend[i]<0 && Up[i]>Up[i-1])  //if the current trend is negative upper channel as our trailing stoploss

        { Up[i]=Up[i-1]; //keeping the up channel flat whenver up channel value increases. Here want to trail the upperchannel - trail downwards. if the upper channel value is decrated

		}

      

      if (flag==1) //transition from buy to sell;

       {  Up[i]=(H[i]+L[i])/2+(Factor*iATR[i]); //resetting the upper channel when fresh sell signal happens. upper channel will act like a short TSL

        } 

      if (flagh==1) //sell to buy

        { Dn[i]=(H[i]+L[i])/2-(Factor*iATR[i]); //resetting the down channel fresh uptrend (buy signal happens) lower channel will act like a long TSL

         } 
         
         
         
         
         
      if (trend[i]==1) {

         TrendUp[i]=Dn[i];  //remodified down channel

         if (changeOfTrend == 1) {  //negative trend to positive trend

            TrendUp[i-1] = TrendDown[i-1];  //transition/swithcover in Trailing stops

            changeOfTrend = 0;

         }

      }

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

         TrendDown[i]=Up[i];  //remodified up channel

         if (changeOfTrend == 1) {

            TrendDown[i-1] = TrendUp[i-1]; //transition/swithcover in Trailing stops


            changeOfTrend = 0;

         }

      } 
       
      






}//for loop


}





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 Candles AND X-Axis 
SetChartOptions(0, chartShowArrows | chartShowDates); //x-Axis will be plottted
Plot(Close,"Close",colorDefault,GetPriceStyle() | styleNoTitle);



Multipier=Param("Factor",3,1,10,0.1);
Period=Param("ATR Periods",10,1,100,1);
colorup = ParamColor("Up Color",colorGreen);
colordown = ParamColor("Down Color",colorRed);

supertrend(Multipier,Period);



//Plot Trailing Stoploss
Plot(TrendUp,"Trend",colorup,styleThick);
Plot(TrendDown,"Down",colordown,styleThick);

//Plot(up,"upper",colorRed,styleLine | styleThick);
//Plot(Dn,"Lower",colorgreen,styleLine | styleThick);


Buy = trend == 1;
Sell = trend == -1;


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


Short = Sell;
Cover = Buy;

//Non Repainting  - Signals happens only after the close of the current ( 1 bar delay is introduced while making non repainting)
//Intialize trade delay to zero to avoid any over-riding from external parameters - 
SetTradeDelays(0,0,0,0);


//Generate Signals on Closing Basis - Non Repainting and Signals delayed by 1 bar
Buy = Ref(Buy,-1);
Sell = Ref(Sell,-1);
Short = Ref(Short,-1);
Cover = Ref(Cover,-1);


buycontinue = Flip(Buy,Sell);
shortcontinue = Flip(Short,Cover);



//Buy at Next Bar Open, Trade Delay is already given at 
BuyPrice=ValueWhen(Buy,Open);
SellPrice=ValueWhen(Sell,Open);
ShortPrice=ValueWhen(Short,Open);
CoverPrice=ValueWhen(Cover,Open);

/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-60);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-70);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-65);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=60);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=70);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-65);




for( i = 0; i < BarCount; i++ ) 
 { 
if( Buy[i] ) PlotText("Buy",i,L[i],colorWhite,colorLime,-40);
if( Short[i] ) PlotText("Short",i,H[i],colorWhite,colorRed,40);
//if( Sell[i] ) PlotText( "Selln@" + C[ i ], i, H[ i ]+dist[i], colorRed, colorYellow ); 
 } 




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


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

{

if(Buy[i] == 1)

{

entry = open[i];

sig = 1;  //flag contains 1 when buy is valid

sl = TrendSL[i]; //initial stop for buy

tar1 = entry + (entry * .0050);

tar2 = entry + (entry * .0092);

tar3 = entry + (entry * .0179);

 

bars = i;

i = 0;

}

if(Sell[i] == 1)

{

sig = -1; //flag contains -1 wjhen sell is valid

entry = open[i];

sl = TrendSL[i]; //initial stop for the sell

tar1 = entry - (entry * .0050);

tar2 = entry - (entry * .0112);

tar3 = entry - (entry * .0212);

 

 

bars = i;  // i - holds the value of bar index, computing the barindex value when the signal happened

i = 0;

}

}//for loop



Offset = 20;

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

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

sl = ssl[BarCount-1];

 

//plot target lines

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

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

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


_SECTION_END();

_SECTION_BEGIN("Signal Dashboard");

messageboard = ParamToggle("Message Board","Show|Hide",1);
upcolor = ParamColor("Up Color",colorBlue);
dncolor = ParamColor("Down Color",colorRed);



if (messageboard == 1 )

{

GfxSelectFont( "Tahoma", 13, 100 );

GfxSetBkMode( 1 );

GfxSetTextColor( colorWhite );


//Dashboard color changes dynamically according to the signals continuation
color = IIf(buycontinue, upcolor, IIf(shortcontinue, dncolor, Null));



GfxSelectSolidBrush(SelectedValue(color));


pxHeight = Status( "pxchartheight" ) ;

xx = Status( "pxchartwidth");

Left = 1100;
width = 310;

x = 5;
x2 = 360;
y = pxHeight;

sigstatus = WriteIf(buycontinue,"Buy Signal @ ","Sell Signal @");

 

GfxSelectPen( colorGreen, 1); // broader color
GfxRoundRect( x, y - 98, x2, y , 7, 7 ) ;
GfxTextOut( ( "Marketcalls - Supertrend"),13,y-100);
GfxTextOut( (" "),27,y-100);

if(SelectedValue(Buycontinue))
{
GfxTextOut( ("Last " + sigstatus + " Signal came " + BarsSince(Buy) * Interval()/60 + " mins ago"), 13, y-80) ; // The text format location
GfxTextOut( ("" + sigstatus + " : " + ValueWhen(Buy,BuyPrice)), 13, y-60);
GfxTextOut( ("Profit/Loss : " + NumToStr(Close-ValueWhen(Buy,BuyPrice),1.2)), 13, y-22);
}

if(SelectedValue(Shortcontinue))
{
GfxTextOut( ("Last " + sigstatus + " Signal came " + BarsSince(short) * Interval()/60 + " mins ago"), 13, y-80) ; // The text format location
GfxTextOut( ("" + sigstatus + " : " + ValueWhen(Short,ShortPrice)), 13, y-60);
GfxTextOut( ("Current P/L : " + NumToStr(ValueWhen(Short,ShortPrice)-Close,1.2)), 13, y-22);
}


GfxTextOut( ("Trailing SL : " + Ref(TrendSL,-1) + " (" + WriteVal(IIf(sig == -1,entry-sl,sl-entry), 2.2) + ")"), 13, y-40);


}


_SECTION_END();

_SECTION_BEGIN("Top Dashboard");

X0 = 10;
Y0 = 20;

procedure DrawData (Text, x1, y1, x2, y2, colorFrom, colorTo)
{
	GfxSetOverlayMode(0);
	GfxSelectFont("Verdana", 8.5, 700);
	GfxSetBkMode(1);
	GfxGradientRect(x1, y1, x2, y2, colorFrom, colorTo);
	GfxDrawText(Text, x1, y1, x2, y2, 32|1|4|16);
}


DrawData (Name(), X0, Y0, X0+150, Y0+20, colorGrey40, colorblack);
DrawData (Date(), X0+155, Y0, X0+320, Y0+20, colorGrey40, colorblack);
DrawData ("Open : " + Open, X0+325, Y0, X0+450, Y0+20, colorGrey40, colorblack);
DrawData ("Close : " + Close, X0+455, Y0, X0+580, Y0+20, colorGrey40, colorblack);
DrawData ("High : " + High, X0+585, Y0, X0+710, Y0+20, colorGrey40, colorblack);
DrawData ("Low : " + Low, X0+715, Y0, X0+840, Y0+20, colorGrey40, colorblack);


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

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

Reversal Finder – Tradingview to Amibroker AFL Code Conversion

Reversal Finder is designed to identify potential reversal signals in a stock's price action. It highlights specific bars that meet the criteria for a...
Rajandran R
2 min read

CM Williams VIX FIX Pinescript to Amibroker AFL Conversion

Thought of converting some of the top-rated pinescript codes to Amibroker AFL code. So started with CM Williams VIX FIX with 51,000+ ratings for...
Rajandran R
1 min read

69 Replies to “Supertrend V3.0 AFL code with Buy and Sell Alerts”

  1. Great job Sir !! Can you kindly provide us a MT4 version of this wonderful indicator please

    Thanks in advance.

  2. While scan using the analysis getting error 29 on line 475 and col 45 -variable entry used without having been initialized.
    Can you give solution for removing this error.
    Thanks.

    1. You will get such error only if you dont have enough data in any one of the symbol. Its better to have a watchlist with limited set of symbols and also make sure that you have enough candle available in the scanning timeframe.

  3. Should be able to make phone call/sms alert (may be plug model wil help) to your desired mobile using api such as twilio

  4. Sir,

    Please guide how to insert your code in amibroker & RUN THE SAME AS results on your website & results in amibroker is different

  5. Hi Sir,
    I am looking for a afl that gives alert when 78-62% retracement from the pr.high or low. Does it possible to do automatic with the above said requirements. i have found many Fibonacci afls, But nothing shows the reversal exploraion or alert

    1. 1)Make sure you have enough candles in your charts – a min of 200 candles on any timeframe is required
      2)Make sure you are using Amibroker 5.6 version or above
      3)Download the Zip folder or copy the AFL using the Raw button. Avoid copying the AFL directly from the above Editor.

      Following these three steps you should be able to install the indicator properly.

  6. Sri Rajendran, it is a great job. Excellent chart and it is serving many traders.May I suggest a small improvement : A day separating vertical line (dotted) will help in study.
    You may consider to incorporate in the chart.
    Thanks for the excellent chart.

  7. Sir,

    Please guide. I have read all your notes for mapping now RTD to amibroker. my excel sheet RTNOW refreshed properly but no data comes inamibroker.

    Please guide in setup

  8. Hi, sir please try to add additional text, in terms of points moved in short and long trades with respect to high (in case of buy ) and low ( in case of sell ) from the signal, keeping the same last 5 trades . keep the points moved in the sub bracket sir ,so that its easy to take a decision for profit as a scalping , please please post it immediately sir

  9. Thank you sir nest rtd works fine as now replacement . Sir ihave incurred huge losses earlier. can u please tell how to trade on your nifty chart or some good strategy in options so that i can recover my losses.

  10. Hi, I get an error stating Variable ‘entry’ used without having been initialized. this error is appearing sometimes and does not appear sometime in the market watch. But when I click on analysis and explore this error comes every time. Please advice. I use AmiBroker 5.7 with GFDL data

  11. I am not sure but wanted to ask whether there any change in factor and period from 3, 7 to 4, 10. If yes is this to change in market condition. Would like to understand the reason if there was any change

  12. what can i say …… u do Gr8 job… Rajandra,,,, thanks alot

    wish u happy new year ….2015

  13. Can u please guide what trade 1 & trade 5 denotes which one is the latest trade. Also what is the calculation crieteria for the same

  14. Hi!

    Thanks for the new version…..it looks good visualy…

    when i tried to backtest in amibroker 5.9,,,it gave NO TRADES in 1.5 year data but when did scan …it gave buy or sell but at the same time short or cover……..

    previous version gave result……

    what is the ideal settings for nifty and banknifty…..without whipsaws….

    thanks

  15. Dear Sir,
    Super trend is really helping us taking correct trading decision, just wondering if there is any possibility to include SL and Target in alertif mail function.

    Regards
    Sandip

  16. Hi sir,

    please add additional information in the afl that pips moved for high in buy signal , and pips moved low for sell signal , please try to add it sir , it will be great help by keeping the same above last 5 trades give this additional information ..thanks in advance sir

      1. Hi sir,

        please add additional information in the afl that pips moved for high in buy signal , and pips moved low for sell signal , please try to add it sir , it will be great help by keeping the same above last 5 trades give this additional information ..thanks in advance sir

  17. Sir,

    It is possible to get last 5 trades report of 15 min or hourly basis trades also at your live charts

      1. may be a drag & drop menu for trade reports work i.e.if person select for 15 min or 1 hour only trade report for that shows

  18. Hi Raj, Thanks for the share. Is it best used in 5 min or 15 min chart ? Coz confused as to in which time frame it works best.

  19. Dear Rajandran,

    “1)Make sure you have enough candles in your charts — a min of 200 candles on any timeframe is required
    2)Make sure you are using Amibroker 5.6 version or above
    3)Download the Zip folder or copy the AFL using the Raw button. Avoid copying the AFL directly from the above Editor.

    Following these three steps you should be able to install the indicator properly.”

    I have met all the 3 conditions however facing the below challenges:

    1. “variable entry used without having been initialized.” error while scanning. I have real-time data since 8th Dec ’14.

    2. Trading Dashboard not visible.

    3. Time Left not visible.

    4. Last 5 trades shows result only of longs and not of shorts.

    Thanks.

  20. sir backtest showing only one date i want all signal in result in 5min timeframe how to ??

      1. Sir what do you mean by 12 consecutive losses some time back, as we are believing only 8 consecutive losses, its strange to me now

  21. Sir,

    If you conduct work shop in Chennai, it will very help full to us..Please in chennai.

  22. Sir, when all the three targets are achieved as per your Super Trend V 3.0, but price is still moving above or below the targets then how to set new targets or stop loss
    can you advice sir

    regards

    1. You have to re-write your rules programatically to do that. Any thing you have to do customization according to your requirement you have to sit and tweak it out programatically.

  23. How long did it take to code with such complex stuff. I just started learning AFL do you have any suggestions what to refer or any courses etc.

  24. How long did it take to code such complex stuff. I just started learning AFL any suggestions.

  25. Hi sir , please try to add just 3 more last trades, so that we can clearly see the last 8 trades resuts, its great help to take the deicsions , please try to add 3 more trade results sir …….hope you will update it asap. thanks in advance sir

  26. sir ..

    Please tell once again ” How to Trade with this formula”

    Profitable ???

    i using but ****

    Please Explain

    Thank you.

    1. Supertrend is yet another trading strategy. So test it out if it suits your risk profile then trade it otherwise try to understand what is your risk ability. Else try to find the strategy thats suits your risk profile.

  27. Hi sir, please see , last 5 trades statistics were showing wrong , please try to coreect it sir, and is it possible to add just 3 more results for it, so total 8 trades visisble clearly , already its great tool adding this will enhance the trader money management please try to see

    thanks and regards

  28. Hi sir , please cehck in few scrips like nicke , silver and also in nifty future stocks trade 4 and trade 5 were showing wrong results, please try to correct them sir, and also please try to add 3 more trade results sir, its a great ehlp please do it sir , thanks alot for sharing this to traders at free of cost

  29. Hi sir, you are giving free servide but to maximise the benefit please check once last trade results are showing wrong sir, please cehck once sir, and also add 3 more trades sir, please please do it sir

      1. Does this mean we need to download the supertrend 4.0 afl again which is corrected for the above said issue? Please advice.

  30. I want to create a dll plugin which reads buy/sell signal from real time data in amibroker. Then I want to send those signals to my website.
    Do I need to code the entire thing in afl ? How should I proceed ?

  31. Dear Sir,
    Am new to this business and just discovered about supertrend could you please let me know how to use this particular version of supertrend in Pi by Zerodha and if not what would be other similar options, if any?

    thanks.

    1. Supertrend is achieved with advance AFL. In other hand Pi itself uses TradeScript and it is very difficult to compose supertrend with it.
      What u could do is to connect Pi with Amibroker with Pibridge, a bridging app comes with one week trial and 500 rs afterwards from Zerodha . Whenever supertrend generate signal , it will automatically published into Pi trading platform under “generated alert” tab.

  32. Sir

    I started using your AFL, which is very good.

    One small issue.
    How to see “trigger value” or stoploss value on “Y axis” sir??

    I can see close value on Y axis, but can’t see stoploss value.
    Can you please help me

    Thanks

  33. What is the meaning of Factor??

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

    Pd=Param(“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 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) {

    flag=1;

    }

    else {

    flag=0;

    }

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

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

    }

    if (trend[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;

  34. dear sir!
    I’ve following you for 3 years and really believe in your code honestly.
    Now, I wanna understand the logic to expand or develop it. So, can you explain this text for me to understand what is express for?

    “…………………….”

Leave a Reply

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