TradingView – Moving Average (Automated Trading)

Automate a moving-average crossover strategy in TradingView and place real orders in your broker account.

TradingViewAutomated tradingIntraday
In short

This guide shows how to automate a simple moving-average crossover strategy in TradingView for intraday trading. You write the strategy in Pine Script, backtest it, then connect a TradingView alert to a webhook so AutoTrader Web places real orders in your broker account. Automated trading on TradingView works with leading Indian stock brokers. The strategy is for learning and demonstration only, with no promise of returns.

In this post, we will set up automated trading for a moving-average strategy inside TradingView. At the time of writing, this works with leading Indian stock brokers.

Why use a strategy

A TradingView strategy gives you a few useful benefits:

  • Backtesting
  • Easy way to add and configure parameters
  • Easy way to double the quantity when the signal changes
  • Use of placeholders provided by the strategy

This strategy is for learning and demonstration purposes only. We do not promise any returns.

Demo

TradingView – Moving Average Automated Trading Intraday (Hindi)

Strategy logic

This is a basic simple moving-average crossover strategy. It runs only between the session times you set. So set the start time and end time for when you want to start and stop your intraday trading.

The rules are simple:

  • Take a long position when the short-term moving average crosses the long-term moving average from below.
  • Take a short position when the short-term moving average crosses the long-term moving average from above.

The strategy uses double quantity for every signal except the first and the last. This makes sure the position is reversed each time the signal changes.

For example, say you set the quantity to 10. The strategy enters the first position with quantity 10. After that, every signal uses double the base quantity, so each new signal reverses the position. Finally, once the session time has passed, the strategy squares off the open position.

Setup

Before you start, complete these three steps:

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

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

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

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

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

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

// See if intraday session is active
bool intradaySession = barInSession(i_marketSession)

// Trade only if intraday session is active

// Long position
strategy.entry(id = "Long", direction = strategy.long, 
     when = longCondition and intradaySession)

// Short position
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")

Step 2: Backtest and optimize

  1. Click the “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. Your strategy will be added to the chart and it will automatically open the “Strategy Tester”
  4. You can see backtest results in the “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 means changing the parameters to improve the strategy performance
    1. Click the small Settings icon in the “Strategy Tester”, just to the right of your strategy name. Modify the parameters and backtest again.

Parameters

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

Important: 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 good set of parameters, the next step is to set up 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 added to your chart (click the 3 dots and you will see this option)
  2. A create alert window will open, which looks like this

Create alert

Create Alert

Alert settings

Let us now understand the alert settings.

Condition

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

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

Webhook URL

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

Replace the apiKey, account name and group parameters with your values:

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

Alert name

You can give the alert any name of your choice.

Message

This part is important. It decides 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 and the JSON message format are explained in our TradingView docs. Read it for detailed information. Here we focus on the important ones:

  • exchange: The exchange on which your symbol is traded
  • symbol: The AutoTrader Web broker-independent symbol. More details are in the instruments and symbols guide.
  • tradeType: BUY or SELL (picked up automatically from the strategy using a placeholder)
  • quantity: Quantity of the order (picked up automatically from the strategy using a placeholder)
    • We are not giving a fixed quantity here
    • As per the strategy logic, the first order and the last (square-off) order use the quantity set in the strategy parameters
    • All other orders between the first and last order use double quantity
    • You can also observe the quantities on the chart
  • analysis: All other values passed below the orders section (below the orders’ closing square bracket) are OPTIONAL. They are extra information that can help when you investigate a problem.
    • Here we print the short and long moving-average values when the alert fired, so we can confirm everything is working as expected
    • You can see these values in the AutoTrader Web server logs (Activity)

Precautions

  • Once an alert is set, the strategy runs as per the session time you set in the parameters.
  • If you modify the alert in the middle of the session, be careful to set the session start time after the current time. Otherwise you might see unexpected orders being fired:
    • There is nothing wrong with AutoTrader Web in this case. If TradingView sends a buy or sell signal, AutoTrader Web will place the order.
    • If you modify the alert and set the session start time earlier than the current time, the strategy takes double quantity for the first signal, which is wrong.
    • Any charting software can show issues like repaint when you modify something live, so understand this and be careful.
  • More information is available in our TradingView docs.

References

Disclaimer

We provide this strategy for demonstration purposes. You can use it as learning or reference material. We do not promise any kind of financial returns based on this strategy.

Ideally, you should research and build your own strategies and backtest them before making them live.

Next steps

Was this page helpful?

Last updated 20 June 2026