Skip to main content

Official Python client for QJ Trader — Canadian and selected US market data and order entry.

Project description

qjtrader

Hosted assistants should use the delegated OAuth connector from QJ Gateway, which keeps the trading client secret out of chat. This SDK remains the full programmatic client for Python services and local agents.

PyPI version Python versions License

Official Python client for the QJ Trader AI Trading APIs — stream real-time Canadian and selected US market data and send orders through entitled Canadian or US gateway accounts (Montréal Exchange derivatives, and equities across every lit exchange and dark pool) over one authenticated connection.

pip install qjtrader
  • Free sandbox, no approval. Create an account at gateway.qjtrader.ai, click Create sandbox credential, and you get a client_id + client_secret that stream simulated data and return simulated fills — in the exact production wire format, 24/7.
  • Sandbox → production without a code change. Request licensed data and order authority independently; the Gateway promotes the credential server-side and reports the authoritative state.
  • Stdlib only. No dependencies — easy to install, easy to audit.
  • Verifiable releases. Published straight from this repo via PyPI Trusted Publishing with signed PEP 740 provenance — no manual uploads, no stored tokens. See SECURITY.md to verify a release.

Quickstart

Get a sandbox key from the console, then:

export QJ_CLIENT_ID="your-client-id"
export QJ_CLIENT_SECRET="your-client-secret"

Send an order

import qjtrader

client = qjtrader.Client()  # reads QJ_CLIENT_ID / QJ_CLIENT_SECRET from the environment

with client.orders() as oe:
    fill = oe.order_and_wait(
        sym="MX:CRAU26", side="buy", qty=1, price=97.00, account="SIM", tif="ioc",
    )
    print(fill)   # {'type': 'exec', 'status': 'filled', 'last_px': 97.0, 'cum_qty': 1, ...}

Lower-level, if you want every message:

with client.orders() as oe:
    cid = oe.order(sym="MX:CRAU26", side="buy", qty=1, price=97.00, account="SIM")
    for msg in oe.updates(timeout=10):
        print(msg)          # accepted -> new -> (partial)* -> filled | canceled | replaced
    oe.cancel(cid)
    print(oe.status())      # open orders + session state

Stream market data

import qjtrader

client = qjtrader.Client()

with client.market_data() as md:
    md.subscribe(["CA:RY", "CA:RY.PT", "MX:CRAU26", "US:@ESU26"], depth=5)
    for msg in md.messages(timeout=30):
        if msg["type"] == "quote":
            print(msg["symbol"], msg["data"]["bid"], msg["data"]["ask"])
  • CA:RY is the consolidated Canadian equity book (each level tagged with its venue); CA:RY.PT is PURE (CSE) only. Futures like MX:CRAU26 and selected US contracts such as US:@ESU26 are venue-native. Production access remains product- and entitlement-specific. See the full symbology reference.

Check what is available

Coverage differs by product and entitlement, especially for US depth. The offline matrix requires no credential or network connection:

from qjtrader import market_availability

print(market_availability()["markets"]["US"])

Verified examples include AAPL L1, SPY L1/L2, and selected US futures L1/L2. AAPL depth, NDX, and US listed-option depth are not currently available. See Market Availability.

Command line

The package installs a qjtrader command:

qjtrader init my-strategy --symbol MX:CRAU26
qjtrader subscribe CA:RY MX:CRAU26 US:@ESU26 --watch 30
qjtrader order --sym MX:CRAU26 --side buy --qty 1 --price 97.00 --account SIM --tif ioc
qjtrader status
qjtrader cancel --orig qj-abc123

# strategies: the same file runs in backtest and live
qjtrader backtest examples/strategy_meanreversion.py --symbol MX:CRAU26 --bars 200
qjtrader run       examples/strategy_meanreversion.py --symbols MX:CRAU26 --tag mr1

qjtrader init creates a small local project that observes by default and keeps order mutation disabled until the user deliberately changes allow_orders. It is designed for a coding agent to inspect, test, and run locally without adding a cloud IDE or another account-setup step.

Strategies — one contract, every venue

Subclass Strategy and the same file runs in the backtest engine, a paper run, or live (plan §10). Backtests are offline and deterministic (no network, no secrets); qjtrader run hosts it against a live/paper credential, tags every order with the strategy name (so the journal groups by strategy), and cancels everything on Ctrl-C.

from qjtrader import Strategy, run_backtest, synthetic_bars

