Indicator · Pine Script v5 · Own pane

KLDS v2 Kelly Position Sizer

by AssetWhisper

An indicator in a separate pane that simulates trades from a chosen signal source (MACD with RSI, breakout, mean reversion or an external series), each with an ATR stop, an R-multiple target and a time exit.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code187
Settings12inputs
LicenceMPL-2.0
Last update7 weeks ago10 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

187 lines of Pine Script v5 from indicators/KLDS_Kelly_Position_Sizer.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

KLDS_Kelly_Position_Sizer.pine
//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AssetWhisper — https://assetwhisper.com/indicators/
// ============================================================================
//  KLDS v2 — Kelly Position Sizer (simulador de señales + Kelly fraccional)
//  Idea: el tamaño de posición debería depender de la ventaja real reciente del
//  sistema, no de un % fijo. v2 simula cada señal como una operación con stop en
//  ATR y target en múltiplos de R (con salida por tiempo), acumula la distribución
//  de resultados en R y calcula Kelly (fraccional, con cota inferior de Wilson para
//  el win rate y contrastado con la versión continua μ/E[R²]), traduciéndolo a % de
//  riesgo por operación y unidades. Acepta como fuente de señales una serie externa
//  de cualquier otro indicador (input.source): p. ej. la salida "export" de LHS v2.
// ============================================================================
indicator("KLDS v2 — Kelly Position Sizer", shorttitle="KLDS v2", overlay=false, max_labels_count=200)

grpS = "Señales"
sigMode = input.string("MACD+RSI", "Signal source", options=["External", "MACD+RSI", "Breakout", "Mean Reversion"], group=grpS)
extSrc  = input.source(close, "External series (>0 long, <0 short; fires on 0-cross)", group=grpS)
grpT = "Simulación de operación"
stopATR = input.float(1.5, "Stop (ATR mult)", minval=0.2, maxval=10, step=0.1, group=grpT)
targetR = input.float(2.0, "Target (R mult)", minval=0.25, maxval=10, step=0.25, group=grpT)
maxBars = input.int(20, "Time exit (bars)", minval=2, maxval=200, group=grpT)
maxOpen = input.int(5, "Max simultaneous simulated trades", minval=1, maxval=20, group=grpT)
grpK = "Kelly"
sampleN   = input.int(40, "Results window (trades)", minval=10, maxval=200, group=grpK)
minN      = input.int(15, "Min trades for sizing", minval=5, maxval=100, group=grpK)
kFrac     = input.float(0.5, "Kelly fraction", minval=0.1, maxval=1.0, step=0.05, group=grpK)
kCap      = input.float(5.0, "Max risk per trade (%)", minval=0.5, maxval=25, step=0.5, group=grpK)
useWilson = input.bool(true, "Use Wilson lower bound for win rate", group=grpK)
equity    = input.float(10000, "Account equity", minval=100, group=grpK)

// === SEÑALES ===
atr = ta.atr(14)
rsi = ta.rsi(close, 14)
[macdL, sigL, _] = ta.macd(close, 12, 26, 9)
[bbB, bbU, bbL] = ta.bb(close, 20, 2)
dcH = ta.highest(high, 20)
dcL = ta.lowest(low, 20)
macdLong  = ta.crossover(macdL, sigL) and rsi < 70
macdShort = ta.crossunder(macdL, sigL) and rsi > 30
brkLong   = ta.crossover(close, dcH[1])
brkShort  = ta.crossunder(close, dcL[1])
mrLong    = close < bbL and rsi < 30 and close > close[1]
mrShort   = close > bbU and rsi > 70 and close < close[1]
extLong   = extSrc > 0 and extSrc[1] <= 0
extShort  = extSrc < 0 and extSrc[1] >= 0
longSig  = sigMode == "External" ? extLong : sigMode == "MACD+RSI" ? macdLong : sigMode == "Breakout" ? brkLong : mrLong
shortSig = sigMode == "External" ? extShort : sigMode == "MACD+RSI" ? macdShort : sigMode == "Breakout" ? brkShort : mrShort

