Theme:

DEX Monitor WebSocket APIs Documentation

```markdown

DEX Monitor WebSocket APIs

Complete documentation for all WebSocket endpoints in the DEX Monitor service.


1. Live Trades Feed

Full Endpoint Address

ws://your-domain.com/tzone_apis/services/dex-monitor/ws/live-trades

Purpose

Provides real-time stream of DEX pool trades with human-readable token names, DEX information, and pool metadata from CoinGecko OnChain API. Filters trades by minimum volume and returns most recent transactions first.

How to Use It

  1. Connect to WebSocket with query parameters
  2. Specify min_volume, limit, network, and interval
  3. Server pushes new trade data at specified interval
  4. Client receives real-time trade updates
  5. Connection remains open for continuous streaming

Upstream Params

| Parameter | Type | Default | Range | Description | |-----------|------|---------|-------|-------------| | min_volume | float | 1000.0 | ≥ 0 | Minimum trade volume in USD to filter | | limit | int | 50 | 1-100 | Number of trades to return per update | | interval | float | 15.0 | ≥ 5.0 | Push interval in seconds (minimum 5s) | | network | string | "eth" | eth, polygon, arbitrum, optimism, base, bsc, avalanche, fantom | Blockchain network to monitor |

Client-side Filters/Search/Sort/Pagination

No client-side filtering available - All filtering done server-side via query parameters

Sorting: Automatically sorted by block_timestamp (most recent first)

Pagination: Not applicable (streaming feed, use limit to control batch size)

Example Request to Trigger the API

JavaScript/TypeScript: ```typescript const ws = new WebSocket( 'ws://localhost:8000/tzone_apis/services/dex-monitor/ws/live-trades' + '?min_volume=5000' + '&limit=50' + '&network=eth' + '&interval=15' );

ws.onopen = () => { console.log('✅ Connected to live trades feed'); };

ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log('📊 Live trades update:', data); // Update UI with new trades };

ws.onerror = (error) => { console.error('❌ WebSocket error:', error); };

ws.onclose = () => { console.log('🔌 Disconnected from live trades feed'); }; ```

Python: ```python import asyncio import websockets import json

async def connect_live_trades(): uri = ( "ws://localhost:8000/tzone_apis/services/dex-monitor/ws/live-trades" "?min_volume=5000&limit=50&network=eth&interval=15" ) async with websockets.connect(uri) as websocket: while True: data = await websocket.recv() trades = json.loads(data) print(f"📊 Received {len(trades['rows'])} trades") for trade in trades['rows']: print(f" {trade['token_pair']}: ${trade['volume_in_usd']}")

asyncio.run(connect_live_trades()) ```

cURL (for testing): ```bash

Note: cURL doesn't support WebSocket natively, use wscat instead

