Python NinjaTrader 8 API examples
Build NinjaTrader 8 trading bots in Python. Place orders, manage positions, and stream live market data over the CrossTrade REST + WebSocket API. requests for REST, websockets for streaming.
Using Python against the CrossTrade NinjaTrader API
Python is the most popular language for trading-bot prototypes. The CrossTrade REST API is plain JSON over HTTPS, so requests is all you need for order placement and account inspection. For streaming quotes and live P&L, asyncio + websockets gives you a clean coroutine flow.
requests (or httpx) websockets (asyncio) Watch the request get written
A pseudo-developer types out a real POST PlaceOrder call against your NinjaTrader 8 account. The animation runs on a loop; the static snippet below is yours to copy.
Complete Python PlaceOrder example
import requests
TOKEN = "your-bearer-token"
url = "https://app.crosstrade.io/v1/api/accounts/Sim101/orders/place"
headers = {
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
}
order = {
"instrument": "MES 12-25",
"action": "BUY",
"orderType": "MARKET",
"quantity": 1,
"timeInForce": "DAY",
}
r = requests.post(url, headers=headers, json=order)
print(r.status_code, r.json())
# 200 {'orderId': 'cb1fc8d4...', 'success': True} Streaming data with websockets (asyncio)
Same flow on a persistent connection: open the socket, send a subscribe message, receive market data or P&L pushes in real time. CrossTrade's WebSocket is at wss://app.crosstrade.io/ws/stream with the same Bearer token in the request header.
Complete Python WebSocket example
import asyncio, json, websockets
async def stream_pnl():
uri = "wss://app.crosstrade.io/ws/stream"
headers = {"Authorization": "Bearer YOUR_TOKEN"}
async with websockets.connect(uri, extra_headers=headers) as ws:
await ws.send(json.dumps({"action": "streamPnl", "enabled": True}))
async for raw in ws:
msg = json.loads(raw)
if msg.get("type") == "pnlUpdate":
for acct in msg["accounts"]:
print(acct["name"], acct["pnl"]["totalNet"])
asyncio.run(stream_pnl()) The full Python-compatible API surface
Every endpoint documented with request/response schemas, error codes, rate-limit notes, and language-specific code samples.
Common questions
Is Python a good language for algorithmic trading on NinjaTrader 8?
Yes. Python is the most popular language for trading research and bot prototyping, and CrossTrade's REST + WebSocket APIs were designed with Python clients in mind. You get the standard library (requests, websockets, asyncio), the data ecosystem (pandas, numpy, ta-lib), and the broker bridge (CrossTrade Add-On into NT8). Everything you need without writing C#.
Do I need a CrossTrade Python SDK?
You don't โ the API is plain JSON over HTTPS, so the requests library is all you need. For async, use httpx or aiohttp. For WebSocket, use the websockets package. Most users prefer the bare-API approach because they integrate CrossTrade calls into existing trading code rather than wrapping them.
Should I use requests, httpx, or aiohttp?
requests for simple synchronous scripts (the example above). httpx if you need both async and sync from the same client. aiohttp if you're already inside an asyncio app. All three send the same Authorization: Bearer header and the same JSON body. Only the call style changes.
How does this integrate with pandas?
Cleanly. GetJournalTrades, GetExecutions, and GetBars all return JSON arrays that pandas reads in one line: pd.DataFrame(response.json()["trades"]). From there you have the full pandas / numpy / scipy stack for analysis, backtest stats, and signal engineering.
What about backtest libraries like backtrader, vectorbt, or zipline?
Use them for offline research; CrossTrade complements them. Pull historical bars via GetBars, run your backtest in vectorbt, then place live orders via the REST API. You don't replace one with the other. CrossTrade is the execution + live-data layer.
Can I run an async WebSocket loop and place REST orders from the same script?
Yes. The standard pattern is asyncio for the WebSocket loop and httpx.AsyncClient (or aiohttp) for REST calls inside the same event loop. You can also call sync requests.post from within an async function if you're careful not to block the loop for long.
How fast is Python for trading? Will it bottleneck on latency?
For the 99% of strategies that operate on second/minute bars, Python is plenty fast. CrossTrade's round-trip latency is around 50ms median; Python's call overhead is negligible against that. For sub-millisecond strategies (Level 2 market making, true HFT) you'd move to a compiled language anyway, but that's a tiny minority.
How do I handle the API rate limit?
CrossTrade allows 180 req/min (3/sec) with a burst of 20, shared across REST + WebSocket. Use a simple time-based throttle, or libraries like ratelimit or aiolimiter. On a 429 response, back off and retry; CrossTrade returns standard X-RateLimit headers.
Can I package my Python bot as a single binary?
Yes โ PyInstaller, Nuitka, or pex bundle Python plus your script into a standalone executable. Useful for Windows VPS deployment where you don't want to install Python on every host.
Build your first NinjaTrader 8 trading bot in Python
One bearer token, one URL, every NinjaTrader endpoint. Ship to Sim101 first.