TradingView strategy research

Pyramiding strategy: adding to winners within a risk budget

A pyramiding strategy adds to a position after price moves in its favor. Each addition needs its own trigger and quantity, plus a check of the entire position against a loss budget and an exposure ceiling. A profitable first entry does not make later entries free: adding at higher prices raises the average cost and the amount that can be lost on a reversal. The worked example below adds 100, 50, and 25 shares while keeping a shared stop fixed.

See the decision guide

A three-layer rulebook before the first order

This illustrative long-only experiment starts after a close crosses above the prior 20-bar high. It adds only after a later close is at least 2% above the most recent entry fill. Quantities decline from 100 to 50 to 25 shares. These settings define a reproducible experiment; they are not optimized recommendations or reported trading results.

  • This page studies adding after favorable movement. Doubling after a loss is a different sizing policy; partial take profits reduce exposure rather than add it.
  • Use actual fill prices for the next trigger. A decision price and the eventual transaction price can differ.
DecisionExplicit ruleReason to reject an add
Initial entryOne breakout event while flat; 100 shares.Invalid stop distance, insufficient funds, or planned risk above the budget.
Second entryAfter the first fill, a close at least 2% above that fill; 50 shares.First order has not filled, or the combined position fails a limit.
Third entryAfter the second fill, a close at least 2% above that fill; 25 shares.A prior layer is still pending, or the combined position fails a limit.
Further entriesNone until the whole position has closed.A persistent signal is not a fourth permission to buy.
ExitUse the same fixed stop for all layers in the baseline.Do not move the stop farther away to accommodate an addition.

Worked example: 175 shares do not have the first entry cost

Assume USD shares with a point value of 1, a $100,000 account, a fixed stop at $96, and hypothetical fills at $100, $102, and $104.04. Ignore costs and gaps for this arithmetic only. Weighted entry = sum(quantity × fill price) / total quantity. Planned loss at the stop = sum(quantity × (fill price - stop)).

  • Total acquisition cost is $17,701. At $104.04, current notional is 175 × $104.04 = $18,207 and unrealized profit is $506.
  • A reversal from $104.04 to the $96 stop gives back that $506 and loses another $901 relative to entry cost: an equity decline of $1,407 before fees.
  • A hypothetical gap fill at $94 produces 175 × $94 - $17,701 = -$1,251. A $901 planned stop loss therefore does not cap the realized loss.
  • All layers belong to the same price path. Counting three entries as three independent successful strategy observations would overstate the sample.
Filled layerAdded shares × fillTotal sharesWeighted entryLoss if all exit at $96
First100 × $100 = $10,000100$100.00$400
Second50 × $102 = $5,100150$100.6667$700
Third25 × $104.04 = $2,601175$101.1486$901

Use the remaining risk budget to size the next layer

For the worked example, choose a $1,000 planned loss budget, equal to 1% of starting account equity. This is a research assumption, not a recommended allocation. After two layers, $700 is committed. At the third planned fill of $104.04, each additional share adds $8.04 of stop risk. With no cost reserve, the remaining $300 permits floor(300 / 8.04) = 37 shares; the proposed 25 shares fit.

  • With a $100 allowance for estimated fees and adverse execution, only $200 remains after the first two layers. The third layer is then capped at floor(200 / 8.04) = 24 shares. The original 25-share plan fails that stricter policy.
  • For positive long-position loss distances, quantity cap = floor((budget - existing planned loss - cost allowance) / ((planned entry - stop) × point value)). Round down again to a valid lot increment. Skip when the numerator or stop distance is nonpositive.
  • Use consistent currencies. Convert quote-currency risk to account currency when they differ. Futures point values, FX lot conventions, and minimum quantities make share-based arithmetic unsuitable without adjustment.
  • If different layers have different stops, calculate each layer separately. A conservative loss budget sums max(0, entry - stop) × quantity × point value and does not spend hypothetical stop profits from earlier layers.

Margin and exposure need their own limit

Suppose the research plan also caps current notional at 20% of the original $100,000 account, or $20,000. The three-layer example uses $18,207 at the third fill, so it passes at that moment. Price changes can later push current notional above the ceiling even without another order; specify whether that means no further adds or an active reduction.

  • TradingView margin settings specify the funded percentage. A 100% margin assumption requires full funding; 25% permits more leverage. Insufficient equity can cause simulated forced liquidation.
  • At $104.04, 25% of the $18,207 current position value is $4,551.75. That funding figure is different from the $901 planned stop loss and the $18,207 market exposure.
  • Before each add, apply the smallest quantity allowed by the loss budget, notional ceiling, available funds, and tradable lot size. Borrowing capacity is not permission to exceed the risk budget.

What Pine Script pyramiding does and does not restrict

TradingView applies pyramiding to strategy.entry(), not strategy.order(). A limit of 3 permits three open entry trades in one position, including the first entry. It is an entry-count setting, not a cash-risk limit.

MechanismBehavior to account for
strategy.entry()Current documentation specifies a default pyramiding value of 1. Opposite-direction entries normally reverse the position.
strategy.order()Ignores pyramiding and changes the net position through its orders. Implement an explicit exposure check when using it.
Simultaneous price ordersMultiple limit, stop, or stop-limit entries created on one tick can all fill when triggered, exceeding the pyramiding limit.
Repeated conditionsTrack which layers were submitted and filled. A condition remaining true should not repeatedly submit the same intended addition.

Pine Script v6: sequential adds with a planned price-risk check