// === SIMULADOR DE OPERACIONES ===
var array<int>   oDir   = array.new<int>()
var array<float> oEntry = array.new<float>()
var array<float> oStop  = array.new<float>()
var array<float> oTgt   = array.new<float>()
var array<int>   oBar   = array.new<int>()
var array<float> results = array.new<float>()     // resultado de cada operación en R

// 1) resolver operaciones abiertas con la barra actual (nunca en la barra de entrada)
nO = array.size(oDir)
if nO > 0
    for i = nO - 1 to 0
        d = array.get(oDir, i)
        e = array.get(oEntry, i)
        s = array.get(oStop, i)
        tg = array.get(oTgt, i)
        b = array.get(oBar, i)
        if bar_index > b
            riskAbs = math.abs(e - s)
            hitStop = d > 0 ? low <= s : high >= s
            hitTgt  = d > 0 ? high >= tg : low <= tg
            float res = na
            if hitStop                                   // conservador: stop y target en la misma barra cuenta como stop
                res := -1.0
            else if hitTgt
                res := targetR
            else if bar_index - b >= maxBars
                res := riskAbs > 0 ? (close - e) * d / riskAbs : 0.0
            if not na(res)
                array.push(results, res)
                if array.size(results) > sampleN
                    array.shift(results)
                array.remove(oDir, i)
                array.remove(oEntry, i)
                array.remove(oStop, i)
                array.remove(oTgt, i)
                array.remove(oBar, i)

// 2) abrir nuevas operaciones simuladas
openTrade(d) =>
    if array.size(oDir) < maxOpen and atr > 0
        riskAbs = stopATR * atr
        array.push(oDir, d)
        array.push(oEntry, close)
        array.push(oStop, close - d * riskAbs)
        array.push(oTgt, close + d * riskAbs * targetR)
        array.push(oBar, bar_index)
if longSig
    openTrade(1)
if shortSig
    openTrade(-1)

// === ESTADÍSTICAS Y KELLY ===
nR = array.size(results)
wins = 0
sumW = 0.0
sumL = 0.0
sumR = 0.0
sumR2 = 0.0
if nR > 0
    for i = 0 to nR - 1
        v = array.get(results, i)
        sumR += v
        sumR2 += v * v
        if v > 0
            wins += 1
            sumW += v
        else
            sumL += -v
losses = nR - wins
p      = nR > 0 ? wins / nR : 0.0
avgW   = wins > 0 ? sumW / wins : 0.0
avgL   = losses > 0 ? sumL / losses : 0.0
payoff = avgL > 0 ? avgW / avgL : 0.0
expectancyR = nR > 0 ? sumR / nR : 0.0
// Cota inferior de Wilson (95%) del win rate: penaliza muestras pequeñas
zW  = 1.96
pLB = nR > 0 ? (p + zW * zW / (2 * nR) - zW * math.sqrt(p * (1 - p) / nR + zW * zW / (4 * nR * nR))) / (1 + zW * zW / nR) : 0.0
pUse = useWilson ? pLB : p
kellyBin  = payoff > 0 ? pUse - (1 - pUse) / payoff : 0.0            // f* = p - q/b
kellyCont = nR > 0 and sumR2 > 0 ? (sumR / nR) / (sumR2 / nR) : 0.0  // aproximación continua μ/E[R²]
kellyUse  = math.min(kellyBin, kellyCont)                            // se toma la más conservadora
riskPct   = nR >= minN ? math.max(0.0, math.min(kCap, kellyUse * kFrac * 100)) : 0.0
riskPctS  = ta.ema(riskPct, 3)
riskAmt   = equity * riskPctS / 100
stopDistNow = stopATR * atr
units     = stopDistNow > 0 ? riskAmt / stopDistNow : 0.0
notional  = units * close

sizeCat = nR < minN ? "WAIT (n<" + str.tostring(minN) + ")" : riskPctS < 0.25 ? "AVOID" : riskPctS < 1 ? "SMALL" : riskPctS < 2.5 ? "MODERATE" : "LARGE"
sizeColor = nR < minN ? color.gray : riskPctS < 0.25 ? color.red : riskPctS < 1 ? color.orange : riskPctS < 2.5 ? color.lime : color.green

