TradingView – Supertrend (Automated Trading)

Supertrend - TradingView

In this post, we will implement automated trading on a Supertrend strategy inside TradingView. At the time of writing, automated trading on TradingView is supported for 5Paisa, AC Agarwal, AliceBlue, AnandRathi, Angel, ATS, Choice, Finvasia, Flattrade, Fyers, IIFL, Jainam, Kotak, Mastertrust, Motilal, Profitmart, SAS, SW Capital, Upstox, Wisdom Capital, Zerodha, Symphony XTS.

The primary reason to use strategies are:

  • Backtesting
  • Easily add and configure parameters
  • Easily double the quantity when the signal changes
  • Use placeholders available from strategy

The strategy is for learning & demonstration purposes only. We DO NOT promise any returns.

Admin

Demo

TradingView – Supertrend Automated Trading Intraday (English)

Strategy Logic

This is a very basic Supertrend strategy. It will run between the specified session time. So set the start time and end time when you want to start & stop your intraday trading respectively.

Take a long position, when the price crosses above Supertrend.

Take a short position, when the price crosses below Supertrend.

Automatically use double quantity for all signals except first and last. This will make sure, that our positions is reversed whenever there is a change in signal.

Assume you have set a quantity to be 10. The strategy will enter into a position with quantity 10. After this, for every signal the quantity is double the base quantity. This makes sure we take a reverse position every time the signal changes. Finally, if the session end time has passed, the strategy will square off the open position.

Setup

Process

Step 1: Create a strategy

  1. Go to TradingView
  2. Click on Chart option on the top
  3. Choose the stock/derivative you want to work on by selecting the Symbol (you can see the symbol on LEFT TOP section of the chart screen)
    1. You can select any symbol (stock, derivatives on NSE, BSE or MCX)
  4. Click on Pine Editor (it can be found on BOTTOM section of the chart screen)
  5. Change the name from “Untitled Script” to “Supertrend – Intraday
  6. Remove existing content from the script and add following moving average code
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pritesh-StocksDeveloper
 
//@version=5
strategy("Supertrend - Intraday", overlay=true, calc_on_every_tick = false)
 
// ********** Strategy inputs - Start **********
 
// Used for intraday handling
// Session value should be from market start to the time you want to square-off 
// your intraday strategy
// Important: The end time should be at least 2 minutes before the intraday
// square-off time set by your broker
var i_marketSession = input.session(title="Market session",
     defval="0915-1455", confirm=true)
 
var float i_multiplier = input.float(title = "Multiplier",
     defval = 4, step = 0.1, confirm=true)
 
var int i_atrPeriod = input.int(title = "ATR Period",
     defval = 14, confirm=true)
 
// ********** Strategy inputs - End **********
 
 
// ********** Supporting functions - Start **********
 
// A function to check whether the bar or period is in intraday session
barInSession(sess) => time(timeframe.period, sess) != 0
 
// ********** Supporting functions - End **********
 
 
// ********** Strategy - Start **********
 
[superTrend, dir] = ta.supertrend(i_multiplier, i_atrPeriod)
 
colResistance = dir == 1 and dir == dir[1] ? color.new(color.red, 0) : color.new(color.red, 100)
colSupport = dir == -1 and dir == dir[1] ? color.new(color.green, 0) : color.new(color.green, 100)
 
plot(superTrend, color = colResistance, linewidth=2)
plot(superTrend, color = colSupport, linewidth=2)
 
// Long/short condition
longCondition = close > superTrend
shortCondition = close < superTrend
 
// See if intraday session is active
bool intradaySession = barInSession(i_marketSession)
 
// Trade only if intraday session is active
  
// Long position
// When longCondition and intradaySession both are true
strategy.entry(id = "Long", direction = strategy.long, 
     when = longCondition and intradaySession)
  
// Short position
// When shortCondition and intradaySession both are true
strategy.entry(id = "Short", direction = strategy.short, 
     when = shortCondition and intradaySession)
  
// Square-off position (when session is over and position is open)
squareOff = (not intradaySession) and (strategy.position_size != 0)
strategy.close_all(when = squareOff, comment = "Square-off")
 
// ********** Strategy - End **********

