AMM liquidity provision mathematics including constant-product, concentrated liquidity, price impact, and LP share calculations

MITAuto-check passed

Install Lp Math

skills CLI
$ npx skills add agiprolabs/claude-trading-skills --skill lp-math -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install agiprolabs/claude-trading-skills lp-math --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/agiprolabs/claude-trading-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/lp-math .claude/skills/lp-math && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
lp-math
GitHub stars
410
Token cost
~2.5k tokens
SKILL.md length
831 words
Files
5 (incl. scripts, references)
Skills in repo
68
Repo updated
First seen
Licence
MIT

At a glance

AMM liquidity provision mathematics including constant-product, concentrated liquidity, price impact, and LP share calculations

  • Works in 7 steps: Constant Product AMM (xy = k) → Concentrated Liquidity (CLMM) → Price Impact → …
  • SKILL.md covers 1. Constant Product AMM (xy = k), 2. Concentrated Liquidity (CLMM), 3. Price Impact and 4. LP Share Calculations, plus 3 more sections
  • Runs Python scripts from its folder

What it does

Lp Math is an agent skill from agiprolabs/claude-trading-skills. AMM liquidity provision mathematics including constant-product, concentrated liquidity, price impact, and LP share calculations

Its SKILL.md is about 2.5k tokens, which your agent loads only when the skill is triggered. The skill folder holds 6 other files, including scripts and reference files (for example `references/amm_formulas.md`, `references/pool_mechanics.md` and `scripts/amm_calculator.py`).

It works with Circle USDC. The repository describes itself as: 68 trading, DeFi, and quantitative finance Agent Skills. Works with Claude Code, Cursor, Codex, Gemini CLI, and 30+ other tools. The licence is MIT.

Example prompts

  • “/lp-math”

Requirements

  • Python 3

Workflow steps

7 steps, taken from the step headings in SKILL.md.

  1. Constant Product AMM (xy = k)
  2. Concentrated Liquidity (CLMM)
  3. Price Impact
  4. LP Share Calculations
  5. Fee Accrual
  6. Solana Pool Types
  7. Practical Decision Framework

What it can do on your machine

Read from SKILL.md and the folder at commit 981e1d7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 2 files in scripts/ (Python), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Lp Math loads about 2.5k tokens when it runs, and up to ~5.7k if it reads all its reference files. Until then it costs about 34 tokens; SKILL.md has 831 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~34
When it runs · the whole SKILL.md, loaded when a task matches
~2.5k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~5.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from agiprolabs/claude-trading-skills at commit 981e1d7, republished under its MIT licence (© agiprolabs). 831 words, ~2,497 tokens.

