npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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/optimizer

Trade 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 sigma

Key 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