class Buy2Percent(Strategy):
    def on_bar(self, ctx, bar):
        if ctx.position(bar["symbol"]) == 0 and bar["close"] < ctx.param("floor", 0):
            ctx.buy(bar["symbol"], 1, bar["close"], tif="ioc")
    def on_fill(self, ctx, fill):
        ctx.log("filled", fill.get("cid"), "@", fill.get("last_px") or fill.get("price"))

report = run_backtest(Buy2Percent(), synthetic_bars("MX:CRAU26", 200), params={"floor": 95})
print(report["total_pnl"], report["positions"])

The bar-level backtester is for logic; L2 event-replay with queue-model fills (microstructure truth) comes from the paper environment.

Configuration

Client() reads these (constructor args override environment):

Setting Env var Default
Client ID QJ_CLIENT_ID — (required)
Client secret QJ_CLIENT_SECRET — (required)
Token endpoint QJ_TOKEN_URL QJ Cognito token URL
Market-data host QJ_DATA_HOST data-feed.qjtrader.ai:7000
Order-entry host QJ_ORDERS_HOST orders.qjtrader.ai:7001
Pinned CA/cert QJ_CA_FILE none (standard public-CA validation)

Tokens are minted for you (OAuth2 client-credentials) and refreshed automatically before they expire — you never handle them directly. Need a raw token (e.g. for the WebSocket interface)? client.token(qjtrader.MARKET_DATA_SCOPE).

Use client.session_info() when a local agent needs the Gateway's authoritative data and order environments. client.search_universe() and client.describe_instrument(symbol) provide small, machine-readable discovery helpers so code does not have to infer product identity from prose.

Both public API hosts use standard public-certificate validation. QJ_CA_FILE remains available for controlled private deployments but is not required for the hosted QJ Gateway services.

How it works

Both APIs speak NDJSON over TLS — one JSON object per line, UTF-8, newline-terminated, authenticated with an OAuth2 JWT sent on the first line. The order lifecycle is a deterministic, journaled state machine (accepted → new → (partial)* → filled | canceled | replaced), commands are idempotent per client order id (cid), and the server enforces pre-trade risk checks + cancel-on-disconnect. Full protocol: Order Entry and Market Data.

Use it from an LLM (MCP)

Prefer to drive QJ from Claude or another AI assistant? The companion qjtrader-mcp server exposes these APIs as Model Context Protocol tools — subscribe to quotes and place simulated orders in plain language, no code. Order tools refuse a live credential by default (sandbox-only unless you opt in). Add it to Claude Code with:

claude mcp add qjtrader -e QJ_CLIENT_ID=... -e QJ_CLIENT_SECRET=... -e QJ_ENV=sandbox -- uvx qjtrader-mcp

The console's "Connect your AI" panel generates this for you, pre-filled.

Links

License

Apache-2.0. See LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

qjtrader-0.5.2.tar.gz (67.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

qjtrader-0.5.2-py3-none-any.whl (55.2 kB view details)

Uploaded Python 3

File details

Details for the file qjtrader-0.5.2.tar.gz.

File metadata

  • Download URL: qjtrader-0.5.2.tar.gz
  • Upload date:
  • Size: 67.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for qjtrader-0.5.2.tar.gz
Algorithm Hash digest
SHA256 a3086f16348a596e3c8f21d12532b02dbf3bafb0d58fd57ae471a7be80731147
MD5 f7e2b708a5095bd9cf771d3e7eef881f
BLAKE2b-256 b0be1a4e4056a7cbafc1ade83226dc9165084dc002db1be85559d0148da680b0

See more details on using hashes here.

Provenance

The following attestation bundles were made for qjtrader-0.5.2.tar.gz:

Publisher: publish.yml on QJTrader/qjtrader-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file qjtrader-0.5.2-py3-none-any.whl.

File metadata

  • Download URL: qjtrader-0.5.2-py3-none-any.whl
  • Upload date:
  • Size: 55.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for qjtrader-0.5.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c71885995ec4502a243ce998b5b6f0c50e241255481187596faaeeda1409e82d
MD5 d3034c184ab088c8e8a72b5b539218b0
BLAKE2b-256 4d0a60f5c65c337f16e6ce369170c2662c4da74ab8f406185d82d691d107be6b

See more details on using hashes here.

Provenance

The following attestation bundles were made for qjtrader-0.5.2-py3-none-any.whl:

Publisher: publish.yml on QJTrader/qjtrader-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page