Skip to main content

11 Trade Command Examples

Working Pine + JSON pairs for the use cases that come up over and over. Each example shows the Pine alert source and the resulting JSON payload TradingView fires at the TVH webhook. Copy, adapt, ship.

TL;DR
  • Pine produces a JSON string and passes it as the alert_message. TradingView fires the webhook with that string verbatim.
  • Placeholders like {{ticker}} and {{timenow}} are substituted by TradingView before the request leaves their servers.
  • Replace <token> and <apiKey> with your actual values. The token lives in Account → Settings; the apiKey is the name you gave the credentials in Account → Settings → API Keys.

Example 1 — Long Market on Binance Spot

Use case: simplest possible market buy. 1% of available USDT balance.

//@version=5
strategy("Long Market — Binance Spot", overlay=true)

fastEma = ta.ema(close, 9)
slowEma = ta.ema(close, 21)
longSignal = ta.crossover(fastEma, slowEma)

alert_message = '{"exchange":"binance","pair":"' + syminfo.ticker + '","apiKey":"binance-main","isBuy":true,"isMarket":true,"unitsType":"percent","unitsPercent":1,"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '","token":"<token>"}'

if longSignal
strategy.entry("L", strategy.long, alert_message=alert_message)

plot(fastEma, color=color.green)
plot(slowEma, color=color.red)

Why this works: market buy with percent-of-balance sizing is the lowest-friction setup on a spot account. No leverage, no SL/TP — fits a "always in the market on EMA cross" pattern. alertTimestamp ensures TradingView retries don't double-buy.

Variations: use isSell: true for a sell/short entry, or replace unitsPercent with useFixedSize: true, fixedQuoteSize: 100 to spend exactly $100 per trade.


Example 2 — Long Limit with Chase Fallback on Bybit

Use case: entry-limit chase that falls back to market after the chase budget (30 attempts × 10 s ≈ 5 min) is exhausted.

//@version=5
strategy("Long Chase — Bybit Futures", overlay=true)

rsi = ta.rsi(close, 14)
longSignal = ta.crossover(rsi, 30) // oversold reversal

alert_message = '{"exchange":"bybit","pair":"' + syminfo.ticker + '","apiKey":"bybit-main","isBuy":true,"isLimit":true,"limitPriceType":"bestPrice","unitsType":"percent","unitsPercent":2,"chaseLimitOrder":true,"updateLimitOrderTimeInterval":10,"updateLimitOrderBuyMarketAfterNotFilled":true,"stopLossType":"percent","stopLossPercent":1.0,"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '","token":"<token>"}'

if longSignal
strategy.entry("L", strategy.long, alert_message=alert_message)

Why this works: chase keeps you maker-side on a 10-second cadence, then market-orders if the price has run away by the end of the budget. postOnly: true is the default, so the chase stays maker-only. SL is a flat 1% percent — works regardless of fill price.

Variations: add useEntireAccountBalance: true for Bybit UTA full-balance entries (replaces unitsType / unitsPercent). Drop updateLimitOrderBuyMarketAfterNotFilled to bail out instead of taking market on a missed chase.


Example 3 — Short with Absolute SL and Two TPs on Binance Futures

Use case: short entry with fixed-price SL and two scaled TPs at fixed levels.

//@version=5
strategy("Short — Fixed SL/TP", overlay=true)

resistance = 67500.0
support1 = 64000.0
support2 = 62500.0
stopLevel = 68200.0

shortSignal = close < resistance and close > support1 and ta.crossunder(close, ta.ema(close, 20))

alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","isSell":true,"isMarket":true,"leverage":5,"marginType":"isolated","unitsType":"percent","unitsPercent":3,"stopLossType":"absolute","stopLoss":' + str.tostring(stopLevel) + ',"targetType":"absolute","targetAmountInPercent":true,"targets":[{"price":' + str.tostring(support1) + ',"amount":50},{"price":' + str.tostring(support2) + ',"amount":50}],"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '","token":"<token>"}'

if shortSignal
strategy.entry("S", strategy.short, alert_message=alert_message)

Why this works: absolute SL/TP levels match an S/R-based setup where you know the lines, with a clean 50/50 scale-out across two support targets.

Variations: drop marginType if you don't want to switch the per-pair setting. Add cancelAllOrders: true to clean the slate before entry.


Example 4 — Multi-TP Scale-Out (3 Targets, 33% each)

Use case: three percent-based TPs, sized so the remainder rolls over correctly.

//@version=5
strategy("Multi-TP Scale-Out", overlay=true)

donchianUpper = ta.highest(close, 20)
breakoutLong = ta.crossover(close, donchianUpper[1])

alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","isBuy":true,"isMarket":true,"leverage":10,"unitsType":"percent","unitsPercent":2,"stopLossType":"percent","stopLossPercent":1.5,"targetType":"percent","targetAmountInPercent":true,"targets":[{"takeProfitPercent":0.7,"amount":33},{"takeProfitPercent":1.4,"amount":33},{"takeProfitPercent":2.1,"amount":34}],"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '","token":"<token>"}'

