Trading API Reference

Reference documentation for TradeStaq's internal trading API endpoints.

Overview

The Trading API powers the dashboard's trading functionality. While primarily used internally, understanding these endpoints helps with:

  • Debugging trade issues
  • Understanding execution flow
  • Building custom integrations

Note: Direct API access is not currently available for external use. Use webhooks for automated trading.

Trade Execution Flow

┌─────────────────────────────────────────────────────────────────┐
│                    TRADE EXECUTION FLOW                         │
│                                                                 │
│  ┌──────────┐    ┌──────────────┐    ┌─────────────────────┐   │
│  │  Signal  │───▶│  Validation  │───▶│  Risk Management    │   │
│  │  Input   │    │  & Auth      │    │  (SL/TP/Size)       │   │
│  └──────────┘    └──────────────┘    └──────────┬──────────┘   │
│                                                  │              │
│                                                  ▼              │
│  ┌──────────┐    ┌──────────────┐    ┌─────────────────────┐   │
│  │  Result  │◀───│   Exchange   │◀───│  Order Builder      │   │
│  │  Return  │    │   Execution  │    │  (Format & Sign)    │   │
│  └──────────┘    └──────────────┘    └─────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘

Signal Processing

Signal Types

TypeSourceProcessing
Webhook SignalExternal POST requestQueued, validated, executed
Strategy SignalTradeStaq spinDirect execution
Copy SignalMaster traderProportional copy
Manual SignalDashboard UIImmediate execution

Signal Queue

Signals are processed in order with priorities:

PrioritySignal TypeTypical Wait
1 (Highest)Manual close< 100ms
2Strategy exit< 200ms
3Strategy entry< 300ms
4Webhook signal< 500ms

Order Types

Market Orders

Execute immediately at current market price.

{
  "type": "market",
  "side": "buy",
  "symbol": "BTC/USDT",
  "amount": 0.1
}
FieldTypeDescription
typestring"market"
sidestring"buy" or "sell"
symbolstringTrading pair
amountnumberBase currency amount

Limit Orders

Execute at specified price or better.

{
  "type": "limit",
  "side": "buy",
  "symbol": "BTC/USDT",
  "amount": 0.1,
  "price": 50000
}
FieldTypeDescription
typestring"limit"
pricenumberLimit price

Stop Loss Orders

Close position when price reaches stop level.

{
  "type": "stop_loss",
  "symbol": "BTC/USDT",
  "stopPrice": 48000,
  "closePercent": 100
}

Take Profit Orders

Close position when price reaches profit target.

{
  "type": "take_profit",
  "symbol": "BTC/USDT",
  "takeProfitPrice": 55000,
  "closePercent": 100
}

Position Management

Position Object

{
  "id": "pos_abc123",
  "symbol": "BTC/USDT",
  "side": "long",
  "size": 0.1,
  "entryPrice": 50000,
  "currentPrice": 51000,
  "pnl": 100,
  "pnlPercent": 2.0,
  "leverage": 10,
  "margin": 500,
  "liquidationPrice": 45000,
  "stopLoss": 48000,
  "takeProfit": 55000,
  "createdAt": "2024-01-01T00:00:00Z"
}

Position Fields

FieldTypeDescription
idstringUnique position identifier
symbolstringTrading pair
sidestring"long" or "short"
sizenumberPosition size in base currency
entryPricenumberAverage entry price
currentPricenumberCurrent market price
pnlnumberUnrealized PnL in quote currency
pnlPercentnumberUnrealized PnL percentage
leveragenumberPosition leverage
marginnumberUsed margin
liquidationPricenumberLiquidation price (futures)
stopLossnumberStop loss price
takeProfitnumberTake profit price
createdAtstringPosition open timestamp

Order Responses

Successful Order

{
  "success": true,
  "orderId": "ord_xyz789",
  "status": "filled",
  "symbol": "BTC/USDT",
  "side": "buy",
  "type": "market",
  "amount": 0.1,
  "filledAmount": 0.1,
  "avgPrice": 50010,
  "fee": 0.00005,
  "timestamp": 1704067200000
}

Order Status Values

StatusDescription
pendingOrder submitted, awaiting exchange
openOrder accepted, waiting to fill
partially_filledPartially executed
filledFully executed
cancelledCancelled by user or system
rejectedRejected by exchange
expiredTime limit exceeded

Failed Order

{
  "success": false,
  "error": "Insufficient balance",
  "code": "INSUFFICIENT_BALANCE",
  "details": {
    "required": 5000,
    "available": 3000
  }
}

Exchange Normalization

TradeStaq normalizes data across exchanges for consistency.

Symbol Normalization

Exchange FormatTradeStaq Format
BTCUSDT (Binance)BTC/USDT
BTCUSDT (ByBit)BTC/USDT
BTC-USDT (OKX)BTC/USDT

Order Side Normalization

ExchangeLong EntryShort Entry
Binance SpotBUYN/A
Binance FuturesBUYSELL
ByBitBuySell

Price Precision

Prices are rounded to exchange-specific precision:

SymbolPrice PrecisionQuantity Precision
BTC/USDT2 decimals5 decimals
ETH/USDT2 decimals4 decimals
DOGE/USDT5 decimals0 decimals

Error Handling

Error Categories

CategoryCodesRetry?
Validation1xxxNo
Authentication2xxxNo
Exchange3xxxMaybe
Rate Limit4xxxYes (with delay)
Server5xxxYes

Common Error Codes

