@the-situation/optimizer
v0.12.1
Published
Budget-constrained trade optimizer for The Situation prediction markets
Downloads
99
Readme
@the-situation/optimizer
Budget-constrained trade optimizer and LP profitability math for normal-distribution prediction markets on The Situation protocol.
Install
npm install @the-situation/optimizerTrade Optimization
optimizeNormalTrade(input): TradeOptimizationResult
Finds the trade (mu_g, sigma_g) that maximizes net expected value (EV minus collateral) under the trader's belief distribution, subject to collateral <= budget. Returns a no-trade result when no positive-net trade exists.
Input fields (TradeOptimizationInput):
| Field | Type | Description |
|-------|------|-------------|
| budget | number | Trader's budget in collateral tokens |
| beliefMean | number | Trader's belief about the settlement mean |
| beliefSigma | number | Trader's belief uncertainty (standard deviation) |
| marketMean | number | Current market distribution mean |
| marketSigma | number | Current market distribution sigma |
| effectiveK | number | AMM invariant after LP scaling |
| payoutAmplifier | number? | Multiplies position value (default 1) |
| constraints.maxSigmaRatio | number? | Max ratio between candidate and market sigma (default 4.0) |
| constraints.maxMeanSepSigmas | number? | Max mean shift in sigma units (default 4.0) |
Output fields (TradeOptimizationResult):
| Field | Type | Description |
|-------|------|-------------|
| optimizedMean | number | Target distribution mean |
| optimizedSigma | number | Target distribution sigma |
| optimizedVariance | number | Target variance (sigma squared) |
| collateralRequired | number | Collateral cost of the optimized trade |
| expectedValue | number | Gross expected payout under belief distribution |
| roi | number | Net ROI: (EV - collateral) / collateral. Zero means break-even. |
| beliefUtilization | number | Fraction of intended belief shift expressed (0-1) |
| isBudgetSufficient | boolean | Whether the optimizer could reach the full belief point |
| budgetSurplus | number | budget - collateralRequired |
When no profitable trade exists, returns collateralRequired = 0, roi = 0, and optimizedMean = marketMean.
import { optimizeNormalTrade } from '@the-situation/optimizer';
const result = optimizeNormalTrade({
budget: 100,
beliefMean: 55,
beliefSigma: 8,
marketMean: 50,
marketSigma: 10,
effectiveK: 0.5,
});
console.log(result.optimizedMean); // ~53.2
console.log(result.collateralRequired); // ~42.7
console.log(result.roi); // ~0.18 (18% expected net return)
console.log(result.beliefUtilization); // ~0.64 (64% of belief shift expressed)LP Profitability
fAt(x, mu, sigma, k): number
The AMM's closed-form f-position evaluated at settlement outcome x:
f(x; mu, sigma, k) = k / sqrt(sigma * sqrt(pi)) * exp(-0.5 * ((x - mu) / sigma)^2)This is the core building block for LP P&L. Returns 0 for degenerate inputs.
buildLpPayoffCurve(input): LpPayoffCurveResult
Samples the LP's settlement P&L curve over an outcome range.
lpPnl(v) = poolShare * [f(v; mu_0, sigma_0, k_0) - f(v; mu_t, sigma_t, k_t)]The LP profits when traders move the market away from the realized outcome relative to the LP-entry distribution; they lose when traders move it closer. With no scenario distribution provided (no-trade case), P&L is 0 everywhere.
Input (LpPayoffInput): marketMean, marketSigma, effectiveK, poolShare, totalBacking, and optional scenarioMean, scenarioSigma, scenarioK, samples (default 200), range.
Output: points[] (v, lpPnl, isProfitable), deposit, peakPnl, peakV, troughPnl, troughV, breakEvenLow, breakEvenHigh.
computeKeyLpScenarios(input): LpKeyScenarios
Five-point summary at the LP-entry distribution's mean and +/-1 and +/-2 sigma. Each scenario returns { settlement, lpPnl, returnPct }.
computeLPClaimComponentValue(component, settlementValue): number
Evaluates a single LP claim component's value at a settlement outcome: lambda * pdf(x*; mean, sigma). Used for client-side settlement preview.
computeTotalLPClaimValue(components, settlementValue): number
Sums claim component values across multiple add_liquidity deposits.
previewLPSettlement(input): { claimValue, proRataResidual, totalPayout, depositCost, netPnl }
Full settlement payout preview. Combines the LP's claim value with their pro-rata share of residual pool backing.
estimateLpFeeYield(input): number | null
Heuristic fee yield: (lpFeeBps / 10_000) * newPoolTotal * assumedTurnover. This is risk-free protocol rent independent of trader skill.
computeLpWorstCaseLoss(input): number | null
Speculative loss bound: poolShare * k_t / sqrt(sigma_t * sqrt(pi)). The LP can never lose more than their deposit regardless of this bound.
import { buildLpPayoffCurve, computeKeyLpScenarios } from '@the-situation/optimizer';
const curve = buildLpPayoffCurve({
marketMean: 50,
marketSigma: 10,
effectiveK: 0.5,
poolShare: 0.25,
totalBacking: 1000,
scenarioMean: 55, // traders pushed the mean up by 5
scenarioSigma: 10,
});
console.log(curve.peakPnl); // LP's best-case P&L
console.log(curve.troughPnl); // LP's worst-case P&L
console.log(curve.breakEvenLow); // lower break-even settlement value
const scenarios = computeKeyLpScenarios({
marketMean: 50,
marketSigma: 10,
effectiveK: 0.5,
poolShare: 0.25,
totalBacking: 1000,
scenarioMean: 55,
scenarioSigma: 10,
});
console.log(scenarios.atMean.returnPct); // P&L as % of deposit at mean
console.log(scenarios.atPlus1Sigma.returnPct); // P&L at +1 sigmaKey Concepts
effectiveK: The AMM invariant scaled by LP deposits. effective_k = max(base_k, base_k * pool_backing / initial_backing). Larger k means higher collateral costs and deeper liquidity.
Net EV vs Gross EV: The optimizer maximizes net EV (expected payout minus collateral), not gross EV. Gross EV can be positive while the trade still loses money after accounting for the collateral posted. Net EV is the trader's actual expected P&L.
2D Grid Search: The optimizer scans a 50x50 grid over (mu_g, sigma_g) within policy bounds. Unlike the older sigma-sweep approach, this correctly handles the non-monotone net EV surface where collateral and expected payout move in opposite directions.
LP P&L Model: poolShare * (f_entry(x*) - f_final(x*)). This is zero-sum against the trader pool. When f_entry == f_final (no trades happened), P&L is 0 everywhere -- the LP gets back exactly their deposit.
License
MIT
