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
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.
1//@version=52strategy("Risk-Based Sizing", overlay=true,3 initial_capital=10000,4 default_qty_type=strategy.fixed,5 commission_value=0.075, slippage=2)67// === 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")1213// === CALCULATIONS ===14atr = ta.atr(14)15fast = ta.ema(close, emaFast)16slow = ta.ema(close, emaSlow)1718// === POSITION SIZE CALCULATION ===19// Risk amount in dollars20riskAmount = strategy.equity * (riskPct / 100)2122// Distance to stop in price23stopDist = atr * atrMult2425// Position size in units (coins)26posSize = riskAmount / stopDist2728// === ENTRY ===29longSignal = ta.crossover(fast, slow)30if longSignal31 stopPrice = close - stopDist32 strategy.entry("Long", strategy.long, qty=posSize)33 strategy.exit("SL", "Long", stop=stopPrice)3435// === EXIT ===36if ta.crossunder(fast, slow)37 strategy.close("Long", comment="EMA cross exit")Determine risk amount
Calculate stop distance
Compute position size
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.
1//@version=52strategy("Forex Lot Sizer", overlay=true,3 initial_capital=10000,4 default_qty_type=strategy.fixed,5 currency=currency.USD)67riskPct = 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)1011riskAmount = strategy.equity * riskPct / 10012lots = riskAmount / (stopPips * pipValue)13miniLots = lots * 1014microLots = lots * 1001516// Display position size on chart17var label sizeLabel = na18label.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.
1//@version=52strategy("Pyramid Strategy", overlay=true,3 initial_capital=10000,4 default_qty_type=strategy.percent_of_equity,5 pyramiding=3,6 commission_value=0.075)78ema21 = ta.ema(close, 21)9ema50 = ta.ema(close, 50)10atr = ta.atr(14)1112upTrend = ema21 > ema501314// 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)1819// Entry 2: Add on strength (30% of equity)20if strategy.position_size > 0 and close > strategy.position_avg_price * 1.0221 strategy.entry("Pyr2", strategy.long,22 qty=strategy.equity * 0.3 / close)2324// Entry 3: Final add (20% of equity)25if strategy.position_size > 0 and close > strategy.position_avg_price * 1.0526 strategy.entry("Pyr3", strategy.long,27 qty=strategy.equity * 0.2 / close)2829// Trailing stop for the entire position30strategy.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)3637// Emergency exit38if 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.
1//@version=52strategy("Risk Manager Template", overlay=true,3 initial_capital=10000,4 default_qty_type=strategy.fixed,5 commission_value=0.075, slippage=2)67// === 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")1213// === TRACKING VARIABLES ===14var float dailyPnL = 0.015var int consecLosses = 016var float lastEquity = strategy.initial_capital17var bool newDay = false1819// Detect new day20newDay := ta.change(time("D")) != 021if newDay22 dailyPnL := 0.02324// Track closed trades25if strategy.closedtrades > 026 lastPnL = strategy.closedtrades.profit(strategy.closedtrades - 1)27 if ta.change(strategy.closedtrades) > 028 dailyPnL += lastPnL29 if lastPnL < 030 consecLosses += 131 else32 consecLosses := 03334// === FILTERS ===35dailyLossOK = dailyPnL > -(strategy.equity * maxDailyLossPct / 100)36consecLossOK = consecLosses < maxConsecLoss37equityMA = ta.sma(strategy.equity, 20)38equityCurveOK = useEquityFilter ? strategy.equity > equityMA : true3940canTrade = dailyLossOK and consecLossOK and equityCurveOK4142// === YOUR STRATEGY LOGIC HERE ===43atr = ta.atr(14)44signal = ta.crossover(ta.ema(close, 9), ta.ema(close, 21))4546if signal and canTrade47 stopDist = atr * 248 posSize = (strategy.equity * riskPct / 100) / stopDist49 strategy.entry("Long", strategy.long, qty=posSize)50 strategy.exit("SL", "Long", stop=close - stopDist)5152// === DASHBOARD ===53var table dash = table.new(position.top_right, 2, 5,54 bgcolor=color.new(color.black, 80), border_width=1)55if barstate.islast56 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
Put this lesson to work
Free on Thrive, no account needed.