Sizing details¶
TradeScript stays on //@version=1. size: declares an amount or objective;
allocate: optionally divides a shared objective; risk: declares hard caps.
This reference gives the exact forms and their effects. Begin with position sizing for a guided explanation.
Public grammar and defaults¶
size: P% [of portfolio | of starting capital | of capital]
[per instrument | in total | across active instruments]
size: N units [per instrument]
size: L lots [per instrument] # Forex currency pairs only
size: risk R% [of portfolio | of starting capital | of capital]
[per trade] [with stop S%]
size: vol target V% [annualized | monthly | daily]
[over N daily bars] [per instrument | across active instruments]
resize: daily | weekly
Each declaration is one line. Percentage values must be positive and no more than
100%; unit counts are positive integers. Case and repeated whitespace normalize,
but the number must touch % (5%, not 5 %), and word
order and complete token consumption matter. Duplicate sections or conflicting
modifiers fail. units is canonical; unit is singular. shares/share remain
quantity aliases. capital remains a basis alias, rendered as starting capital.
Risk's optional legacy per trade is omitted from canonical output.
Bare percentages use this strategy's current marked portfolio value, rather
than the broker account's total wealth or remaining buying power. Omitted scope
comes from strategy shape, independently of symbol: versus universe::
| declaration | Independent entry/exit | Hold target book |
|---|---|---|
size: 5% |
5% per entering instrument | One 5% selected-book budget |
size: 5% per instrument |
5% per entering instrument | 5% per selected position |
size: 50% in total |
Split over the full fixed eligible list; inactive shares unused | Split over selected positions |
size: 50% across active instruments |
Split over active membership; intentional book rebalance | Rejected: hold already supplies membership |
size: 100 units |
100 for each entering position | 100 for each selected position |
Declare a concrete eligible list. Dynamic named universes, pairs/spreads and option structures are deferred. An edited list applies through stop/redeploy; it does not hot-reload a running deployment's membership.
Forex standard lots¶
//@version=1
symbol: EUR_USD
run: each bar
size: 0.1 lots
entry:
long when: close > sma(20)
exit:
long when: close < sma(20)
One standard Forex lot is 100,000 units of the base currency: 2 lots
means 200,000 EUR for EUR_USD, or 200,000 USD for USD_JPY. 0.1 lots means
10,000 base units. Leverage changes required margin, never this quantity.
OANDA receives signed native units, with conversion performed exactly once.
Use a positive plain decimal (lot or lots), without exponent notation.
0.00001 lot resolves to one native unit if the route permits it. Amounts
producing fractional native units are rejected without rounding. Native integer
bounds and supplied broker minimum/precision/order/position rules still apply.
Live OANDA requires fresh account-specific CURRENCY classification and
quantity metadata; the Forex market label alone does not classify a CFD/metal.
A local override such as long 0.02 lots when: close > sma(20) replaces that
entry's global size. Hold uses the same lot count per selected currency pair,
which means neither equal account-currency notional nor equal risk. These fixed
targets are admitted in full or skipped under known local capacity. Broker fills
can still be partial. Limits apply to the submitted delta and reachable position
separately, including independently fillable pending orders.
in total, active/shared allocation, money bases, allocate:, scheduled resize,
mini/micro aliases and lot-denominated partial exits are unsupported with lots.
Existing exits close actual native holdings without another lot multiplier.
Equity/SME, derivatives, metals, CFDs and crypto lots are outside this iteration.
Unknown equity lots do not silently turn into shares.
Backtests and the explicit nonleveraged paper route share a versioned known- currency, unit-one simulation convention. This is not historical broker limit or availability evidence. Live broker rejection remains authoritative, including aggregate account positions belonging to other strategies.
Money basis and capacity¶
For positive marked strategy equity E, starting capital C, optional Max capital K:
portfolio basis B = min(E, K when set)
starting-capital basis B = min(C, E, K when set)
desired allocation = P × B
Blank Max capital adds no ceiling. Both bases shrink with losses. With C=10,000 and E=12,000, bare 5% desires 600; explicit starting-capital 5% desires 500. With E=8,000, both desire 400. Max capital caps the money basis; it is neither broker balance nor gross exposure nor posted margin.
A percentage entry opens up to its assigned desired target, limited by known available strategy capacity, execution costs, pending increases, authored caps and actual venue rounding/minimums. With E=6,000 and 2,500 spendable unreserved cash, a 50% target desires 3,000 and can buy up to 2,500 before costs. At 500 per whole unit that means at most five units. Existing independent holdings remain untouched. This is approximately 41.7% achieved allocation, not 50%.
Report desired amount, admitted quantity/amount and limiting reason separately from confirmed fills. A broker partial fill or refusal is a different outcome. An admitted independent position does not automatically top up when cash arrives, a price changes or its entry condition remains true. A genuine new entry/reversal recomputes; hold/active-book evaluations may deliberately rebalance.
Fixed units, Forex lots and stop-risk preserve their full calculated venue-valid target or skip under known local limits. They are not clipped to residual capacity. Volatility has its own constrained-objective rules and reports achievable volatility.
Pending increases reserve capacity. Submitted reductions release none until confirmed execution and applicable settlement rules allow it. Long/short exposure consumes positive gross or margin capacity; net zero does not free budget. Missing trustworthy prices, terms, conversion or pending state blocks increases; retain provable reductions. Do not queue a missed edge or automatically retry a terminal unfilled remainder.
Independent and shared percentages¶
//@version=1
universe: [AAPL, MSFT, NVDA, AMZN]
run: daily
size: 10%
entry:
long when: rsi(14) < 30
exit:
long when: rsi(14) > 55
Each entering name desires 10% of the portfolio basis. There is no shared allocator. Continuing positions do not shrink to fund new ones.
//@version=1
universe: [AAPL, MSFT, NVDA, AMZN]
run: daily
size: 50% in total
entry:
long when: rsi(14) < 30
exit:
long when: rsi(14) > 55
Equal allocation is the default: each eligible name receives a 12.5% assigned share even if only one or two names signal. Inactive shares stay unused. New entries are capped by the remaining authored shared budget as well as whole-strategy capacity, without resizing continuing holdings. If an existing position drifts beyond the budget, block increases rather than force a sale.
Use across active instruments only when active membership should divide the
whole budget and resize continuing positions. Choose this scope only when membership changes should cause a rebalance.
Fixed quantities by instrument¶
Use an explicit quantity map when instruments need different targets:
//@version=1
universe: [EUR_USD, GBP_USD]
run: each bar
size: {EUR_USD: 1 lot, GBP_USD: 2 lots}
entry:
long when: close > 0
For equities or native Forex units, use the same form with whole units:
//@version=1
universe: [AAPL, MSFT]
run: each bar
size: {AAPL: 10 units, MSFT: 5 units}
entry:
long when: close > 0
Every key must match an instrument in the complete explicit symbol/universe
scope exactly, including exchange qualifiers and case. Map order does not change
execution order. All values use one quantity kind: units or lots. unit/units
and lot/lots are accepted; share/shares remain units aliases. Maps are
bounded to 500 names of at most 128 characters. Units are positive whole counts
no greater than 2,147,483,647. Lots retain bounded exact decimal strings and must
resolve to legal native Forex quantities using the selected runtime's terms.
Each entry uses its own full fixed target or skips for known insufficient
capacity; an existing same-direction position or pending entry is not topped up
on each bar. Short entries use the same quantities with opposite direction.
Hold selection uses the mapped target for each selected eligible instrument.
Confirmed exits still close actual holdings. Standard Forex lots always convert
100,000 base units once, independent of leverage. India/equity lots remain
unsupported. Local quantity overrides, allocate:, mixed unit/lot values,
percentage map values, duplicate names and missing/extra keys are rejected.
Percentage allocation remains the separate shared-budget allocate: form below.
Optional allocation¶
allocate: equal weight
allocate: inverse volatility over N bars
allocate: {AAPL: 70%, MSFT: 30%}
Dictionary keys must match the full explicit eligible list exactly, without
missing/extra/duplicate names; positive weights total exactly 100%. Ordinary total
mode leaves inactive dictionary shares unused; active scope renormalizes over
active members. Dictionary allocation for both ranked and fixed-membership hold
is deferred. Allocation beside independent percentages, fixed units or stop-risk
is rejected. Do not declare a separate allocator beside hold: equal weight.
Inverse volatility refreshes completed-history estimates when actually sizing.
Its N bars window uses signal bars, distinct from volatility targeting's daily
window. Ordinary total-mode continuing holdings stay unchanged even when new
coefficients differ. Invalid estimates must not silently become equal weights.
//@version=1
universe: [AAPL, MSFT, NVDA, AMZN]
run: monthly
size: 80%
allocate: inverse volatility over 63 bars
define score = rank(value) + rank(quality) + rank(momentum)
hold: long top half by score
risk: max 40% per instrument, gross <= 80%
The selected names share an 80% budget. Hold controls membership; exit: clauses
are ignored with TS-HOLD-EXIT-IGNORED. Separate independent entries with hold
are rejected. Percentage hold evaluations can rebalance the target book.
Fixed units and stop-risk¶
//@version=1
symbol: TCS
size: 100 units
entry:
long when: rsi(14) < 30
exit:
long when: rsi(14) > 55
Fixed units are per position and unchanged by fixed leverage or Forex Max. Existing
venue quantity conversion and minimum steps still apply. Local long N units /
short N units override per-instrument top-level sizing; all entries may supply
local units instead of a top-level size. Local quantities cannot mix with a shared
objective. Simultaneous long and short conditions resolve one signed net target
before admission. Continuing same-side positions retain entry-only semantics.
//@version=1
symbol: AAPL
run: daily
size: risk 1% with stop 5%
entry:
long when: close > high[1]
exit:
long when: close < low[1]
Risk means planned stop loss per trade, with portfolio basis by default. At B=100,000, 1% risk is 1,000; at price 100 and a 5% stop, desired quantity is 200 units before venue conversion/rounding and admission. Three simultaneous 1%-risk trades imply approximately 3% planned open risk, without an implicit combined risk cap.
The inline percentage stop supplies both sizing distance and actual engine-watched
protection. Legacy separate stop: 5% works; identical duplicates canonicalize,
conflicting stops fail. ATR/points/absolute-price stops are unsupported for this
risk objective. Stop-risk hold is deferred. Leverage does not multiply the loss
budget or risk-derived quantity. Stops do not guarantee realized loss bounds;
gaps, slippage, fees and outages matter. Broker-native protection is not established
by this language contract.
Volatility and resize¶
//@version=1
universe: [AAPL, MSFT, NVDA, AMZN]
run: monthly
size: vol target 10%
resize: weekly
hold: long top half by momentum
The target number is required; omitted period means annualized. Default history
is 63 completed daily returns, requiring at least 64 valid completed closes,
independently of signal timeframe. over N daily bars changes this returns window
(N at least two). The history must contain valid completed observations; forming or future candles do not count.
Daily/monthly/annual scaling is 1, √21, √252.
Independent volatility targets size at entry. Active/hold combined objectives
re-solve on membership changes using signed covariance and account-currency P&L:
estimated volatility = sqrt(qᵀΣq) / E. E is marked strategy equity, not capped
basis B. A long/short hedge has different covariance from a long/long book;
independent contributions do not promise one combined target. Apply hard caps,
conversion and rounding, then report requested versus achievable volatility.
Zero, missing, stale or non-finite estimates block increases and keep ordinary
exits/reductions available; no epsilon sizing or fixed/equal fallback.
Only volatility accepts resize: daily or weekly. Resize changes size, not
selection or entry intent. Unchanged membership/drift does not resize without it.
Scheduled size-only changes of 5% or less of actual
absolute held notional are skipped, allowing drift to accumulate. New entries,
exits, required reductions and membership rebalances bypass that buffer.
Forex deployment modes¶
Percentage sizing in Forex depends on the selected deployment mode. Max allocates a percentage of the sizing basis as desired margin using current instrument margin rates. Fixed leverage requests percentage exposure multiplied by the chosen leverage, subject to both gross and margin capacity. These modes do not multiply fixed-unit, stop-risk or solved-volatility quantities.
A Forex lot is always 100,000 base-currency units. Instrument classification, conversion, minimum quantities and current account limits must be available. A missing price or conversion can block new exposure. Confirmed reductions and account settlement determine when capacity is available again.
Historical Forex Max backtest support is a separate runtime capability; accepted syntax does not prove it.
Unsupported combinations¶
Dynamic named universes, pairs/spreads, options, pyramiding/tranches, India/equity lots, advanced solver allocations, and opposite derivation with active shared sizing are outside the current executable contract. Fixed-hold dictionary allocation and combined planned-risk caps are deferred. Forex standard lots are supported only for eligible currency pairs.