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
| Type | Source | Processing |
|---|---|---|
| Webhook Signal | External POST request | Queued, validated, executed |
| Strategy Signal | TradeStaq spin | Direct execution |
| Copy Signal | Master trader | Proportional copy |
| Manual Signal | Dashboard UI | Immediate execution |
Signal Queue
Signals are processed in order with priorities:
| Priority | Signal Type | Typical Wait |
|---|---|---|
| 1 (Highest) | Manual close | < 100ms |
| 2 | Strategy exit | < 200ms |
| 3 | Strategy entry | < 300ms |
| 4 | Webhook signal | < 500ms |
Order Types
Market Orders
Execute immediately at current market price.
{
"type": "market",
"side": "buy",
"symbol": "BTC/USDT",
"amount": 0.1
}
| Field | Type | Description |
|---|---|---|
type | string | "market" |
side | string | "buy" or "sell" |
symbol | string | Trading pair |
amount | number | Base currency amount |
Limit Orders
Execute at specified price or better.
{
"type": "limit",
"side": "buy",
"symbol": "BTC/USDT",
"amount": 0.1,
"price": 50000
}
| Field | Type | Description |
|---|---|---|
type | string | "limit" |
price | number | Limit 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
| Field | Type | Description |
|---|---|---|
id | string | Unique position identifier |
symbol | string | Trading pair |
side | string | "long" or "short" |
size | number | Position size in base currency |
entryPrice | number | Average entry price |
currentPrice | number | Current market price |
pnl | number | Unrealized PnL in quote currency |
pnlPercent | number | Unrealized PnL percentage |
leverage | number | Position leverage |
margin | number | Used margin |
liquidationPrice | number | Liquidation price (futures) |
stopLoss | number | Stop loss price |
takeProfit | number | Take profit price |
createdAt | string | Position 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
| Status | Description |
|---|---|
pending | Order submitted, awaiting exchange |
open | Order accepted, waiting to fill |
partially_filled | Partially executed |
filled | Fully executed |
cancelled | Cancelled by user or system |
rejected | Rejected by exchange |
expired | Time 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 Format | TradeStaq Format |
|---|---|
BTCUSDT (Binance) | BTC/USDT |
BTCUSDT (ByBit) | BTC/USDT |
BTC-USDT (OKX) | BTC/USDT |
Order Side Normalization
| Exchange | Long Entry | Short Entry |
|---|---|---|
| Binance Spot | BUY | N/A |
| Binance Futures | BUY | SELL |
| ByBit | Buy | Sell |
Price Precision
Prices are rounded to exchange-specific precision:
| Symbol | Price Precision | Quantity Precision |
|---|---|---|
| BTC/USDT | 2 decimals | 5 decimals |
| ETH/USDT | 2 decimals | 4 decimals |
| DOGE/USDT | 5 decimals | 0 decimals |
Error Handling
Error Categories
| Category | Codes | Retry? |
|---|---|---|
| Validation | 1xxx | No |
| Authentication | 2xxx | No |
| Exchange | 3xxx | Maybe |
| Rate Limit | 4xxx | Yes (with delay) |
| Server | 5xxx | Yes |
Common Error Codes
| Code | Name | Description |
|---|---|---|
1001 | INVALID_SYMBOL | Symbol not supported |
1002 | INVALID_AMOUNT | Amount too small/large |
1003 | INVALID_PRICE | Price outside valid range |
2001 | UNAUTHORIZED | Invalid authentication |
2002 | BOT_PAUSED | Bot is paused |
3001 | INSUFFICIENT_BALANCE | Not enough funds |
3002 | POSITION_NOT_FOUND | No position to close |
3003 | EXCHANGE_ERROR | Exchange returned error |
4001 | RATE_LIMITED | Too many requests |
5001 | INTERNAL_ERROR | Server error |
Execution Timing
Latency Breakdown
| Stage | Typical Time | Max Time |
|---|---|---|
| Signal validation | 10-20ms | 50ms |
| Risk checks | 5-10ms | 20ms |
| Order building | 5-10ms | 20ms |
| Exchange API | 100-300ms | 2000ms |
| Total | 120-340ms | 2090ms |
Factors Affecting Latency
| Factor | Impact |
|---|---|
| Exchange API speed | Major |
| Network conditions | Moderate |
| Order complexity | Minor |
| Server load | Minor |
Paper Trading
Paper trading simulates real execution:
Differences from Live
| Aspect | Live | Paper |
|---|---|---|
| Fill price | Market price | Signal price |
| Slippage | Yes | No |
| Partial fills | Possible | Always 100% |
| Fees | Real | Simulated |
| Latency | Real | ~10ms |
Paper Balance
| Property | Value |
|---|---|
| Initial balance | $10,000 USDT |
| Refill cooldown | 24 hours |
| Fee simulation | 0.1% maker/taker |
Best Practices
For Reliability
- Handle all error codes - Don't assume success
- Implement timeouts - Set reasonable limits
- Log everything - For debugging
- Use idempotent operations - Avoid duplicates
For Performance
- Batch when possible - Reduce API calls
- Cache static data - Symbol info, balances
- Use websockets - For real-time updates
- 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
symbol | string | Yes | Trading pair (e.g., BTC/USDT) |
exchangeId | string | Yes | Exchange document ID |
timeframe | string | Yes | Interval (1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w) |
limit | number | No | Number 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:
| Parameter | Type | Required | Description |
|---|---|---|---|
period | string | No | Time period (today, week, month, 7d, 30d, 90d, ytd, all) |
startDate | string | No | Custom range start (ISO date) |
endDate | string | No | Custom range end (ISO date) |
includeEquity | boolean | No | Include 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 profilemoderate(3-4): Balanced risk/rewardhigh(5-7): Aggressive tradingextreme(8-10): Very high risk
Use Cases:
- Risk monitoring
- Portfolio management
- Automated risk controls
- Compliance reporting
Next Steps
- Webhook API - External signal integration
- Rate Limits - Understanding limits
- Troubleshooting - Error resolution