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.

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 (a stock, or a derivative on the Indian stock exchanges)
  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=6

// "calc_on_every_tick = true" means the strategy checks the signal on every
// price change (tick), not only when the candle closes. So your order fires
// faster during live trading. The catch: results while the candle is still
// forming can change until it closes, so live trades may not match backtest
// results. Set it to "false" if you want to act only on closed candles.
strategy("Moving Average - Intraday", shorttitle = "MA - Intraday",
     overlay = true, calc_on_every_tick = true)


// ========================================================================
//  YOUR SETTINGS
//  You change all of these from the strategy Settings window on the chart.
//  You do NOT need to edit the code.
// ========================================================================

// Trading time window for the day. Format is START-END in 24-hour time.
// Example "0915-1455" = start at 9:15 am, stop new trades and square off by
// 2:55 pm. Keep the end time at least 2 minutes before your broker's auto
// square-off time.
i_marketSession = input.session(title = "Market session",
     defval = "0915-1455", confirm = true, group = "Strategy")

// Short-term moving average length (fewer candles = reacts faster).
i_shortPeriod = input.int(title = "Short MA Period",
     defval = 10, minval = 2, maxval = 20, confirm = true, group = "Strategy")

// Long-term moving average length (more candles = smoother, slower).
i_longPeriod = input.int(title = "Long MA Period",
     defval = 40, minval = 3, maxval = 120, confirm = true, group = "Strategy")

// ----- Where to send the order (set these once in Settings) -----
// Your AutoTrader Web account name (or a Group name to trade many accounts).
i_account  = input.string("ACC_NICKNAME", "Account or Group name",
     tooltip = "Your Pseudo account name, or a Group name to trade many accounts at once",
     group = "Order routing")
// Tick this ON only if the name above is a Group, not a single account.
i_useGroup = input.bool(false, "This is a Group account",
     tooltip = "Tick this if the name above is a Group account", group = "Order routing")
// The contract/stock to trade, written the AutoTrader Web way.
// Examples: NIFTY_28-JUL-2026_FUT (a future) or SBIN (a stock).
i_symbol   = input.string("NIFTY_28-JUL-2026_FUT", "Symbol",
     tooltip = "AutoTrader Web broker-independent symbol, e.g. NIFTY_28-JUL-2026_FUT or SBIN",
     group = "Order routing")
// The exchange code for that symbol. Use NFO for futures/options, NSE for stocks.
i_exchange = input.string("NFO", "Exchange",
     tooltip = "Exchange code, e.g. NFO for futures/options or NSE for stocks",
     group = "Order routing")
// Product type: INTRADAY (same-day), DELIVERY, or NORMAL (carry forward).
i_product  = input.string("INTRADAY", "Product type",
     tooltip = "INTRADAY, DELIVERY or NORMAL", group = "Order routing")


// ========================================================================
//  THE ALERT MESSAGE (this is what tells AutoTrader Web what to do)
// ========================================================================
//
// AutoTrader Web reads a simple text, ONE setting per line, like this:
//
//     account=ACC_NICKNAME
//     symbol=NIFTY_28-JUL-2026_FUT
//     exchange=NFO
//     producttype=INTRADAY
//     tradetype=BUY
//     ordertype=MARKET
//     lots=1
//
// Below, we build that same text automatically from your settings above.
//
//  - The "+" signs just glue the pieces together into one long text.
//  - "\n" means "go to a new line" (the same as pressing Enter). We put one
//    after every setting so each ends up on its own line, exactly as shown
//    above. Without "\n" everything would run together on one line and would
//    not work.
//  - {{strategy.order.action}} and {{strategy.order.contracts}} are TradingView
//    placeholders. TradingView fills them in for you when the alert fires:
//        {{strategy.order.action}}    becomes  BUY  or  SELL
//        {{strategy.order.contracts}} becomes  the size of that order
//    Leave these two exactly as they are. Do NOT type your own BUY/SELL or a
//    fixed number here, or the direction and the reverse-size will be wrong.
//  - Size line: on a futures or options chart, {{strategy.order.contracts}} is a
//    LOT count, so we send "lots=". On a stock chart it is a share count, so we
//    send "quantity=". The line below picks the right one from your symbol, so
//    the same script works for both.
//  - The first line uses "group=" when you ticked "This is a Group account",
//    otherwise "account=". Everything else stays the same.

// Pick the size keyword from the symbol: F&O contracts are counted in lots,
// stocks in shares.
symUpper = str.upper(i_symbol)
isDerivative = str.contains(symUpper, "_FUT") or str.contains(symUpper, "_CE_") or str.contains(symUpper, "_PE_")
sizeKey = isDerivative ? "lots=" : "quantity="

alertMsg = (i_useGroup ? "group=" : "account=") + i_account + "\n" +
     "symbol="      + i_symbol   + "\n" +
     "exchange="    + i_exchange + "\n" +
     "producttype=" + i_product  + "\n" +
     "tradetype={{strategy.order.action}}\n" +
     "ordertype=MARKET\n" +
     sizeKey + "{{strategy.order.contracts}}"


// ========================================================================
//  STRATEGY LOGIC (you normally do not need to touch this)
// ========================================================================

// A small helper that answers: is the current candle inside your trading
// time window? true = yes, we may trade; false = outside your hours.
barInSession(sess) => not na(time(timeframe.period, sess))

// Calculate the two moving averages from your settings.
shortAvg = ta.sma(close, i_shortPeriod)
longAvg  = ta.sma(close, i_longPeriod)

// Draw them on the chart.
plot(series = shortAvg, color = color.red,  title = "Short MA", linewidth = 2)
plot(series = longAvg,  color = color.blue, title = "Long MA",  linewidth = 2)

// The trade rules: go long when the short MA crosses above the long MA,
// go short when it crosses below.
longCondition  = ta.crossover(shortAvg, longAvg)
shortCondition = ta.crossunder(shortAvg, longAvg)

// Are we inside your trading hours right now?
bool intradaySession = barInSession(i_marketSession)

// Enter LONG (buy) on an upward cross, inside your hours.
// We attach our alert text so the order is sent to AutoTrader Web.
if longCondition and intradaySession
    strategy.entry(id = "Long", direction = strategy.long, alert_message = alertMsg)

// Enter SHORT (sell) on a downward cross, inside your hours.
if shortCondition and intradaySession
    strategy.entry(id = "Short", direction = strategy.short, alert_message = alertMsg)

// Square off (close everything) once your hours are over and a trade is open.
squareOff = (not intradaySession) and (strategy.position_size != 0)
if squareOff
    strategy.close_all(comment = "Square-off", alert_message = alertMsg)

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.

No trades in the report? Check the capital

If you add the strategy but the Strategy Tester shows “This report requires trade data” and there are no arrows on the chart, the most common reason is the backtest capital. For a high-value instrument like an index future, one contract can cost more than the money set aside for the test, so the strategy cannot afford even one order and places nothing.

Fix it in the strategy Settings → Properties tab:

  • Increase Initial capital so it can afford at least one contract. For an index future, a large value such as 10000000 works well.
  • You can also lower the Order size, or set a Margin percentage to trade with leverage.

As soon as the capital is enough, the arrows appear on the chart and the report fills in at the bottom.

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

Sign in to AutoTrader Web and open Alert Auto. → Tokens from the left menu. Create a token and copy your private link:

https://signals.stocksdeveloper.in/tradingview/YOUR-TOKEN
  • Keep this link private — it is the key that lets your alerts place orders in your account.
  • You do not put your API key anywhere in TradingView; the link is all you need.
  • If the link is ever exposed, open Alert Auto. → Tokens again, revoke it, and create a new one. The old link stops working at once.

Alert name

You can give the alert any name of your choice.

Message

Good news: you do not write the order by hand. The strategy already builds the full order text from the settings you filled in. So in the Message box, put only this one line:

{{strategy.order.alert_message}}

That is all you type here. When a buy signal fires for 1 lot, AutoTrader Web receives exactly this:

account=ACC_NICKNAME
symbol=NIFTY_28-JUL-2026_FUT
exchange=NFO
producttype=INTRADAY
tradetype=BUY
ordertype=MARKET
lots=1

Where do these values come from? You set them once in the strategy Settings, under the Order routing group:

  • Account or Group name: your Pseudo account name. Tick This is a Group account to send the order to a whole group of accounts instead.
  • Symbol: the AutoTrader Web broker-independent symbol, for example NIFTY_28-JUL-2026_FUT for a future or SBIN for a stock. Keep this format in the box here, so the strategy sets the order size (lots or quantity) for you automatically. AutoTrader Web also accepts TradingView’s own symbol (like NIFTY1! or NIFTYU2026) if you write a plain-text alert yourself — see Using your TradingView symbol. More details are in the instruments and symbols guide.
  • Exchange: the exchange code, for example NFO for futures and options, or NSE for stocks.
  • Product type: INTRADAY for intraday trading.

The last two lines are filled by TradingView for you, so you leave them alone:

  • tradetype: BUY or SELL for each order.
  • lots / quantity: the order size. The strategy sends it as lots for a futures or options symbol, and as quantity (shares) for a stock, picking the right one from your symbol automatically. The first order and the last (square-off) order use the base size you set; the orders in between use double, so each new signal reverses the position. You can see these sizes on the chart.

The full alert format, with every field, option settings and risk limits, is explained in the Alert Automation guide.

After the alert fires, you can follow it from received to placed on the Alert Trail screen in AutoTrader Web.

Coding in Pine? This strategy builds the alert text for you inside the script, so you never type it by hand. For option strategies, our free, open-source StocksDeveloperAlerts library builds ready-made structures like straddles and iron condors.

Important: switch the alert on before the session starts

Switch the alert on before your session start time (in this example, before 9:15 am), while the strategy has no open position. Here is why it matters.

This strategy uses the base quantity for its first trade of the day, and then double the quantity for every trade after that. The double quantity is what reverses the position in a single order: one half closes the old position, and the other half opens the new one in the opposite direction.

Now suppose you switch the alert on in the middle of the session. The strategy may already be in a position from an earlier signal, so the first alert your account receives is a double-quantity reverse order, while your account is still flat. Your account and the strategy then drift apart:

  • That first order makes your account 2 lots, but the strategy is only 1 lot in that direction.
  • The next signal sends a 2-lot order the other way, which closes your account back to zero, while the strategy is now 1 lot the other way. So your account is flat when it should be holding a position, and no reverse position opens.
  • From here, your account stays out of step with the strategy for the rest of the day.

What to do:

  • Switch the alert on before the session opens, so the strategy starts flat and takes the base quantity on its first trade, or
  • If you must start mid-session, set the session start time to a minute or two after the current time. The strategy then starts fresh from that time and takes the base quantity first.

Precautions

  • Once an alert is set, the strategy runs as per the session time you set in the parameters.
  • Switch the alert on before the session starts. See Important: switch the alert on before the session starts above for why, and what to do if you must start mid-session.
  • Any charting software can repaint a signal when you change something live, so be careful when editing an alert during market hours.
  • 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 12 July 2026