// 48 formulas · 8 stages · every one live

the math inside a trading bot

8 stages. 48 formulas. In the order your bot runs them, from raw data to the kill switch. Change any number on any card and watch what it does to your account.

BOTwhat the bot doesTRYlive calculatorKILLShow it fails
See the one-sheet ↓
bot.live()mean reversion · simulated on random data
1data2signal3filter4edge5size6execute7risk8validate
equity$10,000
drawdown0%
trades0
win rate–
STAGE 1

data

clean the feed before you trust itpandas · numpy
1.1

Log return

r = ln(Pₜ / Pₜ₋₁)

BOTEvery calculation runs on log returns. They add across time, simple returns don't.

KILLSMixing simple and log returns when compounding P&L.

1.2

Annualized volatility

σ_year = σ_bar · √(bars per year)

BOTTurns bar volatility into one number you can compare across assets.

KILLSUsing √252 on a market that trades 24/7.

1.3

EWMA volatility

σ²ₜ = λσ²ₜ₋₁ + (1−λ) r²ₜ₋₁

BOTVolatility that reacts to a shock today, not a 20-day average. λ = 0.94 is the RiskMetrics default.

KILLSλ too close to 1: the bot notices a crash a week late.

1.4

ATR

TR = max(H−L, |H−Cₚ|, |L−Cₚ|) · ATR = avg₁₄(TR)

BOTMeasures how far price really moves per bar. Stops and targets are set in ATRs.

KILLSGaps: H−L alone hides the overnight move.

1.5

Bad tick filter

|r − μ| / σ > 6 → flag

BOTCatches broken prints before they become signals.

KILLSDeleting a real crash candle because it looked like an error.

1.6

No lookahead

positionₜ = f(data ≤ t−1)

BOTThe signal only sees closed bars. Fill at the next open, never at the bar that made the signal.

KILLSSame-bar fills: Sharpe 4 in backtest, losses live.

STAGE 2

signal

find the edgenumpy · ta
2.1

Z-score

z = (x − μₙ) / σₙ

BOTHow stretched price is versus its own recent past. The core of mean reversion.

KILLSTrending markets: z hits 3, then 5, then liquidation.

2.2

EMA

EMAₜ = α·Pₜ + (1−α)·EMAₜ₋₁ · α = 2/(n+1)

BOTA moving average that weights recent bars more. Trend filters and crossovers.

KILLSCrossover systems in chop: death by a thousand fees.

2.3

Momentum 12-1

mom = P(t−21) / P(t−252) − 1

BOT12-month return skipping the last month, which tends to reverse. Rank and hold the top.

KILLSMomentum crashes: the losers rip back hardest after a selloff.

2.4

RSI

RSI = 100 − 100 / (1 + avg gain / avg loss)

BOTSpeed of recent moves, scaled 0 to 100.

KILLSTreating 70 as an auto-short in a strong trend.

2.5

Order book imbalance

I = (Q_bid − Q_ask) / (Q_bid + Q_ask)

BOTWhich side of the book is heavier. A short-term direction hint.

KILLSSpoofed size that disappears when you hit it.

2.6

Funding carry

APR = funding per 8h × 3 × 365

BOTPerp funding is a yield. Long spot plus short perp collects it.

KILLSFunding flips negative and the carry turns into a cost.

STAGE 3

filter

is it real or is it noisestatsmodels · scipy
3.1

t-stat of returns

t = mean / (σ / √n)

BOTIs the average return different from zero, or just luck. Below 2, assume luck.

KILLSRunning it on overlapping returns: fake significance.

3.2

ADF test

Δyₜ = α + γ·yₜ₋₁ + εₜ

BOTDoes the series actually come back to its mean. γ < 0 and statistic below −2.86 (5%) says yes.

KILLSTesting the price itself. Prices almost never pass.

3.3

Half-life

half-life = −ln 2 / λ

BOTHow many bars a gap takes to close halfway. Sets hold time and the z lookback.

KILLSHalf-life longer than your patience or your funding.

3.4

Hurst exponent

E[R/S] ∝ n^H

BOTH < 0.5 mean reverts, H > 0.5 trends, 0.5 is a random walk.

KILLSEstimating it on 200 bars. Too short to mean anything.

3.5

Correlation

ρ = cov(x, y) / (σₓ · σᵧ)

BOTRemoves signals that are the same bet twice.

KILLSCorrelations go to 1 exactly when you need them not to.

3.6

Regime switch

σ₂₀ / σ₂₅₂ > 1.5 → high-vol regime

BOTTurns modules on and off depending on how wild the market is.

KILLSA threshold tuned on the same data you test on.

STAGE 4

edge

is it worth tradingnumpy
4.1

Expected value

EV = p·W − (1−p)·L

BOTAverage money per trade. Negative EV, nothing else on this sheet can save you.

KILLSW and L measured before fees.

4.2

Breakeven win rate

p* = 1 / (1 + W/L)

BOTThe minimum win rate for a given payoff.

KILLSChasing win rate while the payoff shrinks.

4.3

Expectancy in R

E[R] = p·R_win − (1−p)·1R

BOTEdge in units of risk, so different stops compare.

KILLSMoving stops changes R mid trade.

4.4

Profit factor

PF = gross wins / gross losses

