D13-F02-A02 / Complete engineering topic

Implementation-Shortfall Execution

A production-minded guide to Implementation-Shortfall Execution.

D13 · EXECUTION AND TRANSACTION COS…
D13-F02-A02Canonical / Tested / Open
D13 / D13-F02

Score an auditable lot-aligned candidate set and explain how adverse movement, urgency, impact, spread, volatility, and risk aversion change the selected child.

The decision this tutorial makes visible

Implementation shortfall begins at a decision clock and includes both executed cost and the consequence of quantity left unexecuted; an execution controller must show how it responds.

The precise question is: Given a decision price and current parent state, which candidate child minimizes an explicit proxy for immediate cost plus residual shortfall risk?

A trader needs to see why the plan changes; a builder needs the same objective, clock, units, thresholds, lot policy, and state to reproduce the decision across code, audit data, visuals, and the playground.

Intuition before notation

Trading more now raises modeled spread and impact cost but reduces residual opportunity and inventory-risk penalties.

This transparent teaching controller is one package-selected variant. Broker algorithms may use richer forecasts, venue state, constraints, and proprietary calibration. Those variants must not be implied by the shared catalog title.

Scope and nearby methods

One-step synthetic candidate controller using a declared proxy objective. It does not implement Perold's full measurement decomposition, Almgren-Chriss optimization, broker logic, venue routing, or post-trade TCA.

VariantDefinitionBest useMain limitation
Perold measurementPaper-versus-reality cost measurePost-decision and post-trade analysisNot a child-selection algorithm
Package proxy controllerFinite candidate scoreTransparent education and testingNot calibrated
Dynamic stochastic controlOptimize over future statesResearch or production modelsHigher model risk

What is sourced, selected, synthetic, and derived

RoleMaterial claimEvidenceBoundary
Sourced factImplementation shortfall as the performance gap between a paper decision and its implementation, including the importance of the decision clock and unexecuted quantity.S1, S2, S3, S4Defines a measurement framework, not the package's candidate-child controller or a universal broker strategy.
Implementation choiceOne-step synthetic candidate controller using a declared proxy objective. It does not implement Perold's full measurement decomposition, Almgren-Chriss optimization, broker logic, venue routing, or post-trade TCA.Frozen package definitionProprietary broker logic and nearby catalog methods are excluded.
Synthetic teaching inputAll orders, prices, coefficients, events, probabilities, and opportunities are repository-authored.datasets/canonical-input.json and scenario-results.jsonThey are not observed customer orders, live venue state, or calibrated forecasts.
Author-derived calculationFor a synthetic 10,000-share buy, the controller compares lot-aligned children from zero to 3,000 shares. The current price is 10 bps above the decision price, so unexecuted quantity carries an adverse-move penalty as well as urgency and volatility-risk penalties.Formula, fixture, Python/TypeScript parity, and independent arithmeticDefinition correctness does not establish execution quality.

Primary sources establish the named research, benchmark, interface, regulatory, or market-structure context. The algorithm, thresholds, fixtures, expected values, and scenario paths are repository-authored implementation choices and synthetic teaching data.

Formula, symbols, and numerical policy

Plain text
For candidate $q$, minimize $S(q)=q(s/2+\alpha q/ADV)+(X-q)(m^++u/H)+(X-q)\lambda\sigma/\sqrt{H}$ over the declared lot-aligned candidate set.
SymbolMeaningUnitPolicy
P_d, P_tDecision and current pricesatomsSigned from parent side
qCandidate childsharesDeclared finite candidate set
S(q)Proxy shortfall scorebps-sharesImplementation choice, not realized IS
  • Use integer shares and an explicit lot size for every parent, child, exposure, and residual quantity.
  • Represent prices as integer atoms; convert to basis points only with the declared side and benchmark.
  • Apply equality, cap, freshness, and fallback rules before formatting any displayed value.
  • Round floating-point scores for display only after the deterministic decision has been made.

Read the formula in the same order as the algorithm. Validate identity, ordering, units, and supported state first. Apply the selected equality and window rules second. Calculate with unrounded numeric values. Round only at the declared presentation boundary, and preserve null as a diagnostic rather than coercing it to zero.

