Skip to main content

Position Sizing & Risk Management in Pine

Calculating position size from risk percentage, forex lot sizes, pyramiding trades, and building risk management directly into strategy scripts.

From Thrive on YouTube

Watch the matching Thrive video

Watch the series
How to Size a Crypto Futures Trade: Risk, Stops and Leverage Explained

How to Size a Crypto Futures Trade: Risk, Stops and Leverage Explained

Part of Start Here: Crypto Futures Basics. Education only. Not financial advice.

Risk-Based Position Sizing

Professional traders never ask "how many coins should I buy?" They ask "how much am I willing to lose on this trade?" Risk-based position sizing calculates the exact quantity to buy so that if your stop loss is hit, you lose exactly your predetermined risk percentage, typically 1–2% of equity. This is the single most important concept in strategy development. A strategy with a 60% win rate will blow up without position sizing. A strategy with a 40% win rate can be profitable with it.

pine-Position sizing from risk percentage
1//@version=5
2strategy("Risk-Based Sizing", overlay=true,
3 initial_capital=10000,
4 default_qty_type=strategy.fixed,
5 commission_value=0.075, slippage=2)
6
7// === INPUTS ===
8riskPct = input.float(1.0, "Risk Per Trade (%)", minval=0.1, maxval=5, step=0.1)
9atrMult = input.float(2.0, "ATR Stop Multiplier", minval=0.5, step=0.5)
10emaFast = input.int(9, "Fast EMA")
11emaSlow = input.int(21, "Slow EMA")
12
13// === CALCULATIONS ===
14atr = ta.atr(14)
15fast = ta.ema(close, emaFast)
16slow = ta.ema(close, emaSlow)
17
18// === POSITION SIZE CALCULATION ===
19// Risk amount in dollars
20riskAmount = strategy.equity * (riskPct / 100)
21
22// Distance to stop in price
23stopDist = atr * atrMult
24
25// Position size in units (coins)
26posSize = riskAmount / stopDist
27
28// === ENTRY ===
29longSignal = ta.crossover(fast, slow)
30if longSignal
31 stopPrice = close - stopDist
32 strategy.entry("Long", strategy.long, qty=posSize)
33 strategy.exit("SL", "Long", stop=stopPrice)
34
35// === EXIT ===
36if ta.crossunder(fast, slow)
37 strategy.close("Long", comment="EMA cross exit")
1

Determine risk amount

If your equity is $10,000 and you risk 1% per trade, your risk amount is $100. This means no single trade can lose more than $100 regardless of the asset price or volatility.
2

Calculate stop distance

Using 2x ATR(14) on BTC daily, if ATR is $2,500, your stop distance is $5,000. On ETH 4H with ATR of $80, stop distance is $160. ATR automatically adapts to volatility.
3

Compute position size

Position size = $100 / $5,000 = 0.02 BTC. If BTC is $60,000, that's a $1,200 position (12% of equity). On ETH: $100 / $160 = 0.625 ETH. The math guarantees your maximum loss.

Calculating Forex Lot Sizes

For traders who also trade forex, position sizing works the same way but uses lot sizes instead of units. One standard lot is 100,000 units. One mini lot is 10,000. One micro lot is 1,000. The pip value depends on the pair and lot size. For EUR/USD with a standard lot, one pip = $10. For a mini lot, one pip = $1.

pine-Forex lot size calculation
1//@version=5
2strategy("Forex Lot Sizer", overlay=true,
3 initial_capital=10000,
4 default_qty_type=strategy.fixed,
5 currency=currency.USD)
6
7riskPct = input.float(1.0, "Risk %", minval=0.1, maxval=5)
8stopPips = input.float(50, "Stop Loss (pips)", minval=5)
9pipValue = input.float(10, "Pip Value per Lot ($)", minval=0.01)
10
11riskAmount = strategy.equity * riskPct / 100
12lots = riskAmount / (stopPips * pipValue)
13miniLots = lots * 10
14microLots = lots * 100
15
16// Display position size on chart
17var label sizeLabel = na
18label.delete(sizeLabel)
19sizeLabel := label.new(bar_index, high,
20 "Risk: $" + str.tostring(riskAmount, "#.##") +
21 "\nLots: " + str.tostring(lots, "#.###") +
22 "\nMini: " + str.tostring(miniLots, "#.##") +
23 "\nMicro: " + str.tostring(microLots, "#.#"),
24 style=label.style_label_down, color=color.new(color.blue, 20),
25 textcolor=color.white, size=size.small)

Pyramiding: Adding to Winners

Pyramiding means adding to a winning position as the trade moves in your favor. The pyramiding parameter in strategy() controls how many entries in the same direction are allowed. With pyramiding=3, you can enter up to three times on the same side. The key is to add with decreasing size. Your first entry is the largest, each additional entry is smaller. This way your average entry price moves slowly and a pullback does not erase all gains.

