Skip to content

API Reference

Complete reference for the QuantFin Bot REST API. The API provides 27 endpoints for comprehensive trading bot management, built with FastAPI and supporting async operations.

Base URL

https://quantfin.dexalgo.org/api

Authentication

All API endpoints require authentication. Include your API token in the Authorization header:

Authorization: Bearer YOUR_API_TOKEN

Rate Limits

Endpoint Category Limit Window
Configuration 10 req/min Per user
Trading Control 5 req/min Per user
Data & Analytics 100 req/min Per user
Health/Monitoring 1000 req/min Global

Data Models

User State Structure

{
  "userId": "string",
  "symbols": {
    "SUI-USDC": {
      "config": {
        "mode": "xgridt_mm_both",
        "order_qty": 10,
        "tp_distance": 0.0009,
        "grid_levels": 3,
        "xgrid_spacing": 0.0024,
        "xgrid_levels": 3,
        "xgrid_max_open": 3,
        "dynamic_distribution": {
          "enabled": true,
          "wallet_exposure_limit_long": 0.01,
          "wallet_exposure_limit_short": 0.01,
          "strength": 1,
          "levels": 3,
          "qty_precision": 1
        }
      },
      "state": {
        "active": true,
        "last_update": "2024-01-15T10:30:00Z",
        "current_position": 150.5,
        "unrealized_pnl": 15.25
      },
      "orders": [],
      "positions": []
    }
  },
  "wallet": {
    "address": "0x...",
    "balance": 1250.75,
    "connected": true
  },
  "settings": {
    "theme": "ocean",
    "notifications": true,
    "auto_backup": true
  }
}

Equity History Schema

{
  "timestamp": "2024-01-15T10:30:00Z",
  "userId": "string",
  "symbol": "SUI-USDC",
  "equity": 1250.75,
  "unrealized_pnl": 15.25,
  "realized_pnl": 235.50,
  "position_size": 150.0,
  "mark_price": 1.8345
}

Endpoints

Configuration Management

GET /config/{user_id}

Retrieve user configuration for all symbols.

Parameters: - user_id (path): User identifier

Response:

{
  "symbols": {
    "SUI-USDC": {
      "mode": "xgridt_mm_both",
      "order_qty": 10,
      "tp_distance": 0.0009,
      "grid_levels": 3,
      "xgrid_spacing": 0.0024,
      "xgrid_levels": 3,
      "xgrid_max_open": 3,
      "dynamic_distribution": {
        "enabled": true,
        "wallet_exposure_limit_long": 0.01,
        "wallet_exposure_limit_short": 0.01,
        "strength": 1,
        "levels": 3,
        "qty_precision": 1
      }
    }
  }
}

POST /config/{user_id}

Update user configuration.

Parameters: - user_id (path): User identifier

Request Body:

{
  "symbol": "SUI-USDC",
  "config": {
    "mode": "market_making_long",
    "order_qty": 15,
    "tp_distance": 0.0012
  }
}

Response:

{
  "status": "success",
  "message": "Configuration updated successfully"
}

GET /presets

Get all available strategy presets.

Response:

{
  "presets": [
    {
      "name": "Safu",
      "description": "Conservative trading with low risk parameters",
      "config": {
        "mode": "market_making_both",
        "order_qty": 5,
        "tp_distance": 0.0015,
        "grid_levels": 2,
        "dynamic_distribution": {
          "wallet_exposure_limit_long": 0.005,
          "wallet_exposure_limit_short": 0.005
        }
      }
    },
    {
      "name": "Moderate",
      "description": "Balanced risk/reward approach",
      "config": {
        "mode": "xgridt_mm_both",
        "order_qty": 10,
        "tp_distance": 0.0009,
        "grid_levels": 3,
        "xgrid_spacing": 0.0024,
        "dynamic_distribution": {
          "wallet_exposure_limit_long": 0.01,
          "wallet_exposure_limit_short": 0.01
        }
      }
    },
    {
      "name": "Aggressive",
      "description": "Higher risk, higher reward strategy",
      "config": {
        "mode": "xgridt_mm_both",
        "order_qty": 20,
        "tp_distance": 0.0006,
        "grid_levels": 5,
        "xgrid_spacing": 0.0036,
        "dynamic_distribution": {
          "wallet_exposure_limit_long": 0.02,
          "wallet_exposure_limit_short": 0.02
        }
      }
    },
    {
      "name": "YachtToday",
      "description": "Maximum risk for maximum potential returns",
      "config": {
        "mode": "xgridt_mm_both",
        "order_qty": 50,
        "tp_distance": 0.0003,
        "grid_levels": 7,
        "xgrid_spacing": 0.0048,
        "dynamic_distribution": {
          "wallet_exposure_limit_long": 0.05,
          "wallet_exposure_limit_short": 0.05
        }
      }
    }
  ]
}

POST /export_config/{user_id}

Export user configuration as downloadable file.

Parameters: - user_id (path): User identifier

Response:

{
  "download_url": "https://quantfin.dexalgo.org/api/downloads/config_user123_20240115.json",
  "expires_at": "2024-01-15T11:30:00Z"
}