if breakoutLong
strategy.entry("L", strategy.long, alert_message=alert_message)

Why this works: sum-of-amounts equals 100 exactly (33 + 33 + 34). TVH does not auto-normalise, so the last slice catches the rounding remainder.

Variations: swap the last target for a trailing leg by setting targets[2].price: 0 and targets[2].trailingPercent: 0.5.


Example 5 — Trailing Stop with Activation Threshold

Use case: trail by 1% once the trade is 2% in profit.

//@version=5
strategy("Trailing Stop Example", overlay=true)

fastSma = ta.sma(close, 10)
slowSma = ta.sma(close, 50)
longSignal = ta.crossover(fastSma, slowSma)

alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","isBuy":true,"isMarket":true,"leverage":3,"unitsType":"percent","unitsPercent":4,"stopLossType":"percent","stopLossPercent":1.5,"useTrailingStopLoss":true,"trailingStopLossPercent":1.0,"trailingStopLossActivationPercent":2.0,"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '","token":"<token>"}'

if longSignal
strategy.entry("L", strategy.long, alert_message=alert_message)

Why this works: initial 1.5% hard stop covers the trade before the trail arms. Trail arms at +2% in profit, then follows price by 1%. No TPs — the trail is the exit.

Variations: combine with one TP at, say, +5% to take partial profit, and let the trail handle the rest by setting targets[0].amount: 50.


Example 6 — DCA Entry (4-leg, 1% apart)

Use case: market entry plus 4 limit-buy DCA legs, total 2% spread.

//@version=5
strategy("DCA Entry — 4-leg", overlay=true)

rsi = ta.rsi(close, 14)
dcaSignal = ta.crossunder(rsi, 25) // deeply oversold

alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","isBuy":true,"isMarket":true,"leverage":3,"unitsType":"percent","unitsPercent":10,"useDca":true,"dcaPercent":2.0,"dcaOrderCount":4,"stopLossType":"percent","stopLossPercent":3.0,"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '","token":"<token>"}'

if dcaSignal
strategy.entry("L", strategy.long, alert_message=alert_message)

Why this works: 10% of balance × 3x = 30% notional spread across 5 fills (1 market + 4 DCA), each ~6% notional. SL sits well past the deepest DCA leg so the strategy has room to average down. dcaPercent: 2.0 means the deepest leg is 2% below entry; intermediate legs at 0.5%, 1.0%, 1.5%.

Variations: a full close already cancels the pair's pending orders (including unfilled DCA legs). To clear a mesh on its own without closing, send a standalone cancelAllDca: true payload.


Example 7 — Hedge Mode Long Open (Binance Futures Dual-Position)

Use case: open a long without closing an existing short on the same pair.

//@version=5
strategy("Hedge Mode Long", overlay=true)

longSignal = ta.crossover(close, ta.vwap)

alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","hedgeMode":true,"isBuy":true,"isMarket":true,"leverage":5,"unitsType":"percent","unitsPercent":2,"stopLossType":"percent","stopLossPercent":1.0,"targetType":"percent","targetAmountInPercent":true,"targets":[{"takeProfitPercent":2.0,"amount":100}],"alertTimestamp":"' + syminfo.ticker + '-long-' + str.tostring(time) + '","token":"<token>"}'

if longSignal
strategy.entry("L", strategy.long, alert_message=alert_message)

Why this works: hedgeMode: true tells TVH this is a dual-position account, so the long opens in addition to any existing short. The -long- infix in alertTimestamp prevents collisions with the corresponding short alert that uses -short-.

Variations: for the exit alert, use orderType: "close" plus closeLong: true to flat just the long side. See Close & Cancel → Hedge-mode close.


Example 8 — Close Position via orderType: "close"

Use case: simple manual or alert-driven flat exit.

//@version=5
strategy("Exit Signal", overlay=true)

exitSignal = ta.crossunder(close, ta.ema(close, 21))

alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","isClose":true,"alertTimestamp":"' + syminfo.ticker + '-exit-' + str.tostring(time) + '","token":"<token>"}'

if exitSignal
strategy.close_all(alert_message=alert_message)

Why this works: orderType: "close" is auto-mapped to isClose=true, isMarket=true. TVH submits an opposite-side market order sized to whatever's open. No need to specify size.

Variations: add useLimitClose: true + isLimit: true + price: 65000 for a limit exit. See Limit Order Management → Limit close.


Example 9 — Strategy-Mode Auto-Close via strategyComment

Use case: one Pine template that handles both entries and exits, no conditional payload logic.

//@version=5
strategy("Strategy Mode Auto-Close", overlay=true)

fastSma = ta.sma(close, 9)
slowSma = ta.sma(close, 21)
longSignal = ta.crossover(fastSma, slowSma)
exitSignal = ta.crossunder(fastSma, slowSma)

