TradingView – Moving Average (Automated Trading)

In this post, we will implement automated trading on a moving average strategy inside TradingView. At the time of writing, automated trading on TradingView is supported for Zerodha, Upstox, AliceBlue, Finvasia, Angel Broking, Fyers.

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

Demo

TradingView – Moving Average Automated Trading Intraday (हिन्दी)

Strategy Logic

This is a very basic simple moving average crossover 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 short term moving average crosses long term moving average from below.

Take a short position, when the short term moving average crosses long term moving average from above.

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 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 “Moving Average – 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=4
strategy("Moving Average - Intraday", shorttitle = "MA - Intraday", 
     overlay=true, calc_on_every_tick = true)

// 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(title="Market session", type=input.session, 
     defval="0915-1455", confirm=true)

// Short & Long moving avg. period input parameters
var int i_shortPeriod = input(title = "Short MA Period", type = input.integer, 
     defval = 3, minval = 2, maxval = 20, confirm=true)
var int i_longPeriod = input(title = "Long MA Period", type = input.integer, 
     defval = 7, minval = 3, maxval = 120, confirm=true)

// A function to check whether the bar or period is in intraday session
barInSession(sess) => time(timeframe.period, sess) != 0

// Calculate moving averages
shortAvg = sma(close, i_shortPeriod)
longAvg = sma(close, i_longPeriod)

// Plot moving averages
plot(series = shortAvg, color = color.red, title = "Short MA", 
     linewidth = 2, transp = 25)
plot(series = longAvg, color = color.blue, title = "Long MA", 
     linewidth = 2, transp = 25)

// Long/short condition
longCondition = crossover(shortAvg, longAvg)
shortCondition = crossunder(shortAvg, longAvg)

// 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", long = strategy.long, 
     when = longCondition and intradaySession)

// Short position
// When shortCondition and intradaySession both are true
strategy.entry(id = "Short", long = 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")

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.

TradingView Strategy Parameters
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}}",
    "short moving avg": "{{plot_0}}",
    "long moving avg": "{{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

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

Leave A Comment

Need Help? Chat with us