#!/usr/bin/env python3 """ headroom_venue_formulas_reference_v1_3_2026-11-15.py. Published by Headroom Research (headroomdesk.com). Code licence: MIT. Test-vector data licence: CC BY 4.0. No market data, no forecast, no network. The reference implementation behind the four pure-arithmetic calculators on headroomdesk.com: liquidation price (Binance USD-M, Bybit USDT perpetual, Delta Exchange India linear), leverage and margin, prop-firm drawdown floors, and position size. Formulas and the pages they come from: SOURCES.md and https://headroomdesk.com/research/venue-formulas/. v1.3 (2026-11-15): ILLUSTRATIVE VENUE CONSTANTS. Every maintenance-margin rate, maintenance amount, deduction, tier or bracket table and fee rate used for a venue formula is now an illustrative value chosen by Headroom, NOT any venue's current or past table. The vectors test the FORMULA (and the tier choice), not a venue's parameters. To compute a real position, take the parameters from the venue's own current page. The checks against venues' own worked examples are not part of this public file; they live on the site, where they are cited and kept current. In their place, each venue formula is checked against its own defining condition (margin left at the liquidation price equals maintenance margin). The functions are unchanged from v1.2. Prop-firm rules (FTMO, FundedNext) are the firms' published rules, with the firms' own worked examples as anchors (also in prop-firm-rules/rules_table.json). Run: python3 headroom_venue_formulas_reference_v1_3_2026-11-15.py -> checks every anchor, writes the vectors python3 headroom_venue_formulas_reference_v1_3_2026-11-15.py --print -> also prints each vector Every function is plain arithmetic on its inputs. Venue parameters are INPUTS. """ import json, math, sys VERSION = "headroom_venue_formulas_reference_v1_3_2026-11-15" OUT = "headroom_venue_formulas_test_vectors_v1_3.json" ILL = "ILLUSTRATIVE constants chosen by Headroom, not any venue's table" # ===================================================================================================== 1. liquidation def liq_binance_usdm(side, qty, entry, wallet_balance, mmr, maint_amount, other_mm=0.0, other_upnl=0.0): """Binance USD-M, one-way mode. Binance's published formula (support FAQ "How to Calculate Liquidation Price of USDⓈ-M Contracts"), one-way terms only: LP = (WB - TMM1 + UPNL1 + cumB - Side*Q*EP) / (Q*MMR - Side*Q) Isolated: WB = the position's isolated wallet balance (initial margin + any margin added), TMM1 = UPNL1 = 0. Cross: WB = cross wallet balance; TMM1 / UPNL1 = maintenance margin / unrealized PnL of all OTHER positions. Side: +1 long, -1 short. qty > 0 (base units). Fees are not a term: they are already out of the wallet balance.""" s = 1 if side == "long" else -1 den = qty * mmr - s * qty return (wallet_balance - other_mm + other_upnl + maint_amount - s * qty * entry) / den def liq_binance_usdm_tiered(side, qty, entry, wallet_balance, brackets, other_mm=0.0, other_upnl=0.0): """Tier choice as Binance does it: the bracket is the one whose notional cap covers the position's notional AT the liquidation price; try brackets from the lowest and keep the first consistent one. brackets: [(cap_notional, mmr, maint_amount)] ascending by cap. Returns (lp, bracket_index).""" for i, (cap, mmr, cum) in enumerate(brackets): lp = liq_binance_usdm(side, qty, entry, wallet_balance, mmr, cum, other_mm, other_upnl) if lp * qty <= cap: return lp, i return lp, len(brackets) - 1 def liq_bybit_linear_isolated(side, qty, entry, leverage, mmr, mm_deduction=0.0, extra_margin=0.0, taker=0.0): """Bybit USDT perpetual, isolated, Unified Trading Account - Bybit's published formula (help centre, "Liquidation Price Calculation under Isolated Mode (Unified Trading Account)", updated 2026-05-28): Long = [EP*Q - EP*Q/Lev - Extra/(1 - taker) - MMded] / [Q - Q*MMR] Short = [EP*Q + EP*Q/Lev + Extra/(1 + taker) + MMded] / [Q + Q*MMR] Maintenance margin is on the position value at the liquidation (mark) price, so MMR sits in the denominator. The estimated fee to close sits in both initial and maintenance margin and cancels; only the added margin carries the taker rate. Q > 0 in base units.""" if side == "long": return (entry * qty - entry * qty / leverage - extra_margin / (1 - taker) - mm_deduction) / (qty - qty * mmr) return (entry * qty + entry * qty / leverage + extra_margin / (1 + taker) + mm_deduction) / (qty + qty * mmr) def liq_bybit_linear_isolated_tiered(side, qty, entry, leverage, tiers, extra_margin=0.0, taker=0.0): """Tier chosen at the liquidation price, as Binance's bracket: tiers [(cap_position_value, mmr, mm_deduction)] ascending; the first tier whose cap covers Q * LP is kept. Returns (lp, tier_index).""" for i, (cap, mmr, ded) in enumerate(tiers): lp = liq_bybit_linear_isolated(side, qty, entry, leverage, mmr, ded, extra_margin, taker) if lp * qty <= cap: return lp, i return lp, len(tiers) - 1 def bybit_fee_to_close(side, qty, entry, leverage, taker): """Bybit's estimated fee to close, reserved inside its initial margin: Q * EP * (1 -/+ 1/Lev) * taker (long: minus; short: plus).""" s = -1 if side == "long" else 1 return qty * entry * (1 + s / leverage) * taker def delta_rate(rate_min, slope, size, threshold): """Delta Exchange's margin schedule (user guide, margin explainer): flat up to a position-size threshold, then linear: rate = rate_min + slope * (size - threshold) for size > threshold.""" return rate_min + slope * max(0.0, size - threshold) def liq_delta_linear_isolated(side, contracts, contract_value, entry, im_rate, mm_rate, extra_margin=0.0): """Delta Exchange India, USD-settled linear futures/perpetuals, isolated (Delta's user guide: a position is liquidated when position margin minus unrealized loss equals maintenance margin; bankruptcy when the loss equals the margin). Margin on the entry notional: M = IM% * N + extra, MM = MM% * N, N = contracts * contract_value * entry. Long: LP = Entry - (M - MM)/(contracts*contract_value) Short: LP = Entry + (M - MM)/(contracts*contract_value) Returns (liquidation price, bankruptcy price).""" s = 1 if side == "long" else -1 q = contracts * contract_value n = q * entry m = im_rate * n + extra_margin mm = mm_rate * n return entry - s * (m - mm) / q, entry - s * m / q # ===================================================================================================== 2. leverage / margin def margin_required(qty, price, leverage, contract_value=1.0, open_fee_rate=0.0): """Initial margin for a new position: notional / leverage, plus the opening fee if the venue reserves it. Returns dict(notional, initial_margin, open_fee, total).""" notional = qty * contract_value * price im = notional / leverage fee = notional * open_fee_rate return dict(notional=notional, initial_margin=im, open_fee=fee, total=im + fee) def max_qty(available, price, leverage, contract_value=1.0, open_fee_rate=0.0, qty_step=0.0): """The largest quantity whose margin plus opening fee fits in the available balance; rounded DOWN to qty_step.""" q = available / (contract_value * price * (1.0 / leverage + open_fee_rate)) return _floor_step(q, qty_step) def effective_leverage(notional_total, equity): """Exposure / equity (what the position really carries, whatever leverage was 'selected').""" return notional_total / equity # ===================================================================================================== 3. prop-firm drawdown PROP_RULES = { # FTMO trading objectives (ftmo.oanda.com/trading-objectives, read 2026-10-29). Equity = balance + open P/L ± swaps - commissions. "FTMO_2STEP": dict(daily_pct=0.05, max_pct=0.10, max_mode="static", day_reset="00:00 CE(S)T", daily_ref="start_of_day_balance", equity_counts_floating=True, daily_breach_at_floor=False, max_breach_at_floor=False), "FTMO_1STEP": dict(daily_pct=0.03, max_pct=0.10, max_mode="eod_trailing", day_reset="00:00 CE(S)T", daily_ref="start_of_day_balance", equity_counts_floating=True, daily_breach_at_floor=False, max_breach_at_floor=False), # FundedNext help centre (articles 9941519 and 8019812, read 2026-10-29): limits a % of the INITIAL balance; the # maximum-loss floor is fixed at initial*(1 - max%). Day reset 00:00 server time (GMT+2, GMT+3 in summer). "FUNDEDNEXT_STELLAR_2STEP": dict(daily_pct=0.05, max_pct=0.10, max_mode="static", day_reset="00:00 server (GMT+2/+3)", daily_ref="start_of_day_balance", equity_counts_floating=True, daily_breach_at_floor=True, max_breach_at_floor=False), "FUNDEDNEXT_STELLAR_1STEP": dict(daily_pct=0.03, max_pct=0.06, max_mode="static", day_reset="00:00 server (GMT+2/+3)", daily_ref="start_of_day_balance", equity_counts_floating=True, daily_breach_at_floor=True, max_breach_at_floor=False), "FUNDEDNEXT_STELLAR_LITE": dict(daily_pct=0.04, max_pct=0.08, max_mode="static", day_reset="00:00 server (GMT+2/+3)", daily_ref="start_of_day_balance", equity_counts_floating=True, daily_breach_at_floor=True, max_breach_at_floor=False), } def prop_drawdown(rule, initial, start_of_day_balances, equity_now): """rule: a PROP_RULES key. start_of_day_balances: the balance recorded at each day's reset, oldest first, the LAST one being today's (day 1's is the initial capital). equity_now: today's current equity. Daily floor = today's start-of-day balance - daily% * initial. Max floor = static: initial * (1 - max%); eod_trailing: max(initial, highest start-of-day balance so far) - max% * initial (can only rise). Returns the two floors, the binding floor, the room left (equity_now - binding floor) and breach flags.""" r = PROP_RULES[rule] sod = start_of_day_balances[-1] daily_floor = sod - r["daily_pct"] * initial if r["max_mode"] == "static": max_floor = initial * (1 - r["max_pct"]) else: max_floor = max([initial] + list(start_of_day_balances)) - r["max_pct"] * initial binding = max(daily_floor, max_floor) return dict(daily_floor=daily_floor, max_floor=max_floor, binding_floor=binding, room=equity_now - binding, daily_breached=(equity_now <= daily_floor) if r["daily_breach_at_floor"] else (equity_now < daily_floor), max_breached=(equity_now <= max_floor) if r["max_breach_at_floor"] else (equity_now < max_floor)) # ===================================================================================================== 4. position size def _floor_step(x, step): if not step: return x return math.floor(x / step + 1e-9) * step def position_size(equity, risk_pct, entry, stop, contract_value=1.0, qty_step=0.0, fee_in=0.0, fee_out=0.0, leverage=None): """Quantity that loses risk_pct of equity if the stop is hit, fees included: loss per unit = |entry - stop| + entry*fee_in + stop*fee_out (per base unit; times contract_value per contract) qty = floor_step(equity * risk_pct / (loss per unit * contract_value)) Returns qty, notional, the risk actually taken after rounding, and (if leverage is given) the margin it needs.""" if entry == stop: raise ValueError("entry equals stop: the risk per unit is zero") per_unit = (abs(entry - stop) + entry * fee_in + stop * fee_out) * contract_value q = _floor_step(equity * risk_pct / per_unit, qty_step) out = dict(side="long" if stop < entry else "short", qty=q, notional=q * contract_value * entry, risk_amount=q * per_unit, risk_pct_actual=q * per_unit / equity) if leverage: out["margin"] = out["notional"] / leverage out["effective_leverage_on_equity"] = out["notional"] / equity return out def stop_beyond_liquidation(side, stop, liq): """True when the liquidation price is reached BEFORE the stop (the site must warn: the stop cannot protect).""" return liq >= stop if side == "long" else liq <= stop # ===================================================================================================== anchors and vectors def close(a, b, tol): return abs(a - b) <= tol # Illustrative tables (Headroom's own values; cumulative amounts made consistent across tiers). BRACKETS_ILL = [(100000, 0.006, 0.0), (500000, 0.008, 200.0), (5000000, 0.015, 3700.0), (20000000, 0.03, 78700.0)] TIERS_ILL = [(1500000, 0.006, 0.0), (2500000, 0.0075, 2250.0), (4000000, 0.009, 6000.0)] def _consistent(table): """cum/deduction continuity: amount_i = amount_{i-1} + cap_{i-1} * (rate_i - rate_{i-1}).""" return all(close(table[k][2], table[k - 1][2] + table[k - 1][0] * (table[k][1] - table[k - 1][1]), 1e-6) for k in range(1, len(table))) def anchors(): """Checks the code must pass before any vector is written. Venue formulas: their own defining condition (margin left at the liquidation price = maintenance margin) with illustrative inputs. Prop-firm rules: the firms' own published worked examples.""" res = [] # Binance USD-M: WB - TMM1 + UPNL1 + s*Q*(LP - EP) = Q*LP*MMR - cum for side, wb, mmr, cum, tmm, upnl in (("long", 3000.0, 0.006, 0.0, 0.0, 0.0), ("short", 3000.0, 0.006, 0.0, 0.0, 0.0), ("long", 20000.0, 0.008, 200.0, 1500.0, -2500.0)): s = 1 if side == "long" else -1 lp = liq_binance_usdm(side, 0.5, 60000.0, wb, mmr, cum, tmm, upnl) lhs = wb - tmm + upnl + s * 0.5 * (lp - 60000.0) res.append((f"Binance USD-M formula identity, {side}, {'cross' if tmm else 'isolated'}", close(lhs, 0.5 * lp * mmr - cum, 1e-6), round(lp, 4))) # Tier choice: the chosen row's cap covers Q*LP; the row below does not ok = _consistent(BRACKETS_ILL) and _consistent(TIERS_ILL) for qty in (0.5, 1.7, 3.0, 20.0): lp, i = liq_binance_usdm_tiered("long", qty, 60000.0, qty * 60000.0 / 20, BRACKETS_ILL) ok &= lp * qty <= BRACKETS_ILL[i][0] and (i == 0 or lp * qty > BRACKETS_ILL[i - 1][0]) for qty in (20.0, 25.5, 35.0, 50.0): lp, i = liq_bybit_linear_isolated_tiered("long", qty, 60000.0, 20, TIERS_ILL, 0.0, 0.0006) ok &= lp * qty <= TIERS_ILL[i][0] and (i == 0 or lp * qty > TIERS_ILL[i - 1][0]) # Boundary: notional at ENTRY is above the first cap, at the liquidation price below it, so the first row applies ok &= liq_binance_usdm_tiered("long", 1.7, 60000.0, 1.7 * 60000.0 / 20, BRACKETS_ILL)[1] == 0 and 1.7 * 60000.0 > BRACKETS_ILL[0][0] ok &= liq_bybit_linear_isolated_tiered("long", 25.5, 60000.0, 20, TIERS_ILL, 0.0, 0.0006)[1] == 0 and 25.5 * 60000.0 > TIERS_ILL[0][0] res.append(("Tier choice at the liquidation price, not at entry (illustrative tables, continuous amounts)", ok, None)) # Bybit isolated: EP*Q/L + extra/(1 -/+ taker) + s*Q*(LP - EP) = LP*Q*MMR - deduction for side, extra, ded in (("long", 500.0, 0.0), ("short", 500.0, 0.0), ("long", 1000.0, 450.0)): s = 1 if side == "long" else -1 q, ep, lev, mmr, tk = 1.0, 60000.0, 20, 0.0085 if ded else 0.006, 0.0006 lp = liq_bybit_linear_isolated(side, q, ep, lev, mmr, ded, extra, tk) lhs = ep * q / lev + extra / (1 - s * tk) + s * q * (lp - ep) res.append((f"Bybit isolated formula identity, {side}, extra {extra:g}, deduction {ded:g}", close(lhs, lp * q * mmr - ded, 1e-6), round(lp, 4))) # Delta linear isolated: M - s*... loss at LP leaves MM; at bankruptcy leaves 0 for side in ("long", "short"): s = 1 if side == "long" else -1 q, ep, im, mm = 500 * 0.001, 60000.0, 0.0125, 0.006 lp, bk = liq_delta_linear_isolated(side, 500, 0.001, ep, im, mm) m, mmv = im * q * ep, mm * q * ep res.append((f"Delta linear formula identity, {side}: margin left = MM at LP, 0 at bankruptcy", close(m + s * q * (lp - ep), mmv, 1e-6) and close(m + s * q * (bk - ep), 0.0, 1e-6), (round(lp, 4), round(bk, 4)))) # FTMO trading-objectives examples ($100,000) a = prop_drawdown("FTMO_2STEP", 100000, [100000], 99000) b = prop_drawdown("FTMO_2STEP", 100000, [100000, 102000], 101000) c = prop_drawdown("FTMO_2STEP", 100000, [100000, 102000, 101000], 100000) res.append(("FTMO 2-Step daily limits 95,000 / 97,000 / 96,000; max-loss 90,000 static", (a["daily_floor"], b["daily_floor"], c["daily_floor"], c["max_floor"]) == (95000, 97000, 96000, 90000), None)) d = prop_drawdown("FTMO_1STEP", 100000, [100000], 99000) e = prop_drawdown("FTMO_1STEP", 100000, [100000, 104000], 104000) f = prop_drawdown("FTMO_1STEP", 100000, [100000, 104000, 103000], 103000) res.append(("FTMO 1-Step daily 97,000 day 1; max-loss trails 90,000 -> 94,000 -> stays 94,000", (d["daily_floor"], d["max_floor"], e["max_floor"], f["max_floor"]) == (97000, 90000, 94000, 94000), None)) g = prop_drawdown("FTMO_1STEP", 100000, [100000, 102000, 101000], 100000) res.append(("FTMO 1-Step daily 99,000 (day 2 at 102,000) and 98,000 (day 3 at 101,000)", prop_drawdown("FTMO_1STEP", 100000, [100000, 102000], 0)["daily_floor"] == 99000 and g["daily_floor"] == 98000, None)) fn = [prop_drawdown(k, 100000, [100000], 100000)["max_floor"] for k in ("FUNDEDNEXT_STELLAR_2STEP", "FUNDEDNEXT_STELLAR_1STEP", "FUNDEDNEXT_STELLAR_LITE")] res.append(("FundedNext max-loss floors 90,000 / 94,000 / 92,000 (static)", fn == [90000, 94000, 92000], None)) return res def vectors(): """The test vectors: inputs -> expected outputs, with tolerances. Venue constants are illustrative.""" V = [] def add(calc, case, inputs, expected, tol, note=""): V.append(dict(calculator=calc, case=case, inputs=inputs, expected=expected, tolerance=tol, note=note)) # ---- 1. liquidation, Binance USD-M formula for side, lev in (("long", 10), ("short", 10), ("long", 50), ("short", 3)): qty, ep, mmr, cum = 0.5, 60000.0, 0.006, 0.0 wb = qty * ep / lev lp = liq_binance_usdm(side, qty, ep, wb, mmr, cum) add("liquidation", f"binance_formula_isolated_{side}_{lev}x", dict(venue="binance_usdm", mode="isolated", side=side, qty=qty, entry=ep, wallet_balance=wb, mmr=mmr, maint_amount=cum), dict(liq_price=round(lp, 6)), dict(liq_price=0.01), ILL) lp = liq_binance_usdm("long", 2.0, 60000.0, 12000.0 + 3000.0, 0.008, 200.0) add("liquidation", "binance_formula_isolated_long_added_margin", dict(venue="binance_usdm", mode="isolated", side="long", qty=2.0, entry=60000.0, wallet_balance=15000.0, mmr=0.008, maint_amount=200.0), dict(liq_price=round(lp, 6)), dict(liq_price=0.01), "10x initial margin 12,000 plus 3,000 added; " + ILL) lp = liq_binance_usdm("long", 0.5, 60000.0, 20000.0, 0.008, 200.0, 1500.0, -2500.0) add("liquidation", "binance_formula_cross_other_positions", dict(venue="binance_usdm", mode="cross", side="long", qty=0.5, entry=60000.0, wallet_balance=20000.0, mmr=0.008, maint_amount=200.0, other_mm=1500.0, other_upnl=-2500.0), dict(liq_price=round(lp, 6)), dict(liq_price=0.01), "cross: other positions' maintenance margin and open P/L; " + ILL) brackets = [list(b) for b in BRACKETS_ILL] for qty in (0.5, 1.7, 3.0, 20.0): lp, i = liq_binance_usdm_tiered("long", qty, 60000.0, qty * 60000.0 / 20, BRACKETS_ILL) add("liquidation", f"binance_formula_tiered_long_{qty}btc_20x", dict(venue="binance_usdm", mode="isolated", side="long", qty=qty, entry=60000.0, wallet_balance=qty * 60000.0 / 20, brackets=brackets), dict(liq_price=round(lp, 6), bracket_index=i), dict(liq_price=0.01, bracket_index=0), "tests the bracket choice at the liquidation price; " + ILL) # ---- 1. liquidation, Bybit USDT perpetual formula (isolated, UTA) for side, lev in (("long", 10), ("short", 10), ("long", 25), ("short", 5)): lp = liq_bybit_linear_isolated(side, 0.5, 60000.0, lev, 0.006, 0.0, 0.0, 0.0006) add("liquidation", f"bybit_formula_isolated_{side}_{lev}x", dict(venue="bybit_linear", mode="isolated", side=side, qty=0.5, entry=60000.0, leverage=lev, mmr=0.006, mm_deduction=0.0, extra_margin=0.0, taker=0.0006), dict(liq_price=round(lp, 6)), dict(liq_price=0.01), ILL) lp = liq_bybit_linear_isolated("long", 2.0, 60000.0, 10, 0.0085, 450.0, 1000.0, 0.0006) add("liquidation", "bybit_formula_isolated_long_deduction_extra", dict(venue="bybit_linear", mode="isolated", side="long", qty=2.0, entry=60000.0, leverage=10, mmr=0.0085, mm_deduction=450.0, extra_margin=1000.0, taker=0.0006), dict(liq_price=round(lp, 6)), dict(liq_price=0.01), "deduction and added margin; " + ILL) lp = liq_bybit_linear_isolated("short", 1.0, 40000.0, 20, 0.006, 0.0, 500.0, 0.0006) add("liquidation", "bybit_formula_isolated_short_extra_margin", dict(venue="bybit_linear", mode="isolated", side="short", qty=1.0, entry=40000.0, leverage=20, mmr=0.006, mm_deduction=0.0, extra_margin=500.0, taker=0.0006), dict(liq_price=round(lp, 6)), dict(liq_price=0.01), "added margin enters as extra / (1 + taker) on a short; " + ILL) tiers = [list(t) for t in TIERS_ILL] for qty in (20.0, 25.5, 35.0, 50.0): lp, ti = liq_bybit_linear_isolated_tiered("long", qty, 60000.0, 20, TIERS_ILL, 0.0, 0.0006) add("liquidation", f"bybit_formula_tiered_long_{qty:g}btc_20x", dict(venue="bybit_linear", mode="isolated", side="long", qty=qty, entry=60000.0, leverage=20, tiers=tiers, extra_margin=0.0, taker=0.0006), dict(liq_price=round(lp, 6), tier_index=ti), dict(liq_price=0.01, tier_index=0), "the tier is chosen at the liquidation price; " + ILL) # ---- 1. liquidation, Delta Exchange India linear formula for side, im, mm in (("long", 0.0125, 0.006), ("short", 0.0125, 0.006), ("long", 0.08, 0.006), ("short", 0.025, 0.003)): lp, bk = liq_delta_linear_isolated(side, 500, 0.001, 60000.0, im, mm) add("liquidation", f"delta_formula_isolated_{side}_im{im}_mm{mm}", dict(venue="delta_india_linear", mode="isolated", side=side, contracts=500, contract_value=0.001, entry=60000.0, im_rate=im, mm_rate=mm), dict(liq_price=round(lp, 6), bankruptcy_price=round(bk, 6)), dict(liq_price=0.01, bankruptcy_price=0.01), ILL) r = delta_rate(0.006, 0.0005, 8.0, 4.0) add("liquidation", "delta_formula_rate_schedule_above_threshold", dict(rate_min=0.006, slope=0.0005, size=8.0, threshold=4.0), dict(rate=round(r, 10)), dict(rate=1e-12), "flat-then-linear schedule shape; " + ILL) # ---- 2. leverage / margin m = margin_required(0.75, 60000.0, 20, open_fee_rate=0.0006) add("margin", "margin_required_0.75btc_20x_fee", dict(qty=0.75, price=60000.0, leverage=20, contract_value=1.0, open_fee_rate=0.0006), {k: round(v, 6) for k, v in m.items()}, dict(notional=0.01, initial_margin=0.01, open_fee=0.01, total=0.01), "fee rate " + ILL) m = margin_required(250, 60000.0, 50, contract_value=0.001) add("margin", "margin_required_250_contracts_0.001_50x", dict(qty=250, price=60000.0, leverage=50, contract_value=0.001), {k: round(v, 6) for k, v in m.items()}, dict(notional=0.01, initial_margin=0.01, open_fee=0.01, total=0.01)) fc = bybit_fee_to_close("short", 0.5, 60000.0, 10, 0.0006) m = margin_required(0.5, 60000.0, 10) add("margin", "bybit_formula_cost_with_fee_to_close_short_10x", dict(venue="bybit_linear", side="short", qty=0.5, price=60000.0, leverage=10, taker=0.0006), dict(initial_margin=round(m["initial_margin"], 6), fee_to_close=round(fc, 6), bybit_initial_margin_shown=round(m["initial_margin"] + fc, 6)), dict(initial_margin=0.01, fee_to_close=0.01, bybit_initial_margin_shown=0.01), "initial margin shown including the reserved fee to close; taker " + ILL) q = max_qty(1000.0, 60000.0, 10, open_fee_rate=0.0006, qty_step=0.001) add("margin", "max_qty_1000usdt_10x_step0.001", dict(available=1000.0, price=60000.0, leverage=10, open_fee_rate=0.0006, qty_step=0.001), dict(max_qty=round(q, 6)), dict(max_qty=0.0), "rounded down to the step") add("margin", "effective_leverage", dict(notional_total=45000.0, equity=5000.0), dict(effective_leverage=9.0), dict(effective_leverage=1e-9)) # ---- 3. prop-firm drawdown (firms' published rules; unchanged from v1.2) cases = [("FTMO_2STEP", [100000], 96500), ("FTMO_2STEP", [100000, 102000], 96900), ("FTMO_2STEP", [100000, 94000, 91500], 90500), ("FTMO_1STEP", [100000, 104000, 103000], 95000), ("FTMO_1STEP", [100000, 104000, 103000], 93900), ("FUNDEDNEXT_STELLAR_2STEP", [100000, 104000], 98900), ("FUNDEDNEXT_STELLAR_1STEP", [100000, 96500], 93950), ("FUNDEDNEXT_STELLAR_LITE", [100000], 96500), ("FTMO_2STEP", [100000, 101000], 96000), ("FTMO_1STEP", [100000, 104000], 94000), ("FUNDEDNEXT_STELLAR_2STEP", [100000, 101000], 96000), ("FUNDEDNEXT_STELLAR_1STEP", [100000, 94000], 94000)] for k, sods, eq in cases: o = prop_drawdown(k, 100000, sods, eq) add("prop_drawdown", f"{k.lower()}_days{len(sods)}_eq{eq}", dict(rule=k, initial=100000, start_of_day_balances=sods, equity_now=eq), o, dict(daily_floor=0.0, max_floor=0.0, binding_floor=0.0, room=0.0, daily_breached=0, max_breached=0)) # ---- 4. position size ps = [dict(equity=10000.0, risk_pct=0.01, entry=60000.0, stop=59400.0, qty_step=0.001), dict(equity=10000.0, risk_pct=0.01, entry=60000.0, stop=60900.0, qty_step=0.001, fee_in=0.0006, fee_out=0.0006, leverage=10), dict(equity=25000.0, risk_pct=0.005, entry=60000.0, stop=58500.0, contract_value=0.001, qty_step=1, fee_in=0.0006, fee_out=0.0006, leverage=25), dict(equity=10000.0, risk_pct=0.01, entry=1.08500, stop=1.08300, contract_value=100000, qty_step=0.01), dict(equity=10000.0, risk_pct=0.01, entry=2000.00, stop=1990.00, contract_value=100, qty_step=0.01)] names = ["btc_long_1pct_no_fees", "btc_short_1pct_fees_10x", "contracts_long_0.5pct_fees_25x", "eurusd_lots_long_20pips", "xauusd_lots_long_10usd"] for nm, p in zip(names, ps): o = position_size(**p) add("position_size", nm, p, {k: (round(v, 8) if isinstance(v, float) else v) for k, v in o.items()}, dict(qty=0.0, notional=0.01, risk_amount=0.01, risk_pct_actual=1e-6, margin=0.01, effective_leverage_on_equity=1e-6)) lp = liq_binance_usdm("long", 1.0, 60000.0, 60000.0 / 50, 0.006, 0.0) add("position_size", "stop_beyond_liquidation_warning", dict(side="long", entry=60000.0, stop=58000.0, liq_from="binance formula, isolated 50x, mmr 0.006 (illustrative)", liq_price=round(lp, 6)), dict(warn=stop_beyond_liquidation("long", 58000.0, lp)), dict(warn=0), f"at 50x the liquidation (~{lp:,.0f}) comes before a 58,000 stop: a calculator must warn") return V def main(): ok = True print(f"# {VERSION}") for name, good, val in anchors(): print(f"ANCHOR {'PASS' if good else 'FAIL'} {name}" + (f" -> {val}" if val is not None else "")) ok &= good V = vectors() with open(OUT, "w") as fh: json.dump(dict(version=VERSION, n=len(V), constants_note=ILL, vectors=V), fh, indent=1) print(f"vectors written: {len(V)} -> {OUT}") if "--print" in sys.argv: for v in V: print(json.dumps(v)) sys.exit(0 if ok else 1) if __name__ == "__main__": main()