Skip to main content
Version: 1.0 (Current)

API Overview

The x3Algo API provides programmatic access to all algorithm builder features, allowing you to create, manage, and monitor trading algorithms through HTTP requests.

Base URL​

All API requests should be made to:

Production:  https://api.x3algo.com
Development: http://localhost:8000

API Versioning​

The current API version is v1. All endpoints are prefixed with /api:

https://api.x3algo.com/api/trading/algorithms
https://api.x3algo.com/api/backtests

Future versions will be introduced as /api/v2 when breaking changes are required. The v1 API will be maintained for backward compatibility.

Architecture​

The x3Algo API follows RESTful principles:

  • Resources are represented as nouns (e.g., /algorithms, /backtests)
  • HTTP methods indicate actions (GET, POST, PUT, PATCH, DELETE)
  • Status codes indicate success or failure
  • JSON is used for request and response bodies

Request Flow​

Client → API Gateway → Authentication → Rate Limiting → Controller → Service → Repository → Database

Authentication​

All API endpoints (except authentication endpoints) require a valid JWT access token.

Authentication Methods:

  1. JWT Bearer Token (Recommended)

    • Include in Authorization header
    • Format: Bearer <access_token>
    • Expires after 15 minutes
  2. Session Cookie (Web applications)

    • Automatically included by browser
    • HTTP-only, secure cookie
    • Expires after 7 days

See Authentication Reference for detailed information.

Rate Limiting​

Rate limits protect the API from abuse and ensure fair usage:

Endpoint TypeRate LimitWindow
Authentication5 requests15 minutes
Trading Operations100 requests1 minute
Backtesting10 requests1 minute
General API1000 requests15 minutes

Rate Limit Headers:

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

When rate limit is exceeded, you'll receive a 429 Too Many Requests response:

{
"error": {
"message": "Rate limit exceeded",
"code": "TOO_MANY_REQUESTS",
"status": 429,
"retryAfter": 60
}
}

Request Format​

Headers​

All requests should include:

Content-Type: application/json
Authorization: Bearer <access_token>

Request Body​

Request bodies must be valid JSON:

{
"name": "My Trading Algorithm",
"strategyType": "momentum",
"timeframe": "15m"
}

Response Format​

Success Response​

Successful responses return the requested data with appropriate status code:

{
"id": "507f1f77bcf86cd799439011",
"name": "My Trading Algorithm",
"status": "active",
"createdAt": "2024-01-15T10:30:00Z"
}

Collection Response:

{
"data": [
{ "id": "1", "name": "Algorithm 1" },
{ "id": "2", "name": "Algorithm 2" }
],
"pagination": {
"page": 1,
"limit": 20,
"total": 45,
"totalPages": 3
}
}

Error Response​

Error responses follow a standard format:

{
"error": {
"message": "Algorithm not found",
"code": "NOT_FOUND",
"status": 404,
"details": {},
"requestId": "abc-123-def"
}
}

See Error Codes Reference for complete error documentation.

HTTP Status Codes​

Status CodeMeaningUsage
200 OKSuccessGET, PUT, PATCH requests
201 CreatedResource createdPOST requests
204 No ContentSuccess, no bodyDELETE requests
400 Bad RequestInvalid inputValidation errors
401 UnauthorizedAuthentication requiredMissing/invalid token
403 ForbiddenInsufficient permissionsAccess denied
404 Not FoundResource doesn't existInvalid ID
409 ConflictResource conflictDuplicate entry
422 Unprocessable EntityBusiness logic errorInvalid state transition
429 Too Many RequestsRate limit exceededToo many requests
500 Internal Server ErrorServer errorUnexpected error

Pagination​

List endpoints support pagination using query parameters:

GET /api/trading/algorithms?page=1&limit=20

Parameters:

  • page - Page number (default: 1)
  • limit - Items per page (default: 20, max: 100)

Response:

{
"data": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 100,
"totalPages": 5
}
}

Filtering and Sorting​

Filtering​

Filter results using query parameters:

GET /api/trading/algorithms?status=active&strategyType=momentum

Sorting​

Sort results using sort and order parameters:

GET /api/trading/algorithms?sort=createdAt&order=desc

Parameters:

  • sort - Field to sort by (e.g., createdAt, name)
  • order - Sort direction (asc or desc)

Idempotency​

Some operations support idempotency to prevent duplicate actions:

POST /api/trading/algorithms/:id/start
Idempotency-Key: unique-key-123

If the same idempotency key is used within 24 hours, the original response is returned without executing the operation again.

CORS​

The API supports Cross-Origin Resource Sharing (CORS) for web applications:

Allowed Origins:

  • https://x3algo.com
  • https://trade.x3algo.com
  • http://localhost:4000 (development)
  • http://localhost:4001 (development)

Allowed Methods:

  • GET, POST, PUT, PATCH, DELETE, OPTIONS

Allowed Headers:

  • Content-Type, Authorization, X-Request-ID

Timestamps​

All timestamps are in ISO 8601 format with UTC timezone:

2024-01-15T10:30:00Z

Data Types​

TypeFormatExample
StringUTF-8 text"My Algorithm"
NumberInteger or float100, 3.14
Booleantrue/falsetrue
DateISO 8601"2024-01-15T10:30:00Z"
ObjectIdMongoDB ObjectId"507f1f77bcf86cd799439011"
ArrayJSON array["AAPL", "GOOGL"]
ObjectJSON object{"key": "value"}

API Endpoints​

Authentication​

Algorithms​

Backtests​

SDK and Libraries​

Official SDKs are planned for:

  • JavaScript/TypeScript - For Node.js and browser applications
  • Python - For data analysis and algorithmic trading

Currently, use any HTTP client library:

JavaScript (Axios):

const axios = require('axios')

const api = axios.create({
baseURL: 'https://api.x3algo.com',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
})

const algorithms = await api.get('/api/trading/algorithms')

Python (Requests):

import requests

headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}

response = requests.get(
'https://api.x3algo.com/api/trading/algorithms',
headers=headers
)
algorithms = response.json()

cURL:

curl -X GET https://api.x3algo.com/api/trading/algorithms \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json"

Webhooks​

Webhooks allow you to receive real-time notifications for events:

  • Algorithm started/stopped
  • Trade executed
  • Backtest completed
  • Daily loss limit reached

See Webhooks Documentation (coming soon) for setup instructions.

Best Practices​

1. Use HTTPS​

Always use HTTPS in production to encrypt data in transit.

2. Store Tokens Securely​

  • Never expose access tokens in client-side code
  • Store tokens in secure, HTTP-only cookies or secure storage
  • Rotate tokens regularly

3. Handle Rate Limits​

  • Implement exponential backoff for retries
  • Cache responses when appropriate
  • Use webhooks instead of polling

4. Validate Input​

  • Validate all input on client side before sending
  • Handle validation errors gracefully
  • Provide clear error messages to users

5. Handle Errors​

  • Always check response status codes
  • Implement proper error handling
  • Log errors for debugging

6. Use Pagination​

  • Always paginate large result sets
  • Use reasonable page sizes (20-50 items)
  • Implement infinite scroll or "Load More" buttons

7. Monitor API Usage​

  • Track API calls and response times
  • Set up alerts for errors and rate limits
  • Monitor performance metrics

Support​

For API support:

Changelog​

v1.0.0 (Current)​

  • Initial API release
  • Algorithm CRUD operations
  • Backtesting endpoints
  • Authentication with JWT

Future updates will be documented here.