Indicator · Pine Script v6 · On the chart

Expectancy Lab

by jayadevrana

Expectancy Lab plots fast and slow exponential moving averages on the price chart to generate crossover signals.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code112
Settings5inputs
LicenceMPL-2.0
Last update2 days ago26 Oct 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

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.

Details

Published by

jayadevrana on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Moving averages, Trend, Screeners & dashboards

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.

Topics

algorithmic-tradingbacktestingema-crossoverpine-scriptpine-script-v6pinescriptrsitechnical-analysistrading-automationtrading-indicators

Settings

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

SettingTypeDefaultVariable
Fast averageint20fastLen
Slow averageint50slowLen
Stop = ATR xfloat2.0atrMult
Target = R xfloat2.0rr
Kelly fraction to actually usefloat0.5kellyCap
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

218 stars

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

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of TradersPost Trading Checklist
92 stars

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

Indicator v5 TrendMoving averages
Updated 8 weeks ago · Custom licence GitHub repository of Moon Dev Rainbow MA Ribbon 10-50

EMA Ribbon Overlay

by iamrichardD
57 stars

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

Indicator v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon Overlay
53 stars

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

Indicator v6 TrendOscillators & momentum
Updated 2 months ago · MPL-2.0 GitHub repository of Candle Counter + MA + RSI + Mode
43 stars

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

Indicator v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of Trend Strength & Volatility

Market Monitor - 15m

by chris-c-thomas
14 stars

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

Indicator v6 TrendMoving averages
Updated 6 months ago · MIT GitHub repository of Market Monitor - 15m

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers