futures-trading Advanced

TopstepX Automated Trading: Complete API Integration Guide

Sentinel Team · 2026-03-23

Key Takeaways

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:

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:

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:

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:

  1. Track the token expiration time from the auth response
  2. Refresh the token before it expires (recommended: 5-10 minutes before expiry)
  3. Use the refresh endpoint to obtain a new token without re-entering credentials
  4. 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:

  1. Establish a SignalR connection to the Hub URL
  2. Include your access token in the connection handshake
  3. Subscribe to the event channels you need (orders, positions, quotes, account)
  4. 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:

  1. Reconnection callback: Log when the connection drops and reconnects
  2. State reconciliation: After reconnecting, query the REST API for current positions and orders to sync state
  3. Maximum reconnection attempts: After N failed attempts (e.g., 10), alert the operator and flatten positions through the REST API
  4. 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:

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:

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:

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:

  1. Track all fills (from OrderUpdate events)
  2. Calculate realized PnL from closed trades
  3. Add unrealized PnL from open positions (from PositionUpdate events)
  4. Compare total (realized + unrealized) against your daily loss threshold
  5. 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:

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:

  1. Connection test: Verify authentication, WebSocket connection, and event reception
  2. Order test: Place and cancel orders of every type (market, limit, stop, bracket)
  3. Position test: Open, modify, and flatten positions
  4. Risk test: Deliberately trigger your daily loss limit and flatten time to verify they work
  5. Disconnect test: Kill your network connection and verify the bot handles reconnection correctly
  6. Edge case test: Place orders at market close, during thin liquidity, and with unusual quantities

Logging

Log everything during testing:

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:

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:

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

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.