Trading Engine (AMM)
Details on the constant product formula and how trades are executed on-chain.
Pricing Formula
The instantaneous price P of a share is determined by the ratio of the reserves. For a YES share:
P_{YES} = y / (x + y)Where x is the YES reserve and y is the NO reserve. The price of a NO share is always 1 - P_{YES}.
Trade Execution
When a trade is executed, the smart contract calculates the new reserves needed to maintain the constant k, and the amount of base currency (USDC) required for the transaction.
// Pseudocode for trade execution
fn execute_trade(
reserve_x: u64,
reserve_y: u64,
amount_in: u64
) -> (u64, u64) {
let k = reserve_x * reserve_y;
// Calculate shares out, new reserves, fees, and final cost
// ... complex math involving k ...
return (shares_out, total_cost);
}All trades incur a small **trading fee** (currently 2%), which is added back to the liquidity pool, rewarding LPs.
Price Impact
Because the AMM determines price based on reserves, large trades will cause **price slippage** (price impact). The trading panel provides a quote to show the estimated price before execution.
Warning: Be mindful of price impact, especially on low-liquidity markets. Always check the quoted price before confirming.