Step 2: Backtest & optimize

  1. Click “Add to chart” button above the pine script editor
  2. You can select the values of the parameters (short/long term moving average etc.)
  3. You strategy will be added to the chart & it will automatically open “Strategy Tester
  4. You can see backtest results in “Strategy Tester“, there are 3 different sections:
    1. Overview – Graphical representation of your backtest results
    2. Performance Summary – Summary statistics of your backtest results
    3. List of trades – All trades that were generated by your strategy during backtesting
  5. Optimization involves changing the parameters to improve the strategy performance
    1. You can click the small Settings icon available in “Strategy Tester” just to the right of your strategy name. Modify the parameters and backtest again.

Parameters

See below screenshots to understand how to set the parameters of the strategy as well as contracts (or quantity).

Important: Make sure you set the session ending time at least 2 minutes before your broker’s intraday square-off time.

Supertrend Parameters
TradingView Strategy Parameters
Supertrend Parameters (Quantity)
TradingView Strategy Quantity

Step 3: Automated Trading

Once you have found a correct set of parameters which give good performance. The next step is to setup automated trading.

  1. Click on the create alert button
    1. You can find this button in the strategy tester (next to the strategy name)
    2. It is also available next to the indicator that has been added to your chart (click the 3 dots & you will see this option
  2. A create alert window will be open, which looks like this
Create alert
Create Alert

Alert Settings

Let us now understand the alert settings that we have set.

Condition

The value of condition should be the strategy that you just added.

Important: You must set desired parameters to your strategy before creating the alert.

Webhook Url

https://tv.stocksdeveloper.in/?apiKey=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX&account=ACC-NAME&group=false

Replace the api key, account name & group parameters with your values.

  • API Key can be found in AutoTrader Web menu (Settings -> API Key)
    • Do not share this key with anyone
  • ACC-NAME is your pseudo account or group account name, see this link if you want to understand what these are.
  • group should be true if you are passing a group account, false otherwise

Alert Name

You can give any name of your choice to the alert.

Message

This is important, this will decide what orders will be placed in your account.

{
    "command": "PLACE_ORDERS",
    "orders": [
        {
            "variety": "REGULAR",
            "exchange": "NSE",
            "symbol": "SBIN",
            "tradeType": "{{strategy.order.action}}",
            "orderType": "MARKET",
            "productType": "INTRADAY",
            "quantity": {{strategy.order.contracts}}
        }
    ],
    "exchange": "{{exchange}}",
    "ticker": "{{ticker}}",
    "price": "{{close}}",
    "supertrend-resistance": "{{plot_0}}",
    "supertrend-support": "{{plot_1}}",
    "timenow": "{{timenow}}"	
}

Most of these parameters & JSON message format has been explained in our Trading View docs. You can read it for detailed information, we will focus on the important ones here.

  • exchange: The exchange on which your symbol is traded
  • symbol: The AutoTrader Web broker independent symbol, more details on this are here
  • tradeType: BUY or SELL (automatically picked up from the strategy using a placeholder)
  • quantity: Quantity of the order (automatically picked up from the strategy using a placeholder)
    • Note that we are not giving a fixed quantity here
    • As per our strategy’s logic, first order & last (square-off) order will have quantity set in strategy’s parameters
    • All other orders that fall in-between first and last order will have double quantity
    • You can observe the quantities on the chart as well
  • analysis: All other values passed below the orders section (below the orders’ ending square bracket) are OPTIONAL & used as additional information which can be useful for investigation when there is a problem
    • You can see that we are printing the values of short & long moving average when the alert was fired; so that we can make sure everything is working as expected
    • You will be able to see these values in AutoTrader Web server logs (Activity)

Precautions

  • Once an alert is set, this strategy will run as per the session time set by the user in the parameters
  • If you modify the alert in the middle of the session, then be careful about setting start time of session after current time. Otherwise TradingView, you might see unexpected orders being fired:
    • There is nothing wrong with AutoTrader Web in this case. If trading view sends a buy or sell signal; then AutoTrader Web will place the order
    • If you modify the alert and set session start time earlier that current time, then strategy will take double quantity for first signal, which is wrong.
    • Any charting software is susceptible to issue like repaint when you modify something in live, so you must understand it and be careful
  • More information is available on the our Trading View docs

References

I have around 15 years of experience 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 :-)

1 thought on “TradingView – Supertrend (Automated Trading)”
  • Saravjeet Singh says:

    Great work

    October 15, 2022 at 10:15 am

Comments are closed.