pine-Pyramiding: adding to winners
1//@version=5
2strategy("Pyramid Strategy", overlay=true,
3 initial_capital=10000,
4 default_qty_type=strategy.percent_of_equity,
5 pyramiding=3,
6 commission_value=0.075)
7
8ema21 = ta.ema(close, 21)
9ema50 = ta.ema(close, 50)
10atr = ta.atr(14)
11
12upTrend = ema21 > ema50
13
14// Entry 1: Initial position (50% of equity)
15if upTrend and ta.crossover(close, ema21)
16 strategy.entry("Pyr1", strategy.long,
17 qty=strategy.equity * 0.5 / close)
18
19// Entry 2: Add on strength (30% of equity)
20if strategy.position_size > 0 and close > strategy.position_avg_price * 1.02
21 strategy.entry("Pyr2", strategy.long,
22 qty=strategy.equity * 0.3 / close)
23
24// Entry 3: Final add (20% of equity)
25if strategy.position_size > 0 and close > strategy.position_avg_price * 1.05
26 strategy.entry("Pyr3", strategy.long,
27 qty=strategy.equity * 0.2 / close)
28
29// Trailing stop for the entire position
30strategy.exit("Trail", "Pyr1", trail_points=atr*2/syminfo.mintick,
31 trail_offset=atr/syminfo.mintick)
32strategy.exit("Trail2", "Pyr2", trail_points=atr*2/syminfo.mintick,
33 trail_offset=atr/syminfo.mintick)
34strategy.exit("Trail3", "Pyr3", trail_points=atr*2/syminfo.mintick,
35 trail_offset=atr/syminfo.mintick)
36
37// Emergency exit
38if ta.crossunder(ema21, ema50)
39 strategy.close_all(comment="Trend reversal")

Complete Risk-Managed Strategy Template

This template combines risk-based sizing, maximum daily loss limits, consecutive loss tracking, and an equity curve filter into a single reusable framework. The equity curve filter pauses trading when the strategy's own equity curve drops below its moving average: the idea is to stop trading when the strategy itself is in a drawdown, since drawdowns tend to cluster.

pine-Risk management template
1//@version=5
2strategy("Risk Manager Template", overlay=true,
3 initial_capital=10000,
4 default_qty_type=strategy.fixed,
5 commission_value=0.075, slippage=2)
6
7// === RISK PARAMETERS ===
8riskPct = input.float(1.0, "Risk Per Trade (%)")
9maxDailyLossPct = input.float(3.0, "Max Daily Loss (%)")
10maxConsecLoss = input.int(3, "Max Consecutive Losses")
11useEquityFilter = input.bool(true, "Use Equity Curve Filter")
12
13// === TRACKING VARIABLES ===
14var float dailyPnL = 0.0
15var int consecLosses = 0
16var float lastEquity = strategy.initial_capital
17var bool newDay = false
18
19// Detect new day
20newDay := ta.change(time("D")) != 0
21if newDay
22 dailyPnL := 0.0
23
24// Track closed trades
25if strategy.closedtrades > 0
26 lastPnL = strategy.closedtrades.profit(strategy.closedtrades - 1)
27 if ta.change(strategy.closedtrades) > 0
28 dailyPnL += lastPnL
29 if lastPnL < 0
30 consecLosses += 1
31 else
32 consecLosses := 0
33
34// === FILTERS ===
35dailyLossOK = dailyPnL > -(strategy.equity * maxDailyLossPct / 100)
36consecLossOK = consecLosses < maxConsecLoss
37equityMA = ta.sma(strategy.equity, 20)
38equityCurveOK = useEquityFilter ? strategy.equity > equityMA : true
39
40canTrade = dailyLossOK and consecLossOK and equityCurveOK
41
42// === YOUR STRATEGY LOGIC HERE ===
43atr = ta.atr(14)
44signal = ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
45
46if signal and canTrade
47 stopDist = atr * 2
48 posSize = (strategy.equity * riskPct / 100) / stopDist
49 strategy.entry("Long", strategy.long, qty=posSize)
50 strategy.exit("SL", "Long", stop=close - stopDist)
51
52// === DASHBOARD ===
53var table dash = table.new(position.top_right, 2, 5,
54 bgcolor=color.new(color.black, 80), border_width=1)
55if barstate.islast
56 table.cell(dash, 0, 0, "Daily P&L", text_color=color.gray)
57 table.cell(dash, 1, 0, str.tostring(dailyPnL, "#.##"),
58 text_color=dailyPnL >= 0 ? color.green : color.red)
59 table.cell(dash, 0, 1, "Consec Losses", text_color=color.gray)
60 table.cell(dash, 1, 1, str.tostring(consecLosses),
61 text_color=consecLosses >= maxConsecLoss ? color.red : color.green)
62 table.cell(dash, 0, 2, "Can Trade", text_color=color.gray)
63 table.cell(dash, 1, 2, canTrade ? "YES" : "NO",
64 text_color=canTrade ? color.green : color.red)

The equity curve filter

When your strategy equity drops below its own 20-period SMA, the equity curve filter pauses new entries. This is meta-risk-management. You are using the strategy's performance to decide whether to keep trading. Studies show this reduces max drawdown by 20–40% in most trend-following systems, at the cost of missing some recovery trades.

Put this lesson to work

Free on Thrive, no account needed.