// Single template — TVH derives direction from strategy.order.action
// and auto-closes when strategy.order.comment contains "exit"
alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","orderType":"{{strategy.order.action}}","strategyComment":"{{strategy.order.comment}}","isMarket":true,"unitsType":"percent","unitsPercent":3,"stopLossType":"percent","stopLossPercent":1.5,"alertTimestamp":"{{ticker}}-{{timenow}}","token":"<token>"}'

if longSignal
strategy.entry("L", strategy.long, comment="Long Entry", alert_message=alert_message)
if exitSignal
strategy.close("L", comment="Long Exit", alert_message=alert_message)

Why this works: when strategy.close("L") fires, TradingView substitutes {{strategy.order.action}} as "sell" (the closing side) and {{strategy.order.comment}} as "Long Exit". The strategyComment contains the substring exit, so TVH's auto-close logic kicks in: isClose=true, isMarket=true. The trade closes regardless of the orderType value. See Anatomy → strategyComment auto-close.

Variations: add strategyCloseValue: "EXIT-CONFIRMED" to register an extra close marker on top of the built-in close/exit/flat scan. Note it adds a trigger, it doesn't disable the built-in three — keep those words out of entry comments either way.


Example 10 — Scaled Order Range Entry

Use case: five limit buys distributed between $63,500 and $64,500.

//@version=5
strategy("Scaled Range Entry", overlay=true)

bbMiddle = ta.sma(close, 20)
bbStdev = ta.stdev(close, 20)
bbLower = bbMiddle - bbStdev * 2
bbLowerLower = bbMiddle - bbStdev * 3

scaledSignal = ta.crossunder(close, bbLower)

alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","isBuy":true,"isLimit":true,"leverage":2,"unitsType":"percent","unitsPercent":5,"useScaledOrders":true,"scaledLowerPrice":' + str.tostring(bbLowerLower) + ',"scaledUpperPrice":' + str.tostring(bbLower) + ',"scaledOrderNumbers":5,"scaledOrderStyle":"even","stopLossType":"percent","stopLossPercent":2.5,"alertTimestamp":"' + syminfo.ticker + '-' + str.tostring(time) + '","token":"<token>"}'

if scaledSignal
strategy.entry("L", strategy.long, alert_message=alert_message)

Why this works: Bollinger lower-band cross fires the entry; five equal-sized limits ladder between the −2σ and −3σ bands. No market component. SL is a percent so it sits below whichever leg fills lowest.

Variations: add scaledOrderStyle: "smallBig" to weight more capital on the lower legs (averaging down faster) — smaller orders at the highest entry, larger at the lowest.


Example 11 — Math Expression SL (Dynamic via stopLossExpression)

Use case: SL computed server-side from the entry price, same template for longs and shorts.

//@version=5
strategy("Dynamic SL via stopLossExpression", overlay=true)

fastEma = ta.ema(close, 9)
slowEma = ta.ema(close, 21)
longSignal = ta.crossover(fastEma, slowEma)
shortSignal = ta.crossunder(fastEma, slowEma)

// Same template works for both directions:
// - on buy: SL = entry - 0.015 * entry (1.5% below)
// - on sell: TVH auto-flips '-' to '+', SL = entry + 0.015 * entry (1.5% above)
alert_message = '{"exchange":"binance-futures","pair":"' + syminfo.ticker + '","apiKey":"binance-futures-main","orderType":"{{strategy.order.action}}","isMarket":true,"unitsType":"percent","unitsPercent":2,"stopLossType":"absolute","stopLossExpression":"{{strategy.order.price}}-0.015*{{strategy.order.price}}","targetType":"absolute","takeProfitExpression":"{{strategy.order.price}}+0.030*{{strategy.order.price}}","targets":[{"price":0,"amount":100}],"alertTimestamp":"{{ticker}}-{{timenow}}","token":"<token>"}'

if longSignal
strategy.entry("L", strategy.long, alert_message=alert_message)
if shortSignal
strategy.entry("S", strategy.short, alert_message=alert_message)

Why this works: TradingView substitutes {{strategy.order.price}} with the literal entry price (e.g. 65000). TVH then evaluates the expression server-side: SL = 65000 − 975 = 64025, TP = 65000 + 1950 = 66950. Risk-reward 1:2.

On the short signal, the sign-flip rule mirrors everything — same template, opposite-side SL/TP. See Math Expressions → Smart sign-flipping.

Variations: chain two expressions for asymmetric R:R, or pre-compute the SL in Pine if you want ATR-based offsets that aren't expressible as percent-of-entry.


Next

  • Gotchas — 15 footguns and their fixes. Read before deploying any of these examples to live.
  • Pine Cookbook — full Pine strategies (EMA, RSI, Donchian, ATR, DCA, Multi-TF, Strategy Tester compatibility) you can drop into TradingView.