wash-trading-api.md 14 KB

Wash Trading API Contracts

Date: 2024-12-29
Feature: Multi-account wash trading system for BTC pairs
Status: Complete

API Overview

Base URL: http://localhost:3000/api/v1
Authentication: Bearer token (JWT)
Content-Type: application/json
Rate Limiting: 100 requests/minute per client

Endpoints

1. Session Management

Create Wash Trading Session

POST /sessions

Request Body:

{
  "name": "BTC Wash Trading Session 1",
  "strategyId": "equal-volume-btc",
  "accountIds": ["account-1", "account-2", "account-3"],
  "targetVolume": 10.5,
  "duration": 3600000
}

Response (201 Created):

{
  "success": true,
  "data": {
    "id": "session-123",
    "name": "BTC Wash Trading Session 1",
    "strategy": {
      "id": "equal-volume-btc",
      "name": "Equal Volume BTC Strategy",
      "type": "equal_volume",
      "symbol": "BTC/USD"
    },
    "accounts": ["account-1", "account-2", "account-3"],
    "status": "pending",
    "targetVolume": 10.5,
    "currentVolume": 0,
    "startTime": null,
    "endTime": null,
    "duration": 3600000,
    "createdAt": "2024-12-29T10:00:00Z",
    "updatedAt": "2024-12-29T10:00:00Z"
  }
}

Get Session Status

GET /sessions/{sessionId}

Response (200 OK):

{
  "success": true,
  "data": {
    "id": "session-123",
    "name": "BTC Wash Trading Session 1",
    "status": "active",
    "targetVolume": 10.5,
    "currentVolume": 3.2,
    "progress": 30.5,
    "orderPairs": 15,
    "successfulPairs": 12,
    "failedPairs": 1,
    "riskMetrics": {
      "totalExposure": 50000,
      "maxDrawdown": 0.02,
      "currentDrawdown": 0.01,
      "riskScore": 25,
      "alerts": []
    },
    "startTime": "2024-12-29T10:05:00Z",
    "estimatedEndTime": "2024-12-29T11:05:00Z"
  }
}

List All Sessions

GET /sessions?status=active&limit=10&offset=0

Query Parameters:

  • status (optional): Filter by session status
  • limit (optional): Number of sessions to return (default: 10)
  • offset (optional): Number of sessions to skip (default: 0)

Response (200 OK):

{
  "success": true,
  "data": {
    "sessions": [
      {
        "id": "session-123",
        "name": "BTC Wash Trading Session 1",
        "status": "active",
        "targetVolume": 10.5,
        "currentVolume": 3.2,
        "progress": 30.5,
        "startTime": "2024-12-29T10:05:00Z"
      }
    ],
    "pagination": {
      "total": 1,
      "limit": 10,
      "offset": 0,
      "hasMore": false
    }
  }
}

Start Session

POST /sessions/{sessionId}/start

Response (200 OK):

{
  "success": true,
  "data": {
    "id": "session-123",
    "status": "active",
    "startTime": "2024-12-29T10:05:00Z",
    "message": "Session started successfully"
  }
}

Pause Session

POST /sessions/{sessionId}/pause

Response (200 OK):

{
  "success": true,
  "data": {
    "id": "session-123",
    "status": "paused",
    "pausedAt": "2024-12-29T10:30:00Z",
    "message": "Session paused successfully"
  }
}

Resume Session

POST /sessions/{sessionId}/resume

Response (200 OK):

{
  "success": true,
  "data": {
    "id": "session-123",
    "status": "active",
    "resumedAt": "2024-12-29T10:35:00Z",
    "message": "Session resumed successfully"
  }
}

Stop Session

POST /sessions/{sessionId}/stop

Response (200 OK):

{
  "success": true,
  "data": {
    "id": "session-123",
    "status": "completed",
    "endTime": "2024-12-29T10:40:00Z",
    "finalVolume": 8.7,
    "message": "Session stopped successfully"
  }
}

2. Account Management

List Accounts

GET /accounts

Response (200 OK):

{
  "success": true,
  "data": {
    "accounts": [
      {
        "id": "account-1",
        "name": "Primary Trading Account",
        "address": "0x1234567890abcdef1234567890abcdef12345678",
        "balance": {
          "total": 100000,
          "available": 85000,
          "used": 15000
        },
        "positions": [
          {
            "symbol": "BTC/USD",
            "side": "long",
            "size": 0.5,
            "entryPrice": 45000,
            "markPrice": 46000,
            "unrealizedPnl": 500
          }
        ],
        "riskLimits": {
          "maxPositionSize": 0.1,
          "stopLossThreshold": 0.05,
          "maxSlippage": 0.02
        },
        "isActive": true,
        "lastUpdated": "2024-12-29T10:00:00Z"
      }
    ]
  }
}

Get Account Details

GET /accounts/{accountId}

Response (200 OK):

