Supertrend Automated Trading in Indian Markets


In this article, we will look at how to automatically trade in Indian stock markets using supertrend indicator.

Demo Video

AmiBroker Automated Trading


  • You will need AmiBroker charting software (even free version is sufficient)
  • You will need market datafeed
  • You need to install AutoTrader Web AmiBroker library
  • You need to have a trading platform supported by AutoTrader Web


Supertrend is a widely used technical indicator that works well in trending markets. The focus here is to look at the automation side, anyone interested in knowing more about Supertrend can simply Google it.

Supertrend generates buy/sell signals on chart. Every trader might have his own methods of how to trade those signals, we will consider a very simple method.


We will define quantity as a chart parameter. Once we get our first signal of the trading session, we will enter into a position with initial quantity set in parameters (Example, 10). From 2nd signal onward, we will use double quantity (20 in this case). This will make sure we close the previous position and enter into a new position as per the signal. It means after first signal we will always have a position open in the direction/signal of supertrend. At the end, we also set some chart parameters which will allow us set automatic square-off time.

Just to reiterate, how you trade using supertrend is your choice; but the basic logic for supertrend given here will remain the same.


  1. Start AutoTrader Desktop Client
  2. Use the afl for supertrend in AmiBroker
  3. Set chart parameters (Supertrend settings, trading settings etc.)
  4. Start your price datafeed
  5. That’s it, you are done. The system will automatically trade, whenever there is a signal.


Supertrend AFL
Supertrend AFL
Supertrend Chart Parameters
Supertrend Chart Parameters

Supertrend AFL Code

The sample afl can be found in AutoTrader installation (C:\autotrader\scripts\amibroker\Formulas\AutoTrader) & we have also given the code below. The explanation is already included in the AFL, please look at comments.

Those who are not interest in automation part can simply remove section 1 & section 3 from below code.

* AmiBroker supertrend with square-off option. 
* You need to set appropriate values in chart parameters.
* User Guide:
* API Docs:
* Symbol Search:
* Author - Stocks Developer

* This section contains all includes & should be at the top of your strategy afl.

#include <>
#include <>
#include <>


* SuperTrend indicator based automated trading afl example.
* There are many configurations available, please see chart parameters:
* - Automated time based square-off
* - Ability to place order on next bar or candle
* NOTE: It is recommended to start with a blank chart.

* How to see strategy logs in AMIBroker?
* 1. Enable log window from amibroker menu (Window -> Log)
* 2. You will see log window at the bottom.
* 3. Go to "Trace" tab (all strategy logs are printed here).

* This section contains your strategy afl code.


// SuperTrend parameters
Multiplier = Param("Period", 7, 1, 50 );
Period = Param("Multiplier", 3, 1, 10 );

// Chart parameters
UpColor = ParamColor("Up Color", colorGreen);
DownColor = ParamColor("Down Color", colorRed);
WickUpColor = ParamColor("Wick UP Color", colorLime);
WickDownColor = ParamColor("Wick Down Color", colorOrange);
ResistanceColor = ParamColor("Resistance", colorRed);
SupportColor = ParamColor( "Support", colorGreen);
Style = ParamStyle("Line Style", styleThick);

// Refresh even when minimized, see below link
RefreshPeriod = Param( "Timed Refresh Period", 5, 1, 300);
RequestTimedRefresh(RefreshPeriod, False);
SetChartOptions(0, chartShowArrows|chartShowDates);        
SetBarFillColor(IIf(C>O, UpColor, IIf(C<=O, DownColor, colorLightGrey)));        

Plot(C, "Price", IIf(C>O, WickUpColor, IIf(C<=O, WickDownColor, colorLightGrey)), styleCandle | styleNoTitle);

_N(Title = "Supertrend: " + 
	StrFormat("{{INTERVAL}} {{DATE}} \nOpen= %g, HiGH= %g, LoW= %g, Close= %g (%.1f%%) {{VALUES}}", 
		O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));         
function calculateSupertrend(Period, Multiplier)

	for( i = Period; i < BarCount; i++ )
		UpperBand[i]=((High[i] + Low[i])/2) + Multiplier*ATR_Val[i];
		LowerBand[i]=((High[i] + Low[i])/2) - Multiplier*ATR_Val[i];
		final_UpperBand[i] = IIf( ((UpperBand[i]<final_UpperBand[i-1]) OR (Close[i-1]>final_UpperBand[i-1])), (UpperBand[i]), final_UpperBand[i-1]);
		final_LowerBand[i] = Iif( ((LowerBand[i]>final_LowerBand[i-1]) OR (Close[i-1]<final_LowerBand[i-1])), (LowerBand[i]), final_LowerBand[i-1]);
		SuperTrend[i] = IIf(((SuperTrend[i-1]==final_UpperBand[i-1]) AND (Close[i]<=final_UpperBand[i])),final_UpperBand[i],
		IIf(((SuperTrend[i-1]==final_UpperBand[i-1]) AND (Close[i]>=final_UpperBand[i])),final_LowerBand[i],
		IIf(((SuperTrend[i-1]==final_LowerBand[i-1]) AND (Close[i]>=final_LowerBand[i])),final_LowerBand[i],
		IIf(((SuperTrend[i-1]==final_LowerBand[i-1]) AND (Close[i]<=final_LowerBand[i])),final_UpperBand[i],0))));

	Plot( SuperTrend, "SuperTrend", IIf( SuperTrend>Close, ResistanceColor, SupportColor), Style);
	Return SuperTrend;  

