""" MIA Market Intelligence Access Guide
This guide shows how to access all the market intelligence through APIs.
-
ARBITRAGE OPPORTUNITIES
-
/api/db/arbitrage?limit=100&min_profit=0.1 Returns all discovered arbitrage cycles with profit %
-
/api/arbitrage/{asset} Returns arbitrage routes for specific starting asset
-
/api/db/dashboard Complete summary including arbitrage count
-
-
TRADING SIGNALS
-
/api/db/signals?limit=100&status=ACTIVE All detected trading signals (ACTIVE, CLOSED, PENDING)
-
/api/db/signals?status=ACTIVE Currently active signals only
-
-
SELECTED MARKETS
-
/api/db/markets All markets selected for trading with volumes
-
/api/db/markets/{exchange} Markets on specific exchange (binance, kraken, etc)
-
/api/markets/top?limit=20 Top markets by alpha score
-
-
MARKET TOPOLOGY & GRAPH
-
/api/db/correlations?limit=100 Asset correlations and relationships
-
/api/db/flows/{asset} Liquidity flows for asset (inflows/outflows)
-
/api/graph/correlations Full correlation graph
-
/api/graph/clusters Market communities/clusters
-
-
PRICING & SPREADS
-
/api/pricing/{asset} Current prices across all exchanges
-
/api/spreads/{asset}/{quote}?exchanges=binance,kraken Bid/ask spreads by exchange
-
-
COMPLETE DASHBOARD
- /api/db/dashboard
Full summary with all stats:
- Market statistics (total, active, volume)
- Signal statistics (active, closed, win rate)
- Graph statistics (assets, nodes, edges, correlations)
- Arbitrage count
- Recent signals
- /api/db/dashboard
Full summary with all stats:
-
SYSTEM HEALTH
-
/api/health System status and component health
-
/api/stats Comprehensive statistics (markets, signals, events)
-
curl http://localhost:8001/api/db/arbitrage?limit=200&min_profit=0.5
curl http://localhost:8001/api/db/signals?status=ACTIVE&limit=50
curl http://localhost:8001/api/db/markets/binance
curl http://localhost:8001/api/pricing/BTC
curl http://localhost:8001/api/db/dashboard
curl http://localhost:8001/api/db/correlations?limit=50
curl http://localhost:8001/api/db/flows/ETH
curl http://localhost:8001/api/search/bitcoin
import httpx
async with httpx.AsyncClient() as client: # Get arbitrage opportunities response = await client.get( "http://localhost:8001/api/db/arbitrage", params={"limit": 100, "min_profit": 0.1} ) arbitrage = response.json() print(f"Found {arbitrage['count']} opportunities") for opp in arbitrage['opportunities']: print(f" {opp['cycle']}: {opp['profit_percentage']:.2f}%")
# Get dashboard
response = await client.get("http://localhost:8001/api/db/dashboard")
dashboard = response.json()
print(f"Markets: {dashboard['market_stats']['total_markets']}")
print(f"Signals: {dashboard['signal_stats']['active_signals']}")
print(f"Arbitrage: {dashboard['arbitrage_count']}")
-
INGESTION LAYER
- 5 exchange adapters fetch real-time data
- WebSocketManager streams candles
- Volume discovery finds 1,500+ symbols
-
EVENT FABRIC
- Events emit through fabric.emit()
- DatabaseAdapter batch-consumes to PostgreSQL
- Redis streams queue pending events
-
DATABASE PERSISTENCE
- fabric_events: All system events
- candles: OHLCV data by timeframe
- market_nodes: Selected markets with volumes
- signals: Generated trading signals
- correlations: Inter-asset relationships
- market_flows: Liquidity flows between assets
-
QUERY API (QueryAPI class)
- Reads from PostgreSQL tables
- Aggregates by exchange, asset, type
- Calculates statistics (win rate, correlations)
- Returns structured JSON
-
FASTAPI ENDPOINTS
- HTTP GET endpoints expose QueryAPI
- CORS enabled for web/dashboard access
- JSON responses with metadata
If endpoints return 503 "Database not initialized": → Check if db_pool and redis were passed to initialize_api() → Verify database connection string in .env → Ensure PostgreSQL is running and accessible
If endpoints have no data despite running system: → Run: python diagnose_data_flow.py This checks: - Database table row counts - Redis stream lengths - Recent data timestamps - Data flow bottlenecks
If only cache data shows (no historical): → DatabaseAdapter may not be subscribed to events → Check fabric.subscribers for DatabaseAdapter topics → Verify batch_size and batch_timeout settings
If arbitrage shows 0 but logs show "42 arbs": → MarketIntegration stores in memory → Need to persist ArbitrageRoute to database → Or use /api/arbitrage/{asset} endpoint instead
Port 8001: FastAPI Data Access API
- Full query access to all systems
- Web dashboard at /dashboard
- Health check at /health
Endpoints respond in ~100-500ms:
- Redis caching for frequent queries
- PostgreSQL indexes on symbol, exchange, timestamp
- Query optimization for large datasets
Supported for:
- Real-time queries (latest arbitrage, signals)
- Historical analysis (win rates, correlations)
- Cross-exchange comparisons
- Market topology visualization
-
Start FastAPI: uvicorn api.data_access_api:app --host 0.0.0.0 --port 8001
-
Test endpoints: curl http://localhost:8001/api/db/dashboard curl http://localhost:8001/api/db/arbitrage?limit=20
-
Build UI/dashboard using:
- /api/db/dashboard (summary)
- /api/db/signals (signal list)
- /api/db/markets (market table)
- /api/db/correlations (heatmap)
-
Connect MCP to serve data:
- Call api.data_access_api endpoints
- Format responses for agents
- Provide structured market data to decision systems """
async def test_api(): """Test all API endpoints""" import httpx import asyncio
urls = [
"http://localhost:8001/api/db/dashboard",
"http://localhost:8001/api/db/arbitrage?limit=10",
"http://localhost:8001/api/db/signals?limit=10",
"http://localhost:8001/api/db/markets",
"http://localhost:8001/api/db/correlations?limit=10",
"http://localhost:8001/api/health",
]
async with httpx.AsyncClient(timeout=10) as client:
for url in urls:
try:
response = await client.get(url)
data = response.json()
print(f"✓ {url}")
print(f" Status: {response.status_code}")
if "count" in data:
print(f" Count: {data['count']}")
elif "total_markets" in data.get("market_stats", {}):
print(f" Markets: {data['market_stats']['total_markets']}")
except Exception as e:
print(f"✗ {url}: {e}")
if name == "main": import asyncio asyncio.run(test_api())