🔬 The Swap Lab
Our swap lab is designed so you can learn how to use professional tools without any risk! Customize your rules and watch your investment progress!
Laboratory Tools
The Laboratory is where theoretical knowledge meets practical experimentation. Each tool serves a specific purpose in helping you understand, test, and optimize DeFi strategies without risking real capital.

AMM Sandbox
What AMM stands for: Automated Market Maker - the algorithm that powers decentralized exchanges.
What the AMM Sandbox is: An interactive simulation environment where you can manipulate liquidity pools, execute trades, and observe how prices change according to the constant product formula.
The constant product formula:
x × y = k
Where:
x = amount of token A in pool
y = amount of token B in pool
k = constant (doesn't change)
How to use the AMM Sandbox:
Access: Navigate to Laboratory → AMM Sandbox
Initialize pool:
Token A: Select first token (e.g., ETH)
Token A Amount: Set initial liquidity (e.g., 100 ETH)
Token B: Select second token (e.g., USDC)
Token B Amount: Set initial liquidity (e.g., 200,000 USDC)
Initial k: 100 × 200,000 = 20,000,000
Execute simulated trades:
Buy Token A: Enter amount of B to spend
Watch how A reserves decrease, B reserves increase
Observe price change
See how k remains constant

Analyze results:
Price impact percentage
New pool ratio
Slippage calculation
Arbitrage opportunities
Practical experiments:
Experiment 1: Understanding price impact
Initial pool: 100 ETH / 200,000 USDC (price = $2000/ETH)
Trade: Buy 10 ETH
Calculation:
New ETH amount: 100 - 10 = 90 ETH
k must stay 20,000,000
New USDC amount: 20,000,000 / 90 = 222,222 USDC
USDC spent: 222,222 - 200,000 = 22,222 USDC
Effective price: 22,222 / 10 = $2,222/ETH
Price impact: 11.1%
Learning: Larger trades relative to pool size = higher price impact
Experiment 2: Liquidity depth matters
Pool A: 100 ETH / 200,000 USDC
Pool B: 1000 ETH / 2,000,000 USDC
Same trade: Buy 10 ETH in both pools
Pool A: 11.1% price impact
Pool B: ~1% price impact
Learning: Deeper liquidity = less slippage
Experiment 3: Arbitrage opportunities
External market: ETH = $2000
AMM pool: ETH = $2100 (too expensive)
Arbitrage action: Sell ETH to pool for profit
Pool price drops toward $2000
Learning: Arbitrageurs keep prices aligned

Real-world application:
Before large trades, check liquidity depth
Split large orders across multiple pools
Use aggregators like 1inch that split orders automatically
Understand your effective execution price
Why this matters:
AMMs are THE innovation that makes DeFi possible
Understanding this mechanism is fundamental to all DEX trading
Helps you predict price impact before trading
Essential for LP profitability analysis

Strategy Builder
What it is: An advanced tool for designing, backtesting, and optimizing DeFi trading strategies without coding.
Components of a strategy:
Entry conditions:
Price crosses above/below moving average
RSI oversold/overbought
Volume spike
Time-based (e.g., Monday mornings)
Exit conditions:
Take profit at X% gain
Stop loss at Y% loss
Time-based exit
Indicator-based exit
Position sizing:
Fixed amount
Percentage of portfolio
Kelly Criterion
Risk-adjusted sizing

How to build a strategy:
Navigate to Laboratory → Strategy Builder
Define strategy parameters:
Basic Strategy Example: Mean Reversion
Asset: ETH/USDC
Timeframe: 1 hour
Entry Rule: Price is 5% below 20-period moving average
Exit Rule 1: Price returns to moving average (take profit)
Exit Rule 2: Price drops 10% from entry (stop loss)
Position Size: 10% of portfolio per trade
Backtest:
Historical Period: Select date range (e.g., last 6 months)
Initial Capital: Set starting amount ($10,000)
Run Backtest: Click button
Analyze results:
Total Return: +45%
Number of Trades: 23
Win Rate: 65%
Average Win: +8%
Average Loss: -4%
Max Drawdown: -15%
Sharpe Ratio: 1.8
Profit Factor: 2.2
Advanced strategies to test:

Momentum Strategy:
Entry:
- 50-day MA crosses above 200-day MA (Golden Cross)
- Volume is 2x above average
- RSI > 50
Exit:
- 50-day MA crosses below 200-day MA
- OR 15% stop loss
- OR 40% take profit
Position Size: 25% of portfolio
Grid Trading:
Setup:
- Define price range: $1800 - $2200
- Place 10 buy orders every $40 below current price
- Place 10 sell orders every $40 above current price
- Each order: 1% of portfolio
Rebalance:
- When buy order fills, place sell order above it
- When sell order fills, place buy order below it
Profit:
- Capture volatility in ranging markets
Dollar Cost Averaging (DCA):
Entry:
- Buy fixed amount every week
- Regardless of price
Exit:
- Hold for long term
- Only sell when target reached (e.g., 2x)
Benefits:
- Removes emotion
- Averages entry price
- Works in bull markets
Performance metrics explained:
Sharpe Ratio:
Measures risk-adjusted returns
Formula: (Return - Risk-free rate) / Standard Deviation
1.0 is good
2.0 is excellent
3.0 is exceptional
Max Drawdown:
Largest peak-to-trough decline
Measures worst-case scenario
20% drawdown = you must gain 25% to recover
Keep below 30% for sustainability
Profit Factor:
Gross profits / Gross losses
1.5 is acceptable
2.0 is good
Shows if winners outweigh losers
Win Rate:
Percentage of profitable trades
Can be profitable with 40% win rate if wins are large
High win rate doesn't guarantee profitability
Real-world application:
Quantitative traders use similar tools (QuantConnect, TradingView Pine Script)
Hedge funds backtest strategies extensively before deploying capital
Retail traders can use TradingView strategy tester
Never trust a strategy without proper backtesting
Limitations to understand:
Past performance ≠ future results
Backtesting can be curve-fit (over-optimized)
Doesn't account for slippage, fees, or emotional factors
Market conditions change (regime changes)

Liquidation Simulator
What it is: A tool for understanding and preparing for liquidation scenarios in leveraged positions.
Why liquidations happen: When you borrow funds for leverage, lenders need protection. If your collateral value drops below borrowed amount, the system liquidates your position to protect lenders.
The liquidation process:
Initial state:
Collateral: $10,000 ETH
Borrowed: $50,000 USDC
Leverage: 5x
Health Factor: 2.0 (safe)
Price drops:
ETH drops 30%
Collateral now: $7,000
Borrowed still: $50,000
Health Factor: 1.4 (warning)
Liquidation triggered:
ETH drops 40%
Collateral now: $6,000
Health Factor: 1.2 → Below 1.3 threshold
LIQUIDATED
Liquidation execution:
Protocol sells your $6,000 worth of ETH
Repays $50,000 debt (underwater position)
Liquidation penalty: ~5-10%
You lose everything

How to use the Liquidation Simulator:
Navigate to Laboratory → Liquidation Simulator
Enter position parameters:
Collateral Amount: $10,000
Collateral Asset: ETH (current price $2000)
Borrowed Amount: $40,000
Leverage: 5x
Liquidation Threshold: 130% (platform dependent)
Run simulation:
Scenario 1: ETH drops 10%
New collateral value: $9,000
Health factor: 1.4
Status: Safe
Scenario 2: ETH drops 20%
New collateral value: $8,000
Health factor: 1.25
Status: LIQUIDATION RISK
Scenario 3: ETH drops 25%
New collateral value: $7,500
Health factor: 1.15
Status: LIQUIDATED
Analyze results:
Liquidation price calculated
Safe zone identified
Recommended actions displayed

Liquidation price calculation:
Formula:
Liquidation Price = Entry Price × (1 - (1/Leverage) × Safety Margin)
Example:
Entry: ETH at $2000
Leverage: 5x
Liquidation threshold: 1.3 (130%)
Liquidation price = $2000 × (1 - (1/5) × 0.3) = $2000 × 0.94 = $1,880
This means a 6% drop liquidates your position with 5x leverage
Strategies to avoid liquidation:
1. Use lower leverage:
2x leverage = 50% drop needed for liquidation
5x leverage = 20% drop liquidates
10x leverage = 10% drop liquidates
2. Maintain collateral buffer:
Don't max out your borrowing power
Keep health factor above 2.0
Leave room for volatility
3. Set up alerts:
Alert at health factor 1.8
Alert at health factor 1.5
Alert at 10% from liquidation price
4. Have capital ready:
Keep stablecoins available
Add collateral if position weakens
Don't lock all capital in positions
5. Use stop losses:
Set stop loss before liquidation point
Better to close with small loss than full liquidation
Example: 5% stop loss vs 20% liquidation loss
Real-world liquidation examples:
Black Thursday (March 2020):
ETH dropped 50% in one day
$8M in liquidations on MakerDAO
Gas fees spiked to 400+ gwei
Some positions couldn't add collateral due to network congestion
May 2021 Crash:
$10B in liquidations across all exchanges
Bitcoin dropped from $60k to $30k
Cascading liquidations (one liquidation triggers others)
Terra/LUNA Collapse (May 2022):
$300M+ in liquidations
Liquidation spirals accelerated collapse
Some users lost millions
Real-world platforms and their liquidation parameters:
Aave:
Liquidation threshold: 80-85% (varies by asset)
Liquidation penalty: 5-10%
Health factor calculation includes all assets
MakerDAO:
Collateralization ratio: 150% minimum
Liquidation penalty: 13%
Auction system for liquidated collateral
Compound:
Liquidation threshold: varies (typically 75%)
Liquidation incentive: 8%
Anyone can liquidate underwater positions
dYdX:
Initial margin: 10% (10x leverage)
Maintenance margin: 7.5%
Automatic liquidation by protocol

MEV Calculator
What MEV stands for: Maximal Extractable Value (formerly Miner Extractable Value) - profit that can be extracted from manipulating transaction order in a block.
What it is: MEV is the invisible tax on DeFi transactions. Bots scan pending transactions (mempool), identify profitable opportunities, and front-run, back-run, or sandwich your trades.
Types of MEV:
1. Front-running:
Bot sees your large buy order in mempool
Bot submits same trade with higher gas fee
Bot's transaction executes first
Price increases
Your trade executes at worse price
Bot sells to you at inflated price
2. Back-running:
Bot sees your trade that will impact price
Bot submits transaction after yours
Takes advantage of price change you created
Example: You buy, price rises, bot sells
3. Sandwich attack:
Bot sees your trade
Bot front-runs (buys before you)
Your trade executes (pushes price up)
Bot back-runs (sells to you at high price)
You get worst possible price
Bot profits from both sides
4. Liquidation MEV:
Bots monitor leveraged positions
Detect positions near liquidation
Trigger liquidations for bounty/profit
5. Arbitrage MEV:
Price differences between DEXs
Bots execute simultaneous trades
Profit from price discrepancy

How to use the MEV Calculator:
Navigate to Laboratory → MEV Calculator
Input your trade details:
Token Pair: ETH/USDC
Trade Type: Buy
Amount: 10 ETH
Expected Price: $2000
Slippage Tolerance: 1%
Gas Price: Current network rate
Priority Fee: Additional tip for faster inclusion
Calculate MEV exposure:
Visibility Window: Time in mempool (typically 10-15 seconds)
MEV Bot Activity: Current network activity level
Potential Loss: Estimated sandwich attack impact
Results:
MEV Risk Score: High/Medium/Low
Estimated MEV Loss: $127 (1.27% of trade)
Protection Recommendations: Use Flashbots, set tighter slippage, split order
Simulate protection methods:
Without protection: Expected loss $127
With Flashbots Protect: Expected loss $0
With tighter slippage (0.3%): Expected loss $40
Split into 5 orders: Expected loss $30
Understanding the calculations:
Sandwich attack math: Assume your trade:
Buy 10 ETH for USDC
Pool has 1000 ETH / 2M USDC
Your expected price: $2000
Bot's attack:
Bot front-runs: Buys 5 ETH
Takes price from $2000 to $2050
Your trade executes: Buy 10 ETH
You pay higher price: ~$2075 average
Price goes to $2100
Bot back-runs: Sells 5 ETH
Sells at ~$2090
Profit: $200 (5 ETH × $40 difference)
Your loss:
Expected to pay: $20,000
Actually paid: $20,750
MEV loss: $750
Factors affecting MEV:
Trade size:
Larger trades = more MEV opportunity
$1M trade might lose 2-5% to MEV
$1000 trade might lose 0.1%
Pool liquidity:
Low liquidity pools = more MEV vulnerability
High liquidity = less price impact = less MEV
Network congestion:
High gas prices = more mempool time
More time = more MEV opportunity
Token volatility:
Volatile tokens = more arbitrage opportunities
Stable pairs = less MEV
Protection strategies:
1. Use MEV-protected RPCs:
Flashbots Protect: Transactions sent directly to miners
Bypass mempool entirely
No front-running possible
Same gas cost
2. Private transactions:
Submit to private mempools
Miners include directly
Services: Flashbots, Eden Network, BloXroute
3. Tighter slippage:
Set 0.1-0.3% slippage
Sandwich attack reverts if slippage exceeded
Risk: transaction may fail if price moves
4. Split large orders:
Instead of one 100 ETH trade
Execute ten 10 ETH trades
Reduces price impact
Spreads over time
5. Use DEX aggregators:
1inch, Matcha, Cowswap
Split orders across multiple pools
Reduces price impact per pool
6. CoW Swap (Coincidence of Wants):
Matches orders peer-to-peer first
Only uses AMM if no match
Gasless orders
MEV protection built-in

Real-world MEV statistics:
MEV extracted (all-time):
Over $680M extracted from Ethereum users
$40M+ extracted in May 2021 alone
Average user loses 0.5-1% of trade value
By strategy type:
Sandwich attacks: ~$300M
Arbitrage: ~$250M
Liquidations: ~$130M
Who extracts MEV:
Searchers: Bots scanning for opportunities
Block builders: Construct optimal blocks
Validators: Earn tips for including MEV bundles
Post-merge MEV landscape:
MEV boost: 90%+ of validators use it
Block builders specialize in MEV extraction
More sophisticated strategies emerging
Real tools for MEV protection:
Flashbots Protect RPC: Free, easy to add to MetaMask
Cow Swap: Gasless trades with MEV protection
1inch Fusion: RFQ system bypasses AMMs
Bloackroute: Enterprise-level MEV protection
Last updated