Build the algorithm

  1. Validate side, prices, parent, candidates, lots, and score inputs.
  2. Compute side-aware move from decision price and retain only adverse movement in the proxy.
  3. Score each declared child candidate.
  4. Choose the minimum score with deterministic smaller-child tie-breaking.

Production-minded operational checklist

  1. Freeze decision price and timestamp
  2. Declare candidate set
  3. Version score coefficients
  4. Retain every component for audit

A precise output is unsafe when its decision clock, side, benchmark, limit, lot size, parameter vintage, or source state is ambiguous. Reject ambiguity rather than silently guessing.

Worked synthetic example

The canonical fixture is synthetic teaching data, not an observed control event, customer order, or broker execution. Its primary author-derived output, selected_child_quantity, is The canonical output is shown as a bounded decision summary; full schedules and audit rows remain in the fixture and playground.. The complete input and output are in datasets/canonical-input.json and datasets/expected-output.json.

For a synthetic 10,000-share buy, the controller compares lot-aligned children from zero to 3,000 shares. The current price is 10 bps above the decision price, so unexecuted quantity carries an adverse-move penalty as well as urgency and volatility-risk penalties.

Counterfactual checkpoint

No adverse move. Set current price equal to the decision price. The output changes because The proxy no longer charges unexecuted quantity for an already adverse move.

The structured result retains state and diagnostics in addition to the primary number. That makes the calculation independently reviewable and prevents a partial, null, rejected, or venue-bounded outcome from being mistaken for an unqualified value.

Boundary and counterexample workbook

The playground computes every scenario at 61 deterministic parameter states. The table uses the declared focus step and states whether that focus reproduces the canonical fixture. The full state ledger and compressed transition segments are in datasets/scenario-results.json.

ScenarioReview focusPurposeStatePrimary outputDiagnosticDecision segments
Canonical signed-price sweepStep 30 · canonical fixtureMove a buy from favorable to adverse relative to its decision price and land on the canonical state. Synthetic inputs; the output is a teaching plan, not a fill or best-execution claim.execute-nowselected child 3000 sharesscore 122453.181772; move 10.0 bps1
Exact decision-price equalityStep 30 · comparison focusSet current price equal to the decision benchmark so adverse movement is zero. Synthetic inputs; the output is a teaching plan, not a fill or best-execution claim.execute-nowselected child 3000 sharesscore 52453.181772; move 0.0 bps1
High-volatility residual riskStep 30 · comparison focusRaise volatility so unexecuted quantity becomes more expensive in the proxy. Synthetic inputs; the output is a teaching plan, not a fill or best-execution claim.execute-nowselected child 3000 sharesscore 156111.464556; move 10.0 bps1
High urgencyStep 30 · comparison focusRaise the residual urgency penalty as the hypothetical deadline approaches. Synthetic inputs; the output is a teaching plan, not a fill or best-execution claim.execute-nowselected child 3000 sharesscore 138203.181772; move 10.0 bps1
High impact restraintStep 30 · comparison focusRaise immediate impact cost so the selected child can shrink. Synthetic inputs; the output is a teaching plan, not a fill or best-execution claim.execute-nowselected child 3000 sharesscore 122993.181772; move 10.0 bps1
Wide candidate capStep 30 · comparison focusAllow larger candidate children while retaining the same score formula. Synthetic inputs; the output is a teaching plan, not a fill or best-execution claim.execute-nowselected child 6000 sharesscore 79624.675298; move 10.0 bps1
Sell-side adverse moveStep 30 · comparison focusReverse the sign convention and move a sell below its decision price. Synthetic inputs; the output is a teaching plan, not a fill or best-execution claim.execute-nowselected child 3000 sharesscore 122453.181772; move 10.0 bps1

These rows are not backtest observations. They are controlled counterexamples that expose how one driver changes the state, output, or reason code while the rest of the contract stays fixed.

Visualize the boundary

Implementation-Shortfall Execution annotated teaching map

Open this SVG at full size, or use the guided playground to compare the seven topic-specific canonical, boundary, policy, and failure scenarios.

