Pine Script Strategy & Position Sizing

Pine Script Pyramiding: How to Scale Into Strategy Positions

Pyramiding limits successive strategy.entry() trades contributing to the same-direction position. The current manual documents a default of 1: one entry, without additions. A value of 3 allows up to three total entries, not three additions. It does not constrain strategy.order(), and multiple price-based entries created on the same tick can exceed the usual limit.

Build Pyramiding Strategies with AI

How pyramiding works in TradingView strategies

A pyramiding value of 3 allows an initial trade and two additions through strategy.entry() under the usual count rule. The filled quantities increase position_size and determine the quantity-weighted position_avg_price. For example, 10 shares at 100 and 20 shares at 110 yield (1000 + 2200) / 30 = 106.6667 before display rounding. This position average is not a session VWAP indicator.

Pyramiding settingTotal entries permittedOrder behavior when condition repeatsTypical use cases
pyramiding = 1 (default)1 entry maxNew entry signals in same direction are ignoredStandard swing and trend-following strategies
pyramiding = 22 total entriesAllows one additional scale-inInitial position + confirmation add-on
pyramiding = 3 to 5Up to 3-5 entriesAllows progressive additions as trend progressesMulti-stage breakout or dip-buying systems
pyramiding = 10+Up to 10+ entriesPermits deep DCA laddersGrid trading and dollar-cost averaging strategies

Complete Pine Script v6 trend-scaling strategy with pyramiding

This long-only teaching strategy allows three market entries on qualifying breakout signals. Its exit prices are recalculated from current position average and ATR. This is a moving bracket, not a trailing stop: an ATR increase or added entry can move the stop away from price. It does not freeze initial risk or guarantee that later entries are profitable.

  • Five percent of equity per entry is exposure sizing, not a fixed loss budget. Costs are omitted. Entries fill on the next available tick under the default settings.
  • The bracket is submitted only after a filled position is observed at a calculation; default close-only execution leaves a delay on the entry bar. No immediate protective-order guarantee is made.
  • For a chart acceptance test, check that at most three sequential market entries accumulate, recompute the weighted entry price, and observe how rising ATR moves both exit prices. These are proposed checks, not reported runtime results.
Pine Script v6: three total entries and a recalculated ATR bracketpinescript
//@version=6
strategy("Pyramiding Trend Scaler [v6]", 
         overlay = true, 
         initial_capital = 10000, 
         pyramiding = 3, 
         default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 5)

// Trend filter
trendEma = ta.ema(close, 200)
plot(trendEma, "200 EMA", color = color.blue, linewidth = 2)

// Breakout trigger
priorHigh = ta.highest(high, 10)[1]
newHighBreakout = ta.crossover(close, priorHigh)
atrVal = ta.atr(14)
isUptrend = close > trendEma

// Entry signal: allows up to 3 entries because pyramiding = 3
if newHighBreakout and isUptrend and not na(atrVal)
    strategy.entry("Long", strategy.long)

// Risk management across all pyramided positions
if strategy.position_size > 0
    avgPrice = strategy.position_avg_price
    
    // Stop loss placed 2 ATR below average entry price
    stopLevel = avgPrice - (atrVal * 2.0)
    // Take profit placed 4 ATR above average entry price
    targetLevel = avgPrice + (atrVal * 4.0)
    
    strategy.exit("Exit All", from_entry = "Long", stop = stopLevel, limit = targetLevel)
    
// Plots must be in global scope.
plot(strategy.position_size > 0 ? strategy.position_avg_price : na, "Average Entry Price", color = color.yellow, style = plot.style_linebr)

Managing distinct entry IDs vs. single shared IDs

When designing pyramiding strategies, developers choose between two order management patterns:

  • Shared IDs: matching entries remain separate trades in one net position. A strategy.exit() call with from_entry="Long" can create exits for each matching entry; do not infer one physical order or simultaneous live fills from the shared ID.
  • Distinct IDs: from_entry can restrict exit orders to a particular entry ID. Trade-list allocation defaults to FIFO; close_entries_rule="ANY" changes allocation where applicable. Verify targeted orders and the reported closed-trade attribution separately.
  • By default an opposite strategy.entry() increases the transaction quantity to close the existing position and open the requested opposite size. Risk settings can restrict directions; an entry call is not automatically a close-only instruction.

Backtesting pitfalls with strategy pyramiding

Scaling into positions alters backtest statistics dramatically. Watch out for these mathematical biases:

  • Margin exhaustion: If default_qty_type is fixed cash or percent of equity, ensure your account retains sufficient free margin for the 3rd or 4th entry; otherwise, TradingView drops subsequent orders.
  • A larger position has greater price sensitivity. Whether its largest size occurs near a market top depends on the realized path; the entry count alone cannot establish that outcome.
  • Test losing streaks, gaps and financing costs. Adding to losing positions can increase loss concentration; no universal win rate or inevitable outcome follows from the pyramiding setting.
Where Pineify fits

Pine Script AI Coding Agent

Generate rule-based pyramiding strategies, multi-entry ladders, and volume-weighted position management in Pine Script v6 with the AI Coding Agent.

Also useful: Strategy Optimizer. Compare supported input configurations while holding data and costs fixed. Pyramiding is a strategy property here, not an input exposed by this example; do not assume the optimizer changes it automatically.

Build Pyramiding Strategies with AI

Frequently asked questions

Scaling into positions and strategy pyramiding increases exposure and potential drawdown. Backtested simulations may not reflect margin calls, execution delays, or liquidity limitations during live trading.

Sources and verification