SuperTrend = calculateSupertrend(Period,Multiplier);

// This will tell us if the line is green or red (i.e. buy or sell)
// Close > Supertrend == BUY Signal otherwise SELL
SupertrendSignal = Close > SuperTrend;

// This will tell us whenever there is a change in signal
SignalChanged = SupertrendSignal != Ref(SupertrendSignal, -1);

// If supertrend is buy and signal just changed
Buy = SupertrendSignal AND SignalChanged;

// If supertrend is sell and signal just changed
Sell = (!SupertrendSignal) AND SignalChanged;

// Additional safety, remove excessive signals

// This is only added for backtesting


* This section contains your code for placing orders.
* shouldSquareOff() returns 1 when current time goes beyond square off time.
if(shouldSquareOff()) {
	if(!isSquareOffRequestSent()) {
		// Square off position, as current time has gone passed square off time
		// Assuming the position is MIS
		squareOffPosition(AT_ACCOUNT, "DAY", "MIS", AT_EXCHANGE, AT_SYMBOL);
		saveStaticVariable(AT_ACCOUNT, AT_SQUARE_OFF_STATUS_KEY, 1);
else {

	BuySignal = Buy;
	SellSignal = Sell;

		// Use signals from previous bar (when place order on next bar is turned on)
		BuySignal = Ref(Buy, -1);
		SellSignal = Ref(Sell, -1);		

	* If control reaches here, it means we are before square off time,
	* so we can place orders.
	if ( LastValue(BuySignal) == True &amp;&amp; isNewBar() )
		* We do some calculation to double the quantity, for all orders except first.
		* This is done so that we can re-enter a position. Following this approach
		* we can avoid using Short &amp; Cover.
		quantity = calcDoubleQuantity(AT_ACCOUNT, AT_SYMBOL, AT_QUANTITY);

			AT_PRODUCT_TYPE, quantity, buyPrice, defaultTriggerPrice(), True);

	if ( LastValue(SellSignal) == True &amp;&amp; isNewBar() )
		* We do some calculation to double the quantity, for all orders except first.
		* This is done so that we can re-enter a position. Following this approach
		* we can avoid using Short &amp; Cover.
		quantity = calcDoubleQuantity(AT_ACCOUNT, AT_SYMBOL, AT_QUANTITY);
			AT_PRODUCT_TYPE, quantity, sellPrice, defaultTriggerPrice(), True);
		// Special handling when place order on next bar or candle is ON
		// This must be done after place order code
		if(LastValue(Buy) == True || LastValue(Sell) == True ||
			LastValue(Short) == True || LastValue(Cover) == True) {
			// Save time of current bar when we get signal
			saveStaticVariable(AT_ACCOUNT, AT_PREVIOUS_BAR_END_TIME, Status( "lastbarend" ));


After spending more than 12 years developing Financial Software, I took a break from my career to start my own algorithmic trading setup. This new journey started well and along with my own proprietary trading systems, I also started building automation systems for retail traders, fund managers and HNIs. I was employed with firms like Morgan Stanley, HSBC & SunGard. I work on various technologies, but my strengths are building server side cloud based algorithmic trading systems built primarily using Java programming language. Apart from all of this, I am a big fan of Formula 1 racing :-)

13 thoughts on “Supertrend Automated Trading in Indian Markets”
  • rajni kant says:

    so good to see that you are giving examples of trading systems and how to use them with auto trader functions. can you add also examples of scaling in or out functions along with buy sell orders using half of the quantity.? thanks.

    November 3, 2019 at 3:00 pm
  • akash says:

    your platform is not suitable to trad in live account..because it gets disconnected automatically and I need to re login and need to keep watching that connectivity is going or or disconnected.

    November 7, 2019 at 10:49 am
    • Admin says:

      Disconnections will happen on upstox and aliceblue if you manually logged into to trading platform. Because that will invalidate AutoTrader’s login into your trading platform.

      November 8, 2019 at 7:05 am
  • Mahesh Thimmaraju says:

    Actually .. lots of sytax error in file

    December 9, 2019 at 5:45 pm
    • Admin says:

      In your strategy afl, use
      You must be on amibroker version 5.7 or below.

      December 12, 2019 at 5:42 pm
  • pawan says:

    Hi Admin,

    Good Application. Please add trailing Stoploss. This will make new traders to try your application more.

    January 10, 2020 at 4:27 pm
    • Pritesh says:

      You can use Bracket Orders which have an option to set trailing stoploss.

      January 13, 2020 at 3:54 am
  • niket says:

    Are you proveide RENKO chart in nearer future?

    January 22, 2020 at 9:41 am
  • Yadav says:

    Hai sir, I am ur subscriber. I have only one request that please make martingale strategy afl including exposure using supertrend for aututrader and publish us. Because doubling of amount for the next trade gives profit whenever losing a trade. Please look into the matter. One more request that please upgrade the software for pacing orders into multiple clients by using single charting platform.

    January 25, 2020 at 12:01 pm
  • Kanchan says:

    Multiplier = Param(“Period”, 7, 1, 50 );
    Period = Param(“Multiplier”, 3, 1, 10 );

    What does 1,50 & 1,10 used for ?
    What are typically suitable values for Period & Multiplier for Banknifty intraday please ?

    January 26, 2020 at 9:43 am
    • Pritesh says:

      Param is an amibroker function, more details are available on:

      Suitable values are not given by us, it is upto the user to perform relevant analysis/backtesting and come up with values that he/she feels comfortable.

      January 26, 2020 at 1:54 pm
Leave A Comment