BOTOne-line health check. Under 1.2 after costs is thin.

KILLSOne huge winner carrying the whole number.

4.5

Bayesian win rate

p̂ = (α + wins) / (α + β + n)

BOTShrinks a small sample toward the prior, so 7 of 10 isn't treated as 70%.

KILLSA prior so strong the data never moves it.

4.6

Net edge

net = gross − 2·(fee + slippage)

BOTEvery trade pays twice: in and out.

KILLSBacktests that assume zero slippage.

STAGE 5

size

how much to betnumpy
5.1

Risk-based size

size = equity · risk% / |entry − stop|

BOTThe stop sets the size. The dollar loss at the stop is always the same.

KILLSMoving the stop after entry.

5.2

Kelly criterion

f* = p − (1−p) / b

BOTBet size that grows the account fastest. Most funds use half.

KILLSPlugging in backtest p. Real p is lower.

5.3

Continuous Kelly

f* = μ / σ²

BOTKelly for a return stream, gives leverage.

KILLSμ is the noisiest number in finance.

5.4

Volatility target

w = σ_target / σ_realized

BOTShrinks in storms, grows in calm. Same risk every day.

KILLSNo cap: tiny vol means huge leverage.

5.5

Risk parity

wᵢ ∝ 1 / σᵢ

BOTEach asset adds the same risk, not the same dollars.

KILLSIgnores correlation between the assets.

5.6

Liquidation price

P_liq ≈ P_entry · (1 − 1/L + mmr)

BOTLong with leverage L: how far down until the exchange closes you.

KILLSWicks: price touches it for one second, you're gone.

STAGE 6

execute

where the edge leaks outorder book data
6.1

Spread cost

spread = (ask − bid) / mid

BOTMarket orders pay half the spread each side.

KILLSSpread widens 10× in the news candle.

6.2

Microprice

P_micro = (P_b·Q_a + P_a·Q_b) / (Q_a + Q_b)

BOTFair price that leans toward the heavier side of the book.

KILLSThin books where one order flips it.

6.3

Square-root impact

ΔP / P ≈ σ · √(Q / V)

BOTYour own order moves price. Bigger orders cost more per unit.

KILLSBacktests that fill any size at the last price.

6.4

VWAP

VWAP = Σ pᵢqᵢ / Σ qᵢ

BOTThe benchmark for how well you got filled.

KILLSChasing VWAP while price trends away.

6.5

Slippage

slip = (fill − expected) / expected

BOTLog it on every trade. It's where live and backtest split.

KILLSNot logging it, so you never see the leak.

6.6

Maker vs taker

round trip = 2 × fee

BOTLimit orders pay less, market orders pay more.

KILLSLimit orders that never fill on the best moves.

STAGE 7

risk

stay alivenumpy · pandas
7.1

Max drawdown

DD = (peak − equity) / peak

BOTThe deepest fall from a high. The number that ends accounts.

KILLSJudging it from one backtest path.

7.2

Recovery math

gain needed = DD / (1 − DD)

BOTLosses cost more than they look.

KILLSSizing up to win it back.

7.3

Value at Risk

VaR₉₅ = 1.645 · σ · V

BOTLoss you exceed on 1 day in 20.

KILLSFat tails: real crashes are far past 1.645σ.

7.4

Portfolio volatility

σₚ = √(wᵀ Σ w)

BOTRisk of everything together, correlations included.

KILLSUsing calm-period correlations.

7.5

Risk of ruin

ruin = ((1−p) / p)^N

BOTChance to lose N units before you stop, for even-money bets.

KILLSBetting 1/5 of the account: N = 5, ruin 37%.

7.6

Kill switch

equity < peak·(1 − DD_max) → stop

BOTHard rule in code. No human override at 3am.

KILLSA kill switch you can turn off when tilted.

STAGE 8

validate

don't fool yourselfscikit-learn · vectorbt
8.1

Sharpe ratio

SR = mean(r − r_f) / σ · √252

BOTReturn per unit of pain, annualized.

KILLSBacktest Sharpe above 3 usually means a bug.

8.2

Sharpe t-stat

t ≈ SR · √years

BOTIs the Sharpe real or luck.

KILLSSix months of data and a victory lap.

8.3

Multiple testing

P(≥1 false) = 1 − (1 − α)^N

BOTTest enough ideas and some pass by luck.

KILLSNot counting the ideas you threw away.

8.4

Best of N noise

E[max SR] ≈ σ_SR · √(2 ln N)

BOTWhat the best random strategy looks like.

KILLSCalling the winner of a grid search an edge.

8.5

Walk-forward

train [t₀,t₁] → test [t₁,t₂] → roll

BOTThe bot is judged only on data it never saw.

KILLSTuning again after looking at the test set.

8.6

Monte Carlo

shuffle trades ×1,000 → 95th pct DD

BOTYour backtest is one path out of millions. Size for the bad ones.

KILLSShuffling destroys streaks that are real.

No formula matches that.

where to start

  • Never coded a botdata → edge → size → risk. Then build one paper bot.
  • Have a bot that losesexecute and validate first. The leak is usually there.
  • Have a bot that worksfilter and risk. Make it survive a bad year.

the whole thing on one sheet

All 48 formulas on one sheet