Pine Script Strategy & Order Execution

Pine Script Limit Orders: How to Code and Backtest in TradingView

In Pine Script, limit orders are placed by passing an absolute target price into the limit parameter of strategy.entry() or strategy.order(). The order remains active on TradingViews simulated broker order book until the market price touches or breaches the limit price, or until the order is explicitly canceled using strategy.cancel().

Build Limit Order Strategies with AI

How limit orders execute in Pine Script strategies

A limit order specifies the maximum price you are willing to pay for a buy, or the minimum price you will accept for a sell. Unlike market orders (which execute immediately at current market price), a limit order waits in the order book. In Pine Script, when you specify limit = targetPrice in strategy.entry() or strategy.order(), the broker emulator checks subsequent price bars. If market low dips down to touch or penetrate your limit price, the order fills at your exact limit price (or better).

Order typeFunction & syntaxExecution conditionFill price characteristics
Market orderstrategy.entry("Long", strategy.long)Executes on open of next barFills at current market price with potential slippage
Limit orderstrategy.entry("Long", strategy.long, limit = 150)Fills only when bar low <= 150Guaranteed fill at limit price or better (zero adverse slippage)
Stop orderstrategy.entry("Long", strategy.long, stop = 160)Triggers when bar high >= 160Turns into market order when price breaks through resistance
Stop-limit orderstrategy.entry(..., stop = 160, limit = 161)Triggers at stop; caps execution at limitCombines breakout trigger with slippage protection ceiling

Complete Pine Script v6 pullback limit order strategy with expiration timeout

The following complete Pine Script v6 strategy demonstrates how to place a limit order at a Fibonacci retracement level following a breakout, and automatically cancel the pending order if it does not fill within 5 bars.

Pine Script v6: Pullback limit order entry with 5-bar cancellation timeoutpinescript
//@version=6
strategy("Pullback Limit Order Strategy [v6]", 
         overlay = true, 
         initial_capital = 10000, 
         default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 10)

// Inputs
breakoutBars = input.int(20, "Breakout Lookback")
pullbackPercent = input.float(1.5, "Pullback Target %")
cancelAfterBars = input.int(5, "Cancel Timeout (Bars)")

// Track recent breakout
recentHigh = ta.highest(high, breakoutBars)[1]
breakoutOccurred = ta.crossover(close, recentHigh)

// Order tracking state
var int orderPlacedBar = na
var float pendingLimitPrice = na

// When a breakout occurs, place a limit buy order below current price to catch a pullback
if breakoutOccurred and strategy.position_size == 0
    pendingLimitPrice := close * (1 - pullbackPercent / 100)
    orderPlacedBar := bar_index
    
    // Submit limit buy order
    strategy.entry("PullbackBuy", strategy.long, limit = pendingLimitPrice)

// If order has been pending for more than cancelAfterBars without filling, cancel it
isOrderExpired = (bar_index - orderPlacedBar >= cancelAfterBars)
if isOrderExpired and strategy.position_size == 0
    strategy.cancel("PullbackBuy")
    pendingLimitPrice := na

// Visualize pending limit price
plot(pendingLimitPrice, "Pending Limit Level", color = color.green, style = plot.style_circles)

// Risk management exit for filled positions
if strategy.position_size > 0
    entryPrice = strategy.position_avg_price
    strategy.exit("Exit", from_entry = "PullbackBuy", 
                  stop = entryPrice * 0.98, 
                  limit = entryPrice * 1.04)

TradingView backtesting assumptions for limit orders

When evaluating backtested strategies that use limit orders, understand how TradingViews execution engine models historical price movement:

  • High/Low boundary touch: On historical bars, TradingView assumes a limit order fills if the bar range covers the limit price (i.e. low <= limit for a buy order). In live markets with thin liquidity, price may touch a level without filling all queued volume.
  • Backtest fill assumptions: Under Strategy Settings, you can configure "Verify price for limit orders" with an additional tick threshold to ensure price penetrates deeper into the level before registering a fill.
  • No adverse slippage: In TradingView simulations, limit orders never suffer adverse slippage; they fill exactly at the limit price or better. This makes limit strategies look cleaner in backtests than market order strategies.

Best practices: Canceling unfilled limit orders

A critical mistake in automated trading is leaving abandoned limit orders open indefinitely. If the market breaks out, reverses, and crashes three weeks later, an old forgotten limit buy order will fill right into a bear market. Follow these safeguards:

  • Always assign explicit order IDs: Use distinct names like "PullbackBuy" so you can invoke strategy.cancel("PullbackBuy") cleanly.
  • Track order age with bar_index: Store the bar_index when the order was submitted and cancel it after a fixed duration (e.g. 3 to 10 bars).
  • Clear pending state upon position fill: When strategy.position_size changes from 0 to positive, clear any pending limit trackers.
Where Pineify fits

Pine Script AI Coding Agent

Generate sophisticated limit order entries, breakout-pullback strategies, and automated order cancellation rules in Pine Script v6 with the AI Coding Agent.

Also useful: Strategy Optimizer. Optimize pullback depth percentages and cancellation timeouts across historical backtest data.

Build Limit Order Strategies with AI

Frequently asked questions

Limit orders minimize execution slippage but introduce fill risk (unfilled orders during rapid market advances). Backtested fills assume ideal order book matching.

Sources and verification