UNPKG

kestrel.markets

Version:

A typed, token-efficient language + runtime for agentic trading: agents author bounded plans, the runtime fires them at the tick. CLI + typed library + MCP server.

1,460 lines (1,448 loc) 125 kB
import { orgPathUnresolvableReason, perLegFillQualifierReason } from "./bin-mn7wcxhv.js"; import { sha256 } from "./bin-8pchjxn2.js"; import { CanonicalSeriesProvider, CanonicalState, EXEC_FAIR_QUOTE_MODEL, FakeOrgFacts, TriggerEvaluator, UNKNOWN, buildSurface, defaultSeriesRegistry, durationMs, executionFairOutcome, executionFairSpot, impliedForward, interpIv, isFairRefusal, isUnknown, pathKey } from "./bin-am3351y2.js"; import { mulberry32 } from "./bin-73jr945c.js"; import { dexp, greeks, intrinsic } from "./bin-df1tn094.js"; import { foldBook, isCalibratedSupport } from "./bin-3ft0k1jq.js"; import { KestrelParseError, assertNever, parse } from "./bin-2ywrx58g.js"; import { __export } from "./bin-wckvcay0.js"; // src/fill/index.ts var exports_fill = {}; __export(exports_fill, { strictCross: () => strictCross, spotStrictCross: () => spotStrictCross, reconstructHeldOptionLegs: () => reconstructHeldOptionLegs, markHeldLegsPerWake: () => markHeldLegsPerWake, makerFairHazard: () => makerFairHazard, loadEpisodeSigmoidParams: () => loadEpisodeSigmoidParams, isCalibratedSupport: () => isCalibratedSupport, intrinsic: () => intrinsic, heldPositionAsOfGradedBus: () => heldPositionAsOfGradedBus, guardedPfill: () => guardedPfill, guardedIntentOf: () => guardedIntentOf, guardIntent: () => guardIntent, directionalPfill: () => directionalPfill, classifyMoneyness: () => classifyMoneyness, StrictCrossV1: () => StrictCrossV1, SpotFillEngine: () => SpotFillEngine, SimFillEngine: () => SimFillEngine, STRICT_CROSS_LIMITS: () => STRICT_CROSS_LIMITS, SETTLE_MARK_STALE_AFTER_MS: () => SETTLE_MARK_STALE_AFTER_MS, SELL_FAR_OTM_CAP: () => SELL_FAR_OTM_CAP, OPTION_CONTRACT_MULTIPLIER: () => OPTION_CONTRACT_MULTIPLIER, MakerFairV1: () => MakerFairV1, MakerFairCalV1: () => MakerFairCalV1, MONEYNESS_DEEP_OTM_FRAC: () => MONEYNESS_DEEP_OTM_FRAC, MONEYNESS_ATM_BAND: () => MONEYNESS_ATM_BAND, MAKER_FAIR_LIMITS: () => MAKER_FAIR_LIMITS, MAKER_FAIR_DEFAULT_HAZARD: () => MAKER_FAIR_DEFAULT_HAZARD, EPISODE_REMINT_DT_REF_MS: () => EPISODE_REMINT_DT_REF_MS, BUY_FAR_OTM_CROSSING: () => BUY_FAR_OTM_CROSSING }); // src/fill/guarded-intent.ts var MONEYNESS_ATM_BAND = 0.02; var MONEYNESS_DEEP_OTM_FRAC = 0.15; function classifyMoneyness(spot, strike, right) { if (spot === undefined || !Number.isFinite(spot) || spot <= 0) return; const otmFrac = right === "C" ? (strike - spot) / spot : (spot - strike) / spot; if (otmFrac >= MONEYNESS_DEEP_OTM_FRAC) return "deep_otm"; if (otmFrac > MONEYNESS_ATM_BAND) return "otm"; if (otmFrac >= -MONEYNESS_ATM_BAND) return "atm"; return "itm"; } function guardIntent(input) { const { side, strike, right } = input; if (strike === undefined || right === undefined) return { side, unresolved: false }; const m = classifyMoneyness(input.resolveSpot(), strike, right); if (side === "buy") { return m === undefined ? { side, unresolved: false } : { side, moneyness: m, unresolved: false }; } if (m === undefined) return { side, moneyness: "deep_otm", covered: false, unresolved: true }; return { side, moneyness: m, covered: false, unresolved: false }; } function guardedIntentOf(order) { return { side: order.side, ...order.moneyness !== undefined ? { moneyness: order.moneyness } : {}, ...order.covered !== undefined ? { covered: order.covered } : {}, unresolved: false }; } var SELL_FAR_OTM_CAP = 0.01; var BUY_FAR_OTM_CROSSING = 1.5; function isFarOtm(moneyness) { return moneyness === "deep_otm"; } function guardedPfill(pSym, guarded) { if (!isFarOtm(guarded.moneyness)) return pSym; if (guarded.side === "buy") return Math.min(1, pSym * BUY_FAR_OTM_CROSSING); if (guarded.covered === true) return pSym; return Math.min(pSym, SELL_FAR_OTM_CAP); } // src/fill/model.ts var NO_QUEUE_POSITION = { code: "no-queue-position", note: "recorded top-of-book tape only; the judge cannot observe queue position or fill priority" }; var BOOK_TAPE_RESOLUTION = { code: "book-tape-resolution", note: "fills resolve at the recorded book tape's resolution; no intra-tick or intraminute sequencing" }; var STRICT_CROSS_LIMITS = [ NO_QUEUE_POSITION, BOOK_TAPE_RESOLUTION, { code: "strict-cross-only", note: "credits a fill only on a strict tape cross; no passive/maker fill is ever credited (a conservative floor)" } ]; var MAKER_FAIR_LIMITS = [ NO_QUEUE_POSITION, BOOK_TAPE_RESOLUTION, { code: "maker-fill-modeled", note: "passive maker fills are a modeled per-second hazard near fair, not observed executions" } ]; function strictCross(order, leg) { if (order.side === "buy") { if (leg.ask !== null && leg.ask < order.px) return true; return leg.last !== undefined && leg.last <= order.px; } if (leg.bid !== null && leg.bid > order.px) return true; return leg.last !== undefined && leg.last >= order.px; } function directionalPfill(pSym, opts) { const guarded = { side: opts.isBuy ? "buy" : "sell", ...opts.moneyness !== undefined ? { moneyness: opts.moneyness } : {}, ...opts.covered !== undefined ? { covered: opts.covered } : {}, unresolved: false }; return guardedPfill(pSym, guarded); } class StrictCrossV1 { name = "strict-cross"; version = "v1"; self_limitation = STRICT_CROSS_LIMITS; assess(order, leg, _ctx) { if (strictCross(order, leg)) { return { fill: { qty: order.qty, px: order.px }, pFill: 1, kind: "cross", support: "calibrated" }; } return { pFill: 0, kind: "no-cross", support: "calibrated" }; } } var MAKER_FAIR_DEFAULT_HAZARD = { version: "uncalibrated-0", calibrated: false, baseHazardPerSec: 0.05, edgeScale: 0.5, fairFloor: 0.05 }; function makerFairHazard(params, edgeRel, dtMs) { if (dtMs <= 0) return 0; const decay = dexp(-Math.max(edgeRel, 0) / params.edgeScale); const lambda = params.baseHazardPerSec * decay; const dtSec = dtMs / 1000; return 1 - dexp(-lambda * dtSec); } class MakerFairV1 { name = "maker-fair"; version = "v1"; self_limitation = MAKER_FAIR_LIMITS; params; constructor(params = MAKER_FAIR_DEFAULT_HAZARD) { this.params = params; } get calibration() { return { version: this.params.version, calibrated: this.params.calibrated }; } assess(order, leg, ctx) { if (strictCross(order, leg)) { return { fill: { qty: order.qty, px: order.px }, pFill: 1, kind: "cross", support: "calibrated" }; } if (ctx.fair === undefined) { return { pFill: 0, kind: "no-fair", support: "extrapolated" }; } const denom = Math.max(Math.abs(ctx.fair), this.params.fairFloor); const edgeRel = Math.abs(order.px - ctx.fair) / denom; const hSym = makerFairHazard(this.params, edgeRel, ctx.dtSinceLast); const h = guardedPfill(hSym, guardedIntentOf(order)); const support = this.params.calibrated ? "calibrated" : "extrapolated"; return { pFill: h, kind: "hazard", support }; } } function sigmoid(x) { return 1 / (1 + dexp(-x)); } var clamp01 = (p) => p < 0 ? 0 : p > 1 ? 1 : p; function loadEpisodeSigmoidParams(raw) { const o = raw; const hc = o?.hazard_constants; if (typeof o?.version !== "string" || hc === undefined || hc === null) { throw new Error("fill: malformed hazard-params (need string `version` + `hazard_constants`)"); } const num = (v, where) => { if (typeof v !== "number" || !Number.isFinite(v)) throw new Error(`fill: hazard-params ${where} must be a finite number`); return v; }; const side = (s, name) => { const o2 = s; if (o2 === undefined) throw new Error(`fill: hazard-params missing side ${name}`); const saturated = o2.saturated === true; const uStarRaw = o2.u_star; return { alpha: num(o2.alpha, `${name}.alpha`), uStar: uStarRaw === null || uStarRaw === undefined ? null : num(uStarRaw, `${name}.u_star`), rho: num(o2.rho, `${name}.rho`), floor: num(o2.floor, `${name}.floor`), saturated, internalizationFloor: num(o2.internalization_floor, `${name}.internalization_floor`) }; }; return { version: o.version, buy: side(hc.BUY, "BUY"), sell: side(hc.SELL, "SELL") }; } class MakerFairCalV1 { name; version = "cal"; self_limitation = MAKER_FAIR_LIMITS; params; constructor(params) { this.params = params; this.name = `maker-fair-v1+${params.version}`; } get calibration() { return { version: this.params.version, calibrated: true }; } assess(order, leg, ctx) { if (strictCross(order, leg)) { return { fill: { qty: order.qty, px: order.px }, pFill: 1, kind: "cross", support: "calibrated" }; } const c = order.side === "buy" ? this.params.buy : this.params.sell; const twoSided = leg.bid !== null && leg.ask !== null && leg.ask - leg.bid > 0 && ctx.fair !== undefined; if (!twoSided) { return { pFill: clamp01(c.internalizationFloor), kind: "cal-dark", episodeKey: "dark", support: "extrapolated" }; } const halfSpread = (leg.ask - leg.bid) / 2; const a = order.side === "buy" ? order.px - ctx.fair : ctx.fair - order.px; const u = a / halfSpread; const pSym = c.saturated ? c.rho : c.floor + (c.rho - c.floor) * sigmoid(c.alpha * (u - (c.uStar ?? 0))); const p = guardedPfill(pSym, guardedIntentOf(order)); return { pFill: clamp01(p), kind: "cal-sigmoid", episodeKey: "lit", support: "calibrated" }; } } // src/fill/engine.ts function episodeSeed(runSeed, modelVersion, ref, episodeIndex) { const h = sha256(`${runSeed}|${modelVersion}|${ref}|${episodeIndex}`); return parseInt(h.slice(0, 8), 16) >>> 0; } var EPISODE_REMINT_DT_REF_MS = 5000; var EPISODE_SURVIVAL_SATURATION_EPS = 0.000000001; var SETTLE_MARK_STALE_AFTER_MS = 300000; class SimFillEngine { #model; #multiplier; #sampler; #staleMarkAfterMs; #resting = new Map; #filled = []; #cancelled = new Set; #seen = new Set; #events = []; #carried = []; #lastPrint = new Map; #settled = false; constructor(opts) { this.#model = opts.model; this.#multiplier = opts.multiplier ?? 1; this.#sampler = opts.sampler; this.#staleMarkAfterMs = opts.staleMarkAfterMs ?? SETTLE_MARK_STALE_AFTER_MS; } get events() { return this.#events; } restingRefs() { return [...this.#resting.keys()]; } expectedFillProb(ref) { const st = this.#resting.get(ref); return st === undefined ? undefined : 1 - st.survival; } place(order, ts) { if (this.#settled) throw new Error(`SimFillEngine: place after settle (${order.ref})`); if (this.#seen.has(order.ref)) { throw new Error(`SimFillEngine: duplicate order ref ${JSON.stringify(order.ref)}`); } this.#seen.add(order.ref); this.#resting.set(order.ref, { order, lastTs: ts, survival: 1, supportExtrapolated: false, sampledFilled: false, episodeIndex: 0, cadenceAnchorTs: ts }); this.#emit("place", ts, order, { px: order.px }); return order.ref; } seedFilled(order, basis, ts) { if (this.#settled) throw new Error(`SimFillEngine: seedFilled after settle (${order.ref})`); if (this.#seen.has(order.ref)) { throw new Error(`SimFillEngine: duplicate order ref ${JSON.stringify(order.ref)}`); } this.#seen.add(order.ref); const seeded = { ...order, px: basis }; this.#emit("place", ts, seeded, { px: basis }); this.#emit("fill", ts, seeded, { px: basis, reason: "carried" }); this.#filled.push({ order: seeded, fillPx: basis, fillTs: ts, sampledFilled: this.#sampler !== undefined, viaSampled: false, support: "calibrated", survivalAtFill: 1 }); } carriedInventory() { return this.#carried; } cancel(ref, ts) { const st = this.#resting.get(ref); if (st === undefined) return false; this.#resting.delete(ref); this.#cancelled.add(ref); this.#emit("cancel", ts, st.order, { reason: "cancelled" }); return true; } onBook(instrument, leg, ts, fair) { if (this.#settled) throw new Error("SimFillEngine: onBook after settle"); const before = this.#events.length; const legKey = `${instrument}|${leg.strike}|${leg.right}`; const priorPrint = this.#lastPrint.get(legKey); const freshPrint = leg.last !== undefined && priorPrint !== undefined && leg.last !== priorPrint; if (leg.last !== undefined) this.#lastPrint.set(legKey, leg.last); let assessLeg = leg; if (!freshPrint && leg.last !== undefined) { const { last: _stale, ...rest } = leg; assessLeg = rest; } const matches = []; for (const st of this.#resting.values()) { const o = st.order; if (o.instrument === instrument && o.strike === leg.strike && o.right === leg.right) { matches.push(st); } } for (const st of matches) { if (ts < st.lastTs) continue; const dt = Math.max(0, ts - st.lastTs); const view = { side: st.order.side, qty: st.order.qty, px: st.order.px, strike: st.order.strike, right: st.order.right, ...st.order.moneyness !== undefined ? { moneyness: st.order.moneyness } : {}, ...st.order.covered !== undefined ? { covered: st.order.covered } : {} }; const res = this.#model.assess(view, assessLeg, fair === undefined ? { dtSinceLast: dt } : { fair, dtSinceLast: dt }); st.lastTs = ts; if (res.fill !== undefined) { this.#resting.delete(st.order.ref); const floorSampled = this.#sampler !== undefined || st.sampledFilled; this.#filled.push({ order: st.order, fillPx: res.fill.px, fillTs: ts, sampledFilled: floorSampled, viaSampled: false, support: "calibrated", survivalAtFill: st.survival }); this.#emit("fill", ts, st.order, { px: res.fill.px, reason: res.kind }); continue; } if (res.pFill > 0) { const keyed = res.episodeKey !== undefined; const catchUp = keyed && res.episodeKey === st.lastEpisodeKey; let mints; if (!keyed) { mints = 1; } else if (!catchUp) { mints = 1; st.cadenceAnchorTs = ts; } else { const windows = Math.floor((ts - st.cadenceAnchorTs) / EPISODE_REMINT_DT_REF_MS); mints = windows; st.cadenceAnchorTs += windows * EPISODE_REMINT_DT_REF_MS; } for (let m = 0;m < mints; m++) { if (catchUp && st.survival < EPISODE_SURVIVAL_SATURATION_EPS) break; const mintIndex = st.episodeIndex; st.episodeIndex = mintIndex + 1; st.survival *= 1 - res.pFill; if (!isCalibratedSupport(res.support)) st.supportExtrapolated = true; if (res.episodeKey !== undefined) st.lastEpisodeKey = res.episodeKey; let sampledThisMint = false; if (this.#sampler !== undefined && !st.sampledFilled) { const draw = mulberry32(episodeSeed(this.#sampler.runSeed, this.#model.version, st.order.ref, mintIndex))(); if (draw < res.pFill) { sampledThisMint = true; st.sampledFilled = true; } } if (res.episodeKey !== undefined) { const epSupport = isCalibratedSupport(res.support) ? "calibrated" : "extrapolated"; this.#emitHazard(ts, st.order.ref, mintIndex, res.episodeKey, res.pFill, epSupport, sampledThisMint); } if (sampledThisMint) { this.#resting.delete(st.order.ref); this.#filled.push({ order: st.order, fillPx: st.order.px, fillTs: ts, sampledFilled: true, viaSampled: true, support: isCalibratedSupport(res.support) ? "calibrated" : "extrapolated", survivalAtFill: st.survival }); this.#emit("fill", ts, st.order, { px: st.order.px, reason: "sampled" }); break; } } } } return this.#events.slice(before); } settle(settleSpot, ts, opts) { const carry = opts?.carry ?? false; const mark = opts?.mark; const asOfTs = mark?.asOfTs ?? null; const ageMs = asOfTs === null ? null : Math.max(0, ts - asOfTs); const stale = ageMs === null || ageMs > this.#staleMarkAfterMs; const parity = stale ? mark?.parity ?? null : null; const resolvedSpot = parity !== null ? parity.spot : settleSpot; const source = !stale ? "market" : parity !== null ? "parity" : "stale"; const staleness = ageMs === null ? "provenance unstated (no spot observation on the tape)" : `value last established ${ageMs}ms before settle (> ${this.#staleMarkAfterMs}ms threshold)`; const note = !stale ? undefined : parity !== null ? `settle mark ${settleSpot} is stale: ${staleness}; recovered via closing put-call parity at strike ${parity.strike} ⇒ ${parity.spot}` : `settle mark ${settleSpot} is stale: ${staleness}; no closing put-call parity derivable — mark-uncertain`; const settleMark = { px: resolvedSpot, asOfTs, lastObservedTs: mark?.lastObservedTs ?? null, ageMs, staleAfterMs: this.#staleMarkAfterMs, stale, source, markUncertain: stale && parity === null, ...note !== undefined ? { note } : {} }; const outcomes = []; let floorTotal = 0; let expectedTotal = 0; let sampledTotal = 0; for (const lot of this.#filled) { const floorFilled = !lot.viaSampled; const expectedProb = lot.viaSampled ? 1 - lot.survivalAtFill : 1; const oc = this.#outcome(lot.order, resolvedSpot, floorFilled, floorFilled ? lot.fillPx : null, expectedProb, lot.support, lot.sampledFilled); outcomes.push(oc); floorTotal += oc.floorPnl; expectedTotal += oc.expectedPnl; if (oc.sampled !== undefined) sampledTotal += oc.sampled.pnl; if (carry) this.#carried.push({ order: { ...lot.order, px: oc.intrinsicAtSettle }, basis: oc.intrinsicAtSettle }); } for (const st of this.#resting.values()) { this.#emit("cancel", ts, st.order, { reason: "expired-unfilled" }); const support = st.supportExtrapolated ? "extrapolated" : "calibrated"; const oc = this.#outcome(st.order, resolvedSpot, false, null, 1 - st.survival, support, st.sampledFilled); outcomes.push(oc); floorTotal += oc.floorPnl; expectedTotal += oc.expectedPnl; if (oc.sampled !== undefined) sampledTotal += oc.sampled.pnl; } this.#resting.clear(); this.#settled = true; for (const oc of outcomes) this.#emitSettleTelemetry(oc, ts); if (outcomes.length > 0) { this.#events.push({ ts, stream: "TELEMETRY", type: "settle_mark", px: settleMark.px, ...settleMark.asOfTs !== null ? { as_of_ts: settleMark.asOfTs } : {}, ...settleMark.lastObservedTs !== null ? { last_observed_ts: settleMark.lastObservedTs } : {}, ...settleMark.ageMs !== null ? { age_ms: settleMark.ageMs } : {}, stale_after_ms: settleMark.staleAfterMs, stale: settleMark.stale, source: settleMark.source, mark_uncertain: settleMark.markUncertain, ...settleMark.note !== undefined ? { note: settleMark.note } : {} }); } const cal = this.#model.calibration; return { settleSpot: resolvedSpot, settleMark, fillModel: `${this.#model.name}/${this.#model.version}`, ...cal !== undefined ? { hazardVersion: cal.version, calibrated: cal.calibrated } : {}, multiplier: this.#multiplier, outcomes, floorTotal, expectedTotal, ...this.#sampler !== undefined ? { sampledTotal } : {} }; } #outcome(order, settleSpot, floorFilled, floorFillPx, expectedFillProb, support, sampledFilled) { const intr = intrinsic(settleSpot, order.strike, order.right); const perContract = order.side === "buy" ? intr - order.px : order.px - intr; const scaled = perContract * order.qty * this.#multiplier; return { ref: order.ref, ...order.plan !== undefined ? { plan: order.plan } : {}, ...order.plan_instance !== undefined ? { plan_instance: order.plan_instance } : {}, instrument: order.instrument, side: order.side, qty: order.qty, px: order.px, strike: order.strike, right: order.right, floorFilled, floorFillPx, expectedFillProb, support, intrinsicAtSettle: intr, floorPnl: floorFilled ? scaled : 0, expectedPnl: expectedFillProb * scaled, ...this.#sampler !== undefined ? { sampled: { filled: sampledFilled, pnl: sampledFilled ? scaled : 0 } } : {} }; } #emitHazard(ts, orderId, episodeIndex, episodeKey, pFill, support, sampled) { this.#events.push({ ts, stream: "TELEMETRY", type: "hazard", order_id: orderId, episode_index: episodeIndex, episode_key: episodeKey, p_fill: pFill, support, ...this.#sampler !== undefined ? { sampled } : {} }); } #emitSettleTelemetry(oc, ts) { this.#events.push({ ts, stream: "TELEMETRY", type: "settle", order_id: oc.ref, expected_fill_prob: oc.expectedFillProb, support: oc.support, floor_filled: oc.floorFilled, floor_pnl: oc.floorPnl, expected_pnl: oc.expectedPnl, ...oc.sampled !== undefined ? { sampled_filled: oc.sampled.filled, sampled_pnl: oc.sampled.pnl } : {} }); } #emit(action, ts, order, extra) { const payload = { order_id: order.ref, ...order.plan !== undefined ? { plan: order.plan } : {}, ...order.plan_instance !== undefined ? { plan_instance: order.plan_instance } : {}, instrument: order.instrument, side: order.side, qty: order.qty, strike: order.strike, right: order.right, ...extra }; this.#events.push({ ts, stream: "ORDER", type: action, ...payload }); } } // src/fill/spot.ts function spotStrictCross(order, quote) { const last = quote.last ?? null; if (order.side === "buy") { return quote.ask !== null && quote.ask < order.px || last !== null && last < order.px; } return quote.bid !== null && quote.bid > order.px || last !== null && last > order.px; } class SpotFillEngine { #multiplier; #resting = new Map; #filled = []; #seen = new Set; #events = []; #lastQuote = new Map; #settled = false; constructor(opts = {}) { this.#multiplier = opts.multiplier ?? 1; } get events() { return this.#events; } restingRefs() { return [...this.#resting.keys()]; } currentQuote(instrument) { return this.#lastQuote.get(instrument); } place(order, ts) { if (this.#settled) throw new Error(`SpotFillEngine: place after settle (${order.ref})`); if (this.#seen.has(order.ref)) { throw new Error(`SpotFillEngine: duplicate order ref ${JSON.stringify(order.ref)}`); } this.#seen.add(order.ref); this.#resting.set(order.ref, { order, lastTs: ts }); this.#emit("place", ts, order, { px: order.px }); return order.ref; } cancel(ref, ts) { const st = this.#resting.get(ref); if (st === undefined) return false; this.#resting.delete(ref); this.#emit("cancel", ts, st.order, { reason: "cancelled" }); return true; } onQuote(instrument, quote, ts) { if (this.#settled) throw new Error("SpotFillEngine: onQuote after settle"); this.#lastQuote.set(instrument, { quote, ts }); const before = this.#events.length; const matches = []; for (const st of this.#resting.values()) { if (st.order.instrument === instrument) matches.push(st); } for (const st of matches) { if (ts < st.lastTs) continue; st.lastTs = ts; if (spotStrictCross(st.order, quote)) { this.#resting.delete(st.order.ref); this.#filled.push({ order: st.order, fillPx: st.order.px, fillTs: ts }); this.#emit("fill", ts, st.order, { px: st.order.px, reason: "cross" }); } } return this.#events.slice(before); } settle(settleSpot, ts, markAsOf) { const outcomes = []; let floorTotal = 0; let expectedTotal = 0; for (const lot of this.#filled) { const oc = this.#outcome(lot.order, settleSpot, true, lot.fillPx, 1); outcomes.push(oc); floorTotal += oc.floorPnl; expectedTotal += oc.expectedPnl; } for (const st of this.#resting.values()) { this.#emit("cancel", ts, st.order, { reason: "expired-unfilled" }); const oc = this.#outcome(st.order, settleSpot, false, null, 0); outcomes.push(oc); floorTotal += oc.floorPnl; expectedTotal += oc.expectedPnl; } this.#resting.clear(); this.#settled = true; for (const oc of outcomes) { this.#events.push({ ts, stream: "TELEMETRY", type: "settle", order_id: oc.ref, expected_fill_prob: oc.expectedFillProb, support: oc.support, floor_filled: oc.floorFilled, floor_pnl: oc.floorPnl, expected_pnl: oc.expectedPnl }); } return { settleSpot, fillModel: "spot-strict-cross/v1", multiplier: this.#multiplier, outcomes, floorTotal, expectedTotal, markAsOf, settleTs: ts, staleMark: markAsOf < ts }; } #outcome(order, settleSpot, floorFilled, floorFillPx, expectedFillProb) { const perShare = order.side === "buy" ? settleSpot - order.px : order.px - settleSpot; const scaled = perShare * order.qty * this.#multiplier; return { ref: order.ref, ...order.plan !== undefined ? { plan: order.plan } : {}, ...order.plan_instance !== undefined ? { plan_instance: order.plan_instance } : {}, instrument: order.instrument, side: order.side, qty: order.qty, px: order.px, floorFilled, floorFillPx, expectedFillProb, support: "calibrated", markSpot: settleSpot, floorPnl: floorFilled ? scaled : 0, expectedPnl: expectedFillProb * scaled }; } #emit(action, ts, order, extra) { const payload = { order_id: order.ref, ...order.plan !== undefined ? { plan: order.plan } : {}, ...order.plan_instance !== undefined ? { plan_instance: order.plan_instance } : {}, instrument: order.instrument, side: order.side, qty: order.qty, ...extra }; this.#events.push({ ts, stream: "ORDER", type: action, ...payload }); } } // src/fill/mark-to-model.ts var OPTION_CONTRACT_MULTIPLIER = 100; var r2 = (x) => Math.round(x * 100) / 100; function booksAtWakes(events, instrument, ascWakes) { const out = new Array(ascWakes.length).fill(null); let state; let w = 0; for (const ev of events) { while (w < ascWakes.length && ascWakes[w] < ev.ts) { out[w] = state ?? null; w++; } if (w >= ascWakes.length) break; if (ev.stream === "TICK" && ev.type === "BOOK" && ev.instrument === instrument) { state = foldBook(ev, state); } } for (;w < ascWakes.length; w++) out[w] = state ?? null; return out; } function sellablePerContract(leg, book) { if (book === null) return 0; const q = book.legs.find((l) => l.strike === leg.strike && l.right === leg.right); if (q === undefined) return 0; return leg.side === "buy" ? q.bid ?? 0 : -(q.ask ?? 0); } function markHeldLegsPerWake(input) { const mult = input.multiplier ?? OPTION_CONTRACT_MULTIPLIER; if (input.markToModel !== true) { return { enabled: false, marks: [], standDownFloorUsd: 0 }; } const marks = []; const ascWakes = [...input.wakeTsList].sort((a, b) => a - b); const books = booksAtWakes(input.events, input.instrument, ascWakes); for (let i = 0;i < ascWakes.length; i++) { const ts = ascWakes[i]; const book = books[i]; for (const leg of input.legs) { if (leg.expiry?.kind === "expiry-tag" && book?.expiry !== undefined && leg.expiry.tag !== book.expiry) { throw new Error(`mark-to-model: held leg ${leg.strike}${leg.right} tenor "${leg.expiry.tag}" != book expiry "${book.expiry}" — ` + `the execution book is keyed by symbol with ONE expiry; a multi-tenor position needs the (symbol, expiry) ` + `re-keying that is deliberately out of scope for this marking seam.`); } } let sellable = 0; let mtm = 0; for (const leg of input.legs) { const s = sellablePerContract(leg, book); sellable += s; mtm += (leg.side === "buy" ? s - leg.basisPremium : s + leg.basisPremium) * leg.qty * mult; } marks.push({ ts, bookAsOfTs: book?.asof_ts ?? null, sellablePerContract: r2(sellable), mtmUsd: r2(mtm) }); } const standDownFloorUsd = marks.length > 0 ? marks[marks.length - 1].mtmUsd : 0; return { enabled: true, marks, standDownFloorUsd }; } // src/fill/held-position.ts function reconstructHeldOptionLegs(graded, instrument) { const acc = new Map; for (const e of graded) { if (e.stream !== "ORDER" || e.type !== "fill") continue; if (e.instrument !== instrument) continue; if (e.strike === undefined || e.right === undefined) continue; const signed = e.side === "buy" ? e.qty : -e.qty; const key = `${e.strike}|${e.right}`; const a = acc.get(key) ?? { qty: 0, absQtyPx: 0, absQty: 0, strike: e.strike, right: e.right }; a.qty += signed; a.absQtyPx += Math.abs(e.qty) * (e.px ?? 0); a.absQty += Math.abs(e.qty); acc.set(key, a); } const legs = []; for (const a of acc.values()) { if (a.qty === 0) continue; legs.push({ side: a.qty > 0 ? "buy" : "sell", qty: Math.abs(a.qty), strike: a.strike, right: a.right, basisPremium: a.absQty > 0 ? a.absQtyPx / a.absQty : 0 }); } return legs; } var INERT = { enabled: false, legs: [], marks: [], standDownFloorUsd: 0, thetaBleed: null }; function heldPositionAsOfGradedBus(input) { if (input.markToModel !== true || input.wakeTsList.length === 0) return INERT; const legs = reconstructHeldOptionLegs(input.graded, input.instrument); if (legs.length === 0) return INERT; const multOpt = input.multiplier === undefined ? {} : { multiplier: input.multiplier }; const marked = markHeldLegsPerWake({ events: input.tape, instrument: input.instrument, legs, wakeTsList: input.wakeTsList, markToModel: true, ...multOpt }); const lastMark = marked.marks[marked.marks.length - 1]; if (lastMark === undefined) return { ...INERT, legs }; return { enabled: true, legs, marks: marked.marks, standDownFloorUsd: marked.standDownFloorUsd, thetaBleed: { ts: input.recordTs, instrument: input.instrument, floor_pnl: marked.standDownFloorUsd, wakes: marked.marks.length, last_sellable: lastMark.sellablePerContract } }; } // src/validate/unknown-series.ts function collectSeriesOperands(t, out) { switch (t.kind) { case "cmp": case "cross": if (t.left.kind === "series") out.push(t.left); if (t.right.kind === "series") out.push(t.right); return; case "event": { const of = t.of; if (of?.kind === "series") out.push(of); return; } case "break-hold": case "within": case "until": case "at": collectSeriesOperands(t.inner, out); return; case "nth": collectSeriesOperands(t.event, out); return; case "not": collectSeriesOperands(t.term, out); return; case "and": case "or": for (const term of t.terms) collectSeriesOperands(term, out); return; case "phase": case "time-window": case "fill": case "held-stop": case "clock-stop": return; default: return assertNever(t, "collectSeriesOperands"); } } function unknownSeriesRejection(st, registry) { const triggers = []; if (st.when !== undefined) triggers.push(st.when); for (const c of st.clauses) if ("when" in c && c.when !== undefined) triggers.push(c.when); const refs = []; for (const t of triggers) collectSeriesOperands(t, refs); for (const ref of refs) { if (ref.segments.length !== 1) continue; const seg = ref.segments[0]; if (seg === undefined || seg.selector !== undefined) continue; const name = seg.name; if (registry.lookup(name)?.kind === "market") continue; const canon = registry.lookup(name.toLowerCase()); if (canon?.kind === "market") { return { message: `arm: unknown series ${JSON.stringify(name)} in a trigger of plan ${JSON.stringify(st.name)} — ` + `no such series is registered. Did you mean the market series ${JSON.stringify(canon.name)}? ` + `Series names are case-sensitive and the platform market facts are lowercase — fix the name ` + `(fail-closed at arm, RUNTIME §8; a plan armed on an unknown series can never fire).`, repair: canon.name }; } } return null; } // src/engine/pricing.ts function isUnresolvable(r) { return "unresolvable" in r; } function isBad(r) { return "bad" in r; } var EPS = 0.000000001; function cleanNum(x) { return Math.round(x * 1e8) / 1e8; } function snap(px, tick, dir) { if (!(tick > 0)) return cleanNum(px); const t = px / tick; const n = dir === "down" ? Math.floor(t + EPS) : Math.ceil(t - EPS); return cleanNum(n * tick); } function midOf(q) { if (q.bid === null || q.ask === null) return null; return cleanNum(0.5 * (q.bid + q.ask)); } var BOOK_FRESH_WITHIN_MS = SETTLE_MARK_STALE_AFTER_MS; function fairInputWithBook(fairInput, ctx) { const { asof } = fairInput; const age = asof === undefined ? undefined : ctx.now - asof; const bookFresh = age !== undefined && age >= 0 && age <= BOOK_FRESH_WITHIN_MS; return { ...fairInput, legBid: ctx.quote.bid, legAsk: ctx.quote.ask, bookFresh }; } function resolveFair(ctx) { if (ctx.instrumentKind === "spot") { const f = executionFairSpot({ bid: ctx.quote.bid, ask: ctx.quote.ask, asof: ctx.now }); if (f === null) { return { bad: "fair unbuildable for a spot instrument: quote one-sided/dark/crossed — price off @bid/@ask/@mid/@last (ADR-0017)" }; } return { px: f.value, ann: `fair(${EXEC_FAIR_QUOTE_MODEL})` }; } let taint = ""; if (ctx.fairInput !== null) { const f = executionFairOutcome(fairInputWithBook(ctx.fairInput, ctx)); if (!isFairRefusal(f)) { const r = f.receipt; return r.forwardSource === "parity" ? { px: f.value, ann: "fair" } : { px: f.value, ann: `fair(fwd=spot;degraded:${r.forwardDegraded ?? "unspecified"})` }; } if (f.refused === "tainted") taint = `;tainted:${f.reason}`; } const mid = midOf(ctx.quote); if (ctx.side === "buy") { if (mid === null) { return { bad: "fair fallback needs a two-sided mid (BUY) but the book is one-sided/dark" }; } return { px: mid, ann: `fair=fallback(mid${taint})` }; } if (mid === null) { return { px: ctx.intrinsic, ann: `fair=fallback(intrinsic;mid-dark${taint})` }; } return { px: Math.max(mid, ctx.intrinsic), ann: `fair=fallback(max(mid,intrinsic)${taint})` }; } function resolveAnchor(name, ctx) { const q = ctx.quote; switch (name) { case "fair": return resolveFair(ctx); case "intrinsic": return ctx.instrumentKind === "spot" ? { bad: "intrinsic anchor is an option concept — refused for a spot instrument (ADR-0017)" } : { px: ctx.intrinsic, ann: "intrinsic" }; case "basis": if (ctx.instrumentKind === "spot") { return { bad: "basis anchor is an option anchor in v1 — refused for a spot instrument (ADR-0017)" }; } return ctx.basis === null ? { bad: "basis anchor referenced with no held position" } : { px: ctx.basis, ann: "basis" }; case "bid": return q.bid === null ? { bad: "bid anchor but the bid is dark" } : { px: q.bid, ann: "bid" }; case "ask": return q.ask === null ? { bad: "ask anchor but the ask is dark" } : { px: q.ask, ann: "ask" }; case "mid": { const m = midOf(q); return m === null ? { bad: "mid anchor but the book is one-sided/dark" } : { px: m, ann: "mid" }; } case "last": return q.last === undefined ? { bad: "last anchor but no trade has printed for this leg" } : { px: q.last, ann: "last" }; case "join": if (ctx.side === "buy") { return q.bid === null ? { bad: "join anchor but the bid is dark" } : { px: q.bid, ann: "join(bid)" }; } return q.ask === null ? { bad: "join anchor but the ask is dark" } : { px: q.ask, ann: "join(ask)" }; case "improve": if (ctx.side === "buy") { return q.bid === null ? { bad: "improve anchor but the bid is dark" } : { px: cleanNum(q.bid + ctx.tickSize), ann: "improve(bid+1t)" }; } return q.ask === null ? { bad: "improve anchor but the ask is dark" } : { px: cleanNum(q.ask - ctx.tickSize), ann: "improve(ask-1t)" }; case "stub": return { px: ctx.tickSize, ann: "stub" }; case "spot": { if (ctx.instrumentKind !== "spot") { return { bad: "spot anchor is the underlying price — refused for an option leg; use @fair/@mid/@bid/@ask/@last (ADR-0017)" }; } if (ctx.spot === undefined || ctx.spot === null) { return { bad: "spot anchor but the underlying spot is UNKNOWN (gapped/dead feed) — the line de-arms (fail-closed, ven.4)" }; } return { px: ctx.spot, ann: "spot" }; } default: return assertNever(name, "price-anchor"); } } function resolveExpr(expr, ctx) { switch (expr.kind) { case "anchor": return resolveAnchor(expr.name, ctx); case "price-abs": return { px: expr.value, ann: String(expr.value) }; case "price-offset": { const base = resolveExpr(expr.base, ctx); if (isBad(base)) return base; const delta = expr.unit === "c" ? expr.amount * 0.01 : base.px * (expr.amount / 100); const px = expr.sign === "+" ? base.px + delta : base.px - delta; return { px: cleanNum(px), ann: `${base.ann}${expr.sign}${expr.amount}${expr.unit}` }; } case "lean": { const a = resolveExpr(expr.a, ctx); if (isBad(a)) return a; const b = resolveExpr(expr.b, ctx); if (isBad(b)) return b; const px = a.px + (b.px - a.px) * expr.x; return { px: cleanNum(px), ann: `lean(${a.ann},${b.ann},${expr.x})` }; } case "price-fn": { const vals = []; const anns = []; for (const arg of expr.args) { const r = resolveExpr(arg, ctx); if (isBad(r)) return r; vals.push(r.px); anns.push(r.ann); } if (vals.length === 0) return { bad: `${expr.fn}() with no arguments` }; const px = expr.fn === "min" ? Math.min(...vals) : Math.max(...vals); return { px: cleanNum(px), ann: `${expr.fn}(${anns.join(",")})` }; } default: return assertNever(expr, "price-expr"); } } function activeEsc(base, esc, ctx) { if (esc === undefined || esc.length === 0) return { stage: 0, expr: base }; const placedAt = ctx.placedAt ?? ctx.now; const elapsed = Math.max(0, ctx.now - placedAt); let bestIdx = -1; let bestAfter = -1; for (let i = 0;i < esc.length; i++) { const s = esc[i]; if (s === undefined) continue; const afterMs = durationMs(s.after.value, s.after.unit); if (afterMs <= elapsed && afterMs >= bestAfter) { bestAfter = afterMs; bestIdx = i; } } if (bestIdx < 0) return { stage: 0, expr: base }; const chosen = esc[bestIdx]; if (chosen === undefined) return { stage: 0, expr: base }; return { stage: bestIdx + 1, expr: chosen.to }; } function applyCaps(px, ann, line, ctx) { const explicit = line.policy?.caps ?? []; const caps = []; for (const c of explicit) { const r = resolveExpr(c, ctx); if (isBad(r)) return r; caps.push({ px: r.px, ann: r.ann }); } if (ctx.side === "buy" && line.policy?.pricing === "peg") { const f = resolveFair(ctx); if (!isBad(f)) caps.push({ px: f.px, ann: `${f.ann}(default-peg-cap)` }); } if (caps.length === 0) return { px, ann, applied: false }; let bound = caps[0]; for (const c of caps) if (c.px < bound.px) bound = c; if (px > bound.px + EPS) { return { px: bound.px, ann: `${ann} cap(${bound.ann})`, applied: true }; } return { px, ann, applied: false }; } function applyFloors(px, ann, line, ctx) { const explicit = line.policy?.floors ?? []; const floors = []; for (const f of explicit) { const r = resolveExpr(f, ctx); if (isBad(r)) return r; floors.push({ px: r.px, ann: r.ann }); } if (ctx.side === "sell") floors.push({ px: ctx.intrinsic, ann: "intrinsic" }); if (floors.length === 0) return { px, ann, applied: false }; let bound = floors[0]; for (const f of floors) if (f.px > bound.px) bound = f; if (px < bound.px - EPS) { return { px: bound.px, ann: `${ann} floor(${bound.ann})`, applied: true }; } return { px, ann, applied: false }; } function resolvePrice(line, ctx) { const tick = ctx.tickSize; const esc = activeEsc(line.price, line.policy?.esc, ctx); const r0 = resolveExpr(esc.expr, ctx); if (isBad(r0)) return { unresolvable: r0.bad }; let px = r0.px; let ann = esc.stage > 0 ? `esc#${esc.stage}:${r0.ann}` : r0.ann; const capped = applyCaps(px, ann, line, ctx); if (isBad(capped)) return { unresolvable: capped.bad }; px = capped.px; ann = capped.ann; const floored = applyFloors(px, ann, line, ctx); if (isBad(floored)) return { unresolvable: floored.bad }; px = floored.px; ann = floored.ann; px = snap(px, tick, ctx.side === "buy" ? "down" : "up"); if (ctx.side === "sell") { const floorSnapped = snap(ctx.intrinsic, tick, "up"); if (px < floorSnapped) px = floorSnapped; } return decideReprice(px, ann, capped.applied, floored.applied, esc.stage, line, ctx, tick); } function decideReprice(px, ann, capped, floored, escStage, line, ctx, tick) { const prior = ctx.prior; if (prior === undefined) { return { px, sourceAnnotation: ann, capped, floored, escStage }; } if (escStage !== prior.escStage) { return { px, sourceAnnotation: `${ann} [esc:boundary]`, capped, floored, escStage, repriceOf: prior.px }; } if (line.policy?.pricing === "peg") { const drift = Math.abs(px - prior.px); if (drift < tick - EPS) { return { px: prior.px, sourceAnnotation: `${ann} [peg:hold<1tick]`, capped, floored, escStage }; } if (ctx.tokenBucket !== undefined && !ctx.tokenBucket.tryTake()) { return { px: prior.px, sourceAnnotation: `${ann} [peg:denied]`, capped, floored, escStage }; } return { px, sourceAnnotation: `${ann} [peg:reprice]`, capped, floored, escStage, repriceOf: prior.px }; } return { px: prior.px, sourceAnnotation: `${ann} [fix]`, capped, floored, escStage }; } // src/engine/orgfacts.ts function legKey(instrument, strike, right) { return strike === undefined || right === undefined ? `${instrument}|spot` : `${instrument}|${strike}|${right}`; } class BookLedger { #fills = []; #planState = new Map; #planRungs = new Map; #planFills = new Map; #spot = new Map; #childFacts = new Map; #multiplierOf; constructor(multiplierOf) { this.#multiplierOf = multiplierOf; } recordFill(fill) { this.#fills.push(fill); if (fill.plan !== undefined) { this.#planFills.set(fill.plan, (this.#planFills.get(fill.plan) ?? 0) + 1); } } setPlanState(plan, state) { this.#planState.set(plan, state); } setPlanRungs(plan, rungs) { this.#planRungs.set(plan, rungs); } setSpot(instrument, px) { this.#spot.set(instrument, px); } spotOf(instrument) { return this.#spot.get(instrument); } pnl() { let cash = 0; const netQty = new Map; for (const f of this.#fills) { const mult = this.#multiplierOf(f.instrument); cash += (f.side === "sell" ? 1 : -1) * f.qty * f.px * mult; const k = legKey(f.instrument, f.strike, f.right); const cur = netQty.get(k) ?? { instrument: f.instrument, ...f.strike !== undefined ? { strike: f.strike } : {}, ...f.right !== undefined ? { right: f.right } : {}, qty: 0 }; cur.qty += (f.side === "buy" ? 1 : -1) * f.qty; netQty.set(k, cur); } let openMark = 0; for (const pos of netQty.values()) { if (pos.qty === 0) continue; const spot = this.#spot.get(pos.instrument); if (spot === undefined) continue; const mark = pos.strike === undefined || pos.right === undefined ? spot : intrinsic(spot, pos.strike, pos.right); openMark += pos.qty * mark * this.#multiplierOf(pos.instrument); } return cash + openMark; } avgFillPx() { let q = 0; let n = 0; for (const f of this.#fills) { q += f.qty; n += f.qty * f.px; } return q === 0 ? UNKNOWN : n / q; } fillCount() { return this.#fills.length; } setChildFact(child, fact, value) { let facts = this.#childFacts.get(child); if (facts === undefined) { facts = new Map; this.#childFacts.set(child, facts); } facts.set(fact, value); } childFact(fact, quant) { let acc; for (const facts of this.#childFacts.values()) { const v = facts.get(fact); if (v === undefined) continue; acc = acc === undefined ? v : quant === "any" ? Math.max(acc, v) : Math.min(acc, v); } return acc === undefined ? UNKNOWN : acc; } childValues(fact) { const out = []; for (const [child, facts] of this.#childFacts.entries()) { const v = facts.get(fact); if (v !== undefined) out.push({ child, v }); } out.sort((a, b) => a.child < b.child ? -1 : a.child > b.child ? 1 : 0); return out.map((e) => e.v); } planState(plan) { return this.#planState.get(plan); } planRungs(plan) { return this.#planRungs.get(plan) ?? 0; } planFills(plan) { return this.#planFills.get(plan) ?? 0; } dump() { const sortEntries = (m) => [...m.entries()].sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0); return { fills: [...this.#fills], planState: sortEntries(this.#planState), planRungs: sortEntries(this.#planRungs), planFills: sortEntries(this.#planFills), spot: sortEntries(this.#spot), childFacts: [...this.#childFacts.entries()].map(([child, facts]) => [child, sortEntries(facts)]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0) }; } } class EngineOrgFacts { #ledger; #onUnresolved; constructor(ledger, onUnresolved) { this.#ledger = ledger; this.#onUnresolved = onUnresolved; } resolve(segments) { const head = segments[0]; if (head === undefined) return UNKNOWN; if (head.name === "plan" && head.selector?.kind === "sel-name") { const plan = head.selector.name; const field = segments[1]?.name; switch (field) { case "state": { const s = this.#ledger.planState(plan); return s ?? UNKNOWN; } case "rungs": return this.#ledger.planRungs(plan); case "fills": return this.#ledger.planFills(plan); default: return this.#unresolvable(segments); } } if (head.name === "children" && head.selector?.kind === "sel-quant") { const field = segments[1]?.name; if (field === undefined) return this.#unresolvable(segments); const v = this.#ledger.childFact(field, head.selector.q); return isUnknown(v) ? this.#unresolvable(segments) : v; } if (segments.length === 1 && head.selector === undefined) { if (head.name === "pnl") return this.#ledger.pnl(); } if (head.name === "fills" && head.selector === undefined) { const field = segments[1]?.name; if (field === "avg_px") return this.#ledger.avgFillPx(); if (field === "count") return this.#ledger.fillCount(); return this.#unresolvable(segments); } return this.#unresolvable(segments); } quantify(segments) { const head = segments[0]; if (head === undefined) return UNKNOWN; if (head.name === "children" && head.selector?.kind === "sel-quant") { const field = segments[1]?.name; if (field === undefined) return this.#unresolvable(segments); const vals = this.#ledger.childValues(field); return vals.length === 0 ? this.#unresolvable(segments) : vals; } return this.#unresolvable(segments); } #unresolvable(segments) { this.#onUnresolved?.(orgPathUnresolvableReason(pathKey(segments))); return UNKNOWN; } } // src/engine/plans.ts class ArmError extends Error { code; refusals; constructor(code, message, refusals) { super(message); this.name = "ArmError"; this.code = code; if (refusals !== undefined) this.refusals = refusals; } } var ARM_BOUND_NOTHING_MARKER = "ARM bound nothing"; function armRefusalError(refusals) { const code = refusals[0]?.code ?? "unknown-series"; const message = `arm: ${refusals.length} statement(s) refused — ` + refusals.map((r) => `[${r.code}] ${r.message}`).join(" | "); return new ArmError(code, message, refusals); } var EPS2 = 0.000000001; var DEFAULT_SPEC = { tickSize: 0.01, strikeStep: 1, multiplier: 1 }; var SPOT_SERIES_REF = { kind: "series", segments: [{ name: "spot" }] }; class ComposedProvider { market; org; registry; onUnresolved; constructor(market, org, registry, onUnresolved = () => {}) { this.market = market; this.org = org; this.registry = registry; this.