The Mermaid flow answers where the selected calculation sits in the processing sequence. The SVG keeps the formula, output, decision boundary, and invariant visible together. The lab lets the reader step through the same structured states without changing the underlying definition.

Implementation walkthrough

The Python and TypeScript references validate the complete contract, compute one deterministic result, retain reason codes and intermediate quantities, and expose enough state for independent arithmetic. They do not connect to a venue or broker.

The main implementation branches are:

  • candidate total score is minimum — Select candidate, because Explicit immediate-versus-residual trade-off.
  • scores tie — Select smaller child, because Deterministic conservative tie-break.

Neither reference silently fetches data, mutates caller-owned inputs outside the declared engine behavior, guesses hidden state, or substitutes a provider default. Shared JSON fixtures make value, null, state, and reason-code drift visible across languages.

Testing and validation

Definition tests compare every canonical field, reject malformed state, and exercise the material boundary. Family validation recomputes every playground state from the reference function. Independent arithmetic is recorded beside the fixture rather than inferred only from implementation output.

The audit must preserve these invariants:

  • Selected child belongs to the candidate set and does not exceed the parent or cap.
  • All score components are nonnegative.
  • Post-child quantity plus selected child equals remaining parent.
  • The output retains selected_child_quantity, state, limits, and the decision explanation.

Passing these checks proves deterministic behavior under the selected contract. It does not prove model calibration, fill quality, best execution, cost reduction, or profitability.

Failure modes and misuse

  • A plan, score, accepted opportunity, or dark exposure is not an execution and does not guarantee acknowledgement or fill.
  • Synthetic impact, volatility, confidence, depth, and probability inputs do not establish live-market calibration or execution quality.
  • Passing definition tests does not establish best execution, lower realized cost, profitability, or predictive power.

Debugging order

When a result looks surprising, inspect the state in this order:

  1. Confirm the parent side, quantity, lot size, decision clock, and benchmark.
  2. Confirm impact/risk inputs or opportunity observations were available at that decision.
  3. Recalculate thresholds, lot floors, caps, residual quantity, and the selected reason code.
  4. Only then compare Python, TypeScript, article, visual, and playground outputs.

Evidence and historical boundary

Historical decision: deferred. Named broker algorithms and customer executions remain deferred because reproducible evaluation requires the parent instruction, decision clock, algorithm parameters and versions, complete child lifecycle, contemporaneous market data, venue disclosures, fees, corrections, and redistribution rights.

The primary sources are Perold implementation shortfall, Almgren-Chriss (2001), SEC Algorithmic Trading Report, FIXatdl 1.2 RC1. They support the source roles listed in the research ledger, not a redistributable historical observation, a broker algorithm, venue recommendation, customer execution, fill guarantee, best-execution conclusion, cost-savings claim, profitability claim, or prediction claim

Summary and next topic

You can now Continue from Implementation-Shortfall Execution to Arrival-Price Execution without carrying over a benchmark, clock, or decision rule that the next method does not use.. The learning flow is: Almgren-Chriss Optimal Execution → Implementation-Shortfall Execution → Arrival-Price Execution. Carry the result forward only with its scope, clock, state, and evidence label.

Implementation-Shortfall Execution calculation flow

This flow identifies the selected calculation stages and the structured output.

Rendering system map…

Takeaway: The minimum sits where the marginal residual penalty no longer justifies the next increment of modeled immediate impact.

ReferencesPrimary sources and evidence notes

Expand the source trail, evidence role, and limitations behind the engineering choices.

S1 — The Implementation Shortfall: Paper versus Reality

  • Organization or authors: Andre F. Perold
  • Source type: Original peer-reviewed research
  • Publication or effective date: 1988
  • Version: Journal of Portfolio Management 14(3), 4-9; DOI 10.3905/jpm.1988.409150
  • URL or DOI: https://doi.org/10.3905/jpm.1988.409150
  • Accessed: 2026-08-01
  • Jurisdiction: General portfolio implementation and transaction-cost analysis
  • Supports: Implementation shortfall as the performance gap between a paper decision and its implementation, including the importance of the decision clock and unexecuted quantity.
  • Limitations: Defines a measurement framework, not the package's candidate-child controller or a universal broker strategy.