CodeNameDescription
1001INVALID_SYMBOLSymbol not supported
1002INVALID_AMOUNTAmount too small/large
1003INVALID_PRICEPrice outside valid range
2001UNAUTHORIZEDInvalid authentication
2002BOT_PAUSEDBot is paused
3001INSUFFICIENT_BALANCENot enough funds
3002POSITION_NOT_FOUNDNo position to close
3003EXCHANGE_ERRORExchange returned error
4001RATE_LIMITEDToo many requests
5001INTERNAL_ERRORServer error

Execution Timing

Latency Breakdown

StageTypical TimeMax Time
Signal validation10-20ms50ms
Risk checks5-10ms20ms
Order building5-10ms20ms
Exchange API100-300ms2000ms
Total120-340ms2090ms

Factors Affecting Latency

FactorImpact
Exchange API speedMajor
Network conditionsModerate
Order complexityMinor
Server loadMinor

Paper Trading

Paper trading simulates real execution:

Differences from Live

AspectLivePaper
Fill priceMarket priceSignal price
SlippageYesNo
Partial fillsPossibleAlways 100%
FeesRealSimulated
LatencyReal~10ms

Paper Balance

PropertyValue
Initial balance$10,000 USDT
Refill cooldown24 hours
Fee simulation0.1% maker/taker

Best Practices

For Reliability

  1. Handle all error codes - Don't assume success
  2. Implement timeouts - Set reasonable limits
  3. Log everything - For debugging
  4. Use idempotent operations - Avoid duplicates

For Performance

  1. Batch when possible - Reduce API calls
  2. Cache static data - Symbol info, balances
  3. Use websockets - For real-time updates
  4. Minimize payload size - Only send needed data

New API Endpoints

Candlestick Data API

Endpoint: GET /api/charts/candles

Fetch OHLCV (Open, High, Low, Close, Volume) candlestick data for charting.

Query Parameters:

ParameterTypeRequiredDescription
symbolstringYesTrading pair (e.g., BTC/USDT)
exchangeIdstringYesExchange document ID
timeframestringYesInterval (1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w)
limitnumberNoNumber of candles (default: auto-calculated)

Response:

{
  "success": true,
  "data": {
    "symbol": "BTC/USDT",
    "timeframe": "1h",
    "candles": [
      {
        "timestamp": 1704067200000,
        "time": 1704067200,
        "open": 50000,
        "high": 50500,
        "low": 49800,
        "close": 50200,
        "volume": 123.45
      }
    ],
    "usingFallback": false
  }
}

Features:

  • Real-time OHLCV data from exchange
  • Automatic symbol normalization across exchanges
  • Fallback to public data for paper trading
  • Caching for improved performance (60 second cache)
  • Support for spot and futures markets

Use Cases:

  • Position chart rendering
  • Technical analysis
  • Historical price data
  • Trading terminal charting

Bot Analytics API

Endpoint: GET /api/tradedroid/bots/[botId]/analytics

Get comprehensive analytics and performance metrics for a TradeStaq bot.

Query Parameters:

ParameterTypeRequiredDescription
periodstringNoTime period (today, week, month, 7d, 30d, 90d, ytd, all)
startDatestringNoCustom range start (ISO date)
endDatestringNoCustom range end (ISO date)
includeEquitybooleanNoInclude equity curve data

Response:

{
  "success": true,
  "data": {
    "botId": "bot_abc123",
    "botName": "My Trading Bot",
    "symbol": "BTC/USDT",
    "period": "Last 30 Days",
    "metrics": {
      "totalTrades": 45,
      "winningTrades": 28,
      "losingTrades": 17,
      "winRate": 62.22,
      "totalPnL": 1250.50,
      "totalPnLPercent": 12.51,
      "avgWin": 75.30,
      "avgLoss": -35.20,
      "profitFactor": 2.14,
      "maxDrawdown": 8.5,
      "maxDrawdownPercent": 8.5,
      "sharpeRatio": 1.85
    },
    "formatted": {
      "totalPnL": "+$1,250.50",
      "winRate": "62.2%",
      "profitFactor": "2.14",
      "maxDrawdown": "8.5%"
    },
    "equityCurve": [
      {
        "timestamp": 1704067200000,
        "equity": 10000,
        "drawdown": 0
      }
    ],
    "availablePeriods": [
      { "value": "today", "label": "Today" },
      { "value": "7d", "label": "Last 7 Days" }
    ]
  }
}

Metrics Explained:

  • Win Rate: Percentage of profitable trades
  • Profit Factor: Gross profit ÷ Gross loss (higher is better, > 1.5 is good)
  • Max Drawdown: Largest peak-to-trough decline
  • Sharpe Ratio: Risk-adjusted return (> 1.0 is good)

Use Cases:

  • Bot dashboard performance display
  • Historical performance analysis
  • Strategy comparison
  • Risk assessment

Bot Risk Metrics API

Endpoint: GET /api/tradedroid/bots/[botId]/risk

Get detailed risk metrics and exposure analysis for a TradeStaq bot.

Response:

{
  "success": true,
  "data": {
    "botId": "bot_abc123",
    "currentExposure": 0.15,
    "maxExposureAllowed": 0.20,
    "dailyLossLimit": 500,
    "dailyLossUsed": 125.50,
    "consecutiveLosses": 2,
    "maxConsecutiveLosses": 5,
    "riskScore": 3.5,
    "riskLevel": "moderate"
  }
}

Risk Levels:

  • low (1-2): Conservative risk profile
  • moderate (3-4): Balanced risk/reward
  • high (5-7): Aggressive trading
  • extreme (8-10): Very high risk

Use Cases:

  • Risk monitoring
  • Portfolio management
  • Automated risk controls
  • Compliance reporting

Next Steps