Key Takeaways
- TopstepX uses the ProjectX Gateway API for all automated trading -- REST for commands, SignalR WebSocket for real-time updates
- Authentication uses token-based auth through the API portal; tokens must be included in every request header
- The real-time User Hub at
rtc.thefuturesdesk.projectx.com/hubs/userstreams account, order, position, and quote updates via WebSocket - All automated orders must include the isAutomated flag per CME Rule 575 -- this is a regulatory requirement, not optional
- Python, Java, .NET, and JavaScript are all supported; the ProjectX Python SDK (
project-x-py) provides the fastest path to a working integration
This guide is a technical deep-dive into integrating with the TopstepX API for automated futures trading. If you are looking for policy information about whether bots are allowed, start with our TopstepX bot rules guide. This article focuses on the engineering: API architecture, authentication flow, WebSocket connections, order lifecycle, and practical code patterns.
The TopstepX API is powered by ProjectX, which provides the Gateway API used by TopstepX and The Futures Desk platform. All the technical details here apply specifically to the ProjectX Gateway as accessed through a TopstepX account.
API Architecture Overview
The ProjectX Gateway API follows a hybrid REST plus WebSocket architecture:
REST API
The REST API handles synchronous operations:
- Account management: Retrieve account details, balances, and trading permissions
- Order placement: Submit market, limit, stop, and bracket orders
- Order management: Modify or cancel pending orders
- Position queries: Check current open positions and PnL
- Historical data: Retrieve historical price data for backtesting or analysis
- Contract information: Look up contract specifications, tick sizes, and margin requirements
Base URL: https://api.thefuturesdesk.projectx.com
All REST endpoints accept and return JSON. Standard HTTP methods apply: GET for queries, POST for creation, PUT for modification, DELETE for cancellation.
WebSocket (SignalR) Hub
The real-time system uses Microsoft's SignalR library, which provides a persistent WebSocket connection for streaming data:
- Account updates: Balance changes, margin usage, daily PnL
- Order updates: Order acknowledgments, fills, partial fills, rejections, cancellations
- Position updates: Real-time position changes, unrealized PnL
- Market quotes: Real-time bid/ask/last prices for subscribed contracts
Hub URL: https://rtc.thefuturesdesk.projectx.com/hubs/user
SignalR automatically handles connection management, reconnection, and transport fallback (WebSocket to Server-Sent Events to Long Polling). For Python developers, the signalrcore library provides a clean interface to SignalR hubs.
For the official documentation, visit the ProjectX Gateway API docs.
Authentication Flow
Before making any API calls, you need to authenticate and obtain an access token.
Step 1: Obtain API Credentials
After subscribing to TopstepX's API add-on ($29/month), generate your API credentials in the TopstepX dashboard:
- Username: Your TopstepX account email
- API Key: Generated in the API settings panel
- Environment: Live or Simulation (use simulation for testing)
Step 2: Authenticate
Send a POST request to the authentication endpoint with your credentials. The response includes an access token that you will use for all subsequent requests.
POST /api/auth/login
Content-Type: application/json
{
"username": "[email protected]",
"apiKey": "your_api_key"
}
The response returns a JSON object containing your access token and its expiration time. Store this token securely and include it in the Authorization header of all subsequent requests:
Authorization: Bearer <your_access_token>
Step 3: Token Refresh
Access tokens expire after a set period (typically 24 hours). Your bot must handle token refresh automatically:
- Track the token expiration time from the auth response
- Refresh the token before it expires (recommended: 5-10 minutes before expiry)
- Use the refresh endpoint to obtain a new token without re-entering credentials
- Update the Authorization header with the new token
Bots that do not handle token refresh will stop working when the token expires, potentially leaving open positions unmanaged.
Connecting to the Real-Time Hub
The SignalR hub connection is essential for receiving real-time updates about your orders and positions.
Connection Setup
To connect to the User Hub:
- Establish a SignalR connection to the Hub URL
- Include your access token in the connection handshake
- Subscribe to the event channels you need (orders, positions, quotes, account)
- Implement handlers for each event type
The connection negotiation follows the SignalR protocol. In Python with the signalrcore library, the connection pattern is:
hub_url = "https://rtc.thefuturesdesk.projectx.com/hubs/user"
# Build connection with access token
# Subscribe to events: OrderUpdate, PositionUpdate, AccountUpdate, Quote
# Start connection and begin receiving events
Event Types
The hub emits several event types:
OrderUpdate: Fired when any order status changes. Includes order ID, status (Working, Filled, Cancelled, Rejected), fill price, fill quantity, and timestamp.
PositionUpdate: Fired when your position changes. Includes contract symbol, quantity (positive for long, negative for short), average entry price, and unrealized PnL.
AccountUpdate: Fired when account balance or margin changes. Includes current balance, used margin, available margin, and daily PnL.
Quote: Fired on every tick for subscribed contracts. Includes bid price, ask price, last traded price, volume, and timestamp.
Handling Disconnections
SignalR handles reconnection automatically, but your bot should implement additional safeguards:
- Reconnection callback: Log when the connection drops and reconnects
- State reconciliation: After reconnecting, query the REST API for current positions and orders to sync state
- Maximum reconnection attempts: After N failed attempts (e.g., 10), alert the operator and flatten positions through the REST API
- Heartbeat monitoring: If no events are received for an extended period, actively ping the connection to verify it is alive
Order Placement
Placing orders through the API requires constructing a properly formatted order request.
Order Types
The API supports standard CME order types:
- Market order: Execute immediately at the best available price
- Limit order: Execute at the specified price or better
- Stop order: Trigger a market order when price reaches the stop level
- Stop-limit order: Trigger a limit order when price reaches the stop level
- Bracket order: Entry order with attached stop-loss and take-profit orders
Order Request Structure
A typical order request includes:
POST /api/orders
Authorization: Bearer <token>
Content-Type: application/json
{
"accountId": "your_account_id",
"contractId": "NQ_contract_id",
"action": "Buy",
"orderType": "Market",
"quantity": 1,
"isAutomated": true
}
Critical fields:
- accountId: Your TopstepX account identifier
- contractId: The specific contract to trade (obtain from contract lookup endpoint)
- action: Buy or Sell
- orderType: Market, Limit, Stop, StopLimit
- quantity: Number of contracts
- isAutomated: Must be
truefor all bot-placed orders (CME Rule 575) - price: Required for Limit and StopLimit orders
- stopPrice: Required for Stop and StopLimit orders
The isAutomated Flag
Every single order placed by your automated system must include isAutomated: true. This is a regulatory requirement from the CME Group under Rule 575, which mandates that all algorithmic trading activity on CME exchanges must be identified as such.
Omitting this flag or setting it to false when using automated trading is a compliance violation that can result in regulatory penalties.
Bracket Orders
Bracket orders (entry with attached stop-loss and take-profit) are the most common pattern for automated strategies:
{
"accountId": "your_account_id",
"contractId": "NQ_contract_id",
"action": "Buy",
"orderType": "Limit",
"quantity": 1,
"price": 18500.00,
"isAutomated": true,
"bracket": {
"stopLoss": 18480.00,
"takeProfit": 18540.00
}
}
Bracket orders ensure that every entry has defined risk and reward, which is essential for prop firm risk management.
Position Management
Active position management is critical for prop firm compliance.
Querying Current Positions
Use the positions endpoint to check your current state:
GET /api/positions?accountId=your_account_id
Authorization: Bearer <token>
The response includes all open positions with entry price, quantity, side, unrealized PnL, and contract details.
Flatten All Positions
The flatten operation closes all open positions immediately with market orders. This is essential for:
- Daily flatten time compliance (before 3:10 PM CT)
- Emergency position closure when risk limits are breached
- End-of-day cleanup
POST /api/positions/flatten
Authorization: Bearer <token>
{
"accountId": "your_account_id",
"isAutomated": true
}
Daily PnL Tracking
Your bot must track daily PnL in real time and compare it against the daily loss limit. The account update events from the WebSocket provide real-time PnL, but you should also maintain your own independent PnL calculation as a safety check.
The formula for daily PnL monitoring:
- Track all fills (from OrderUpdate events)
- Calculate realized PnL from closed trades
- Add unrealized PnL from open positions (from PositionUpdate events)
- Compare total (realized + unrealized) against your daily loss threshold
- If threshold is reached, flatten all positions and stop trading for the day
Building a Complete Bot: Architecture Pattern
Here is the recommended architecture for a production-grade TopstepX trading bot:
Component 1: Connection Manager
Handles authentication, token refresh, REST client initialization, and SignalR hub connection. This component runs as a background task and ensures the bot always has valid credentials and an active WebSocket connection.
Component 2: Market Data Handler
Processes incoming quote events from the WebSocket hub. Maintains a local order book with current bid/ask/last prices. Feeds price data to the strategy engine. Manages subscriptions to specific contracts.
Component 3: Strategy Engine
The core trading logic. Takes market data as input, applies your strategy rules, and outputs trade signals (Buy, Sell, Flatten, or Hold). This component should be stateless and testable independent of the API connection.
Component 4: Risk Manager
Sits between the strategy engine and the order executor. Validates every trade signal against risk parameters before it becomes an order. Checks daily PnL limit, position size limit, trading hours, flatten time, and any other prop firm rules. Has the authority to reject signals and force-flatten positions.
Component 5: Order Executor
Converts validated trade signals into API order requests. Manages the order lifecycle: submission, acknowledgment, fill, partial fill, rejection, and cancellation. Handles retry logic for transient API errors.
Component 6: State Manager
Maintains the authoritative state of all positions, orders, and account metrics. Reconciles state between local tracking and API queries. Logs all state changes for audit purposes.
Component 7: Monitoring and Alerting
Sends notifications for critical events: connection loss, daily loss limit approaching, flatten time approaching, unexpected errors, and strategy performance deviations. Use Telegram, email, or SMS for alerts.
The Python SDK Shortcut
If you want to skip building the low-level API integration, the ProjectX Python SDK (project-x-py) provides a high-level interface:
- Async/await support for non-blocking operations
- Built-in WebSocket management with automatic reconnection
- Order management with helper methods for common patterns
- Technical indicator calculations
- Market depth analysis
- Historical data retrieval with pandas DataFrame output
Install with: pip install project-x-py
The SDK abstracts away the SignalR connection management, authentication flow, and request formatting, letting you focus on strategy logic rather than API plumbing.
Testing Your Integration
Before connecting to a live account, test thoroughly in the simulation environment.
Simulation Environment
TopstepX provides a simulation environment that mirrors the live API with simulated market data. Use the simulation endpoints for all testing:
- Connection test: Verify authentication, WebSocket connection, and event reception
- Order test: Place and cancel orders of every type (market, limit, stop, bracket)
- Position test: Open, modify, and flatten positions
- Risk test: Deliberately trigger your daily loss limit and flatten time to verify they work
- Disconnect test: Kill your network connection and verify the bot handles reconnection correctly
- Edge case test: Place orders at market close, during thin liquidity, and with unusual quantities
Logging
Log everything during testing:
- Every API request and response
- Every WebSocket event received
- Every strategy signal generated
- Every risk check passed or failed
- Every order state transition
- All errors and exceptions with full stack traces
These logs are invaluable for debugging issues that surface during live trading.
Paper Trading Period
After simulation testing, run your bot against live market data in paper trading mode for at least 5 trading days. Paper trading uses real market data but does not place actual orders. This validates that your strategy performs as expected with real market dynamics (gaps, news events, thin liquidity periods) without risking your evaluation.
Performance Optimization
Once your basic integration works, consider these optimizations:
Minimize API Calls
Every REST API call adds latency. Use the WebSocket hub for real-time data instead of polling REST endpoints. Only use REST for:
- Initial state loading at startup
- State reconciliation after reconnection
- Order placement and cancellation
Local State Management
Maintain a local mirror of your positions and orders using WebSocket events. This eliminates the need to query the API for current state on every strategy tick. Only reconcile against the REST API periodically (e.g., every 5 minutes) or after a reconnection.
Connection Stability
A stable WebSocket connection is critical. Best practices:
- Use a wired Ethernet connection, not WiFi
- Disable power saving features that might sleep the network adapter
- Monitor connection latency and alert if it exceeds thresholds
- Consider running on a machine dedicated to trading (not your general-purpose laptop)
Sentinel Bot: Skip the Engineering
If building and maintaining a custom API integration sounds like more work than you want to take on, Sentinel Bot handles all of this for you. Sentinel integrates with the ProjectX API internally, manages the WebSocket connection, handles authentication and token refresh, and provides a visual strategy builder so you can focus on your trading logic rather than API plumbing.
With Sentinel Bot, the entire integration described in this guide is handled behind the scenes. You configure your strategy through the visual block builder, connect your TopstepX credentials, and launch. The bot handles the rest.
Skip the months of API development. Sentinel Bot handles the TopstepX integration so you can focus on strategy, not code. Start your free trial -->
FAQ
Q: What programming languages does the TopstepX API support?
The ProjectX Gateway API is language-agnostic since it uses REST and SignalR. You can use Python, Java, C#/.NET, JavaScript/Node.js, Go, Rust, or any language that supports HTTP requests and WebSocket connections. Python is the most popular choice due to the official project-x-py SDK and the broad ecosystem of trading libraries.
Q: How do I handle API rate limits?
The ProjectX API has rate limits to prevent abuse. While specific limits are not publicly documented, best practices include: batch requests where possible, use WebSocket for real-time data instead of polling REST endpoints, implement exponential backoff on 429 (Too Many Requests) responses, and cache contract specifications locally.
Q: Can I access historical data through the API for backtesting?
Yes, the API provides historical price data endpoints. However, for comprehensive backtesting, you may want to use a dedicated backtest engine like Sentinel Bot that includes tick-based PnL simulation specifically calibrated for CME futures contracts. The API's historical data is better suited for recent lookback analysis than full-scale strategy development.
Q: What happens if the API goes down while I have open positions?
If you lose connectivity to the API, your existing orders (including stop-loss and take-profit brackets) remain active on the exchange. They do not get cancelled when your bot disconnects. However, your bot cannot place new orders or flatten positions until the connection is restored. This is why bracket orders are recommended: they provide protection even when your bot is disconnected.
Q: Is there a sandbox environment for testing?
Yes, TopstepX provides simulation accounts that use the same API endpoints but with simulated market data and no real capital at risk. Always develop and test against the simulation environment before switching to live trading.
Q: How do I handle multiple TopstepX accounts from one bot?
You can authenticate with multiple accounts and maintain separate WebSocket connections for each. However, ensure each account's risk management is independent. A common pattern is to run a separate bot instance per account, each with its own configuration and risk parameters.
Related Articles
- Can You Use Bots on TopstepX? Rules, Limits and Setup Guide
- How to Pass TopstepX Evaluation with Automated Trading
- How to Backtest Futures Strategies: NQ, ES, CL Step-by-Step Guide
- Best Futures Trading Bot 2026: Top 7 Software Ranked
Disclaimer: This article is for educational purposes only. Trading futures involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results. API specifications and endpoints may change without notice -- always refer to the official ProjectX documentation for current details. Never risk more than you can afford to lose.