AMM Price Simulator

Overview

The AMM Price Simulator (AMMPS) is a core component for accurately modeling trade executions on Uniswap V2-style constant product AMMs. By applying the protocol’s formula to simulate how swaps alter pool reserves, it precisely calculates price impact, slippage, and resulting trade amounts. This level of detail is critical for smaller or less liquid pools, where even modest trades can cause substantial slippage, often enough to erode profits entirely.

By centralizing trading logic, the AMMPS promotes a clear separation of concerns, allowing strategy logic to focus on decision-making rather than AMM dynamics. This clear division of concerns reduces cognitive load, enabling rapid iteration, deeper insights, and more confident decision-making.

Why Price Impact Matters: A Real Example

During development, we encountered an illuminating case with the DOGE-WETH pool that demonstrates why price simulation is crucial:

Initial Testing: Oversized Trade

Initial Pool State:
  Base Reserve: ~200M DOGE
  Quote Reserve: ~8 WETH
  TVL: ~$40K USD

Trade Result:
  Size: Large (Significant % of pool reserves)
  Price Impact: Severe (>40%)

Profit: -800%

Optimized Approach

Same Pool:
  Similar initial reserves
  Similar market conditions

Trade Result:
  Size: Reduced to small % of pool reserves
  Price Impact: Minimal (<0.5%)

Profit: +30%

This real test case demonstrates why accurate price impact simulation is crucial. What appears to be a profitable opportunity can become a significant loss if the trade size isn't correctly calibrated to pool liquidity. The AMMPriceSimulator helps strategies avoid these pitfalls by modeling trade impact before execution.

Simulation Workflow

Core Implementation Details

Inputs

  • reserve_base (Decimal): The current reserve quantity of the base asset in the pool.

  • reserve_quote (Decimal): The current reserve quantity of the quote asset in the pool.

  • amount_in (Decimal): The amount of input tokens provided for the trade.

  • trade_type (str): The direction of the trade ("buy" or "sell").

  • fee (Decimal, optional): The trading fee applied (e.g., 0.003 for a 0.3% fee).

Outputs

  • amount_out (Decimal): The quantity of the output token received after the swap.

  • trade_price (Decimal): The effective execution price of the trade.

  • slippage (Decimal): The percentage deviation of the trade price from the initial spot price.

  • new_reserve_base and new_reserve_quote (Decimal): The updated pool reserves following the trade.

Last updated