// === VISUAL ===
hline(0, "Zero", color=color.gray)
hline(1, "1% risk", color=color.new(color.orange, 60), linestyle=hline.style_dotted)
hline(2.5, "2.5% risk", color=color.new(color.green, 60), linestyle=hline.style_dotted)
plot(riskPctS, "Risk per trade % (fractional Kelly)", color=sizeColor, linewidth=3)
plot(kellyBin * 100, "Full Kelly % (binary)", color=color.new(color.blue, 60), linewidth=1)
plot(expectancyR * 2, "Expectancy R ×2", style=plot.style_columns, color=expectancyR >= 0 ? color.new(color.green, 70) : color.new(color.red, 70))
bgcolor(nR >= minN and kellyUse <= 0 ? color.new(color.red, 92) : na, title="Negative edge")
plot(riskPctS, "KLDS risk % (export)", display=display.none)

if longSig
    label.new(bar_index, 0, "L " + str.tostring(riskPctS, "#.#") + "%", style=label.style_label_up, color=color.new(color.green, 30), textcolor=color.white, size=size.tiny)
if shortSig
    label.new(bar_index, 0, "S " + str.tostring(riskPctS, "#.#") + "%", style=label.style_label_down, color=color.new(color.red, 30), textcolor=color.white, size=size.tiny)

var table t = table.new(position.top_right, 2, 11, bgcolor=color.new(color.black, 60))
table.cell(t, 0, 0, "SIZE", text_color=color.white, text_size=size.small)
table.cell(t, 1, 0, sizeCat, bgcolor=color.new(sizeColor, 30), text_color=color.white, text_size=size.small)
table.cell(t, 0, 1, "Risk / trade", text_color=color.white, text_size=size.small)
table.cell(t, 1, 1, str.tostring(riskPctS, "#.##") + "%  (" + str.tostring(riskAmt, "#") + ")", text_color=sizeColor, text_size=size.small)
table.cell(t, 0, 2, "Units @ stop " + str.tostring(stopATR, "#.#") + " ATR", text_color=color.white, text_size=size.small)
table.cell(t, 1, 2, str.tostring(units, "#.##") + "  (" + str.tostring(notional, "#") + ")", text_color=color.white, text_size=size.small)
table.cell(t, 0, 3, "Win rate (Wilson LB)", text_color=color.white, text_size=size.small)
table.cell(t, 1, 3, str.tostring(p * 100, "#") + "% (" + str.tostring(pLB * 100, "#") + "%)", text_color=p > 0.5 ? color.lime : color.red, text_size=size.small)
table.cell(t, 0, 4, "Payoff (avgW/avgL)", text_color=color.white, text_size=size.small)
table.cell(t, 1, 4, str.tostring(payoff, "#.##") + "  (" + str.tostring(avgW, "#.##") + "R / " + str.tostring(avgL, "#.##") + "R)", text_color=payoff > 1 ? color.lime : color.red, text_size=size.small)
table.cell(t, 0, 5, "Expectancy", text_color=color.white, text_size=size.small)
table.cell(t, 1, 5, str.tostring(expectancyR, "#.##") + " R", text_color=expectancyR > 0 ? color.lime : color.red, text_size=size.small)
table.cell(t, 0, 6, "Kelly bin / cont", text_color=color.white, text_size=size.small)
table.cell(t, 1, 6, str.tostring(kellyBin * 100, "#.#") + "% / " + str.tostring(kellyCont * 100, "#.#") + "%", text_color=color.gray, text_size=size.small)
table.cell(t, 0, 7, "Samples / open", text_color=color.white, text_size=size.small)
table.cell(t, 1, 7, str.tostring(nR) + " / " + str.tostring(array.size(oDir)), text_color=nR >= minN * 2 ? color.lime : nR >= minN ? color.orange : color.red, text_size=size.small)
table.cell(t, 0, 8, "Signal source", text_color=color.white, text_size=size.small)
table.cell(t, 1, 8, sigMode, text_color=color.gray, text_size=size.small)
table.cell(t, 0, 9, "Trade model", text_color=color.white, text_size=size.small)
table.cell(t, 1, 9, "stop " + str.tostring(stopATR, "#.#") + " ATR, tgt " + str.tostring(targetR, "#.##") + "R, " + str.tostring(maxBars) + "b", text_color=color.gray, text_size=size.small)
table.cell(t, 0, 10, "Kelly fraction / cap", text_color=color.white, text_size=size.small)
table.cell(t, 1, 10, str.tostring(kFrac, "#.##") + " / " + str.tostring(kCap, "#.#") + "%", text_color=color.gray, text_size=size.small)

