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:
-
JWT Bearer Token (Recommended)
- Include in
Authorizationheader - Format:
Bearer <access_token> - Expires after 15 minutes
- Include in
-
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 Type | Rate Limit | Window |
|---|---|---|
| Authentication | 5 requests | 15 minutes |
| Trading Operations | 100 requests | 1 minute |
| Backtesting | 10 requests | 1 minute |
| General API | 1000 requests | 15 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 Code | Meaning | Usage |
|---|---|---|
| 200 OK | Success | GET, PUT, PATCH requests |
| 201 Created | Resource created | POST requests |
| 204 No Content | Success, no body | DELETE requests |
| 400 Bad Request | Invalid input | Validation errors |
| 401 Unauthorized | Authentication required | Missing/invalid token |
| 403 Forbidden | Insufficient permissions | Access denied |
| 404 Not Found | Resource doesn't exist | Invalid ID |
| 409 Conflict | Resource conflict | Duplicate entry |
| 422 Unprocessable Entity | Business logic error | Invalid state transition |
| 429 Too Many Requests | Rate limit exceeded | Too many requests |
| 500 Internal Server Error | Server error | Unexpected 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 (ascordesc)
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.comhttps://trade.x3algo.comhttp://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​
| Type | Format | Example |
|---|---|---|
| String | UTF-8 text | "My Algorithm" |
| Number | Integer or float | 100, 3.14 |
| Boolean | true/false | true |
| Date | ISO 8601 | "2024-01-15T10:30:00Z" |
| ObjectId | MongoDB ObjectId | "507f1f77bcf86cd799439011" |
| Array | JSON array | ["AAPL", "GOOGL"] |
| Object | JSON object | {"key": "value"} |
API Endpoints​
Authentication​
- POST /api/auth/signup - Register new user
- POST /api/auth/login - Login user
- POST /api/auth/refresh-token - Refresh access token
- POST /api/auth/logout - Logout user
Algorithms​
- GET /api/trading/algorithms - List algorithms
- POST /api/trading/algorithms - Create algorithm
- GET /api/trading/algorithms/:id - Get algorithm
- PUT /api/trading/algorithms/:id - Update algorithm
- DELETE /api/trading/algorithms/:id - Delete algorithm
- POST /api/trading/algorithms/:id/start - Start algorithm
- POST /api/trading/algorithms/:id/stop - Stop algorithm
- POST /api/trading/algorithms/:id/clone - Clone algorithm
Backtests​
- GET /api/backtests - List backtests
- POST /api/backtests - Create backtest
- GET /api/backtests/:id - Get backtest results
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:
- Documentation: https://x3algo.com/docs
- Contact: https://x3algo.com/contact
Changelog​
v1.0.0 (Current)​
- Initial API release
- Algorithm CRUD operations
- Backtesting endpoints
- Authentication with JWT
Future updates will be documented here.