Skip to content
Back to App

Strategies

A strategy() script calculates chart values and places simulated orders in the Strategy Tester account. Apply it to replay history, inspect its trades, and continue the simulation as new candles are revealed.

Order functions

FunctionBehavior
strategy.entry()Opens or adds an entry; an opposite-direction entry reverses the position
strategy.order()Adds or subtracts its quantity from the net position and ignores pyramiding
strategy.exit()Places stop/limit brackets or trailing stops and reserves their exit quantity
strategy.close()Creates a market close sized from the named entry; FIFO determines which trades close by default
strategy.close_all()Creates a market close for the whole position
strategy.cancel() / strategy.cancel_all()Cancel pending orders, including queued market closes before they fill

Use strategy.long and strategy.short for direction. Prefer an if block for conditional orders. Legacy named when conditions are supported in v5 and rejected in v6, where Pine removed that parameter.

Declaration settings

ParameterDefault in TestMaxMeaning
initial_capital1000000Initial simulated account balance
pyramidingOne concurrent entryMaximum concurrent same-direction entries; see the price-order exception below
default_qty_value1Default order size
default_qty_typestrategy.fixedFixed units, percentage of equity, or a cash budget
close_entries_rule"FIFO"Close oldest trades first; "ANY" targets the requested entry
margin_long, margin_shortv6: 100; v5: 0Required collateral as a percentage of position value
commission_typestrategy.commission.percentPercentage, cash per contract, or cash per order
commission_value0Fee amount in the chosen commission units
slippage0Adverse slippage in price ticks for market and stop fills
process_orders_on_closefalseAllow eligible market orders to fill on the current close

Use literal numeric values for the supported numeric declaration settings. Margin values must be finite and nonnegative; values above 100 are allowed. close_entries_rule accepts the literal strings "FIFO" and "ANY".

Set commission_type and commission_value together when you want a specific fee model. Supported types are strategy.commission.percent, strategy.commission.cash_per_contract, and strategy.commission.cash_per_order. A value of 1 with percentage commission means 1% of transaction value, including the instrument’s point value.

Position sizing and margin

An explicit qty takes precedence over default sizing. Fixed sizing uses units/contracts; percentage sizing uses current equity, and cash sizing uses the specified cash budget. Quantities round down to the instrument’s supplied quantity step. The current fallback is one unit; a finer supplied step supports fractional quantities and is available to Pine as syminfo.mincontract.

With margin enabled, the simulator checks the resulting position’s required collateral and transaction fees before opening or increasing it. An unaffordable entry is not opened, and an unaffordable reversal leaves the existing position intact. Orders that reduce exposure can still close it.

This default changes with the Pine version: v6 requires 100% collateral unless you specify another margin; v5 defaults to disabled margin checks. A v6 script that produces no entries may need a smaller quantity or an appropriate declared capital/margin setting.

If equity falls below required margin, the simulator applies the documented four-times-cover liquidation calculation, rounded to the available quantity step and capped at the open position. Liquidations apply fees and slippage and appear as margin exits. strategy.margin_liquidation_price exposes the calculated threshold; the actual fill uses available OHLC prices and can occur elsewhere after a gap.

Strategy accounting uses the instrument’s cash currency. currency.NONE keeps that native currency; an explicit currency.USD requires known USD instrument data. Automatic currency conversion is not available.

Order timing and the price path

By default, the script creates orders when a candle closes. Market orders fill at the following candle’s open. Resting limit and stop orders follow the documented OHLC path:

  • Open closer to the high: open → high → low → close.
  • Otherwise: open → low → high → close.

The first eligible price encountered determines the fill. A gap through an order uses the next available open. Prices reached before an entry or stop-limit activation cannot fill its later exit. A stop-limit order first activates at its stop, then waits for a price allowed by its limit.

process_orders_on_close=true allows eligible market orders to fill on that closing tick. strategy.close(..., immediately=true) and strategy.close_all(immediately=true) provide this behavior for an individual market close.

Pyramiding limits same-direction entries. As in Pine’s documented price-order exception, multiple price-based entries accepted during the same execution can all fill when reached, even if their combined entry count exceeds the cap. strategy.order() does not use that cap.

Partial exits and FIFO

Each strategy.exit() call reserves its quantity. Later exit calls cannot take quantity already reserved by an earlier call. Percentage reservations are established when the exit is placed rather than recalculated after another exit fills.

For example, with 20 units open, a take-profit call reserving 19 leaves only one unit for a later stop call requesting 20. That stop closes one unit if reached first.

FIFO controls trade allocation, separately from the entry ID used to size or price an order. Suppose Buy1 opened five units, then Buy2 opened ten. strategy.close("Buy2") requests a ten-unit close. Under FIFO, it closes Buy1’s five units first and five from Buy2. A previously placed Buy1 exit can remain active for its reserved quantity against the remaining position.

Set close_entries_rule="ANY" to close the requested entry directly. strategy.close(qty=...) specifies the total close quantity across matching entries, and a cash-per-order close fee is charged once even when the fill spans multiple trades.

Trailing stops and OCA groups

A trailing exit needs trail_offset and either trail_price or trail_points:

strategy.exit("Trail", "Long", trail_points=20, trail_offset=10)

The activation distance and offset are in ticks when using trail_points and trail_offset. Once active, the stop follows favorable prices and does not move backward. Trailing state survives updates to the same exit and is recalculated consistently during a forming candle.

In v6, supplying both relative and absolute exit levels chooses the level expected to trigger first. This applies to profit/limit, loss/stop, and trailing activation pairs. V5 preserves absolute-level precedence.

strategy.entry() and strategy.order() support OCA groups using oca_name with strategy.oca.cancel, strategy.oca.reduce, or strategy.oca.none. Cancel groups remove sibling orders after a fill; reduce groups subtract the filled quantity from siblings. The same name with a different OCA type is a separate group. Custom OCA names on strategy.exit() are not supported.

Forming candles and remaining limits

A forming candle can revise its high, low, close, and provisional fills as replay reveals more data. The tester replaces revised fills, and new strategy orders commit on confirmation. Reapplying a script or changing inputs preserves whether the final candle is still forming.

Bar Magnifier, calc_on_every_tick, calc_on_order_fills, calc_on_every_history_tick, strategy risk-control commands, and automatic currency conversion remain unsupported. The simulation uses available candles rather than TradingView’s complete market-data and broker environment.

Strategy state and results

Scripts can read strategy.position_size, strategy.position_avg_price, strategy.equity, strategy.netprofit, strategy.openprofit, strategy.initial_capital, strategy.account_currency, strategy.margin_liquidation_price, strategy.opentrades, and strategy.closedtrades.

Supported per-trade accessors include entry ID, price, time, size, and profit. Closed trades also expose exit price and time.

The Strategy Tester shows Net P&L, trade count, win rate, drawdown, final balance, current position, an equity curve, and a trade log. Entry and exit markers show simulated fills on the chart. These results belong to the strategy simulation.