DEX Metrics - Measuring On-Chain Trading
Learning Objectives
Calculate DEX trading volume with appropriate filtering for wash trading and arbitrage
Measure order book depth at various price levels and interpret its significance
Analyze bid-ask spreads as indicators of market efficiency and liquidity
Track AMM metrics including TVL, pool utilization, and LP participation
Compare DEX performance against centralized exchanges and assess commercial viability
XRPL operates two simultaneous trading mechanisms:
XRPL TRADING ARCHITECTURE:
ORDER BOOK (Original):
├── Traditional limit order matching
├── Makers place orders, takers fill them
├── Price discovery through bid/ask
├── Since: 2012 (original feature)
└── Still majority of DEX activity
AUTOMATED MARKET MAKER (AMM):
├── Liquidity pool model
├── Price determined by constant product formula
├── LPs provide liquidity, earn fees
├── Since: 2023 (XLS-30 amendment)
└── Growing but smaller share
INTEGRATION:
├── Payment paths use both sources
├── Best execution across both
├── Competition improves pricing
└── Unique in crypto (most chains have one or other)
This dual system creates rich analytical opportunities—and complexity. You need to track both.
Why DEX metrics matter:
DEX HEALTH → NETWORK HEALTH:
Strong DEX:
├── Enables cross-currency payments
├── Supports issued token ecosystem
├── Provides on-chain price discovery
├── Indicates active trading community
└── Essential for commercial use cases
Weak DEX:
├── Limits payment path options
├── Discourages token issuers
├── Forces users to CEX
├── Signals weak utility
└── Concerning for adoption thesis
DEX volume calculation requires parsing OfferCreate transactions:
DEX VOLUME SOURCES:
ORDER BOOK VOLUME:
├── OfferCreate transactions that consume existing offers
├── TakerPays and TakerGets show amounts exchanged
├── Partial fills: Check metadata for actual execution
├── Unfilled orders: NOT volume (just order placement)
AMM VOLUME:
├── Payments routed through AMM pools
├── AMMDeposit/Withdraw: Liquidity changes, not trading volume
├── AMM-to-AMM swaps in payment paths
├── May be harder to isolate from total payment volume
CROSS-TYPE:
├── Some trades use both (path finds best price)
├── Attribution can be complex
├── Focus on total DEX volume, then break down if needed
Practical approach to volume measurement:
VOLUME CALCULATION STEPS:
STEP 1: IDENTIFY DEX TRANSACTIONS
├── OfferCreate with ConsumedOffer metadata
├── Payments that use DEX paths (cross-currency)
├── AMM operations
STEP 2: EXTRACT AMOUNTS
├── For OfferCreate: Look at AffectedNodes for fills
├── For Payments: delivered_amount shows final
├── Handle both XRP (drops) and issued currencies
STEP 3: CONVERT TO COMMON UNIT
├── Option A: XRP-denominated (sum XRP side of trades)
├── Option B: USD-equivalent (requires price data)
├── Option C: By trading pair (granular analysis)
STEP 4: FILTER
├── Exclude wash trading (same entity both sides)
├── Exclude dust trades (<threshold)
├── Exclude known bot-to-bot (where identifiable)
EXAMPLE OUTPUT:
├── Daily DEX volume: 5M XRP
├── USD equivalent: $2.5M (at $0.50)
├── Top pair: XRP/USD.Bitstamp (60%)
├── AMM contribution: 15%
Not all volume is equal:
VOLUME QUALITY TIERS:
HIGH QUALITY VOLUME:
├── Diverse trading pair activity
├── Distribution across many addresses
├── Consistent with market movements
├── Reasonable trade sizes
└── Indicates: Genuine market activity
MEDIUM QUALITY VOLUME:
├── Concentrated in arbitrage patterns
├── Few addresses dominating
├── Predictable, automated patterns
├── Still represents real trading
└── Indicates: Market making, arb activity
LOW QUALITY VOLUME:
├── Self-trading (wash trading)
├── Tiny amounts at high frequency
├── Single entity generating most volume
├── No economic purpose
└── Indicates: Artificial inflation
FILTERING APPROACH:
├── Address analysis: Same entity both sides?
├── Size analysis: Below economic minimum?
├── Pattern analysis: Repetitive non-economic patterns?
├── Time analysis: Concentrated bursts?
Pair-level analysis reveals market structure:
TRADING PAIR ANALYSIS:
MAJOR PAIRS (Typically):
├── XRP/USD (various issuers)
├── XRP/EUR
├── XRP/BTC
├── XRP/RLUSD (growing)
└── Usually 80%+ of volume
STABLECOIN PAIRS:
├── XRP/USDT, XRP/USDC (wrapped)
├── Growing with stablecoin adoption
├── Important for DeFi activity
TOKEN PAIRS:
├── Various issued tokens
├── Often thin liquidity
├── Concentrated activity
PAIR DISTRIBUTION HEALTH:
├── Healthy: Multiple active pairs
├── Concentrated: Single pair dominates (>90%)
├── Growing: New pairs gaining share
├── Declining: Fewer active pairs over time
Depth measures available liquidity at various price levels:
ORDER BOOK DEPTH CONCEPT:
DEPTH DEFINITION:
├── How much can be bought/sold at given price impact
├── Measured in XRP (or USD) at price levels
├── Deeper = More liquidity = Better execution
MEASUREMENT LEVELS:
├── Depth at 0.5%: Within 0.5% of mid price
├── Depth at 1%: Within 1% of mid price
├── Depth at 2%: Within 2% of mid price
├── Depth at 5%: Within 5% of mid price
EXAMPLE:
├── Current mid price: $0.50
├── Depth at 1%: $50,000
├── Meaning: $50K can be traded with <1% slippage
├── Depth at 5%: $200,000
├── Meaning: $200K can be traded with <5% slippage
Practical depth measurement:
DEPTH CALCULATION:
DATA SOURCE:
├── book_offers API command
├── Returns current order book state
├── Need both bid and ask sides
1. Get mid price: (best bid + best ask) / 2
2. Define price levels: mid ± 0.5%, 1%, 2%, 5%
3. Sum order sizes within each level
4. Report: "Depth at X% = Y XRP (or $Z)"
EXAMPLE CODE CONCEPT:
async function getOrderBookDepth(pair) {
const book = await client.request({
command: 'book_offers',
taker_gets: { currency: 'XRP' },
taker_pays: { currency: 'USD', issuer: issuer },
limit: 500
});
// Calculate mid price from best bid/ask
// Sum orders within percentage bands
// Return depth at each level
}
What depth levels mean for different users:
DEPTH ADEQUACY BY USE CASE:
RETAIL TRADING ($100-$10,000):
├── Depth at 1%: $10,000+ sufficient
├── XRPL typically adequate
├── Small traders rarely face slippage issues
ACTIVE TRADING ($10,000-$100,000):
├── Depth at 1%: $50,000+ preferred
├── XRPL marginally adequate for major pairs
├── May need to split larger orders
INSTITUTIONAL ($100,000+):
├── Depth at 1%: $500,000+ needed
├── XRPL DEX typically inadequate
├── Institutions use CEX or OTC
└── This is a DEX limitation
ODL REQUIREMENTS:
├── Depth at <0.5%: Very high requirements
├── Uses specialized market makers
├── Not reflected in public order book depth
├── Separate liquidity infrastructure
Tracking depth trends:
DEPTH TREND ANALYSIS:
HISTORICAL TRACKING:
├── Snapshot depth at regular intervals (hourly, daily)
├── Track average depth over periods
├── Compare across market conditions
WHAT AFFECTS DEPTH:
├── Market volatility (depth withdraws during volatility)
├── XRP price (USD depth changes with XRP price)
├── Market maker participation
├── AMM TVL (adds to effective depth)
HEALTHY TRENDS:
├── Depth growing over time
├── Stable through volatility
├── Multiple price levels populated
├── Recovering quickly after large trades
CONCERNING TRENDS:
├── Depth declining
├── Large gaps appearing
├── Single market maker dominance
├── Slow recovery after fills
The bid-ask spread indicates market efficiency:
SPREAD FUNDAMENTALS:
DEFINITION:
├── Spread = Ask price - Bid price
├── Percentage spread = (Ask - Bid) / Mid × 100%
WHAT SPREAD REPRESENTS:
├── Cost of immediate execution
├── Market maker profit margin
├── Compensation for providing liquidity
├── Indicator of market efficiency
EXAMPLE:
├── Best bid: $0.499
├── Best ask: $0.501
├── Spread: $0.002
├── Percentage: 0.4%
├── To buy and immediately sell: Lose 0.4%
What spread levels indicate:
SPREAD INTERPRETATION:
TIGHT SPREADS (<0.3%):
├── Very efficient market
├── High competition among market makers
├── Suitable for frequent trading
├── Typical for: Major CEX pairs
MODERATE SPREADS (0.3-1.0%):
├── Functional market
├── Reasonable for most purposes
├── Some market maker presence
├── Typical for: XRPL major pairs
WIDE SPREADS (1.0-3.0%):
├── Less efficient market
├── Higher trading costs
├── Limited market maker activity
├── Typical for: XRPL minor pairs
VERY WIDE SPREADS (>3.0%):
├── Illiquid market
├── Challenging for trading
├── May indicate stale orders
├── Typical for: Exotic tokens
XRPL TYPICAL SPREADS:
├── XRP/USD: 0.5-1.5%
├── XRP/EUR: 0.5-2.0%
├── XRP/token: 1.0-5.0%+
├── (Varies significantly by pair and time)
How spreads change:
SPREAD DYNAMICS:
SPREADS WIDEN WHEN:
├── Volatility increases (risk compensation)
├── Volume drops (fewer market makers)
├── News/uncertainty (information asymmetry)
├── After large trades (inventory rebalancing)
SPREADS TIGHTEN WHEN:
├── Volatility decreases
├── Competition increases
├── Volume increases
├── Market confidence high
TRACKING SPREAD CHANGES:
├── Calculate average spread (hourly, daily)
├── Note spread during volatility events
├── Compare to historical patterns
├── Identify structural changes
Context for XRPL DEX spreads:
DEX VS CEX SPREADS:
CENTRALIZED EXCHANGE (e.g., Binance XRP/USD):
├── Typical spread: 0.05-0.1%
├── Very deep liquidity
├── Professional market makers
├── High competition
XRPL DEX (XRP/USD.Bitstamp):
├── Typical spread: 0.5-2.0%
├── Moderate liquidity
├── Fewer market makers
├── Less competition
WHY DEX SPREADS ARE WIDER:
├── Fewer market makers
├── Less volume = less competition
├── No rebate programs
├── No high-frequency trading infrastructure
├── Different user base
IMPLICATIONS:
├── Retail small trades: DEX acceptable
├── Frequent trading: CEX preferred
├── Arbitrage: Keeps DEX/CEX linked
├── Commercial use: Depends on requirements
Understanding XRPL's AMM system:
XRPL AMM OVERVIEW:
STRUCTURE:
├── Constant product formula (x * y = k)
├── Each pool: Two assets (e.g., XRP/USD)
├── LPs deposit both assets, receive LP tokens
├── Trading fees: Set by LP vote (0.0-1.0%)
KEY METRICS:
├── TVL: Total value locked in pools
├── Pool count: Number of active pools
├── LP count: Unique liquidity providers
├── Volume: Trading through AMM paths
XRPL AMM UNIQUE FEATURES:
├── Integrates with order book paths
├── Auction slot mechanism
├── Multi-asset pools possible
├── Native token LP tokens
The primary AMM health metric:
TVL MEASUREMENT:
DEFINITION:
├── Sum of all assets in AMM pools
├── Usually in USD equivalent
├── Represents capital committed to liquidity
CALCULATION:
├── Query all AMM objects
├── Sum asset values in each pool
├── Convert to USD equivalent
XRPL TVL CONTEXT:
├── Current range: $10M-$50M (varies)
├── Small vs Ethereum DeFi ($50B+)
├── Growing from 2023 launch
├── Concentrated in major pools
TVL INTERPRETATION:
├── Higher TVL = More liquidity available
├── Growing TVL = Increasing confidence
├── TVL/Volume ratio = Capital efficiency
├── TVL distribution = Ecosystem breadth
Individual pool metrics:
POOL METRICS:
PER-POOL DATA:
├── Asset composition (e.g., 1M XRP + $500K USD)
├── Current trading fee rate
├── LP token outstanding
├── Recent volume through pool
├── Fee generation
POOL HEALTH INDICATORS:
├── Balanced composition (assets near equal USD value)
├── Active trading (volume > 0)
├── Multiple LPs (not single-LP dominated)
├── Reasonable fee (competitive with alternatives)
TOP POOLS (Typically):
├── XRP/USD stablecoins
├── XRP/RLUSD (growing)
├── Major token pairs
├── (Specific pools change over time)
Liquidity provider analysis:
LP METRICS:
LP COUNT:
├── Unique addresses providing liquidity
├── More LPs = More distributed
├── Single LP = Concentration risk
LP CONCENTRATION:
├── Top 10 LP share of pool
├── <50% = Healthy distribution
├── >80% = Concentration concern
LP RETURNS:
├── Trading fee accumulation
├── Impermanent loss consideration
├── Net LP profitability (difficult to measure)
LP BEHAVIOR:
├── New LPs joining = Confidence
├── LPs withdrawing = Concern
├── LP token price = Pool health signal
Comparing the two systems:
AMM VS ORDER BOOK COMPARISON:
CURRENT DISTRIBUTION (Approximate):
├── Order book: 70-85% of DEX volume
├── AMM: 15-30% of DEX volume
├── Varies by pair and market conditions
ORDER BOOK ADVANTAGES:
├── Better price for larger trades
├── Price discovery
├── No impermanent loss
├── Established infrastructure
AMM ADVANTAGES:
├── Always available liquidity
├── Simple LP participation
├── Passive income potential
├── No order management needed
TREND TO WATCH:
├── AMM share growing or stable?
├── New pools launching?
├── LP participation expanding?
├── Integration improving?
How trades affect prices:
PRICE IMPACT MEASUREMENT:
DEFINITION:
├── Price change caused by a trade
├── Larger trades = Larger impact
├── Key metric for execution quality
CALCULATION:
├── Simulate trade of size X
├── Calculate execution price
├── Compare to current mid price
├── Impact = (Execution - Mid) / Mid × 100%
EXAMPLE:
├── Mid price: $0.50
├── $10K buy executes at: $0.502
├── Impact: 0.4%
├── $100K buy executes at: $0.515
├── Impact: 3.0%
INTERPRETATION:
├── Low impact (<0.5%): Good liquidity
├── Moderate impact (0.5-2%): Acceptable
├── High impact (>2%): Challenging market
├── Very high (>5%): Illiquid, use caution
How well DEX tracks broader market:
PRICE CORRELATION:
MEASUREMENT:
├── Compare DEX price to CEX (e.g., Binance)
├── Calculate difference (DEX vs CEX)
├── Track over time
HEALTHY CORRELATION:
├── Price difference <0.5% most times
├── Arbitrage quickly closes gaps
├── Both markets track together
CONCERNING PATTERNS:
├── Persistent price differences (>1%)
├── Slow arbitrage correction
├── DEX lagging major moves
├── Sign of: Low arbitrage activity
WHY IT MATTERS:
├── Price accuracy for users
├── Fair value execution
├── Confidence in DEX pricing
├── Arbitrage = Market efficiency
Is DEX adequate for business use?
COMMERCIAL REQUIREMENTS:
FOR RETAIL PAYMENTS:
├── Spread: <2% acceptable
├── Depth: $10K+ sufficient
├── Speed: Seconds OK
├── XRPL DEX: Generally adequate
FOR COMMERCIAL REMITTANCE:
├── Spread: <1% needed
├── Depth: $100K+ needed
├── Speed: Seconds required
├── XRPL DEX: Marginal/inadequate
FOR INSTITUTIONAL:
├── Spread: <0.3% expected
├── Depth: $1M+ required
├── Speed: Milliseconds preferred
├── XRPL DEX: Inadequate (use CEX)
CONCLUSION:
├── DEX serves retail well
├── Commercial requires CEX or special arrangements
├── ODL uses private market makers
├── Not a DEX failure—different use cases
Essential DEX tracking:
DEX MONITORING DASHBOARD:
DAILY TRACKING:
├── Total DEX volume (XRP and USD)
├── AMM TVL change
├── Average spread (major pairs)
├── Notable large trades
WEEKLY TRACKING:
├── Volume by pair breakdown
├── AMM vs order book share
├── Depth at 2% (snapshot)
├── New pool launches
├── LP count changes
MONTHLY TRACKING:
├── Volume trend analysis
├── TVL growth trajectory
├── Spread trend analysis
├── DEX/CEX correlation quality
├── Commercial viability assessment
DATA SOURCES:
├── Order book: book_offers API
├── AMM: AMM ledger objects
├── Volume: Transaction analysis or explorers
├── External: CEX prices for comparison
What to watch for:
DEX ALERT THRESHOLDS:
VOLUME ALERTS:
├── Daily volume <50% of 30-day avg → Investigate
├── Single address >30% of volume → Wash trading?
├── Volume spike without price move → Artificial?
LIQUIDITY ALERTS:
├── Depth drops >50% suddenly → Market maker exit?
├── Spread widens >2x normal → Volatility or problem?
├── AMM TVL drops >20% week → LP confidence issue?
STRUCTURE ALERTS:
├── Single pair >95% of volume → Concentration risk
├── DEX/CEX divergence >2% persistent → Arb failure?
├── LP count declining → Participation concern
RESPONSE:
├── Investigate cause before concluding
├── Check market conditions (volatility?)
├── Check news/events
├── Document and continue monitoring
✅ XRPL DEX provides functional on-chain trading for major pairs
✅ AMM integration (since 2023) adds liquidity and path options
✅ DEX metrics can be reliably measured from on-chain data
✅ DEX adequately serves retail trading needs
⚠️ Optimal spread and depth thresholds for "healthy" DEX are somewhat arbitrary
⚠️ AMM still early-stage; long-term contribution unclear
⚠️ Wash trading extent difficult to quantify precisely
⚠️ Commercial viability depends on specific use case requirements
📌 Comparing XRPL DEX to ETH DEXs without accounting for purpose differences
📌 Using unfiltered DEX volume as adoption metric
📌 Assuming DEX inadequacy means network failure (different use cases)
📌 Ignoring spread and depth in favor of volume-only analysis
XRPL's DEX is a functional, mature trading system adequate for retail use cases. It's not competing with Uniswap for DeFi dominance—nor should it be. The dual order book/AMM system is unique and provides real value. Metrics should assess whether the DEX serves its purpose (on-chain exchange, payment paths, token trading) rather than whether it matches systems designed for different purposes.
Assignment: Conduct comprehensive analysis of XRPL DEX health across order book and AMM systems.
Requirements:
Part 1: Volume Analysis (25%)
- Calculate total DEX volume for 30-day period
- Break down by trading pair (top 5-10 pairs)
- Estimate AMM vs order book share
- Apply quality filters and note estimated wash trading
- Compare to historical periods
Part 2: Liquidity Analysis (30%)
- Measure current depth at 0.5%, 1%, 2%, 5% for XRP/USD
- Repeat for at least 2 other major pairs
- Calculate current bid-ask spreads
- Document AMM TVL and pool composition (top 5 pools)
- Assess adequacy for retail, commercial, institutional use cases
Part 3: Market Quality Assessment (25%)
- Calculate price impact for $10K, $50K, $100K trades
- Measure DEX/CEX price correlation (compare to Binance or similar)
- Identify any quality concerns (stale orders, gaps, etc.)
- Compare spreads to historical averages
Part 4: Trend Analysis and Conclusions (20%)
Assess DEX volume trend (growing, stable, declining)
Assess liquidity trend (depth and spread evolution)
Assess AMM growth trajectory
Overall DEX health assessment
Recommendations for monitoring going forward
Volume analysis accuracy (20%)
Liquidity measurement rigor (25%)
Market quality assessment depth (20%)
Trend analysis quality (20%)
Documentation and conclusions (15%)
Time investment: 4-5 hours
Value: DEX health is a key Liquidity Pillar indicator. This analysis becomes your framework for ongoing DEX monitoring.
1. Volume Quality:
DEX shows 10M XRP daily volume, but 70% comes from three addresses trading with each other. How should you report this?
A) Report 10M XRP volume—the transactions are real
B) Report 3M XRP volume after excluding wash trading
C) Report both figures with explanation of methodology
D) Discard the data entirely as unreliable
Correct Answer: C
Explanation: Intellectual honesty requires acknowledging both the raw data and its limitations. Report total volume (10M) while noting that significant portion appears to be wash trading, with filtered volume (~3M) better representing genuine market activity. A misleads by ignoring quality issues. B is useful but loses information. D throws away valid data unnecessarily.
2. Depth Interpretation:
XRP/USD shows $75,000 depth at 2% on XRPL DEX versus $5M on Binance. What is the MOST appropriate conclusion?
A) XRPL DEX is failing—depth should match major exchanges
B) XRPL DEX serves different use cases; retail trades execute fine, institutional need CEX
C) The metrics are not comparable because one is decentralized
D) XRPL needs 100x more liquidity to be useful
Correct Answer: B
Explanation: DEX and CEX serve different purposes and user bases. $75K depth adequately serves retail trades (under $10K). Institutional traders using CEX is expected and appropriate. A applies inappropriate benchmarks. C dismisses valid comparison unnecessarily. D overstates requirements for DEX's actual use case.
3. AMM Metrics:
AMM TVL grows from $15M to $25M over 3 months while LP count stays flat at 800. What does this indicate?
A) Healthy growth—more capital committed to liquidity
B) Concerning concentration—existing LPs adding more, no new participants
C) AMM is failing because LP count isn't growing
D) The metrics are contradictory and data should be verified
Correct Answer: B
Explanation: TVL growth with flat LP count means existing LPs are increasing positions rather than new participants joining. This is growth but with concentration concern—fewer LPs bearing more of the risk. Ideally both metrics would grow. A ignores concentration dynamic. C overstates concern. D misreads valid pattern.
4. Spread Analysis:
Major pair spread is 0.8% on XRPL DEX versus 0.08% on Binance. For a user trading $500 worth of XRP, which statement is MOST accurate?
A) The user should avoid XRPL DEX entirely due to 10x wider spread
B) The $4 difference ($4 vs $0.40) matters but may be acceptable for the convenience of on-chain trading
C) Spreads are irrelevant for small trades
D) The user should always use the lowest spread option
Correct Answer: B
Explanation: On a $500 trade, 0.8% spread costs ~$4 versus ~$0.40 on Binance. The $3.60 difference is meaningful but not prohibitive—users may prefer on-chain trading for other reasons (no account, self-custody, speed). A is too absolute. C dismisses real cost. D ignores other factors in trading venue choice.
5. Commercial Viability:
A remittance company wants to use XRPL DEX for $50K daily transfers. Current DEX shows 1.2% spread and $80K depth at 2%. Is this viable?
A) Yes—depth exceeds daily volume needs
B) No—1.2% spread is too costly for commercial operations
C) Marginal—spread creates significant cost; may need special arrangements or use ODL infrastructure
D) Cannot assess without knowing the currency corridor
Correct Answer: C
Explanation: $50K daily with 1.2% spread creates ~$600/day trading cost—significant for commercial operations. Depth is barely adequate ($80K for $50K trades risks moving the market). Commercial viability is marginal; ODL typically uses dedicated market makers rather than public DEX for this reason. A ignores spread cost. B is too definitive without context. D adds complexity but the core assessment is possible.
- XRPL.org DEX documentation
- XLS-30 AMM amendment specification
- XRPScan DEX statistics
- XRPL Services trading data
- Direct API: book_offers, amm_info commands
- CEX APIs for spread/depth comparison
- DeFi Llama for cross-chain TVL context
For Next Lesson:
Lesson 9 examines Fee Economics—how XRPL's fee structure works, what fee patterns reveal about network usage, and the economics of the validator system.
End of Lesson 8
Total words: ~6,700
Estimated completion time: 55 minutes reading + 4-5 hours for deliverable
Key Takeaways
Volume requires quality filtering
: Raw DEX volume includes wash trading and arbitrage. Filter by address patterns and trade economics before drawing conclusions.
Depth matters more than volume for usability
: A DEX can have high volume but thin depth (many small trades). Depth at 1-2% determines practical trading capacity.
Spreads indicate market efficiency
: XRPL DEX spreads (0.5-2%) are wider than CEX but acceptable for most use cases. Track spread trends for market health.
AMM adds dimension to analysis
: Since 2023, TVL and LP metrics provide additional liquidity health indicators. Track AMM share growth and LP participation.
Commercial viability has specific requirements
: Retail use cases are well-served. Institutional requirements exceed current DEX capacity—this is expected and OK. ---