Trading Control

POST /start/{user_id}

Start trading bot for specified user.

Parameters: - user_id (path): User identifier

Request Body:

{
  "symbols": ["SUI-USDC", "BTC-USDC"],
  "dry_run": false
}

Response:

{
  "status": "started",
  "message": "Trading bot started successfully",
  "timestamp": "2024-01-15T10:30:00Z",
  "session_id": "session_abc123",
  "active_symbols": ["SUI-USDC", "BTC-USDC"]
}

POST /stop/{user_id}

Stop trading bot for specified user.

Parameters: - user_id (path): User identifier

Request Body:

{
  "cancel_orders": true,
  "close_positions": false
}

Response:

{
  "status": "stopped",
  "message": "Trading bot stopped successfully",
  "timestamp": "2024-01-15T10:35:00Z",
  "orders_cancelled": 5,
  "positions_closed": 0
}

GET /status/{user_id}

Get current bot status.

Parameters: - user_id (path): User identifier

Response:

{
  "status": "running",
  "uptime": "2h 45m",
  "last_trade": "2024-01-15T10:25:00Z",
  "active_symbols": ["SUI-USDC"],
  "active_orders": 3,
  "current_positions": {
    "SUI-USDC": 150.5
  },
  "session_id": "session_abc123"
}

POST /emergency_stop/{user_id}

Emergency stop - immediately cancel all orders and stop trading.

Parameters: - user_id (path): User identifier

Response:

{
  "status": "emergency_stopped",
  "message": "Emergency stop executed",
  "timestamp": "2024-01-15T10:40:00Z",
  "orders_cancelled": 8,
  "positions_status": "open"
}

Data & Analytics

GET /equity_history/{user_id}

Get historical equity data for charting and analysis.

Parameters: - user_id (path): User identifier - symbol (query, optional): Filter by symbol - start_date (query, optional): Start date (ISO format) - end_date (query, optional): End date (ISO format) - limit (query, optional): Maximum records (default: 1000)

Response:

{
  "data": [
    {
      "timestamp": "2024-01-15T10:00:00Z",
      "userId": "user123",
      "symbol": "SUI-USDC",
      "equity": 1250.75,
      "unrealized_pnl": 15.25,
      "realized_pnl": 235.50,
      "position_size": 150.0,
      "mark_price": 1.8345
    }
  ],
  "total_records": 1247,
  "filtered_records": 100
}

GET /trading_stats/{user_id}

Get comprehensive trading statistics.

Parameters: - user_id (path): User identifier - symbol (query, optional): Filter by symbol - period (query, optional): Time period (1d, 7d, 30d, all)

Response:

{
  "summary": {
    "total_trades": 1247,
    "win_rate": 0.67,
    "profit_factor": 1.89,
    "total_pnl": 2845.32,
    "total_fees": 156.78,
    "net_pnl": 2688.54
  },
  "risk_metrics": {
    "max_drawdown": -156.78,
    "max_drawdown_percent": -0.125,
    "sharpe_ratio": 1.34,
    "sortino_ratio": 1.78,
    "calmar_ratio": 2.15
  },
  "performance": {
    "daily_pnl": 45.32,
    "weekly_pnl": 234.67,
    "monthly_pnl": 1156.89,
    "best_day": 123.45,
    "worst_day": -78.23
  }
}

GET /positions/{user_id}

Get current positions for all symbols.

Parameters: - user_id (path): User identifier

Response:

{
  "positions": [
    {
      "symbol": "SUI-USDC",
      "size": 150.5,
      "side": "long",
      "entry_price": 1.8234,
      "mark_price": 1.8345,
      "unrealized_pnl": 15.25,
      "margin_used": 276.51,
      "liquidation_price": 1.2345,
      "timestamp": "2024-01-15T09:30:00Z"
    }
  ],
  "total_margin_used": 276.51,
  "total_unrealized_pnl": 15.25,
  "account_equity": 1250.75
}

GET /orders/{user_id}

Get order history with filtering options.

Parameters: - user_id (path): User identifier - symbol (query, optional): Filter by symbol - status (query, optional): Filter by status (filled, cancelled, pending) - limit (query, optional): Maximum records (default: 100) - offset (query, optional): Pagination offset

Response:

{
  "orders": [
    {
      "id": "order_123",
      "symbol": "SUI-USDC",
      "side": "buy",
      "type": "limit",
      "quantity": 10,
      "price": 1.8234,
      "filled_quantity": 10,
      "filled_price": 1.8234,
      "status": "filled",
      "timestamp": "2024-01-15T10:15:00Z",
      "fee": 0.0365
    }
  ],
  "total_orders": 1247,
  "filtered_orders": 100
}

User Management

GET /user/{user_id}

Get user account information.

Parameters: - user_id (path): User identifier

Response:

{
  "userId": "user123",
  "created_at": "2024-01-01T00:00:00Z",
  "last_active": "2024-01-15T10:30:00Z",
  "settings": {
    "theme": "ocean",
    "notifications": true,
    "auto_backup": true,
    "email_alerts": false
  },
  "subscription": {
    "tier": "pro",
    "expires_at": "2024-12-31T23:59:59Z"
  },
  "limits": {
    "max_symbols": 6,
    "max_position_size": 10000,
    "api_calls_per_minute": 100
  }
}