This long-only study uses the rulebook above, a stop 4% below the first decision close, rounded down to a tick, and a $1,000 default quote-currency price-risk budget. It submits one layer at a time and keeps that stop fixed. Default bar-close orders normally fill at the next bar open. The check uses the decision close, so a later fill can exceed the estimate or fail the favorable-price condition.

  • The script includes illustrative 0.05% commission on transactions and one tick of slippage in the backtest. Its admission check excludes those costs and has no notional ceiling. Add those separate constraints before using it to implement the full risk policy.
  • The stop is submitted with the initial entry and maintained for later layers. There is no profit target or time exit; a position can remain open at the end of the dataset. Inspect open exposure as well as closed results.
  • Keep the declared calculation settings for this demonstration. Intrabar recalculation changes state handling and requires a separate test of duplicate submissions.
  • Use an adequately funded, positive-price instrument with valid quantities. An unfilled or rejected entry can leave the submission counter waiting; inspect the order history rather than interpreting silence as a risk approval.
Educational order-management example; no measured performance result.pine
//@version=6
strategy("Three-layer pyramiding study", overlay = true, pyramiding = 3,
     initial_capital = 100000, margin_long = 100, margin_short = 100,
     commission_type = strategy.commission.percent, commission_value = 0.05,
     slippage = 1, calc_on_every_tick = false, calc_on_order_fills = false)
float riskBudget = input.float(1000, "Planned price risk (quote currency)", minval = 1)
float breakout = ta.highest(high, 20)[1]
bool firstSignal = ta.crossover(close, breakout)
var int submitted = 0
var float stopPrice = na
bool justClosed = strategy.closedtrades > nz(strategy.closedtrades[1]) and strategy.position_size == 0
if justClosed
    submitted := 0
    stopPrice := na
if not justClosed
    if submitted == 0 and strategy.position_size == 0 and firstSignal
        float candidateStop = math.floor(close * 0.96 / syminfo.mintick) * syminfo.mintick
        float plannedRisk = 100 * (close - candidateStop) * syminfo.pointvalue
        if close > candidateStop and plannedRisk <= riskBudget
            stopPrice := candidateStop
            strategy.entry("L1", strategy.long, qty = 100)
            submitted := 1
    else if submitted > 0 and submitted < 3 and strategy.opentrades == submitted
        float lastFill = strategy.opentrades.entry_price(strategy.opentrades - 1)
        float addQty = submitted == 1 ? 50 : 25
        float existingRisk = (strategy.position_avg_price - stopPrice) * strategy.position_size * syminfo.pointvalue
        float plannedRisk = existingRisk + addQty * (close - stopPrice) * syminfo.pointvalue
        if close >= lastFill * 1.02 and close > stopPrice and plannedRisk <= riskBudget
            strategy.entry(submitted == 1 ? "L2" : "L3", strategy.long, qty = addQty)
            submitted += 1
if submitted > 0
    strategy.exit("Shared stop", stop = stopPrice)
plot(stopPrice, "Shared stop", color.red, style = plot.style_linebr)
plot(breakout, "Prior 20-bar high", color.gray)

Choose a shared stop or separate layer exits deliberately

A shared price stop makes the worked loss calculation easy to audit. Independent stops allow the later layer to leave while an older layer remains, but the remaining risk must then be recomputed. If a partial exit frees an entry slot, decide whether the strategy may refill it; this example prohibits replacement layers within a position.

Exit designPine behavior and audit point
Shared stopstrategy.exit() without from_entry applies across entries and persists for subsequent entries until the position closes.
Separate layer exitsUse distinct entry IDs and from_entry. FIFO is the default close allocation; close_entries_rule = "ANY" changes it. Verify the resulting trade attribution.
Partial exitsSeparate strategy.exit() calls reserve quantities. Check allocation and remaining protection; do not assume every exit controls the full position.

Compare one entry with three layers on the same sample

Freeze the signal, stop, date range, costs, instrument, and execution settings. Run a one-entry baseline and a pyramiding version, then repeat on an untouched later period. Record both the fixed-first-layer comparison and, separately, an equal-risk comparison. Larger position size alone can change profit and drawdown without improving the entry signal.

  • Audit each campaign from flat to flat: trigger time, layer ID, submitted quantity, fill, current stop, estimated remaining risk, and total exposure. Preserve rejected additions too.
  • Test a persistent breakout condition, a gap through the stop, multiple levels crossed in one bar, an add followed by an immediate reversal, insufficient funds, and an open final position.
  • Inspect order sequencing when a bar can reach both an add and an exit. Record the historical fill assumptions and compare finer intrabar data where available.
  • Backtest Deep Report accepts TradingView trade CSV exports for reviewing trade records and distributions. Preserve campaign IDs separately: this page does not claim that the report automatically groups pyramiding layers or reconstructs every intrabar exposure.
Where Pineify fits

Pine Script AI Coding Agent

Provide the layer triggers, quantities, stop policy, risk currency, cost allowance, and exposure ceiling to draft or revise the strategy. Review the generated orders and validate the source before comparing backtests.

Also useful: Backtest Deep Report. Review a TradingView trade CSV alongside your layer log. Imported results describe the exported sample and do not establish live execution quality.

Draft pyramiding rules in Pine Script

Frequently asked questions

Educational strategy research, not investment advice. Prices, quantities, and risk limits are hypothetical. No performance study is reported. Stops, backtests, and syntax checks do not guarantee execution prices, a maximum loss, or future returns.

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.