Pine Script Strategy Position Sizing: Qty, Equity and Margin | SG Group
Skip to the article
TradingView guide · Content reviewed 日本語で読む
Pine Strategy Engineering · TV16

Pine Script Strategy Position Sizing: Fixed, Cash, Percent of Equity, Qty and Margin

The same entry rules can produce a different trade history when Pine reads “10” as ten contracts, ten units of account currency, or ten percent of available equity. This is not a guide to the right lot size. It is an audit of how Pine Script v6 resolves order quantity, how overrides take precedence, and how capital, currency, price and margin enter the simulation.

Who this guide is for: Pine strategy authors whose order sizes do not match expectations, and testers comparing fixed, cash and equity-based sizing

Key points to understand first

QUANTITY PRECEDENCE

Order sizing branches first on whether qty exists

strategy.entry() / strategy.order()
  1. qty is non-naqty contracts, shares, lots or unitsOverrides default_qty_type/value
  2. qty is na or omittedUse the strategy defaultBranch to fixed, cash or percent_of_equity
  • fixedA fixed number of instrument units
  • cashA fixed notional in the account currency
  • percent_of_equityA share of available strategy equity
Conceptual quantity resolution only. Tradable increments, currency conversion, point value and margin calls depend on the symbol and dataset.
01 · Quantity verdict

Position sizing is a test assumption, not a cosmetic setting

Start by separating a strategy default from an order-level override. The default_qty_type and default_qty_value arguments in strategy() apply to entry and order calls that omit qty. If a call supplies a non-na qty, that call does not use the default.

The distinction changes the path of the simulation. Fixed sizing generally sends the same unit count. Cash sizing converts an account-currency notional into units at the order price. Percent-of-equity sizing changes as both available equity and price change. A sizing change therefore deserves its own version label, export and comparison rather than being folded into one undifferentiated result.

02 · Three default types

The same value means three different things

Default quantity types
TypeWhat a value of 10 meansWhat changes quantityAudit point
strategy.fixed10 contracts, shares, lots or unitsOrder overrides and instrument rulesReconcile order quantity with the position left after the fill
strategy.cash10 units of account-currency notionalPrice and currency conversionRecord account and symbol currencies
strategy.percent_of_equity10% of available strategy equityEquity, price, open exposure and marginTrace quantity along the equity path

The numerical value is not comparable until its unit is known.

Conceptual conversionsfixed quantity = default_qty_valuecash quantity ≈ cash allocation ÷ order pricepercent quantity ≈ (available equity × percent ÷ 100) ÷ order priceindicative margin = position notional × margin percent ÷ 100Point value, account-currency conversion, quantity precision, existing positions and emulator rules can alter the real calculation.

Futures and CFDs can have a contract value that is not simply one chart price per contract. Check syminfo.pointvalue and the instrument specification before carrying a stock-style notional calculation across markets. The mini calculator below is deliberately simplified and is not a contract-specification engine.

03 · Override rules

Audit qty precedence before changing Properties

If changing Default order size in Properties leaves results unchanged, inspect every entry and order call for a hard-coded or calculated qty. A non-na value wins. To fall back to the default, omit the argument or deliberately return na when the default should apply.

Sizing precedence by command
Callqty stateSize usedCaveat
strategy.entry / strategy.orderNon-naqty instrument unitsThe strategy default is ignored
strategy.entry / strategy.orderna or omittedstrategy() defaultUsers can adjust it in Properties
strategy.exitqty suppliedAbsolute exit quantityqty wins if qty_percent is also supplied
strategy.close / close_allQuantity tied to the selected open trade or positionNot governed like a new entry

TV17 covers exit reservations, partial exits and OCA behavior.

04 · Capital and margin

Keep only the capital, currency and margin links that change sizing

TV11 covers the full Strategy Properties fingerprint. Here, retain only the dependencies that enter quantity resolution: initial_capital seeds the first percent-of-equity allocation, currency defines the unit of a cash default, and margin_long/margin_short constrain whether the resulting notional can be maintained.

Cash sizing converts account currency into instrument quantity. Percent-of-equity sizing first creates a notional allocation from available equity. Margin does not select the entry qty, but rejected exposure or simulated liquidation can alter the quantity path, so the setting still belongs beside the run.

Three dependencies that touch sizingcash allocation unit = strategy account currencypercent allocation = available equity × percent ÷ 100indicative margin = position notional × margin percent ÷ 100This simplified map excludes currency conversion, point value, quantity steps, existing exposure and the emulator liquidation algorithm.
05 · Controlled sizing run

Hold entries constant and vary only the sizing method

This educational script uses a simple moving-average cross and deliberately omits qty. It is not evidence that the signal has an edge. The omission lets you change fixed, cash and percent-of-equity defaults in Properties without an order-level override silently defeating the test.

Pine Script v6: minimum default-quantity auditpine
//@version=6
strategy(
    "Quantity interpretation audit",
    overlay = true,
    initial_capital = 100000,
    currency = currency.USD,
    default_qty_type = strategy.percent_of_equity,
    default_qty_value = 10,
    margin_long = 100,
    margin_short = 100
)

