1Copy the scriptPress Copy script above, or the copy button on the code below.
2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.
Source Code
112 lines of Pine Script v6 from scripts/expectancy-kelly.pine.txt, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.
expectancy-kelly.pine.txt
//@version=6
indicator("Expectancy Lab", overlay = true)
// 1. A deliberately simple edge, so the maths is the subject, not the signal
fastLen = input.int(20, "Fast average")
slowLen = input.int(50, "Slow average")
atrMult = input.float(2.0, "Stop = ATR x", step = 0.5)
rr = input.float(2.0, "Target = R x", step = 0.5)
kellyCap = input.float(0.5, "Kelly fraction to actually use", step = 0.25)
// 2. The signal. ta.* calls live at the top level, on every bar, always.
atr = ta.atr(14)
fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)
long = ta.crossover(fast, slow)
plot(fast, "Fast", color.aqua)
plot(slow, "Slow", color.orange)
// 3. The trade list, built by hand. One open trade at a time, so a "trade"
// is something you can point at instead of something an engine decided.
// A winner is +rr R and a loser is -1 R, by construction.
var float entry = na
var float stop = na
var float targ = na
var array<float> rs = array.new<float>()
opened = false
hitStop = false
hitTarg = false
if na(entry)
if long and atr > 0
entry := close
stop := close - atrMult * atr
targ := close + atrMult * atr * rr
opened := true
else
if low <= stop
array.push(rs, -1.0)
entry := na
hitStop := true
else if high >= targ
array.push(rs, rr)
entry := na
hitTarg := true
plotshape(opened, "Entry", shape.triangleup, location.belowbar, color.teal)
plotshape(hitTarg, "Target", shape.triangledown, location.abovebar, color.green)
plotshape(hitStop, "Stop", shape.xcross, location.abovebar, color.red)
// 4. The two numbers that decide everything
winRate() =>
n = array.size(rs)
w = 0
for i = 0 to math.max(n - 1, 0)
if n > 0 and array.get(rs, i) > 0
w += 1
n > 0 ? w / n : 0.0
avgOf(cond) =>
n = array.size(rs)
s = 0.0
c = 0
for i = 0 to math.max(n - 1, 0)
if n > 0
v = array.get(rs, i)
if (cond and v > 0) or (not cond and v <= 0)
s += v
c += 1
c > 0 ? s / c : 0.0
// 5. Long-run growth per trade if you bet a fraction f of the account
growth(f, p, q, b) =>
f <= 0 or f >= 1 ? 0.0 : p * math.log(1 + f * b) + q * math.log(1 - f)
// 6. Expectancy, Kelly, and what over-betting does
var table t = table.new(position.top_right, 2, 9, border_width = 1)
row(r, a, b, bg) =>
table.cell(t, 0, r, a, text_color = color.white, text_size = size.normal,
bgcolor = color.new(color.gray, 20), text_halign = text.align_left)
table.cell(t, 1, r, b, text_color = color.white, bgcolor = bg,
text_size = size.normal)
if barstate.islast and array.size(rs) > 5
n = array.size(rs)
p = winRate()
q = 1 - p
aw = avgOf(true) // average win, in R
al = math.abs(avgOf(false)) // average loss, in R
b = al > 0 ? aw / al : 0.0 // payoff ratio
exp = p * aw - q * al // expectancy per trade, in R
kelly = b > 0 ? (p * b - q) / b : 0.0 // the full Kelly fraction
used = kelly * kellyCap
// growth per trade at different bet sizes, from the same p and b
gKelly = growth(math.min(math.max(kelly, 0), 0.99), p, q, b)
gDouble = growth(math.min(math.max(kelly * 2, 0), 0.99), p, q, b)
row(0, "EXPECTANCY LAB", str.tostring(n) + " trades",
color.new(color.blue, 20))
row(1, "win rate p", str.tostring(p * 100, "#.0") + "%",
color.new(color.gray, 30))
row(2, "avg win / avg loss", str.tostring(aw, "#.00") + "R / " +
str.tostring(al, "#.00") + "R", color.new(color.gray, 30))
row(3, "payoff b", str.tostring(b, "#.00"), color.new(color.gray, 30))
row(4, "expectancy per trade", str.tostring(exp, "#.000") + "R",
exp > 0 ? color.new(color.green, 25) : color.new(color.red, 25))
row(5, "full Kelly f*", str.tostring(kelly * 100, "#.0") + "%",
kelly > 0 ? color.new(color.green, 25) : color.new(color.red, 25))
row(6, "what you should bet", str.tostring(used * 100, "#.0") + "% (" +
str.tostring(kellyCap, "#.##") + " Kelly)", color.new(color.teal, 25))
row(7, "log growth at f*", str.tostring(gKelly, "#.0000"),
color.new(color.gray, 30))
worse = gDouble < gKelly
row(8, "at 2x Kelly", str.tostring(gDouble, "#.0000") +
(gDouble <= 0 ? " RUIN" : ""),
worse ? color.new(color.red, 25) : color.new(color.gray, 30))
Overview
Expectancy Lab simulates one trade at a time using an ATR-based stop loss and a risk-to-reward target multiplier. The script tracks historical trade outcomes to calculate win rate, payoff ratio, expectancy, and Kelly criterion bet sizing, displaying results in an on-chart table. Settings adjust the moving average lengths, ATR multiplier, target ratio, and Kelly fraction cap. As an indicator, it cannot execute broker orders, and the statistics table requires at least six recorded trades to populate.
The inputs you can change from the gear icon on the chart. Defaults are the author's.
Setting
Type
Default
Variable
Fast average
int
20
fastLen
Slow average
int
50
slowLen
Stop = ATR x
float
2.0
atrMult
Target = R x
float
2.0
rr
Kelly fraction to actually use
float
0.5
kellyCap
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.
TradersPost Trading Checklist is an overlay indicator that evaluates a suite of popular technical conditions for long and short trade setups. It checks session-anchored VWAP, fast and slow EMA alignments and crosses, 200 SMA, RSI overbought or oversold conditi
This indicator plots five moving averages of a chosen source on the price chart, defaulting to EMA lengths 10, 20, 30, 40 and 50. The user can switch the average type to SMA, WMA or HMA and recolor each line. Wide translucent glows sit under the lines, and sof
Calculates exponential moving averages for fast, pivot, and slow lengths along with optional 50, 100, and 200 simple moving average context lines. It visualizes bullish and bearish ribbon fills on the main price chart alongside MACD calculations to generate ea
This indicator analyzes historical candle direction and price range over a configurable lookback window to gauge market trend. It categorizes trend direction using candle count, price range sum, or both. Signals are filtered using a Simple Moving Average to en
This indicator evaluates market momentum and risk by calculating trend metrics and volatility stats, displaying them in an on-chart table pane. It measures short-term and long-term trend strength via two MACD configurations built on three customizable EMA leng
Market Monitor - 15m is a directional bias chart overlay designed for 15-minute intraday chart analysis. It calculates a triple exponential moving average ribbon with EMA cloud shading, session VWAP with multiplier bands, prior day levels, a 30-minute opening