TradingView Backtesting

Stop vs Stop-Limit Orders: Trigger and Fill Assumptions in Pine

A stop-loss order usually means a stop order that becomes a market order when triggered. Its stop price does not guarantee its fill price. A stop-limit order activates a limit order instead: it restricts the acceptable execution price but may leave the position open. In Pine, distinguish that single stop-limit order from a stop-loss and take-profit bracket before comparing backtest results.

Build an order comparison

Separate the trigger from the acceptable fill

For a protective sell order on a long position, the stop normally sits below the current market. The trigger activates the order; it is not a reservation of liquidity. Investor.gov describes these mechanics for stock orders. Confirm the order types and trigger rules with the broker for your instrument.

  • For a buy stop used to cover a short, the direction reverses: the trigger is normally above market and the buy limit is the maximum acceptable price.
  • A sell limit below the stop gives some room after activation. Setting both equal is permitted by some systems but leaves no price buffer; it does not assure a fill.
  • A trailing stop changes how the trigger moves. Its eventual market or limit behavior still needs to be specified.
PropertyStop / stop-marketStop-limit
After activationMarket orderLimit order
Sell execution priceCan be below the stopAt the limit or higher, if filled
Gap below both levelsCan execute at a substantially lower priceCan remain unfilled below the sell limit
Main exposureUncertain exit priceContinued exposure while waiting
What is guaranteed?The stop price is not guaranteedThe limit constrains price, not whether or when a fill occurs

A 100-share gap example

Assume a hypothetical long position of 100 shares bought at $100, a sell stop at $98, and an alternative stop-limit with the same stop and a $97.50 sell limit. Both alternatives are active before the event. Ignore fees and assume the stated fills cover all 100 shares. These are separate scenarios, not observed trades or guaranteed broker outcomes.

  • Planned stop risk was ($100 - $98) × 100 = $200. The $94 exit loses 3 times that amount before costs.
  • The $0.50 gap between stop and limit is an execution constraint. It is not a $0.50 cap on further losses.
  • A temporary rebound can produce a fill, but neither a later recovery nor available buying size is assured.
Price eventStop outcomeStop-limit outcome
Orderly decline through $98 with buyers at $97.90Assumed fill $97.90; realized P/L = ($97.90 - $100) × 100 = -$210An assumed $97.90 fill is allowed because it is above $97.50; the same -$210 P/L
Previous close $99; next opening market $94, then stays below $97.50Assumed fill $94; realized P/L = ($94 - $100) × 100 = -$600Stop activates, but a $94 sale violates the limit. Position stays open; at $94 its unrealized P/L is -$600
After that gap, price recovers and the sell limit fills at $97.50The earlier $94 exit is already completeRealized P/L = ($97.50 - $100) × 100 = -$250, conditional on that later fill
After that gap, price instead falls to $90 with no limit fillThe assumed realized loss remains $600Position remains open; unrealized P/L = ($90 - $100) × 100 = -$1,000

Pine uses the same parameter names for different orders

The function matters. TradingView documents a single stop-limit order when strategy.entry or strategy.order receives both stop and limit. With strategy.exit, the same pair creates separate stop-loss and take-profit orders. Treating that bracket as a stop-limit exit changes the experiment.

  • stop and limit are absolute price levels. strategy.exit loss and profit use tick distances; a dollar amount or percentage cannot be substituted without conversion.
  • A visit to the limit price before the stop activates does not fill an inactive limit order.
  • Manage cancellation and remaining quantity if another exit can close the position. A leftover sell order can otherwise create an unintended short.
Pine commandMeaning to verify
strategy.exit with stop onlyA price-based stop-loss exit linked to the specified entry.
strategy.exit with stop and limitA stop-loss and take-profit bracket; it is not a single stop-limit exit.
strategy.order with stop and limitOne stop-limit order. An opposite-side order can reduce a position, but its quantity must match the intended reduction.
strategy.entry with stop and limitOne stop-limit entry. An opposite entry can reverse a position, so it is not a drop-in protective exit.

Run one controlled exit comparison

This Pine v6 example enters one unit once, then submits one opposing order for that position. Toggle only the exit type between runs. It places protection at the first bar-close calculation that sees the filled entry, so the entry bar is unprotected until that calculation. That deliberate timing limitation must remain visible when interpreting the result. This is an order-mechanics example, not an entry strategy.

  • Keep chart history fixed: entryBar is an index from the first loaded bar, so loading different history changes the selected entry.
  • Two ticks of configured slippage apply to eligible market and stop fills. On a $0.01 tick symbol that is $0.02 per share, not 2%. The limit offset defaults to five ticks.
  • There is one entry and no competing exit, scale-in, or re-entry. Adding any of them requires explicit pending-order cancellation and quantity handling.
  • Inspect an unfilled stop-limit as an open exposure. Do not compare only closed-trade profit if one version never exits.