int fastLength = input.int(20, "Fast length", minval = 1)
int slowLength = input.int(50, "Slow length", minval = 2)
float fast = ta.sma(close, fastLength)
float slow = ta.sma(close, slowLength)

bool longCondition = ta.crossover(fast, slow)
bool flatCondition = ta.crossunder(fast, slow)

if longCondition and strategy.position_size == 0
    strategy.entry("Long", strategy.long)

if flatCondition and strategy.position_size > 0
    strategy.close("Long")

plot(fast, "Fast", color.aqua)
plot(slow, "Slow", color.orange)
plot(strategy.position_size, "Position size", display = display.data_window)
plot(strategy.equity, "Equity", display = display.data_window)

Adding a non-na qty to the entry call overrides the declared default for that order.

Keep code and signals fixed. Run fixed, cash and percent-of-equity variants one at a time. For each run, record type, value, capital, currency, margin, period, symbol, timeframe and costs, then save a separately named List of Trades export.

06 · Practical audit

Reconcile an equity allocation with the first trades

The mini calculator divides an equity allocation by a simple order price and estimates collateral. It assumes one unit has a notional equal to price. It excludes futures point value, FX conversion, CFD contract size, quantity steps, open exposure and trading costs.

  1. Capture Properties

    Record quantity type and value, capital, currency, margin, commission and slippage.

  2. Reconcile the first three trades

    Compare entry price, transaction size, resulting position and equity available at entry.

  3. Change one condition

    Keep signals fixed and change only the sizing type or the sizing value.

  4. Export separately

    Name each Strategy Tester CSV/XLSX with the sizing assumption and version.

  5. Compare the path

    Review return, drawdown, trade loss distribution, size concentration and margin events over the same period.

07 · Quantity ledger

Bind one quantity ledger to one Strategy Tester export

Define the research unit as one run, one quantity-ledger row and one Strategy Tester export. Use a shared version ID so the source-side qty path and the realized transaction quantities can be reconciled later without relying on memory.

Minimum ledger fields are version ID, script hash, symbol, timeframe, entry ID, sizing type and value, override state, account and symbol currencies, point value, margin, and expected versus observed quantity for the first three trades. Mark any mismatch unresolved before publication.

Put the version ID and sizing method in the filename instead of overwriting fixed, cash and percent-of-equity runs. The ledger then separates entry-rule behavior from compounding and late-sample size concentration using the same evidence trail.

EDUCATIONAL MINI CALCULATOR

Percent-of-equity order-size estimate

Estimate allocation, units and margin in a simplified one-unit-equals-price model.

Notional allocationaccount currency
Unrounded quantity estimateunit
Indicative required marginaccount currency

Formula: allocation=a×c÷100; quantity=allocation÷b; margin=allocation×d÷100. Excludes contract size, point value, currency conversion, quantity steps, costs, slippage and existing exposure.

Frequently asked questions

Why does changing Default order size in Properties have no effect?

A non-na qty may still be present in strategy.entry() or strategy.order(). That call uses qty instead of the default quantity type and value.

Does percent_of_equity keep the loss per trade at the same percentage?

No. It allocates order notional as a percentage of available equity. Loss at the stop also needs stop distance, value per unit, rounding, gaps and slippage.

Does 25% margin mean 25% risk?

No. Margin is the broker-emulator collateral requirement for the position notional. It is separate from the loss budget and tolerated drawdown.

How do I return qty to the Properties default?

Omit qty from strategy.entry() or strategy.order(), or pass na on the branch that should use the default. Check that a wrapper or intermediate expression does not replace it with a number.

Primary sources and verification links

  1. TradingView Pine Script — Declaration statementsOfficial default quantity, capital, currency and margin definitions.
  2. TradingView Pine Script — StrategiesOfficial position-sizing, emulator, order and margin behavior.
  3. TradingView Pine Script — Strategies FAQOfficial fixed-risk, leverage and no-order troubleshooting examples.
  4. TradingView Help — Strategy propertiesMaps the Properties controls to Pine arguments.
  5. TradingView Help — Simulating leverage in Pine ScriptOfficial explanation of margin and simulated liquidation.

Edited and published by: SG Group · Editorial approach: We prioritize official TradingView Help Center and Pine Script documentation, then use exchange, regulator and other primary materials for market and product context. Features, data, pricing and connection terms change, so verify the current interface and linked sources before use.

Important notice: This article provides general education about TradingView interfaces, charts, alerts, screeners, paper trading and Pine Script. It is not investment advice, a trading signal, a recommendation of any instrument, data source or broker, or a guarantee of future price or profit. Features, pricing, data, exchange coverage, notifications, order integrations and Pine Script behavior vary by plan, region, connection and date and may change. Before risking money, verify current TradingView documentation and the terms of the relevant data source and connected provider, then rehearse the workflow with fictional data or paper trading.