// === ALERTAS ===
alertcondition(nR >= minN and kellyUse <= 0 and kellyUse[1] > 0, "KLDS Negative edge", "KLDS v2: Kelly turned non-positive - stop trading this signal")
alertcondition(riskPctS >= 2.5 and riskPctS[1] < 2.5, "KLDS Large size", "KLDS v2: suggested risk per trade above 2.5%")
alertcondition(longSig and riskPctS > 0, "KLDS Long signal", "KLDS v2: long signal - see table for size")
alertcondition(shortSig and riskPctS > 0, "KLDS Short signal", "KLDS v2: short signal - see table for size")
if (longSig or shortSig) and riskPctS > 0
    alert("KLDS v2 " + (longSig ? "LONG " : "SHORT ") + syminfo.ticker + " risk " + str.tostring(riskPctS, "#.##") + "% units " + str.tostring(units, "#.##"), alert.freq_once_per_bar_close)

Overview

KLDS v2 Kelly Position Sizer collects the results over a window and converts them into a fractional Kelly risk percentage, using a lower confidence bound on the hit rate and a cap, then into position units for a given equity. It is a sizing aid, not a trading system.

Details

Published by

AssetWhisper on GitHub

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Signal sourcestringMACD+RSIsigMode
External series (>0 long, <0 short; fires on 0-cross)sourcecloseextSrc
Stop (ATR mult)float1.5stopATR
Target (R mult)float2.0targetR
Time exit (bars)int20maxBars
Max simultaneous simulated tradesint5maxOpen
Results window (trades)int40sampleN
Min trades for sizingint15minN
Kelly fractionfloat0.5kFrac
Max risk per trade (%)float5.0kCap
Use Wilson lower bound for win ratebooltrueuseWilson
Account equityfloat10000equity
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This indicator calculates the distribution of close-to-close percentage changes using rate of change on closing prices. It bins percentage changes into intervals of 0.25 percent increments from negative to positive values and plots a normalized cumulative hist

Indicator v4 Volatility & bands
Updated 12 days ago · GPL-3.0 GitHub repository of Close-to-Close % Change Distribution

This indicator plots a Supertrend-based trend-following setup in a separate pane and skips conditions it treats as a sideways market. A volatility range is built from an ATR value, with RMA, SMA, EMA, or WMA smoothing, or from a fixed point distance. Optional

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper
330 stars

This indicator plots candle range and open-to-close movement as percentages in a separate pane. Range is the high-low difference divided by the low, and change is the close-open difference divided by the open. Both series draw as columns. Teal columns show ran

Indicator v5 Volatility & bands
Updated 2 months ago · None stated GitHub repository of Percent & Volatility [Alorse]

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

Function - Logistic Equation

by ricardosantos79
261 stars

Calculates dynamic modeling values by applying a mathematical logistic differential equation to price change over a specified lookback length. It measures price momentum relative to the recent high-low price range. The script plots positive and negative logist

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Function - Logistic Equation
228 stars

This indicator detects a Bollinger Band squeeze when the bands sit inside Keltner Channels, marking low volatility. It plots red dots during a squeeze and green dots when the bands are outside, in a separate pane. An optional histogram shows momentum as the cl

Indicator v6 Volatility & bandsOscillators & momentum
Updated 3 months ago · None stated GitHub repository of Bollinger Band Squeeze Detector

More Volatility & bands scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers