Introduction
In this article, we will look at how to automatically trade in Indian stock markets using supertrend indicator.
Demo Video
Prerequisite
- 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
Description
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.
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.
Process
- Start AutoTrader Desktop Client
- Use the afl for supertrend in AmiBroker
- Set chart parameters (Supertrend settings, trading settings etc.)
- Start your price datafeed
- That’s it, you are done. The system will automatically trade, whenever there is a signal.
Screenshots
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: https://stocksdeveloper.in/documentation/index/
* API Docs: https://stocksdeveloper.in/documentation/api/
* Symbol Search: https://web.stocksdeveloper.in/instrument
*
* Author - Stocks Developer
*/
/********************************************************************
* SECTION 1 - BEGIN
* This section contains all includes & should be at the top of your strategy afl.
********************************************************************/
#include <autotrader.afl>
#include <autotrader-square-off.afl>
#include <autotrader-next-bar.afl>
/********************************************************************
* SECTION 1 - END
********************************************************************/
/*******************************************************************
* 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).
********************************************************************/
/********************************************************************
* SECTION 2 - BEGIN
* This section contains your strategy afl code.
********************************************************************/
_SECTION_BEGIN("Supertrend");
// 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
// https://forum.amibroker.com/t/program-pauses-when-amibroker-minimized/4145/2
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)
{
ATR_Val=ATR(Period);
UpperBand=LowerBand=final_UpperBand=final_LowerBand=SuperTrend=0;
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
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);
// This is only added for backtesting
Short=Sell;
Cover=Buy;
/********************************************************************
* SECTION 2 - END
********************************************************************/
/********************************************************************
* SECTION 3 - BEGIN
* 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;
if(AT_PLACE_ORDER_ON_NEXT_BAR) {
// 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 && 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 & Cover.
*/
quantity = calcDoubleQuantity(AT_ACCOUNT, AT_SYMBOL, AT_QUANTITY);
placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "BUY", "MARKET",
AT_PRODUCT_TYPE, quantity, buyPrice, defaultTriggerPrice(), True);
}
if ( LastValue(SellSignal) == True && 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 & Cover.
*/
quantity = calcDoubleQuantity(AT_ACCOUNT, AT_SYMBOL, AT_QUANTITY);
placeOrder(AT_ACCOUNT, AT_EXCHANGE, AT_SYMBOL, "SELL", "MARKET",
AT_PRODUCT_TYPE, quantity, sellPrice, defaultTriggerPrice(), True);
}
if(AT_PLACE_ORDER_ON_NEXT_BAR) {
// 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" ));
}
}
}
/********************************************************************
* SECTION 3 - END
********************************************************************/
_SECTION_END();
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 pmyour 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 amDisconnections 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 amActually .. lots of sytax error in algotrader-util.afl file
December 9, 2019 at 5:45 pmIn your strategy afl, use algotrader-util-old.afl
December 12, 2019 at 5:42 pmYou must be on amibroker version 5.7 or below.
Hi Admin,
Good Application. Please add trailing Stoploss. This will make new traders to try your application more.
January 10, 2020 at 4:27 pmYou can use Bracket Orders which have an option to set trailing stoploss.
January 13, 2020 at 3:54 amAre you proveide RENKO chart in nearer future?
January 22, 2020 at 9:41 amNo
January 23, 2020 at 3:05 pmHai 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 pmProviding strategies is not our priority at the moment, please get it developed from freelance developers.
For multiple accounts, refer below link:
https://stocksdeveloper.in/2018/12/08/autotrader-faq/#how-to-trade-multiple-accounts
January 26, 2020 at 9:09 amMultiplier = Param(“Period”, 7, 1, 50 );
Period = Param(“Multiplier”, 3, 1, 10 );
What does 1,50 & 1,10 used for ?
January 26, 2020 at 9:43 amWhat are typically suitable values for Period & Multiplier for Banknifty intraday please ?
Param is an amibroker function, more details are available on:
https://www.amibroker.com/guide/afl/param.html
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 pmnice afl…your sample autotrader afl helped us a lot to begin with…can you include some buy and sell afl for option spread startegy coz new SEBI rule in order to reduce margin has made it near mandatory to buy or sell spreads…how to include another option in buy or sell which is not visible on chart??
February 4, 2021 at 11:47 pmA place order function does not really depend on the chart. It depends on what values are being passed to it’s parameters. So theoretically you can place orders into any number of stocks or derivatives from a single chart. Just make sure you pass correct AT Web instrument (exchange & symbol). Use our global instrument search tool to find AT Web instrument (exchange & symbol). See API docs for more information.
February 5, 2021 at 1:20 pm