{
  "success": true,
  "data": {
    "id": "account-1",
    "name": "Primary Trading Account",
    "address": "0x1234567890abcdef1234567890abcdef12345678",
    "balance": {
      "total": 100000,
      "available": 85000,
      "used": 15000
    },
    "positions": [
      {
        "symbol": "BTC/USD",
        "side": "long",
        "size": 0.5,
        "entryPrice": 45000,
        "markPrice": 46000,
        "unrealizedPnl": 500
      }
    ],
    "riskLimits": {
      "maxPositionSize": 0.1,
      "stopLossThreshold": 0.05,
      "maxSlippage": 0.02
    },
    "isActive": true,
    "createdAt": "2024-12-29T09:00:00Z",
    "lastUpdated": "2024-12-29T10:00:00Z"
  }
}

Update Account Risk Limits

PUT /accounts/{accountId}/risk-limits

Request Body:

{
  "maxPositionSize": 0.15,
  "stopLossThreshold": 0.03,
  "maxSlippage": 0.015
}

Response (200 OK):

{
  "success": true,
  "data": {
    "id": "account-1",
    "riskLimits": {
      "maxPositionSize": 0.15,
      "stopLossThreshold": 0.03,
      "maxSlippage": 0.015
    },
    "updatedAt": "2024-12-29T10:00:00Z",
    "message": "Risk limits updated successfully"
  }
}

3. Strategy Management

List Trading Strategies

GET /strategies

Response (200 OK):

{
  "success": true,
  "data": {
    "strategies": [
      {
        "id": "equal-volume-btc",
        "name": "Equal Volume BTC Strategy",
        "type": "equal_volume",
        "symbol": "BTC/USD",
        "parameters": {
          "volumeDistribution": "equal",
          "priceRange": {
            "min": 0.001,
            "max": 0.01
          },
          "timing": {
            "minInterval": 30000,
            "maxInterval": 120000,
            "orderSize": {
              "min": 0.1,
              "max": 0.5
            }
          },
          "riskLimits": {
            "maxPositionSize": 0.1,
            "stopLossThreshold": 0.05,
            "maxSlippage": 0.02
          }
        },
        "isActive": true,
        "createdAt": "2024-12-29T09:00:00Z"
      }
    ]
  }
}

Create Custom Strategy

POST /strategies

Request Body:

{
  "name": "Custom BTC Strategy",
  "type": "custom",
  "symbol": "BTC/USD",
  "parameters": {
    "volumeDistribution": "weighted",
    "priceRange": {
      "min": 0.002,
      "max": 0.008
    },
    "timing": {
      "minInterval": 45000,
      "maxInterval": 90000,
      "orderSize": {
        "min": 0.2,
        "max": 0.8
      }
    },
    "riskLimits": {
      "maxPositionSize": 0.12,
      "stopLossThreshold": 0.04,
      "maxSlippage": 0.015
    }
  }
}

Response (201 Created):

{
  "success": true,
  "data": {
    "id": "custom-btc-strategy-1",
    "name": "Custom BTC Strategy",
    "type": "custom",
    "symbol": "BTC/USD",
    "parameters": {
      "volumeDistribution": "weighted",
      "priceRange": {
        "min": 0.002,
        "max": 0.008
      },
      "timing": {
        "minInterval": 45000,
        "maxInterval": 90000,
        "orderSize": {
          "min": 0.2,
          "max": 0.8
        }
      },
      "riskLimits": {
        "maxPositionSize": 0.12,
        "stopLossThreshold": 0.04,
        "maxSlippage": 0.015
      }
    },
    "isActive": true,
    "createdAt": "2024-12-29T10:00:00Z"
  }
}

4. Order Management

Get Session Orders

GET /sessions/{sessionId}/orders?status=filled&limit=20&offset=0

Query Parameters:

  • status (optional): Filter by order status
  • limit (optional): Number of orders to return (default: 20)
  • offset (optional): Number of orders to skip (default: 0)

Response (200 OK):

{
  "success": true,
  "data": {
    "orders": [
      {
        "id": "order-pair-1",
        "sessionId": "session-123",
        "buyOrder": {
          "id": "buy-order-1",
          "accountId": "account-1",
          "symbol": "BTC/USD",
          "side": "buy",
          "type": "limit",
          "size": 0.3,
          "price": 45000,
          "status": "filled",
          "filledSize": 0.3,
          "averagePrice": 45005,
          "fees": 13.5,
          "slippage": 0.001,
          "createdAt": "2024-12-29T10:05:00Z"
        },
        "sellOrder": {
          "id": "sell-order-1",
          "accountId": "account-2",
          "symbol": "BTC/USD",
          "side": "sell",
          "type": "limit",
          "size": 0.3,
          "price": 45010,
          "status": "filled",
          "filledSize": 0.3,
          "averagePrice": 45008,
          "fees": 13.5,
          "slippage": 0.001,
          "createdAt": "2024-12-29T10:05:00Z"
        },
        "status": "filled",
        "volume": 0.3,
        "expectedProfit": 3.0,
        "actualProfit": 2.7,
        "fees": 27.0,
        "slippage": 0.001,
        "executionTime": 1250,
        "createdAt": "2024-12-29T10:05:00Z"
      }
    ],
    "pagination": {
      "total": 15,
      "limit": 20,
      "offset": 0,
      "hasMore": false
    }
  }
}

