Pine Script Strategy & Position Sizing

Pine Script Pyramiding: How to Scale Into Strategy Positions

In Pine Script strategies, pyramiding defines the maximum number of consecutive entries allowed in the same direction before an exit occurs. By default, pyramiding = 0 (only one entry allowed). Setting pyramiding to an integer greater than zero enables position scaling, dollar-cost averaging, or trend pyramiding using distinct or identical strategy.entry() call IDs.

Build Pyramiding Strategies with AI

How pyramiding works in TradingView strategies

When you call strategy.entry() while a position is already active in that direction, Pine Scripts broker emulator checks the pyramiding setting declared inside the strategy() statement. If pyramiding = 0 (the default), TradingView discards the new order. If pyramiding is set to 3, the strategy permits up to 3 total entries in that direction. As new entries fill, strategy.position_size grows and strategy.position_avg_price recalibrates to reflect the volume-weighted average price of all combined entries.

Pyramiding settingTotal entries permittedOrder behavior when condition repeatsTypical use cases
pyramiding = 01 entry maxNew entry signals in same direction are ignoredStandard swing and trend-following strategies
pyramiding = 11 entry + 1 scale-in (2 total)Allows 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

The following complete Pine Script v6 strategy demonstrates how to configure pyramiding = 3 to scale into an established trend whenever price breaks out to new 10-bar highs, while protecting all entries with a unified trailing stop anchored to the volume-weighted average price.

Pine Script v6: Strategy scaling into winning trend with pyramiding = 3pinescript
//@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
newHighBreakout = ta.crossover(close, ta.highest(high, 10)[1])
isUptrend = close > trendEma

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

// Risk management across all pyramided positions
if strategy.position_size > 0
    avgPrice = strategy.position_avg_price
    atrVal = ta.atr(14)
    
    // 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)
    
    // Plot current average entry price line
    plot(avgPrice, "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 ID pattern: Calling strategy.entry("Long", strategy.long) with identical IDs accumulates all size into a single unified position. A single strategy.exit("Exit", from_entry = "Long", ...) exits the entire aggregated position simultaneously.
  • Distinct ID pattern: Calling strategy.entry("Entry1", ...), strategy.entry("Entry2", ...) creates distinct sub-orders. You can attach individual strategy.exit() orders to each specific entry ID with unique stop-loss and take-profit targets.
  • Beware position flips: If an opposing strategy.entry("Short", ...) fires while long positions are active, TradingView closes all existing long orders regardless of pyramiding settings and enters short.

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.
  • Drawdown magnification on pullbacks: When pyramiding into a trend, your largest position size is active at the very top of the market. A minor market reversal creates larger dollar losses than initial entries gained.
  • Avoid martingale averaging down: Adding to losing positions without a hard stop creates artificially high win rates right before an catastrophic drawdown ruins the portfolio.
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 performance between pyramiding = 0, 1, 2, and 3 to discover the ideal scaling depth for your asset.

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