Pine v6 syntax checked. Use a standard positive-price chart with sufficient capital and history; inspect the order and fill markers yourself.pinescript
//@version=6
strategy("Stop or stop-limit exit comparison", overlay = true, initial_capital = 100000, slippage = 2)
bool useStopLimit = input.bool(false, "Use stop-limit exit")
int entryBar = input.int(20, "Entry signal bar index", minval = 1)
float riskPercent = input.float(2.0, "Stop distance (%)", minval = 0.1, maxval = 50.0)
int limitOffset = input.int(5, "Sell limit below stop (ticks)", minval = 0)
var bool armed = false
var float stopPrice = na
var float limitPrice = na

if bar_index == entryBar
    strategy.entry("Long", strategy.long, qty = 1)

if strategy.position_size > 0 and not armed
    stopPrice := math.round_to_mintick(strategy.position_avg_price * (1.0 - riskPercent / 100.0))
    limitPrice := stopPrice - limitOffset * syminfo.mintick
    if limitPrice <= 0
        runtime.error("Use a positive-price symbol and a smaller limit offset.")
    strategy.order("Protect", strategy.short, qty = strategy.position_size, stop = stopPrice, limit = useStopLimit ? limitPrice : na)
    armed := true

plot(strategy.position_size > 0 ? stopPrice : na, "Stop", color.red, style = plot.style_linebr)
plot(strategy.position_size > 0 and useStopLimit ? limitPrice : na, "Limit", color.orange, style = plot.style_linebr)

Audit what the broker emulator can and cannot establish

Historical fills depend on the available price sequence and active orders. A candle touching both levels does not establish activation order. Start with standard candles and save the simulation settings with each result.

AssumptionAudit action
Gap across an active stopInspect the next open. The emulator has no intrabar prices inside the gap and can fill a stop there rather than at its level.
Stop-limit activationVerify the stop activated before the eligible limit-price visit. A gap does not remove the limit constraint.
SlippageRecord the configured number of ticks and test several explicit values. Fixed tick slippage is a scenario, not a reconstruction of spreads or market depth.
Limit fillsRecord the limit-fill verification setting. Requiring price to trade beyond the limit makes eligibility stricter but does not model your queue position.
Intrabar sequenceCompare available lower-timeframe detail with the baseline. Bar Magnifier refines historical sequencing; it cannot certify a live fill.
Order creation timeAn order cannot fill on a price move that preceded its activation. Keep script calculation and order timing settings unchanged between runs.

Check broker rules before carrying the result into execution

A Pine backtest does not establish the rules of a connected brokerage account. Investor.gov notes that firms can use different stop triggers, including last-sale or quotation prices. Obtain the policy for the exact instrument, venue, and order ticket.

  • Verify the trigger reference: last trade, bid, ask, or another documented price. A chart price alone may not be that reference.
  • Check eligible trading sessions, time in force, handling of halts, and whether the order is held by the broker or venue.
  • Ask how partial fills, modifications, and cancel requests affect the remaining quantity. A submitted cancel request is not evidence of cancellation.
  • Record the response if the stop-limit remains unfilled. Any later conversion to market creates a new execution decision with its own price risk.

Record planned risk separately from the outcome

Keep the entry, quantity, stop, limit, order submission time, trigger time, fill prices, and remaining quantity in your review. Use Pineify to make the simulation rules explicit, then use Trading Journal notes and trade records to compare the plan with actual execution.

Review field100-share example
Planned risk$200 before fees, based on the $98 stop
Actual or simulated fillLabel which evidence it is; retain $94 only if that was the observed or explicitly assumed fill
Realized P/L-$600 for a complete $94 exit, before fees
Unfilled position100 shares still open if the $97.50 limit never fills; record the valuation time
Deviation to investigate$400 more loss than planned for the $94 fill, or continuing exposure for the unfilled alternative
Where Pineify fits

Pine Script AI Coding Agent

Describe the stop trigger, limit price, quantity, and cancellation rules to generate or revise Pine strategy code. Review the order semantics and test the output in TradingView.

Also useful: Trading Journal. Record trades, stop levels, and review notes so planned risk can be compared with fills and remaining exposure. Journaling does not submit broker orders.

Build an order comparison

Frequently asked questions

Educational information, not investment advice. Prices and outcomes in the worked examples are hypothetical. A syntax check does not verify trading behavior, broker compatibility, or future results.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.