POST /user/{user_id}/settings

Update user settings.

Parameters: - user_id (path): User identifier

Request Body:

{
  "theme": "cyberpunk",
  "notifications": false,
  "auto_backup": true,
  "email_alerts": true
}

Response:

{
  "status": "success",
  "message": "Settings updated successfully",
  "settings": {
    "theme": "cyberpunk",
    "notifications": false,
    "auto_backup": true,
    "email_alerts": true
  }
}

Wallet & Exchange Integration

GET /wallet/{user_id}

Get wallet connection status and balance.

Parameters: - user_id (path): User identifier

Response:

{
  "connected": true,
  "address": "0x1234567890abcdef",
  "balance": {
    "SUI": 1250.75,
    "USDC": 5000.00
  },
  "last_update": "2024-01-15T10:30:00Z",
  "network": "mainnet"
}

POST /wallet/connect

Initiate wallet connection.

Request Body:

{
  "user_id": "user123",
  "wallet_type": "sui",
  "address": "0x1234567890abcdef"
}

Response:

{
  "status": "success",
  "message": "Wallet connected successfully",
  "address": "0x1234567890abcdef",
  "connection_id": "conn_abc123"
}

GET /exchange/status

Get exchange connection status.

Response:

{
  "bluefin": {
    "status": "connected",
    "latency": 45,
    "last_heartbeat": "2024-01-15T10:30:00Z",
    "websocket_status": "connected",
    "api_status": "operational"
  },
  "market_data": {
    "symbols": ["SUI-USDC", "BTC-USDC", "ETH-USDC"],
    "last_update": "2024-01-15T10:30:00Z"
  }
}

Monitoring & Health

GET /health

System health check.

Response:

{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00Z",
  "version": "0.4.0",
  "uptime": "72h 15m",
  "components": {
    "database": "healthy",
    "exchange": "healthy",
    "websocket": "healthy",
    "api": "healthy"
  }
}

GET /metrics

System performance metrics.

Response:

{
  "api": {
    "requests_per_minute": 450,
    "average_response_time": 125,
    "error_rate": 0.002
  },
  "trading": {
    "active_users": 67,
    "trades_per_minute": 23,
    "total_volume_24h": 1250000.00
  },
  "system": {
    "cpu_usage": 0.45,
    "memory_usage": 0.62,
    "disk_usage": 0.23
  }
}

Error Handling

HTTP Status Codes

  • 200 OK: Request successful
  • 201 Created: Resource created successfully
  • 400 Bad Request: Invalid request parameters
  • 401 Unauthorized: Authentication required
  • 403 Forbidden: Insufficient permissions
  • 404 Not Found: Resource not found
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server error

Error Response Format

{
  "error": "INSUFFICIENT_BALANCE",
  "message": "Insufficient balance to place order",
  "details": {
    "required": 1000.00,
    "available": 750.50,
    "symbol": "SUI-USDC"
  },
  "timestamp": "2024-01-15T10:30:00Z",
  "request_id": "req_abc123"
}

Common Error Codes

Code Description
INVALID_PARAMETERS Request parameters are invalid
INSUFFICIENT_BALANCE Not enough balance for operation
WALLET_NOT_CONNECTED Wallet connection required
EXCHANGE_ERROR Exchange operation failed
RATE_LIMITED Too many requests
STRATEGY_ERROR Trading strategy error
CONFIGURATION_ERROR Invalid configuration
AUTHENTICATION_ERROR Authentication failed

SDKs and Examples

Python Example

import requests

base_url = "https://quantfin.dexalgo.org/api"
headers = {"Authorization": "Bearer YOUR_API_TOKEN"}

# Get user configuration
response = requests.get(f"{base_url}/config/user123", headers=headers)
config = response.json()

# Start trading
start_data = {
    "symbols": ["SUI-USDC"],
    "dry_run": False
}
response = requests.post(f"{base_url}/start/user123", json=start_data, headers=headers)
print(response.json())

# Get trading stats
response = requests.get(f"{base_url}/trading_stats/user123", headers=headers)
stats = response.json()
print(f"Total PnL: {stats['summary']['total_pnl']}")

JavaScript Example

const baseUrl = "https://quantfin.dexalgo.org/api";
const headers = {
  "Authorization": "Bearer YOUR_API_TOKEN",
  "Content-Type": "application/json"
};

// Get current positions
async function getPositions(userId) {
  const response = await fetch(`${baseUrl}/positions/${userId}`, {
    headers: headers
  });
  const data = await response.json();
  return data.positions;
}

// Update configuration
async function updateConfig(userId, config) {
  const response = await fetch(`${baseUrl}/config/${userId}`, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(config)
  });
  return response.json();
}

// Usage
getPositions("user123").then(positions => {
  console.log("Current positions:", positions);
});

For more implementation details, see the specific endpoint documentation in Configuration.