Download SKILL.mdSave it as .claude/skills/lp-math/SKILL.md (or your agent's skills folder). This skill also uses 4 other files; get the full folder from GitHub.
name
lp-math
description
AMM liquidity provision mathematics including constant-product, concentrated liquidity, price impact, and LP share calculations

LP Math — AMM Liquidity Provision Mathematics

Automated Market Makers (AMMs) replace traditional orderbooks with liquidity pools. Instead of matching buyers and sellers, a mathematical formula determines prices based on reserve ratios. Liquidity providers (LPs) deposit both assets into a pool and earn fees from every trade.

Understanding the math behind AMMs is essential for:

  • Evaluating whether providing liquidity is profitable after impermanent loss
  • Estimating price impact before executing large trades
  • Comparing capital efficiency across pool types (constant product vs concentrated)
  • Calculating expected fee revenue for a given pool position

Related skills: See impermanent-loss for IL calculations, yield-analysis for LP yield modeling, liquidity-analysis for pool depth assessment.


1. Constant Product AMM (xy = k)

The foundational AMM model used by Raydium V4 and most Solana DEXes.

Core Invariant
x * y = k

Where:

  • x = reserve amount of token X (e.g., SOL)
  • y = reserve amount of token Y (e.g., USDC)
  • k = constant product (increases over time from fees)
Spot Price
P = x / y    (price of Y in terms of X)
P = y / x    (price of X in terms of Y)

For a pool with 100 SOL and 10,000 USDC: price of SOL = 10,000 / 100 = 100 USDC.

Trade Execution

When a trader swaps Δx of token X into the pool:

python
# Output amount (before fees)
delta_y = y * delta_x / (x + delta_x)

# With fee (e.g., 0.3%)
delta_y_after_fee = delta_y * (1 - fee_rate)

# New reserves
x_new = x + delta_x
y_new = y - delta_y_after_fee

The key insight: larger trades get worse prices because each unit moves the ratio further.

Inverse Calculation

To get a specific output amount Δy, the required input is:

python
delta_x = x * delta_y / (y - delta_y)
Price After Trade
python
price_new = y_new / x_new
Worked Example

Pool: 100 SOL / 10,000 USDC (k = 1,000,000), fee = 0.3%

Buy 5 SOL worth of USDC:

  1. Gross output: 10,000 * 5 / (100 + 5) = 476.19 USDC
  2. Fee: 476.19 * 0.003 = 1.43 USDC
  3. Net output: 474.76 USDC
  4. Effective price: 474.76 / 5 = 94.95 USDC/SOL (vs spot 100)
  5. Price impact: (100 - 94.95) / 100 = 5.05%
  6. New reserves: 105 SOL / 9,525.24 USDC
  7. New k: 105 * 9,525.24 = 1,000,150.2 (k increased from fees)

See references/amm_formulas.md for complete derivations.


2. Concentrated Liquidity (CLMM)

Used by Orca Whirlpool, Raydium CLMM, and Meteora DLMM. Liquidity is only active within a chosen price range [P_lower, P_upper].

Key Concepts
L = sqrt(x * y)           # Liquidity within the active range
price_at_tick = 1.0001^tick  # Tick-to-price conversion
Capital Efficiency

Concentrating liquidity in a narrow range provides more depth per dollar:

python
# Capital efficiency ratio
efficiency = sqrt(P_upper / P_lower) / (sqrt(P_upper / P_lower) - 1)

# Example: ±5% range around $100 SOL
P_lower, P_upper = 95, 105
efficiency = sqrt(105/95) / (sqrt(105/95) - 1)  # ≈ 20.5x

A ±5% range is ~20x more capital-efficient than full-range, but the position goes 100% into one asset if price moves outside the range.

Position Value

For a CLMM position with liquidity L in range [P_lower, P_upper] at current price P:

python
if P <= P_lower:
    # All in token X (below range)
    value_x = L * (1/sqrt(P_lower) - 1/sqrt(P_upper))
    value_y = 0
elif P >= P_upper:
    # All in token Y (above range)
    value_x = 0
    value_y = L * (sqrt(P_upper) - sqrt(P_lower))
else:
    # In range — holds both tokens
    value_x = L * (1/sqrt(P) - 1/sqrt(P_upper))
    value_y = L * (sqrt(P) - sqrt(P_lower))
Range Strategy Comparison
RangeEfficiencyIL RiskFee CaptureBest For
±2%~50xVery highHigh if in rangeStablecoins, tight pegs
±5%~20xHighGood for trendingActive management
±25%~4xModerateConsistentSemi-passive
±100%~2xLowLower per $Passive, volatile pairs
Full range1xBaselineAlways earningSet and forget

See references/amm_formulas.md for full CLMM derivations.


3. Price Impact

Constant Product Impact
python
# Price impact as a fraction
price_impact = delta_x / (x + delta_x)

# As percentage of pool
pool_fraction = trade_value / pool_tvl

# Rule of thumb: impact ≈ 2 * pool_fraction for constant product
Multi-Hop Impact

For a route through multiple pools, compound the impacts:

python
def multi_hop_impact(hops: list[dict]) -> float:
    """Calculate total price impact across route legs.

    Args:
        hops: List of {reserve_in, trade_amount} for each leg.

    Returns:
        Total price impact as a fraction.
    """
    remaining = 1.0
    for hop in hops:
        leg_impact = hop["trade_amount"] / (hop["reserve_in"] + hop["trade_amount"])
        remaining *= (1 - leg_impact)
    return 1 - remaining
Impact Thresholds
ImpactAssessmentAction
< 0.1%NegligibleProceed normally
0.1–0.5%LowAcceptable for most trades
0.5–2%ModerateConsider splitting across pools
2–5%HighSplit trade, use TWAP
> 5%SevereReduce size or find deeper pools

4. LP Share Calculations

Initial Deposit (Empty Pool)
python
shares = sqrt(x_deposited * y_deposited)

The first depositor sets the ratio and receives shares equal to the geometric mean.

Show full SKILL.md (331 more words)Show less
Subsequent Deposits
python
shares_minted = min(
    x_added / x_reserve,
    y_added / y_reserve
) * total_shares

Deposits must be proportional to the current reserve ratio. Any excess of one token is not used (or returned, depending on implementation).

Withdrawal
python
x_out = (shares_burned / total_shares) * x_reserve
y_out = (shares_burned / total_shares) * y_reserve

You always receive both tokens in the current ratio.

Share Value
python
share_value = pool_tvl / total_shares
your_value = your_shares * share_value

5. Fee Accrual

Fees accumulate inside the pool, increasing k:

python
# Before trade: k = x * y
# After trade with fee:
# k_new = (x + delta_x) * (y - delta_y_net) > k
# The difference is the fee retained in the pool

# Fee APR estimation
daily_volume = 500_000  # USD
fee_rate = 0.003        # 0.3%
daily_fees = daily_volume * fee_rate  # $1,500
tvl = 2_000_000         # $2M pool
fee_apr = (daily_fees * 365) / tvl    # 27.4%

For CLMM positions, fee earnings depend on:

  • Whether price stays within your range (out-of-range = no fees)
  • Your share of active liquidity in that range
  • Total volume routed through the pool
python
# CLMM fee estimation
your_liquidity = 50_000     # Your L
total_liquidity = 1_000_000  # Total L in your tick range
your_share = your_liquidity / total_liquidity  # 5%
your_daily_fees = daily_fees * your_share  # $75

6. Solana Pool Types

Raydium V4 (Constant Product)
  • Model: Standard xy = k
  • Fee: 0.25% (0.22% to LP, 0.03% to RAY buyback)
  • Best for: New token launches, volatile pairs
  • Note: Integrated with OpenBook for limit order flow
Orca Whirlpool (Concentrated Liquidity)
  • Model: Concentrated liquidity with tick spacing
  • Fee tiers: 0.01%, 0.05%, 0.3%, 1%
  • Position: Represented as NFT (each position is unique)
  • Best for: Major pairs (SOL/USDC), stablecoin pairs
Raydium CLMM
  • Model: Concentrated liquidity (similar to Uniswap V3)
  • Tick spacing: 1, 10, 60, 200
  • Fee tiers: 0.01%, 0.05%, 0.25%, 1%
  • Best for: Pairs with predictable ranges
Meteora DLMM (Dynamic Liquidity Market Maker)
  • Model: Discrete bins instead of continuous ticks
  • Strategies: Spot (uniform), Curve (concentrated), Bid-Ask (around current price)
  • Fees: Dynamic, adjusting based on volatility
  • Best for: Active LPs who rebalance frequently

See references/pool_mechanics.md for detailed mechanics and comparison.


7. Practical Decision Framework

Should You LP?
1. Calculate expected fee APR
2. Estimate impermanent loss for expected price movement
3. Net return = fee APR - IL
4. Compare to simply holding the assets
Which Pool Type?
Stablecoin pair     → CLMM with tight range (±0.5%)
Major pair (SOL/USDC) → CLMM with moderate range (±10-25%)
New/volatile token  → Constant product (full range)
Active management   → Meteora DLMM with dynamic rebalancing
Position Sizing for LP
python
# Never LP more than you can afford to lose to IL
max_lp_allocation = portfolio_value * 0.20  # 20% max in any single pool

# For volatile pairs, reduce further
volatility_adjustment = 1 - (annualized_vol / 2)  # Scale down for vol
adjusted_allocation = max_lp_allocation * max(0.1, volatility_adjustment)

Files

References
  • references/amm_formulas.md — Complete mathematical derivations for constant product and concentrated liquidity AMMs
  • references/pool_mechanics.md — Solana-specific pool mechanics for Raydium, Orca, and Meteora
Scripts
  • scripts/amm_calculator.py — Constant product AMM calculator with trade simulation, LP shares, and fee accrual
  • scripts/clmm_calculator.py — Concentrated liquidity calculator with position valuation, capital efficiency, and range comparison

Quick Reference

FormulaExpression
Constant productx * y = k
Spot priceP = y / x
Trade outputΔy = y * Δx / (x + Δx)
Required inputΔx = x * Δy / (y - Δy)
Price impactΔx / (x + Δx)
Initial LP sharessqrt(x * y)
Subsequent sharesmin(Δx/x, Δy/y) * total
Fee APR(daily_fees * 365) / TVL
CLMM efficiencysqrt(P_u/P_l) / (sqrt(P_u/P_l) - 1)
Tick to price1.0001^tick

© agiprolabs, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 4 other files (scripts, references) in skills/lp-math of agiprolabs/claude-trading-skills.

  • SKILL.md
  • references/amm_formulas.md
  • references/pool_mechanics.md
  • scripts/amm_calculator.py
  • scripts/clmm_calculator.py

Open the folder on GitHubat commit 981e1d7

Compare with similar skills

Lp Math next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Lp Math compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Lp Math this skillagiprolabs/claude-trading-skills410—~2.5kAutomated safety check: PassMIT
Agentic Walletcoinbase/agentic-wallet-skills1273 repos~1kAutomated safety check: PassMIT
Minara Crypto Trading and WalletMinara-AI/minara-skills3581 repos~5.7kAutomated safety check: PassNone
Kleros IPFS Uploadinternet-court/internet-court-skill6.4k—~4.9kAutomated safety check: NotesMIT
Polymarket TradingBlockRunAI/ClawRouter6.6k—~1.4kAutomated safety check: PassMIT
Predexon Prediction Market DataBlockRunAI/ClawRouter6.6k—~4.7kAutomated safety check: PassMIT

Similar skills

  • Agentic Wallet

    coinbase/agentic-wallet-skills

    Crypto wallet operations via the awal CLI — sign in, check balances, send USDC/ETH/POL/SOL, trade tokens, fund the wallet, and use the x402 payment protocol to discover paid services, pay for API…

    127 GitHub starsUsed in 3 repos~1k tokens
    Backend & APIsAuto-check passed
  • Minara Crypto Trading and Wallet

    Minara-AI/minara-skills

    Drives the Minara CLI for crypto swaps, perps, limit orders, wallet transfers, deposits and withdrawals, plus AI market analysis.

    358 GitHub starsUsed in 1 repo~5.7k tokens
    Business, Finance & HRAuto-check passed
  • Kleros IPFS Upload

    internet-court/internet-court-skill

    Uploads one Kleros-related file per paid request to IPFS through the Kleros x402 gateway for 0.01 USDC on Base, returning a CID that Kleros contracts can reference.

    6.4k GitHub stars~4.9k tokensUpdated 1 mo ago
    Backend & APIsAuto-check: notes
  • Polymarket Trading

    BlockRunAI/ClawRouter

    A skill your agent uses when the user wants to actually PLACE, manage, or redeem bets on Polymarket (not just read odds — that's the blockrunpredexon data tools).

    6.6k GitHub stars~1.4k tokensUpdated 3 days ago
    Business, Finance & HRAuto-check passed
  • Predexon Prediction Market Data

    BlockRunAI/ClawRouter

    Reads structured prediction market data for Polymarket, Kalshi and other venues through a local BlockRun gateway: markets, search, leaderboards, wallet analytics and odds.

    6.6k GitHub stars~4.7k tokensUpdated 3 days ago
    Business, Finance & HRAuto-check passed
  • Payment

    second-state/payment-skill

    Request and receive payments. An agent skill from second-state/payment-skill.

    220 GitHub stars~1.5k tokensUpdated 7 mo ago
    Auto-check passed

More from agiprolabs/claude-trading-skills

All 68 skills in this repo
  • Backtrader

    agiprolabs/claude-trading-skills

    Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Birdeye API

    agiprolabs/claude-trading-skills

    Solana token market data via Birdeye — prices, OHLCV, trades, token metadata, security checks, and trader activity

    410 GitHub stars~1.8k tokensUpdated 1 mo ago
    Auto-check passed
  • Coingecko API

    agiprolabs/claude-trading-skills

    Broad crypto market data from CoinGecko covering 13,000+ tokens.

    410 GitHub stars~1.6k tokensUpdated 1 mo ago
    Auto-check passed
  • Cointegration Analysis

    agiprolabs/claude-trading-skills

    Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis

    410 GitHub stars~2.1k tokensUpdated 1 mo ago
    Auto-check passed
  • Copy Trading

    agiprolabs/claude-trading-skills

    Wallet evaluation, monitoring, and copy-trade strategy design for Solana DEX trading

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Correlation Analysis

    agiprolabs/claude-trading-skills

    Cross-asset correlation analysis including rolling correlation, hierarchical clustering, tail dependence, and regime-dependent correlation

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed

Works with

Questions about Lp Math

What does Lp Math do?

AMM liquidity provision mathematics including constant-product, concentrated liquidity, price impact, and LP share calculations. Lp Math is an agent skill from agiprolabs/claude-trading-skills.

How do I install Lp Math in Claude Code?

Run `npx skills add agiprolabs/claude-trading-skills --skill lp-math -a claude-code`. Or copy the skill folder (skills/lp-math in agiprolabs/claude-trading-skills) into .claude/skills/lp-math in your project. Claude Code loads it when a task matches its description.

How do I install Lp Math in Codex?

Run `npx skills add agiprolabs/claude-trading-skills --skill lp-math -a codex`. Or copy the skill folder (skills/lp-math in agiprolabs/claude-trading-skills) into .agents/skills/lp-math in your project. Codex loads it when a task matches its description.

Can I use Lp Math in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add agiprolabs/claude-trading-skills --skill lp-math -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/lp-math, .gemini/skills/lp-math, .github/skills/lp-math and .opencode/skills/lp-math in your project.

What does Lp Math need to run?

Going by SKILL.md and its folder, Lp Math needs Python for the scripts in its folder. Our summary lists: Python 3.

Does Lp Math access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Lp Math safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Lp Math use?

Lp Math is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Lp Math use?

About 2.5k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 3.2k tokens, read only when the agent opens those files.

What are the alternatives to Lp Math?

Skills that share tags, products or a category with Lp Math: Agentic Wallet (coinbase/agentic-wallet-skills, 127 stars), Minara Crypto Trading and Wallet (Minara-AI/minara-skills, 358 stars), Kleros IPFS Upload (internet-court/internet-court-skill, 6.4k stars) and Polymarket Trading (BlockRunAI/ClawRouter, 6.6k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Lp Math?

agiprolabs (a GitHub user) maintains it in agiprolabs/claude-trading-skills, which has 410 GitHub stars. The repository holds 68 skills in this directory. The repository was last updated on September 3, 2026.

Source: agiprolabs/claude-trading-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.