S2 — Optimal Execution of Portfolio Transactions

  • Organization or authors: Robert Almgren and Neil Chriss
  • Source type: Original peer-reviewed research
  • Publication or effective date: 2001
  • Version: Journal of Risk 3, 5-39; DOI 10.21314/JOR.2001.041
  • URL or DOI: https://doi.org/10.21314/JOR.2001.041
  • Accessed: 2026-08-01
  • Jurisdiction: General optimal-execution research
  • Supports: The efficient-frontier framing that balances expected transaction cost from market impact against volatility risk while liquidating a position.
  • Limitations: The package implements a transparent single-asset linear-quadratic, lot-rounded teaching variant; it is not a calibrated reproduction of every paper equation or extension.

S3 — Staff Report on Algorithmic Trading in U.S. Capital Markets

  • Organization or authors: Staff of the U.S. Securities and Exchange Commission
  • Source type: Official regulator staff report
  • Publication or effective date: 2020-08-05
  • Version: Staff report to Congress
  • URL or DOI: https://www.sec.gov/about/reports-publications/algo_trading_report_2020
  • Accessed: 2026-08-01
  • Jurisdiction: United States capital markets
  • Supports: The distinction between demanding and providing liquidity and the operational context in which execution algorithms pursue customer objectives.
  • Limitations: Does not prescribe these formulas, parameters, venue logic, or synthetic fixtures.

S4 — FIX Algorithmic Trading Definition Language Online Specification

  • Organization or authors: FIX Trading Community
  • Source type: Official industry technical standard
  • Publication or effective date: 2021-05-20
  • Version: 1.2 Release Candidate 1
  • URL or DOI: https://www.fixtrading.org/standards/fixatdl-online/
  • Accessed: 2026-08-01
  • Jurisdiction: Cross-market electronic trading interfaces
  • Supports: Machine-readable strategy parameters, legal ranges, validation rules, effective times, expiry times, and disclosure links.
  • Limitations: Defines an interface-description standard, not a universal execution algorithm or fill model.

Evidence boundary

Sources support only their recorded role. They do not validate repository-authored parameters, synthetic opportunities, expected fills, or execution quality.

cost-risk-optimization.ts
/** Deterministic reference algorithms for D13-F02 Cost/Risk Optimization. */

export type JsonObject = Record<string, unknown>;

function integer(name: string, value: unknown, options: { positive?: boolean; nonnegative?: boolean } = {}): number {
  if (typeof value !== "number" || !Number.isInteger(value)) throw new Error(`${name} must be an integer`);
  if (options.positive && value <= 0) throw new Error(`${name} must be positive`);
  if (options.nonnegative && value < 0) throw new Error(`${name} must be nonnegative`);
  return value;
}

function finiteNumber(name: string, value: unknown, options: { positive?: boolean; nonnegative?: boolean } = {}): number {
  if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`${name} must be a finite number`);
  if (options.positive && value <= 0) throw new Error(`${name} must be positive`);
  if (options.nonnegative && value < 0) throw new Error(`${name} must be nonnegative`);
  return value;
}

function sideValue(value: unknown): "buy" | "sell" {
  if (value !== "buy" && value !== "sell") throw new Error("side must be 'buy' or 'sell'");
  return value;
}

function validateQuantity(totalQuantity: unknown, lotSize: unknown): [number, number] {
  const total = integer("total_quantity", totalQuantity, { positive: true });
  const lot = integer("lot_size", lotSize, { positive: true });
  if (total % lot !== 0) throw new Error("total_quantity must be divisible by lot_size");
  return [total, lot];
}

function lotFloor(quantity: number, lotSize: number): number {
  return Math.max(0, Math.floor(quantity / lotSize + 1e-12) * lotSize);
}

function round(value: number, digits: number): number {
  const scale = 10 ** digits;
  return Math.round((value + Number.EPSILON) * scale) / scale;
}

function allocateLots(totalQuantity: number, weights: number[], lotSize: number): number[] {
  if (!weights.length || weights.some((value) => !Number.isFinite(value) || value < 0) || weights.reduce((a, b) => a + b, 0) <= 0) {
    throw new Error("allocation weights must be finite, nonnegative, and have positive total");
  }
  const totalLots = totalQuantity / lotSize;
  const weightSum = weights.reduce((a, b) => a + b, 0);
  const exact = weights.map((weight) => totalLots * weight / weightSum);
  const bases = exact.map((value) => Math.floor(value + 1e-12));
  let residual = totalLots - bases.reduce((a, b) => a + b, 0);
  const order = weights.map((_, index) => index).sort((left, right) => {
    const difference = (exact[right] - bases[right]) - (exact[left] - bases[left]);
    return difference !== 0 ? difference : left - right;
  });
  for (const index of order) {
    if (residual <= 0) break;
    bases[index] += 1;
    residual -= 1;
  }
  return bases.map((lots) => lots * lotSize);
}

function signedMoveBps(side: "buy" | "sell", current: number, benchmark: number): number {
  const direction = side === "buy" ? 1 : -1;
  return direction * (current - benchmark) * 10000 / benchmark;
}

export function almgrenChrissOptimalExecution(input: JsonObject): JsonObject {
  const [total, lot] = validateQuantity(input.total_quantity, input.lot_size);
  const intervals = integer("interval_count", input.interval_count, { positive: true });
  const impactWeight = finiteNumber("temporary_impact_weight", input.temporary_impact_weight, { positive: true });
  const riskWeight = finiteNumber("inventory_risk_weight", input.inventory_risk_weight, { nonnegative: true });
  if (total / lot < intervals) throw new Error("interval_count cannot exceed available lots");

  let kappa = 0;
  let rawTrades: number[];
  if (riskWeight === 0) {
    rawTrades = Array(intervals).fill(1);
  } else {
    kappa = Math.acosh(1 + riskWeight / (2 * impactWeight));
    const denominator = Math.sinh(kappa * intervals);
    const holdings = Array.from({ length: intervals + 1 }, (_, step) => total * Math.sinh(kappa * (intervals - step)) / denominator);
    rawTrades = Array.from({ length: intervals }, (_, index) => holdings[index] - holdings[index + 1]);
  }
  const trades = allocateLots(total, rawTrades, lot);
  let remaining = total;
  let impactScore = 0;
  let riskScore = 0;
  const schedule = trades.map((quantity, index) => {
    remaining -= quantity;
    const impactComponent = impactWeight * quantity * quantity;
    const riskComponent = riskWeight * remaining * remaining;
    impactScore += impactComponent;
    riskScore += riskComponent;
    return { interval: index + 1, target_quantity: quantity, target_remaining_quantity: remaining, temporary_impact_score: round(impactComponent, 6), inventory_risk_score: round(riskComponent, 6) };
  });
  return { total_quantity: total, interval_count: intervals, lot_size: lot, temporary_impact_weight: impactWeight, inventory_risk_weight: riskWeight, kappa: round(kappa, 12), scheduled_quantity: trades.reduce((a, b) => a + b, 0), remaining_quantity: remaining, temporary_impact_score: round(impactScore, 6), inventory_risk_score: round(riskScore, 6), objective_score: round(impactScore + riskScore, 6), schedule, state: riskWeight === 0 ? "risk-neutral" : "risk-adjusted" };
}

export function implementationShortfallExecution(input: JsonObject): JsonObject {
  const [remaining, lot] = validateQuantity(input.remaining_quantity, input.lot_size);
  const side = sideValue(input.side);
  const decisionPrice = integer("decision_price_atoms", input.decision_price_atoms, { positive: true });
  const currentPrice = integer("current_price_atoms", input.current_price_atoms, { positive: true });
  const spread = finiteNumber("spread_bps", input.spread_bps, { nonnegative: true });
  const impact = finiteNumber("impact_coefficient_bps", input.impact_coefficient_bps, { nonnegative: true });
  const adv = integer("average_daily_volume", input.average_daily_volume, { positive: true });
  const volatility = finiteNumber("volatility_bps", input.volatility_bps, { nonnegative: true });
  const aversion = finiteNumber("risk_aversion", input.risk_aversion, { nonnegative: true });
  const urgency = finiteNumber("urgency_bps", input.urgency_bps, { nonnegative: true });
  const intervals = integer("intervals_remaining", input.intervals_remaining, { positive: true });
  const maxChild = Math.min(remaining, integer("max_child_quantity", input.max_child_quantity, { positive: true }));
  const candidateStep = integer("candidate_step_quantity", input.candidate_step_quantity, { positive: true });
  if (maxChild % lot !== 0 || candidateStep % lot !== 0) throw new Error("max_child_quantity and candidate_step_quantity must be lot-aligned");
  const signedMove = signedMoveBps(side, currentPrice, decisionPrice);
  const adverseMove = Math.max(0, signedMove);
  const quantities: number[] = [];
  for (let quantity = 0; quantity <= maxChild; quantity += candidateStep) quantities.push(quantity);
  if (quantities[quantities.length - 1] !== maxChild) quantities.push(maxChild);
  const candidates = quantities.map((quantity) => {
    const residual = remaining - quantity;
    const immediate = quantity * (spread / 2 + impact * quantity / adv);
    const opportunity = residual * (adverseMove + urgency / intervals);
    const risk = residual * (aversion * volatility / Math.sqrt(intervals));
    return { child_quantity: quantity, residual_quantity: residual, immediate_cost_score: round(immediate, 6), opportunity_cost_score: round(opportunity, 6), inventory_risk_score: round(risk, 6), total_score: round(immediate + opportunity + risk, 6) };
  });
  const selected = [...candidates].sort((left, right) => left.total_score - right.total_score || left.child_quantity - right.child_quantity)[0];
  return { side, decision_price_atoms: decisionPrice, current_price_atoms: currentPrice, signed_move_bps: round(signedMove, 6), adverse_move_bps: round(adverseMove, 6), remaining_quantity: remaining, selected_child_quantity: selected.child_quantity, post_child_quantity: selected.residual_quantity, selected_total_score: selected.total_score, selected_immediate_cost_score: selected.immediate_cost_score, selected_opportunity_cost_score: selected.opportunity_cost_score, selected_inventory_risk_score: selected.inventory_risk_score, candidates, state: selected.child_quantity > 0 ? "execute-now" : "wait" };
}

export function arrivalPriceExecution(input: JsonObject): JsonObject {
  const [remaining, lot] = validateQuantity(input.remaining_quantity, input.lot_size);
  const side = sideValue(input.side);
  const arrival = integer("arrival_price_atoms", input.arrival_price_atoms, { positive: true });
  const current = integer("current_price_atoms", input.current_price_atoms, { positive: true });
  const tolerance = finiteNumber("tolerance_bps", input.tolerance_bps, { nonnegative: true });
  const marketVolume = integer("observed_market_volume", input.observed_market_volume, { nonnegative: true });
  const baseRate = integer("base_participation_bps", input.base_participation_bps, { nonnegative: true });
  const defensiveRate = integer("defensive_participation_bps", input.defensive_participation_bps, { nonnegative: true });
  const maxRate = integer("max_participation_bps", input.max_participation_bps, { positive: true });
  const intervals = integer("intervals_remaining", input.intervals_remaining, { positive: true });
  const deadline = integer("deadline_threshold_intervals", input.deadline_threshold_intervals, { positive: true });
  const maxChild = integer("max_child_quantity", input.max_child_quantity, { positive: true });
  if (!(0 <= defensiveRate && defensiveRate <= baseRate && baseRate <= maxRate && maxRate <= 10000)) throw new Error("participation rates must satisfy 0 <= defensive <= base <= max <= 10000");
  if (maxChild % lot !== 0) throw new Error("max_child_quantity must be lot-aligned");
  const signedMove = signedMoveBps(side, current, arrival);
  let priceState: string;
  let chosenRate: number;
  if (intervals <= deadline) { priceState = "deadline-override"; chosenRate = maxRate; }
  else if (signedMove <= -tolerance) { priceState = "favorable"; chosenRate = maxRate; }
  else if (signedMove >= tolerance) { priceState = "adverse"; chosenRate = defensiveRate; }
  else { priceState = "inside-band"; chosenRate = baseRate; }
  const target = lotFloor(marketVolume * chosenRate / 10000, lot);
  const child = Math.min(remaining, maxChild, target);
  return { side, arrival_price_atoms: arrival, current_price_atoms: current, signed_move_bps: round(signedMove, 6), tolerance_bps: tolerance, price_state: priceState, chosen_participation_bps: chosenRate, observed_market_volume: marketVolume, target_from_volume_quantity: target, child_quantity: child, remaining_quantity: remaining - child, state: child === remaining ? "parent-complete" : priceState };
}

export function liquiditySeekingExecution(input: JsonObject): JsonObject {
  const [total, lot] = validateQuantity(input.total_quantity, input.lot_size);
  const side = sideValue(input.side);
  const limitPrice = integer("limit_price_atoms", input.limit_price_atoms, { positive: true });
  const minimumConfidence = integer("minimum_confidence_bps", input.minimum_confidence_bps, { nonnegative: true });
  const maxAge = integer("maximum_age_ms", input.maximum_age_ms, { nonnegative: true });
  const maxTake = integer("max_take_per_event", input.max_take_per_event, { positive: true });
  if (minimumConfidence > 10000) throw new Error("minimum_confidence_bps cannot exceed 10000");
  if (maxTake % lot !== 0) throw new Error("max_take_per_event must be lot-aligned");
  if (!Array.isArray(input.liquidity_events) || input.liquidity_events.length === 0) throw new Error("liquidity_events must be a nonempty array");
  let remaining = total;
  let accepted = 0;
  const events = (input.liquidity_events as unknown[]).map((raw, index) => {
    if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`liquidity_events[${index}] must be an object`);
    const event = raw as JsonObject;
    if (typeof event.event_id !== "string" || !event.event_id.trim()) throw new Error(`liquidity_events[${index}].event_id must be a nonempty string`);
    const price = integer(`liquidity_events[${index}].price_atoms`, event.price_atoms, { positive: true });
    const available = integer(`liquidity_events[${index}].available_quantity`, event.available_quantity, { nonnegative: true });
    const age = integer(`liquidity_events[${index}].age_ms`, event.age_ms, { nonnegative: true });
    const confidence = integer(`liquidity_events[${index}].confidence_bps`, event.confidence_bps, { nonnegative: true });
    if (confidence > 10000) throw new Error(`liquidity_events[${index}].confidence_bps cannot exceed 10000`);
    let reason: string;
    let quantity = 0;
    if (remaining === 0) reason = "parent-complete";
    else if (age > maxAge) reason = "stale";
    else if (confidence < minimumConfidence) reason = "confidence-below-threshold";
    else if ((side === "buy" && price > limitPrice) || (side === "sell" && price < limitPrice)) reason = "outside-limit";
    else { quantity = Math.min(remaining, maxTake, lotFloor(available, lot)); reason = quantity > 0 ? "accepted" : "below-one-lot"; }
    remaining -= quantity;
    accepted += quantity;
    return { event_id: event.event_id.trim(), price_atoms: price, available_quantity: available, age_ms: age, confidence_bps: confidence, planned_take_quantity: quantity, reason, remaining_quantity: remaining };
  });
  return { side, limit_price_atoms: limitPrice, total_quantity: total, accepted_quantity: accepted, remaining_quantity: remaining, accepted_event_count: events.filter((row) => row.reason === "accepted").length, rejected_event_count: events.filter((row) => row.reason !== "accepted").length, events, state: remaining === 0 ? "parent-complete" : accepted > 0 ? "opportunity-found" : "no-eligible-liquidity" };
}

export function opportunisticDarkPoolExecution(input: JsonObject): JsonObject {
  const [total, lot] = validateQuantity(input.total_quantity, input.lot_size);
  const maxFraction = integer("maximum_dark_fraction_bps", input.maximum_dark_fraction_bps, { positive: true });
  const minProbability = integer("minimum_firm_probability_bps", input.minimum_firm_probability_bps, { nonnegative: true });
  const minImprovement = integer("minimum_price_improvement_atoms", input.minimum_price_improvement_atoms, { nonnegative: true });
  const minExecution = integer("minimum_execution_quantity", input.minimum_execution_quantity, { positive: true });
  const maxWindow = integer("max_exposure_per_window", input.max_exposure_per_window, { positive: true });
  const fallback = integer("fallback_window", input.fallback_window, { positive: true });
  if (maxFraction > 10000 || minProbability > 10000) throw new Error("basis-point parameters cannot exceed 10000");
  if (minExecution % lot !== 0 || maxWindow % lot !== 0) throw new Error("minimum_execution_quantity and max_exposure_per_window must be lot-aligned");
  if (!Array.isArray(input.dark_opportunities) || input.dark_opportunities.length === 0) throw new Error("dark_opportunities must be a nonempty array");
  const darkCap = lotFloor(total * maxFraction / 10000, lot);
  let exposed = 0;
  const opportunities = (input.dark_opportunities as unknown[]).map((raw, index) => {
    if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`dark_opportunities[${index}] must be an object`);
    const opportunity = raw as JsonObject;
    if (typeof opportunity.opportunity_id !== "string" || !opportunity.opportunity_id.trim()) throw new Error(`dark_opportunities[${index}].opportunity_id must be a nonempty string`);
    const window = integer(`dark_opportunities[${index}].window`, opportunity.window, { positive: true });
    const indicated = integer(`dark_opportunities[${index}].indicated_quantity`, opportunity.indicated_quantity, { nonnegative: true });
    const probability = integer(`dark_opportunities[${index}].firm_probability_bps`, opportunity.firm_probability_bps, { nonnegative: true });
    const improvement = integer(`dark_opportunities[${index}].price_improvement_atoms`, opportunity.price_improvement_atoms, { nonnegative: true });
    if (probability > 10000) throw new Error(`dark_opportunities[${index}].firm_probability_bps cannot exceed 10000`);
    const capRemaining = Math.max(0, darkCap - exposed);
    let reason: string;
    let quantity = 0;
    if (window >= fallback) reason = "fallback-active";
    else if (probability < minProbability) reason = "firm-probability-below-threshold";
    else if (improvement < minImprovement) reason = "price-improvement-below-threshold";
    else if (indicated < minExecution) reason = "minimum-size-not-met";
    else if (capRemaining === 0) reason = "dark-cap-reached";
    else { quantity = Math.min(capRemaining, maxWindow, lotFloor(indicated, lot)); reason = quantity >= minExecution ? "expose-dark" : "minimum-size-not-met"; if (reason !== "expose-dark") quantity = 0; }
    exposed += quantity;
    return { opportunity_id: opportunity.opportunity_id.trim(), window, indicated_quantity: indicated, firm_probability_bps: probability, price_improvement_atoms: improvement, planned_dark_exposure_quantity: quantity, reason, dark_cap_remaining_quantity: Math.max(0, darkCap - exposed) };
  });
  const fallbackQuantity = total - exposed;
  return { total_quantity: total, maximum_dark_fraction_bps: maxFraction, dark_quantity_cap: darkCap, planned_dark_exposure_quantity: exposed, lit_fallback_quantity: fallbackQuantity, dark_opportunity_count: opportunities.length, accepted_dark_window_count: opportunities.filter((row) => row.reason === "expose-dark").length, opportunities, state: fallbackQuantity === 0 ? "dark-plan-complete" : "lit-fallback-required" };
}

export function calculate(topicId: string, input: JsonObject): JsonObject {
  if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error("inputs must be an object");
  if (topicId === "D13-F02-A01") return almgrenChrissOptimalExecution(input);
  if (topicId === "D13-F02-A02") return implementationShortfallExecution(input);
  if (topicId === "D13-F02-A03") return arrivalPriceExecution(input);
  if (topicId === "D13-F02-A04") return liquiditySeekingExecution(input);
  if (topicId === "D13-F02-A05") return opportunisticDarkPoolExecution(input);
  throw new Error(`unsupported topic_id: ${topicId}`);
}
Full-height labplaygroundOpen full screen