← back
#02Systems & Infrastructure2026

Optimal Sizing

Published multi-crate Rust workspace (v2.0.0) & Python package for profit-maximizing trade sizing across heterogeneous AMM liquidity curves

github ↗crates.io ↗pypi ↗docs.rs ↗live demo ↗
RustCargo WorkspaceCPMM / StableSwap / PMMConcentrated Liquidity (CLMM)Discretized Liquidity Book (DLMM)Velodrome Stable CurvesDual Water-FillingPython (PyO3)WASMTokio WebSocket

Optimal Sizing: Profit-Maximizing Trade Sizing Across Heterogeneous AMM Curves

optimal-sizing is a high-performance, chain-agnostic Rust library and 10-crate workspace published on crates.io and PyPI for computing exact profit-maximizing trade sizes against Constant Product (CPMM), StableSwap, Concentrated Liquidity (CLMM), Discretized Liquidity Books (DLMM), Velodrome Stable, Balancer, and Proactive Market Maker (PMM) liquidity curves.

![Version](https://github.com/Xtley001/optimal-sizing)

![crates.io](https://crates.io/crates/sizing-core)

![PyPI](https://pypi.org/project/optimal-sizing/)

![License: MIT](https://github.com/Xtley001/optimal-sizing/blob/main/LICENSE)

---

Engineering Philosophy: Replacing Heuristics with Provable Optimality

Most trade-sizing implementations in automated trading systems rely on naive grid searches or unexamined bisection loops, providing zero mathematical certainty regarding whether an order size is optimal or bleeding slippage. optimal-sizing eliminates guesswork by establishing explicit mathematical guarantee tiers:

  • `ProvenOptimal`: Solved in closed form with analytic derivative roots (CPMM, Concentrated Liquidity, DLMM step-aggregation).
  • `NumericallyGuaranteed`: Solved via Newton-Raphson solvers with rigorously verified convergence conditions, invariant memoization, and $\sqrt{\text{tolerance}}$ step scaling (StableSwap, Velodrome, Balancer).
  • `EmpiricallyValidated`: Golden-section search conditioned on an active runtime unimodality proof ($f''(\Delta) \le 0$) rather than assumed pool convexity (WooFi v2, DODO PMM).
  • `ComposedFrom`: Joint multi-variable optimization over arbitrary heterogeneous multi-hop cascades.

---

10-Crate Workspace Architecture (v2.0.0 Expansion)

The workspace decouples mathematical optimization, routing, budget allocation, and transport layers across 10 specialized crates:

optimal-sizing/
├── crates/
│   ├── sizing-core/         # Pure math solvers — zero I/O, zero chain dependencies
│   ├── sizing-router/       # Multi-hop heterogeneous routing across arbitrary AMM curves
│   ├── sizing-portfolio/    # Joint budget allocation via Dual Water-Filling algorithm
│   ├── sizing-watch/        # Real-time WebSocket streaming daemon (tokio-tungstenite)
│   ├── sizing-backtest/     # Historical pool replay harness & benchmark suite
│   ├── sizing-cli/          # Command-line interface with route-file JSON ingestion
│   ├── sizing-bench/        # Sub-microsecond latency and precision benchmarks
│   ├── sizing-integration/  # Live Ethereum mainnet multicall integration (Uniswap & Curve)
│   ├── sizing-wasm/         # WebAssembly bindings (@optimal-sizing/wasm) with TypeScript stubs
│   └── sizing-py/           # PyO3 Python bindings verified on Python 3.9–3.12
└── docs/
    ├── whitepaper.md        # Full mathematical derivations, proofs, and convergence bounds
    ├── ARCHITECTURE.md      # Module boundaries, data flow invariants, and non-goals
    ├── API.md               # Trait contracts and public interface specifications
    └── TESTING.md           # Verification contract and proptest suites

---

Major Pillars of the v2.0.0 Upgrade

1. New Curve Families & Heterogeneous Routing

  • Velodrome / Aerodrome Stable Curve ($x^3 y + x y^3 = k$): Implemented using normalized Newton-Raphson iteration preventing Decimal overflow on large reserves $\ge 10^7$. Profit maximized via bracket-contracted golden-section search (NumericallyGuaranteed).
  • Discretized Liquidity Book (DLMM): Models Trader Joe & Meteora bin-partitioned liquidity books. Features analytical closed-form aggregation across profitable tick bins (ProvenOptimal).
  • Multi-Hop Routing: sizing-router evaluates multi-hop swap sequences by performing a joint search over initial leg input size, eliminating compounding per-leg heuristic errors.

2. Adversarial Slippage & Rollup Blob Gas

  • `AdversePricingCurve`: Dynamic price impact scaling that penalizes trades consuming high percentages of marginal pool capacity.
  • EIP-4844 Blob Gas Accounting: Calibrated gas consumption models for Optimism, Base, and Arbitrum rollups factoring in L1 blob submission costs.

3. Constrained Multi-Pool Capital Allocation (sizing-portfolio)

  • Solves the optimal joint allocation of a shared capital budget $B$ across $M$ concurrent arbitrage opportunities.
  • Dual Water-Filling Algorithm: Solves the Lagrange dual via bisection on marginal return $\lambda$ with exact boundary clipping. Operates entirely in fixed-point Decimal arithmetic with zero floating-point imprecision.

4. Streaming Daemon & Historical Replay

  • `sizing-watch`: Upgraded to async WebSocket streaming with eth_subscribe("newHeads"), streaming block event processing, and automatic RPC polling fallback.
  • `sizing-backtest`: Replay harness evaluating multi-pool historical state trajectories, quantifying analytical sizing profits against naive grid-search baselines.

---

Installation & Usage

Rust

cargo add sizing-core sizing-router sizing-portfolio rust_decimal rust_decimal_macros
use rust_decimal_macros::dec;
use sizing_core::curves::Cpmm;
use sizing_core::traits::SizingAlgorithm;
use sizing_core::types::SizingConstraints;

let pool = Cpmm::new(dec!(1_200_000), dec!(800_000), dec!(0.997)).unwrap();
let result = pool.optimal_size(dec!(0.60), SizingConstraints::default()).unwrap();
println!("Optimal input: {} (Guarantee: {:?})", result.optimal_delta, result.guarantee_tier);

Python

pip install optimal-sizing
from optimal_sizing import Cpmm, SizingConstraints
from decimal import Decimal

pool = Cpmm(reserve_in=Decimal("1200000"), reserve_out=Decimal("800000"), fee=Decimal("0.997"))
res = pool.optimal_size(target_price=Decimal("0.60"), constraints=SizingConstraints())
print(f"Optimal Delta: {res.optimal_delta} | Guarantee: {res.guarantee_tier}")