wscat -c "ws://localhost:8000/tzone_apis/services/dex-monitor/ws/live-trades?min_volume=5000&limit=50&network=eth&interval=15" ```

Response Structure

```typescript { // Table Headers "headers": [ { "key": "timestamp", "label": "Timestamp", "sortable": true }, { "key": "token_pair", "label": "Pair", "sortable": true }, { "key": "from_token_name", "label": "From-Token", "sortable": true }, { "key": "to_token_name", "label": "To-Token", "sortable": true }, { "key": "from_token_amount", "label": "From-Amount", "sortable": true }, { "key": "to_token_amount", "label": "To-Amount", "sortable": true }, { "key": "volume_in_usd", "label": "Volume(USD)", "sortable": true }, { "key": "kind", "label": "Type(Buy/Sell)", "sortable": true }, { "key": "dex_name", "label": "DEX", "sortable": true }, { "key": "dex_icon_url", "label": "DEX Icon", "sortable": false }, { "key": "pool_name", "label": "Pool", "sortable": true }, { "key": "tx_hash", "label": "Tx-Hash", "sortable": false } ],

// Table Rows (Trade Data) "rows": [ { "block_timestamp": "2025-10-28T20:10:23Z", "token_pair": "USDC/WETH", "from_token_symbol": "USDC", "to_token_symbol": "WETH", "volume_in_usd": 60376.14, "kind": "BUY", "tx_hash": "0x7592f4d1b24b3fe627d5c2aa13278b9ac0ef405f290e5aa4ab13e87b708a2a6c", "block_timestamp_unix": 1761682223, "block_number": 23678204, "from_token_address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "to_token_address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "from_token_amount": 60326.835748, "to_token_amount": 14.99026789, "price_from_in_usd": 1.00081725, "price_to_in_usd": 4027.68905171, "tx_from_address": "0xe98c552aabf167507fa2ba8ea47c52e45418bd1b", "pool_address": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640", "pool_name": "WETH / USDC", "pool_fee": "0.05", "dex_name": "Uniswap V3", "dex_icon_url": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "network": "eth", "from_token_name": "USD Coin", "from_token_image": "https://coin-images.coingecko.com/coins/images/6319/large/usdc.png", "to_token_name": "Wrapped Ether", "to_token_image": "https://coin-images.coingecko.com/coins/images/2518/large/weth.png" } ],

// Metadata "title": "Live Pool Trades", "total_count": 50, "min_volume_filter": 5000.0, "network": "eth", "data_source": "CoinGecko OnChain API", "last_updated": "2025-10-28T23:40:55.861462", "refresh_interval": 15.0, "connection_status": "active", "api_cache_ttl": "30 seconds", "real_time_feed": true, "timestamp": "2025-10-28T23:40:55.862527" } ```

Example Response

json { "headers": [ {"key": "timestamp", "label": "Timestamp", "sortable": true}, {"key": "token_pair", "label": "Pair", "sortable": true}, {"key": "from_token_name", "label": "From-Token", "sortable": true}, {"key": "to_token_name", "label": "To-Token", "sortable": true}, {"key": "from_token_amount", "label": "From-Amount", "sortable": true}, {"key": "to_token_amount", "label": "To-Amount", "sortable": true}, {"key": "volume_in_usd", "label": "Volume(USD)", "sortable": true}, {"key": "kind", "label": "Type(Buy/Sell)", "sortable": true}, {"key": "dex_name", "label": "DEX", "sortable": true}, {"key": "dex_icon_url", "label": "DEX Icon", "sortable": false}, {"key": "pool_name", "label": "Pool", "sortable": true}, {"key": "tx_hash", "label": "Tx-Hash", "sortable": false} ], "rows": [ { "block_timestamp": "2025-10-28T20:10:23Z", "token_pair": "USDC/WETH", "from_token_name": "USD Coin", "to_token_name": "Wrapped Ether", "from_token_amount": 60326.835748, "to_token_amount": 14.99026789, "volume_in_usd": 60376.14, "kind": "BUY", "dex_name": "Uniswap V3", "dex_icon_url": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "pool_name": "WETH / USDC", "tx_hash": "0x7592f4d1b24b3fe627d5c2aa13278b9ac0ef405f290e5aa4ab13e87b708a2a6c" }, { "block_timestamp": "2025-10-28T20:10:11Z", "token_pair": "USDC/WETH", "from_token_name": "USD Coin", "to_token_name": "Wrapped Ether", "from_token_amount": 19391.976367, "to_token_amount": 4.82246932, "volume_in_usd": 19423.41, "kind": "BUY", "dex_name": "Uniswap V3", "dex_icon_url": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "pool_name": "WETH / USDC", "tx_hash": "0x9f8fb9f332d753592a93637221b3f607b88529723881f6a9af63c84c41ede7d9" } ], "title": "Live Pool Trades", "total_count": 50, "min_volume_filter": 5000.0, "network": "eth", "data_source": "CoinGecko OnChain API", "last_updated": "2025-10-28T23:40:55.861462", "refresh_interval": 15.0, "connection_status": "active", "api_cache_ttl": "30 seconds", "real_time_feed": true, "timestamp": "2025-10-28T23:40:55.862527" }


2. Pool Details

Full Endpoint Address

ws://your-domain.com/tzone_apis/services/dex-monitor/ws/pool-details

Purpose

Get detailed information about a specific liquidity pool including TVL, APY, volume history, and historical chart data. Client sends pool ID via WebSocket message to request specific pool details.

How to Use It

  1. Connect to WebSocket endpoint
  2. Send JSON message with pool_id parameter
  3. Receive detailed pool information
  4. Send additional pool requests as needed
  5. Connection remains open for multiple requests

Upstream Params

No URL parameters - All parameters sent via WebSocket message

Client-side Filters/Search/Sort/Pagination

Example Request to Trigger the API

JavaScript/TypeScript: ```typescript const ws = new WebSocket( 'ws://localhost:8000/tzone_apis/services/dex-monitor/ws/pool-details' );

ws.onopen = () => { console.log('✅ Connected to pool details');

// Request pool details ws.send(JSON.stringify({ pool_id: "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640" })); };

ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log('📊 Pool details:', data);

// Request another pool setTimeout(() => { ws.send(JSON.stringify({ pool_id: "0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8" })); }, 2000); };

ws.onerror = (error) => { console.error('❌ WebSocket error:', error); }; ```

Python: ```python import asyncio import websockets import json

async def connect_pool_details(): uri = "ws://localhost:8000/tzone_apis/services/dex-monitor/ws/pool-details" async with websockets.connect(uri) as websocket: # Request first pool await websocket.send(json.dumps({ "pool_id": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640" }))

    response = await websocket.recv()
    pool_data = json.loads(response)
    print(f"📊 Pool: {pool_data['pool_info']['name']}")
    print(f"   TVL: ${pool_data['pool_info']['tvl']:,.2f}")
    print(f"   APY: {pool_data['pool_info']['apy']:.2f}%")

asyncio.run(connect_pool_details()) ```

Response Structure

typescript { "pool_info": { "id": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640", "name": "WETH / USDC", "dex": "Uniswap V3", "chain": "Ethereum", "tvl": 850000000, "volume_24h": 5000000000, "apy": 0.85, "apy_base": 0.75, "apy_reward": 0.10, "symbol": "WETH-USDC", "url": "https://app.uniswap.org/#/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640", "last_updated": "2025-10-28T23:40:55Z" }, "chart_data": [ { "timestamp": 1761600000000, "value": 840000000, "date": "2025-10-28T12:00:00" }, { "timestamp": 1761603600000, "value": 845000000, "date": "2025-10-28T13:00:00" } ], "data_sources": ["DefiLlama", "CoinGecko"], "last_updated": "2025-10-28T23:40:55.861462" }

Example Response

json { "pool_info": { "id": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640", "name": "WETH / USDC", "dex": "Uniswap V3", "chain": "Ethereum", "tvl": 850000000, "volume_24h": 5000000000, "apy": 0.85, "apy_base": 0.75, "apy_reward": 0.10, "symbol": "WETH-USDC", "url": "https://app.uniswap.org/#/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640", "last_updated": "2025-10-28T23:40:55Z" }, "chart_data": [ { "timestamp": 1761600000000, "value": 840000000, "date": "2025-10-28T12:00:00" }, { "timestamp": 1761603600000, "value": 845000000, "date": "2025-10-28T13:00:00" }, { "timestamp": 1761607200000, "value": 850000000, "date": "2025-10-28T14:00:00" } ], "data_sources": ["DefiLlama", "CoinGecko"], "last_updated": "2025-10-28T23:40:55.861462" }


3. Search Token Pairs

Full Endpoint Address

ws://your-domain.com/tzone_apis/services/dex-monitor/ws/search-pairs

Purpose

Search for liquidity pools containing specific token pairs across different DEXes and blockchains. Returns matching pairs with DEX information, fees, and availability across chains.

How to Use It

  1. Connect with token_a and token_b query parameters
  2. Server starts searching for matching pools
  3. Receive search results at specified interval
  4. Results include all DEXes and chains where pair is available
  5. Re-connect with different tokens to search new pairs

Upstream Params

| Parameter | Type | Default | Description | |-----------|------|---------|-------------| | token_a | string | required | First token in pair (e.g., "ETH", "WETH") | | token_b | string | required | Second token in pair (e.g., "USDC", "USDT") | | interval | float | 60.0 | Push interval in seconds |

Client-side Filters/Search/Sort/Pagination

Example Request to Trigger the API

JavaScript/TypeScript: ```typescript const ws = new WebSocket( 'ws://localhost:8000/tzone_apis/services/dex-monitor/ws/search-pairs' + '?token_a=ETH&token_b=USDC' );

ws.onopen = () => { console.log('✅ Searching for ETH/USDC pairs'); };

ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log(🔍 Found ${data.results.length} pools:);

data.results.forEach((result, idx) => { console.log(${idx + 1}. ${result.dex} (${result.chain}) - ${result.symbol}); console.log(APY: ${result.apy?.toFixed(2)}% | TVL: $${result.tvl?.toLocaleString()}); }); }; ```

Python: ```python import asyncio import websockets import json

async def search_pairs(): uri = ( "ws://localhost:8000/tzone_apis/services/dex-monitor/ws/search-pairs" "?token_a=ETH&token_b=USDC" ) async with websockets.connect(uri) as websocket: response = await websocket.recv() data = json.loads(response)

    print(f"🔍 Search results for {data['search_query']}:")
    for result in data['results']:
        print(f"  • {result['dex']} on {result['chain']}: {result['symbol']}")

asyncio.run(search_pairs()) ```

Response Structure

typescript { "search_query": "ETH/USDC", "results": [ { "dex": "Uniswap V3", "chain": "Ethereum", "symbol": "WETH-USDC", "tvl": 850000000, "apy": 0.85, "match_score": 95, "dex_logo": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "data_source": "DefiLlama", "url": "https://app.uniswap.org/#/pools/..." }, { "dex": "Uniswap V2", "chain": "Ethereum", "symbol": "WETH-USDC", "tvl": 125000000, "apy": 0.35, "match_score": 92, "dex_logo": "https://icons.llamao.fi/icons/protocols/uniswap_v2?w=48&h=48", "data_source": "DefiLlama" } ], "total_results": 12, "data_sources": ["CoinGecko", "DefiLlama"], "last_updated": "2025-10-28T23:40:55.861462" }

Example Response

json { "search_query": "ETH/USDC", "results": [ { "dex": "Uniswap V3", "chain": "Ethereum", "symbol": "WETH-USDC", "tvl": 850000000, "apy": 0.85, "match_score": 95, "dex_logo": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "data_source": "DefiLlama" }, { "dex": "Uniswap V3", "chain": "Polygon", "symbol": "WETH-USDC", "tvl": 45000000, "apy": 1.2, "match_score": 90, "dex_logo": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "data_source": "DefiLlama" }, { "dex": "SushiSwap", "chain": "Ethereum", "symbol": "WETH-USDC", "tvl": 65000000, "apy": 0.52, "match_score": 85, "dex_logo": "https://icons.llamao.fi/icons/protocols/sushiswap?w=48&h=48", "data_source": "DefiLlama" } ], "total_results": 12, "data_sources": ["CoinGecko", "DefiLlama"], "last_updated": "2025-10-28T23:40:55.861462" }


4. Trending Pools

Full Endpoint Address

ws://your-domain.com/tzone_apis/services/dex-monitor/ws/trending-pools

Purpose

Streams ranked trending liquidity pools based on volume-to-TVL ratio, trading activity, and yield opportunities. Updated periodically with latest DeFi pool performance metrics.

How to Use It

  1. Connect with desired limit and interval
  2. Optionally send client-side filters (search, sort, pagination)
  3. Server pushes trending pool rankings at interval
  4. Use pagination to load more pools as needed
  5. Connection remains open for continuous updates

Upstream Params

| Parameter | Type | Default | Range | Description | |-----------|------|---------|-------|-------------| | limit | int | 20 | 1-100 | Number of trending pools to return | | interval | float | 60.0 | ≥ 5 | Push interval in seconds | | search | string | None | - | Search string for filtering pools (optional) | | sort_by | string | None | - | Field to sort by (optional) | | sort_order | string | "asc" | asc, desc | Sort direction | | page | int | 1 | ≥ 1 | Page number for pagination | | page_size | int | 20 | 1-100 | Items per page |

Client-side Filters/Search/Sort/Pagination

Example Request to Trigger the API

JavaScript/TypeScript: ```typescript const ws = new WebSocket( 'ws://localhost:8000/tzone_apis/services/dex-monitor/ws/trending-pools' + '?limit=20&interval=60&sort_by=volume_tvl_ratio&sort_order=desc&page=1&page_size=20' );

ws.onopen = () => { console.log('✅ Connected to trending pools'); };

ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log(📈 Top ${data.rows.length} trending pools:\n);

data.rows.forEach((pool, idx) => { console.log(${idx + 1}. ${pool.symbol} - ${pool.dex} (${pool.chain})); console.log(TVL: $${pool.tvl?.toLocaleString()} | APY: ${pool.apy?.toFixed(2)}%); console.log(Volume/TVL Ratio: ${pool.volume_tvl_ratio?.toFixed(2)}\n); }); }; ```

Python: ```python import asyncio import websockets import json

async def trending_pools(): uri = ( "ws://localhost:8000/tzone_apis/services/dex-monitor/ws/trending-pools" "?limit=20&sort_by=apy&sort_order=desc" ) async with websockets.connect(uri) as websocket: while True: response = await websocket.recv() data = json.loads(response)

        print(f"📈 Trending pools update - {data['total_count']} pools found:")
        for idx, pool in enumerate(data['rows'][:5], 1):
            print(f"  {idx}. {pool['symbol']}: {pool['apy']}% APY")

        await asyncio.sleep(1)

asyncio.run(trending_pools()) ```

Response Structure

typescript { "headers": [ { "key": "rank", "label": "Rank", "sortable": true }, { "key": "pool", "label": "Pool", "sortable": true }, { "key": "dex", "label": "DEX", "sortable": true }, { "key": "chain", "label": "Chain", "sortable": true }, { "key": "tvl", "label": "TVL (USD)", "sortable": true }, { "key": "volume_24h", "label": "24h Volume", "sortable": true }, { "key": "apy", "label": "APY (%)", "sortable": true }, { "key": "volume_tvl_ratio", "label": "Volume/TVL", "sortable": true } ], "rows": [ { "rank": 1, "pool": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640", "dex": "Uniswap V3", "dex_logo": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "chain": "Ethereum", "tvl": 850000000, "volume_24h": 5000000000, "apy": 0.85, "apy_base": 0.75, "apy_reward": 0.10, "volume_tvl_ratio": 5.88, "symbol": "WETH-USDC", "url": "https://app.uniswap.org/#/pools/..." } ], "title": "Trending Liquidity Pools", "total_count": 156, "data_source": "DefiLlama Real API", "last_updated": "2025-10-28T23:40:55.861462" }

Example Response

json { "headers": [ {"key": "rank", "label": "Rank", "sortable": true}, {"key": "pool", "label": "Pool", "sortable": true}, {"key": "dex", "label": "DEX", "sortable": true}, {"key": "chain", "label": "Chain", "sortable": true}, {"key": "tvl", "label": "TVL (USD)", "sortable": true}, {"key": "volume_24h", "label": "24h Volume", "sortable": true}, {"key": "apy", "label": "APY (%)", "sortable": true}, {"key": "volume_tvl_ratio", "label": "Volume/TVL", "sortable": true} ], "rows": [ { "rank": 1, "pool": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640", "dex": "Uniswap V3", "dex_logo": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "chain": "Ethereum", "tvl": 850000000, "volume_24h": 5000000000, "apy": 0.85, "apy_base": 0.75, "apy_reward": 0.10, "volume_tvl_ratio": 5.88, "symbol": "WETH-USDC" }, { "rank": 2, "pool": "0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8", "dex": "Uniswap V3", "dex_logo": "https://icons.llamao.fi/icons/protocols/uniswap_v3?w=48&h=48", "chain": "Ethereum", "tvl": 720000000, "volume_24h": 3500000000, "apy": 1.2, "apy_base": 1.0, "apy_reward": 0.2, "volume_tvl_ratio": 4.86, "symbol": "USDC-WETH" } ], "title": "Trending Liquidity Pools", "total_count": 156, "data_source": "DefiLlama Real API", "last_updated": "2025-10-28T23:40:55.861462" }


5. Trading Volume Timeseries

Full Endpoint Address

ws://your-domain.com/tzone_apis/services/dex-monitor/ws/volume-timeseries

Purpose

Streams historical DEX trading volume time-series data as line/area chart. Supports multiple time periods (1d to all-time) with hourly or daily aggregation. Ready for frontend charting libraries.

How to Use It

  1. Connect with desired time period
  2. Specify update interval
  3. Server pushes volume chart data
  4. Frontend renders using chart library (Chart.js, ApexCharts, etc.)
  5. Connection updates data periodically

Upstream Params

| Parameter | Type | Default | Options | Description | |-----------|------|---------|---------|-------------| | period | string | "7d" | 1d, 7d, 30d, 90d, 1y, all | Time period for chart | | interval | float | 120.0 | ≥ 5 | Push interval in seconds |

Client-side Filters/Search/Sort/Pagination

Example Request to Trigger the API

JavaScript/TypeScript: ```typescript const ws = new WebSocket( 'ws://localhost:8000/tzone_apis/services/dex-monitor/ws/volume-timeseries' + '?period=7d&interval=120' );

ws.onopen = () => { console.log('✅ Connected to volume timeseries'); };

ws.onmessage = (event) => { const data = JSON.parse(event.data);

// Use with ApexCharts const options = { chart: { type: 'area' }, series: data.series, xaxis: { type: 'datetime', categories: data.chart_data.map(d => d.date) }, yaxis: { title: { text: data.y_axis_label } }, title: { text: data.title } };

// Render chart new ApexCharts(document.querySelector('#chart'), options).render();

console.log(📊 Volume data: $${data.total_volume?.toLocaleString()}); console.log(Latest (24h): $${data.latest_volume_24h?.toLocaleString()}); }; ```

Python: ```python import asyncio import websockets import json from datetime import datetime

async def volume_timeseries(): uri = ( "ws://localhost:8000/tzone_apis/services/dex-monitor/ws/volume-timeseries" "?period=7d&interval=120" ) async with websockets.connect(uri) as websocket: response = await websocket.recv() data = json.loads(response)

    print(f"📊 {data['title']} ({data['period'].upper()})")
    print(f"   Total Volume: ${data['total_volume']:,.0f}")
    print(f"   Latest 24h: ${data['latest_volume_24h']:,.0f}")
    print(f"   Data Points: {data['total_data_points']}")
    print(f"   Average Daily: ${data['average_daily_volume']:,.0f}")

asyncio.run(volume_timeseries()) ```

Response Structure

```typescript { // Chart Data Array "chart_data": [ { "timestamp": 1761600000000, // milliseconds "volume": 2500000000, "date": "2025-10-22T12:00:00" }, { "timestamp": 1761603600000, "volume": 2800000000, "date": "2025-10-22T13:00:00" } ],

// Chart Series (for ApexCharts, Chart.js, etc) "series": [ { "name": "DEX Trading Volume", "type": "area", "data": [ [1761600000000, 2500000000], [1761603600000, 2800000000] ], "color": "#3b82f6", "fillOpacity": 0.1, "lineWidth": 2 } ],

// Chart Configuration "chart_type": "area", "y_axis_label": "Trading Volume (USD)", "x_axis_label": "Time", "title": "DEX Trading Volume (7D)",

// Statistics "period": "7d", "total_volume": 175000000000, "latest_volume_24h": 2800000000, "total_data_points": 168, "average_daily_volume": 25000000000,

// Metadata "data_source": "DefiLlama API", "last_updated": "2025-10-28T23:40:55.861462" } ```

Example Response

json { "chart_data": [ { "timestamp": 1761081600000, "volume": 2100000000, "date": "2025-10-22T00:00:00" }, { "timestamp": 1761168000000, "volume": 2350000000, "date": "2025-10-23T00:00:00" }, { "timestamp": 1761254400000, "volume": 2500000000, "date": "2025-10-24T00:00:00" }, { "timestamp": 1761340800000, "volume": 2800000000, "date": "2025-10-25T00:00:00" } ], "series": [ { "name": "DEX Trading Volume", "type": "area", "data": [ [1761081600000, 2100000000], [1761168000000, 2350000000], [1761254400000, 2500000000], [1761340800000, 2800000000] ], "color": "#3b82f6", "fillOpacity": 0.1, "lineWidth": 2 } ], "chart_type": "area", "y_axis_label": "Trading Volume (USD)", "x_axis_label": "Time", "title": "DEX Trading Volume (7D)", "period": "7d", "total_volume": 175000000000, "latest_volume_24h": 2800000000, "total_data_points": 168, "average_daily_volume": 25000000000, "data_source": "DefiLlama API", "last_updated": "2025-10-28T23:40:55.861462" }


6. DEX Rankings

Full Endpoint Address

ws://your-domain.com/tzone_apis/services/dex-monitor/ws/rankings

Purpose

Streams ranked list of DEX platforms by TVL, 24h volume, and other metrics. Includes DEX logos, descriptions, and performance statistics. Updated periodically with latest DeFi data.

How to Use It

  1. Connect to WebSocket with limit and interval
  2. Server pushes updated DEX rankings
  3. Display in sortable table on frontend
  4. Connection remains open for continuous updates
  5. Use pagination to view more DEXes

Upstream Params

| Parameter | Type | Default | Range | Description | |-----------|------|---------|-------|-------------| | limit | int | 50 | 1-100 | Number of DEXes to return | | interval | float | 60.0 | ≥ 5 | Push interval in seconds |

Client-side Filters/Search/Sort/Pagination

Example Request to Trigger the API

JavaScript/TypeScript: ```typescript const ws = new WebSocket( 'ws://localhost:8000/tzone_apis/services/dex-monitor/ws/rankings' + '?limit=50&interval=60' );

ws.onopen = () => { console.log('✅ Connected to DEX rankings'); };

ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log(📊 ${data.title} - ${data.total_count} DEXes\n);

data.rows.forEach((dex) => { console.log(${dex.rank}. ${dex.name}); console.log(TVL: $${dex.tvl?.toLocaleString()}); console.log(24h Volume: $${dex.volume_24h?.toLocaleString()}); console.log(Change (1d): ${dex.change_1d?.toFixed(2)}%\n); }); }; ```

Python: ```python import asyncio import websockets import json

async def dex_rankings(): uri = ( "ws://localhost:8000/tzone_apis/services/dex-monitor/ws/rankings" "?limit=50&interval=60" ) async with websockets.connect(uri) as websocket: response = await websocket.recv() data = json.loads(response)

    print(f"📊 Top {len(data['rows'])} DEX Platforms:\n")
    for dex in data['rows'][:10]:
        print(f"{dex['rank']:2}. {dex['name']:20} | "
              f"TVL: ${dex['tvl']:>15,.0f} | "
              f"24h Vol: ${dex['volume_24h']:>15,.0f}")

asyncio.run(dex_rankings()) ```

Response Structure

typescript { "headers": [ { "key": "rank", "label": "Rank", "sortable": true }, { "key": "name", "label": "Name", "sortable": true }, { "key": "tvl", "label": "TVL (USD)", "sortable": true }, { "key": "volume_24h", "label": "24h Volume", "sortable": true }, { "key": "users_24h", "label": "Users (24h)", "sortable": true }, { "key": "change_1d", "label": "1d Change", "sortable": true }, { "key": "chains", "label": "Chains", "sortable": false } ], "rows": [ { "rank": 1, "name": "Uniswap", "logo": "https://icons.llamao.fi/icons/protocols/uniswap?w=48&h=48", "category": "DEX", "tvl": 3500000000, "volume_24h": 1200000000, "volume_change_24h": -2.5, "users_24h": 45000, "chains": ["Ethereum", "Polygon", "Arbitrum", "Optimism", "Base"], "url": "https://uniswap.org", "description": "Leading decentralized exchange with AMM and concentrated liquidity pools", "change_1d": 2.34, "change_7d": 5.67, "change_1m": 12.45 } ], "title": "DEX Rankings", "total_count": 2456, "data_sources": ["DefiLlama", "CoinGecko"], "last_updated": "2025-10-28T23:40:55.861462" }

Example Response

json { "headers": [ {"key": "rank", "label": "Rank", "sortable": true}, {"key": "name", "label": "Name", "sortable": true}, {"key": "tvl", "label": "TVL (USD)", "sortable": true}, {"key": "volume_24h", "label": "24h Volume", "sortable": true}, {"key": "users_24h", "label": "Users (24h)", "sortable": true}, {"key": "change_1d", "label": "1d Change", "sortable": true}, {"key": "chains", "label": "Chains", "sortable": false} ], "rows": [ { "rank": 1, "name": "Uniswap", "logo": "https://icons.llamao.fi/icons/protocols/uniswap?w=48&h=48", "category": "DEX", "tvl": 3500000000, "volume_24h": 1200000000, "volume_change_24h": -2.5, "users_24h": 45000, "chains": ["Ethereum", "Polygon", "Arbitrum", "Optimism", "Base"], "url": "https://uniswap.org", "description": "Leading decentralized exchange with AMM and concentrated liquidity pools", "change_1d": 2.34, "change_7d": 5.67, "change_1m": 12.45 }, { "rank": 2, "name": "SushiSwap", "logo": "https://icons.llamao.fi/icons/protocols/sushiswap?w=48&h=48", "category": "DEX", "tvl": 850000000, "volume_24h": 350000000, "volume_change_24h": 1.2, "users_24h": 18000, "chains": ["Ethereum", "Polygon", "Arbitrum", "Avalanche"], "url": "https://sushi.com", "description": "Community-governed DEX with farming and staking opportunities", "change_1d": -1.5, "change_7d": 3.2, "change_1m": 8.9 } ], "title": "DEX Rankings", "total_count": 2456, "data_sources": ["DefiLlama", "CoinGecko"], "last_updated": "2025-10-28T23:40:55.861462" }


Common Error Responses

Authentication Error

json { "error": "Authentication failed", "connection_status": "error", "last_updated": "2025-10-28T23:40:55.861462" }

Rate Limited

json { "error": "Rate limited", "retry_after": 60, "last_updated": "2025-10-28T23:40:55.861462" }

API Unavailable

json { "error": "Failed to fetch from upstream API", "data_source": "CoinGecko OnChain API", "connection_status": "error", "last_updated": "2025-10-28T23:40:55.861462" }


Network Support

Supported Blockchain Networks: - eth - Ethereum - polygon - Polygon (Matic) - arbitrum - Arbitrum One - optimism - Optimism - base - Base (Coinbase Layer 2) - bsc - Binance Smart Chain - avalanche - Avalanche C-Chain - fantom - Fantom - gnosis - Gnosis Chain - celo - Celo - linea - Linea - scroll - Scroll


Data Sources

| Source | Coverage | Latency | Reliability | |--------|----------|---------|-------------| | CoinGecko OnChain API | Real pool trades | ~30s | 99.5%+ | | DefiLlama | TVL, yields, overview | ~1min | 99.9%+ | | Llama Icons | DEX protocol logos | Instant | 99.9%+ |


Rate Limits


Common Implementation Patterns

React Hook for Live Trades

```typescript import { useEffect, useState } from 'react';

export function useLiveTrades(minVolume = 1000, limit = 50, network = 'eth') { const [trades, setTrades] = useState([]); const [connected, setConnected] = useState(false);

useEffect(() => { const ws = new WebSocket( ws://localhost:8000/tzone_apis/services/dex-monitor/ws/live-trades + ?min_volume=${minVolume}&limit=${limit}&network=${network}&interval=15 );

ws.onopen = () => setConnected(true);
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  setTrades(data.rows);
};
ws.onclose = () => setConnected(false);

return () => ws.close();

}, [minVolume, limit, network]);

return { trades, connected }; } ```

Vue 3 Composable

```typescript import { ref, onMounted, onUnmounted } from 'vue';

export function useDexRankings(limit = 50) { const rankings = ref([]); let ws;

onMounted(() => { ws = new WebSocket( ws://localhost:8000/tzone_apis/services/dex-monitor/ws/rankings?limit=${limit} ); ws.onmessage = (event) => { rankings.value = JSON.parse(event.data).rows; }; });

onUnmounted(() => ws?.close());

return { rankings }; } ```


Last Updated: 2025-10-28
Version: 1.0.0
Status: ✅ Production Ready ```


📄 Save as dex.md

Save this entire documentation to a file named dex.md in your project documentation directory:

```bash

Create docs directory if it doesn't exist

mkdir -p /home/amired/Codes/tradezone/docs/apis

Save documentation

cat > /home/amired/Codes/tradezone/docs/apis/dex.md << 'EOF' [Content from above] EOF ```

This comprehensive documentation includes everything frontend developers need to integrate with your DEX Monitor WebSocket APIs! ✨