5. Risk Management

Get Risk Metrics

GET /sessions/{sessionId}/risk

Response (200 OK):

{
  "success": true,
  "data": {
    "sessionId": "session-123",
    "totalExposure": 50000,
    "maxDrawdown": 0.02,
    "currentDrawdown": 0.01,
    "sharpeRatio": 1.8,
    "volatility": 0.15,
    "correlation": 0.95,
    "riskScore": 25,
    "alerts": [
      {
        "id": "alert-1",
        "type": "position_size",
        "severity": "medium",
        "message": "Account account-1 position size approaching limit",
        "threshold": 0.08,
        "currentValue": 0.075,
        "accountId": "account-1",
        "isAcknowledged": false,
        "createdAt": "2024-12-29T10:15:00Z"
      }
    ],
    "lastUpdated": "2024-12-29T10:15:00Z"
  }
}

Acknowledge Risk Alert

POST /sessions/{sessionId}/risk/alerts/{alertId}/acknowledge

Response (200 OK):

{
  "success": true,
  "data": {
    "id": "alert-1",
    "isAcknowledged": true,
    "acknowledgedAt": "2024-12-29T10:20:00Z",
    "message": "Risk alert acknowledged successfully"
  }
}

6. System Status

Get System Health

GET /health

Response (200 OK):

{
  "success": true,
  "data": {
    "status": "healthy",
    "timestamp": "2024-12-29T10:00:00Z",
    "version": "1.0.0",
    "uptime": 3600,
    "components": {
      "database": "healthy",
      "pacifica-api": "healthy",
      "websocket": "healthy",
      "risk-manager": "healthy"
    },
    "metrics": {
      "activeSessions": 2,
      "totalAccounts": 20,
      "ordersPerMinute": 45,
      "averageLatency": 85
    }
  }
}

Error Responses

Standard Error Format

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": {
      "field": "targetVolume",
      "reason": "Must be greater than 0"
    }
  }
}

Common Error Codes

  • VALIDATION_ERROR: Request validation failed
  • SESSION_NOT_FOUND: Session does not exist
  • ACCOUNT_NOT_FOUND: Account does not exist
  • STRATEGY_NOT_FOUND: Strategy does not exist
  • INSUFFICIENT_BALANCE: Account balance insufficient
  • RISK_LIMIT_EXCEEDED: Risk limit exceeded
  • RATE_LIMIT_EXCEEDED: API rate limit exceeded
  • INTERNAL_ERROR: Internal server error

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

WebSocket Events

Connection

const ws = new WebSocket('ws://localhost:3000/ws');

Event Types

Session Updates

{
  "type": "session_update",
  "data": {
    "sessionId": "session-123",
    "status": "active",
    "currentVolume": 3.2,
    "progress": 30.5,
    "orderPairs": 15,
    "successfulPairs": 12,
    "failedPairs": 1,
    "timestamp": "2024-12-29T10:15:00Z"
  }
}

Order Updates

{
  "type": "order_update",
  "data": {
    "sessionId": "session-123",
    "orderPairId": "order-pair-1",
    "status": "filled",
    "volume": 0.3,
    "profit": 2.7,
    "fees": 27.0,
    "executionTime": 1250,
    "timestamp": "2024-12-29T10:15:00Z"
  }
}

Risk Alerts

{
  "type": "risk_alert",
  "data": {
    "sessionId": "session-123",
    "alertId": "alert-1",
    "type": "position_size",
    "severity": "medium",
    "message": "Account position size approaching limit",
    "accountId": "account-1",
    "timestamp": "2024-12-29T10:15:00Z"
  }
}

System Status

{
  "type": "system_status",
  "data": {
    "status": "healthy",
    "activeSessions": 2,
    "ordersPerMinute": 45,
    "averageLatency": 85,
    "timestamp": "2024-12-29T10:15:00Z"
  }
}

Rate Limiting

Limits

  • General API: 100 requests/minute per client
  • Session Management: 10 requests/minute per session
  • Order Management: 50 requests/minute per session
  • Risk Management: 20 requests/minute per session

Headers

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

Rate Limit Exceeded Response

{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Try again in 60 seconds.",
    "retryAfter": 60
  }
}

Authentication

Bearer Token

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Token Refresh

POST /auth/refresh

Request Body:

{
  "refreshToken": "refresh_token_here"
}

Response (200 OK):

{
  "success": true,
  "data": {
    "accessToken": "new_access_token",
    "refreshToken": "new_refresh_token",
    "expiresIn": 3600
  }
}