qjtrader 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - name: Install
21
+ run: |
22
+ python -m pip install --upgrade pip
23
+ python -m pip install pytest
24
+ python -m pip install -e .
25
+ - name: Test
26
+ run: pytest -q
27
+
28
+ build:
29
+ runs-on: ubuntu-latest
30
+ steps:
31
+ - uses: actions/checkout@v4
32
+ - uses: actions/setup-python@v5
33
+ with:
34
+ python-version: "3.12"
35
+ - run: python -m pip install build
36
+ - run: python -m build
37
+ - uses: actions/upload-artifact@v4
38
+ with:
39
+ name: dist
40
+ path: dist/*
@@ -0,0 +1,37 @@
1
+ name: Publish to PyPI
2
+
3
+ # Publishes on a version tag (e.g. `v0.1.0`). Uses PyPI Trusted Publishing
4
+ # (OIDC) — no API token/secret needed once the trusted publisher is configured
5
+ # on PyPI (see RELEASING.md).
6
+
7
+ on:
8
+ push:
9
+ tags: ["v*"]
10
+
11
+ jobs:
12
+ build:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: "3.12"
19
+ - run: python -m pip install build
20
+ - run: python -m build
21
+ - uses: actions/upload-artifact@v4
22
+ with:
23
+ name: dist
24
+ path: dist/*
25
+
26
+ publish:
27
+ needs: build
28
+ runs-on: ubuntu-latest
29
+ environment: pypi
30
+ permissions:
31
+ id-token: write # required for trusted publishing
32
+ steps:
33
+ - uses: actions/download-artifact@v4
34
+ with:
35
+ name: dist
36
+ path: dist
37
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,22 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .venv/
12
+ venv/
13
+
14
+ # Env / secrets — never commit credentials
15
+ .env
16
+ *.env
17
+ !example.env
18
+
19
+ # OS / editor
20
+ .DS_Store
21
+ .idea/
22
+ .vscode/
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ Initial release.
6
+
7
+ - `qjtrader.Client` — one entry point for both APIs; credentials + endpoints from args or
8
+ `QJ_*` environment variables. Sandbox and production use the same code.
9
+ - Market data: `client.market_data()` → subscribe / unsubscribe / stream `snapshot`, `quote`,
10
+ `level2`, `trade` messages. Consolidated and per-venue equity symbols (`CA:RY`, `CA:RY.PT`).
11
+ - Order entry: `client.orders()` → `order` / `cancel` / `replace` / `cancel_all` / `status`, plus
12
+ `order_and_wait()`; deterministic order state machine, idempotent `cid`.
13
+ - OAuth2 client-credentials tokens minted + auto-refreshed for you.
14
+ - `qjtrader` command-line tool.
15
+ - Stdlib only; typed (`py.typed`); Python 3.9+.
qjtrader-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 QJ Trader
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,184 @@
1
+ Metadata-Version: 2.4
2
+ Name: qjtrader
3
+ Version: 0.1.0
4
+ Summary: Official Python client for the QJ Trader AI Trading APIs — Canadian market data and order entry.
5
+ Project-URL: Homepage, https://qjtrader.ai
6
+ Project-URL: Documentation, https://docs.qjtrader.ai/docs/ai
7
+ Project-URL: Console, https://console.qjtrader.ai
8
+ Project-URL: Source, https://github.com/QJTrader/qjtrader-python
9
+ Project-URL: Issues, https://github.com/QJTrader/qjtrader-python/issues
10
+ Author: QJ Trader
11
+ License: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: algotrading,canada,finance,market-data,montreal-exchange,order-entry,trading,tsx
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Financial and Insurance Industry
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: Office/Business :: Financial :: Investment
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+
23
+ # qjtrader
24
+
25
+ Official Python client for the **QJ Trader AI Trading APIs** — stream real-time Canadian market
26
+ data and send orders to Canadian venues (Montréal Exchange derivatives, and equities across every
27
+ lit exchange and dark pool) over one authenticated connection.
28
+
29
+ ```bash
30
+ pip install qjtrader
31
+ ```
32
+
33
+ - **Free sandbox, no approval.** Create an account at [console.qjtrader.ai](https://console.qjtrader.ai),
34
+ click *Create sandbox credential*, and you get a `client_id` + `client_secret` that stream
35
+ **simulated** data and return **simulated** fills — in the *exact production wire format*, 24/7.
36
+ - **Sandbox → production with one credential swap.** Your code never changes; the credential decides
37
+ sandbox vs. real, server-side.
38
+ - **Stdlib only.** No dependencies — easy to install, easy to audit.
39
+
40
+ ## Quickstart
41
+
42
+ Get a sandbox key from the [console](https://console.qjtrader.ai), then:
43
+
44
+ ```bash
45
+ export QJ_CLIENT_ID="your-client-id"
46
+ export QJ_CLIENT_SECRET="your-client-secret"
47
+ ```
48
+
49
+ ### Send an order
50
+
51
+ ```python
52
+ import qjtrader
53
+
54
+ client = qjtrader.Client() # reads QJ_CLIENT_ID / QJ_CLIENT_SECRET from the environment
55
+
56
+ with client.orders() as oe:
57
+ fill = oe.order_and_wait(
58
+ sym="MX:CRAU26", side="buy", qty=1, price=97.00, account="SIM", tif="ioc",
59
+ )
60
+ print(fill) # {'type': 'exec', 'status': 'filled', 'last_px': 97.0, 'cum_qty': 1, ...}
61
+ ```
62
+
63
+ Lower-level, if you want every message:
64
+
65
+ ```python
66
+ with client.orders() as oe:
67
+ cid = oe.order(sym="MX:CRAU26", side="buy", qty=1, price=97.00, account="SIM")
68
+ for msg in oe.updates(timeout=10):
69
+ print(msg) # accepted -> new -> (partial)* -> filled | canceled | replaced
70
+ oe.cancel(cid)
71
+ print(oe.status()) # open orders + session state
72
+ ```
73
+
74
+ ### Stream market data
75
+
76
+ ```python
77
+ import qjtrader
78
+
79
+ client = qjtrader.Client()
80
+
81
+ with client.market_data() as md:
82
+ md.subscribe(["CA:RY", "CA:RY.PT", "MX:CRAU26"], depth=5)
83
+ for msg in md.messages(timeout=30):
84
+ if msg["type"] == "quote":
85
+ print(msg["symbol"], msg["data"]["bid"], msg["data"]["ask"])
86
+ ```
87
+
88
+ - `CA:RY` is the **consolidated** Canadian equity book (each level tagged with its venue);
89
+ `CA:RY.PT` is **PURE (CSE)** only. Futures like `MX:CRAU26` are venue-native. See the full
90
+ [symbology reference](https://docs.qjtrader.ai/docs/ai/symbology).
91
+
92
+ ## Command line
93
+
94
+ The package installs a `qjtrader` command:
95
+
96
+ ```bash
97
+ qjtrader subscribe CA:RY MX:CRAU26 --watch 30
98
+ qjtrader order --sym MX:CRAU26 --side buy --qty 1 --price 97.00 --account SIM --tif ioc
99
+ qjtrader status
100
+ qjtrader cancel --orig qj-abc123
101
+
102
+ # strategies: the same file runs in backtest and live
103
+ qjtrader backtest examples/strategy_meanreversion.py --symbol MX:CRAU26 --bars 200
104
+ qjtrader run examples/strategy_meanreversion.py --symbols MX:CRAU26 --tag mr1
105
+ ```
106
+
107
+ ## Strategies — one contract, every venue
108
+
109
+ Subclass `Strategy` and the same file runs in the backtest engine, a paper run, or
110
+ live (plan §10). Backtests are offline and deterministic (no network, no secrets);
111
+ `qjtrader run` hosts it against a live/paper credential, tags every order with the
112
+ strategy name (so the journal groups by strategy), and cancels everything on Ctrl-C.
113
+
114
+ ```python
115
+ from qjtrader import Strategy, run_backtest, synthetic_bars
116
+
117
+ class Buy2Percent(Strategy):
118
+ def on_bar(self, ctx, bar):
119
+ if ctx.position(bar["symbol"]) == 0 and bar["close"] < ctx.param("floor", 0):
120
+ ctx.buy(bar["symbol"], 1, bar["close"], tif="ioc")
121
+ def on_fill(self, ctx, fill):
122
+ ctx.log("filled", fill.get("cid"), "@", fill.get("last_px") or fill.get("price"))
123
+
124
+ report = run_backtest(Buy2Percent(), synthetic_bars("MX:CRAU26", 200), params={"floor": 95})
125
+ print(report["total_pnl"], report["positions"])
126
+ ```
127
+
128
+ The bar-level backtester is for **logic**; L2 event-replay with queue-model fills
129
+ (microstructure truth) comes from the paper environment.
130
+
131
+ ## Configuration
132
+
133
+ `Client()` reads these (constructor args override environment):
134
+
135
+ | Setting | Env var | Default |
136
+ |---|---|---|
137
+ | Client ID | `QJ_CLIENT_ID` | — (required) |
138
+ | Client secret | `QJ_CLIENT_SECRET` | — (required) |
139
+ | Token endpoint | `QJ_TOKEN_URL` | QJ Cognito token URL |
140
+ | Market-data host | `QJ_DATA_HOST` | `data-feed.qjtrader.ai:7000` |
141
+ | Order-entry host | `QJ_ORDERS_HOST` | `orders.qjtrader.ai:7001` |
142
+ | Pinned CA/cert | `QJ_CA_FILE` | none (standard public-CA validation) |
143
+
144
+ Tokens are minted for you (OAuth2 client-credentials) and refreshed automatically before they
145
+ expire — you never handle them directly. Need a raw token (e.g. for the WebSocket interface)?
146
+ `client.token(qjtrader.MARKET_DATA_SCOPE)`.
147
+
148
+ > **Pilot note:** while order entry is in private pilot it may be reached by IP with a pinned
149
+ > certificate provided at onboarding — pass `ca_file="pilot-server.pem"` (or `QJ_CA_FILE`). Market
150
+ > data uses a standard public certificate.
151
+
152
+ ## How it works
153
+
154
+ Both APIs speak **NDJSON over TLS** — one JSON object per line, UTF-8, newline-terminated,
155
+ authenticated with an OAuth2 JWT sent on the first line. The order lifecycle is a deterministic,
156
+ journaled state machine (`accepted → new → (partial)* → filled | canceled | replaced`), commands are
157
+ idempotent per client order id (`cid`), and the server enforces pre-trade risk checks +
158
+ cancel-on-disconnect. Full protocol: **[Order Entry](https://docs.qjtrader.ai/docs/ai/order-entry)**
159
+ and **[Market Data](https://docs.qjtrader.ai/docs/ai/market-data)**.
160
+
161
+ ## Use it from an LLM (MCP)
162
+
163
+ Prefer to drive QJ from Claude or another AI assistant? The companion
164
+ [`qjtrader-mcp`](https://github.com/QJTrader/qjtrader-python) server exposes these APIs as Model
165
+ Context Protocol tools — subscribe to quotes and place **simulated** orders in plain language, no
166
+ code. Order tools refuse a live credential by default (sandbox-only unless you opt in). Add it to
167
+ Claude Code with:
168
+
169
+ ```bash
170
+ claude mcp add qjtrader -e QJ_CLIENT_ID=... -e QJ_CLIENT_SECRET=... -e QJ_ENV=sandbox -- uvx qjtrader-mcp
171
+ ```
172
+
173
+ The console's "Connect your AI" panel generates this for you, pre-filled.
174
+
175
+ ## Links
176
+
177
+ - 📚 Docs: https://docs.qjtrader.ai/docs/ai
178
+ - 🔑 Console (get a key): https://console.qjtrader.ai
179
+ - 🔤 Symbology: https://docs.qjtrader.ai/docs/ai/symbology
180
+ - 🐛 Issues: https://github.com/QJTrader/qjtrader-python/issues
181
+
182
+ ## License
183
+
184
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,162 @@
1
+ # qjtrader
2
+
3
+ Official Python client for the **QJ Trader AI Trading APIs** — stream real-time Canadian market
4
+ data and send orders to Canadian venues (Montréal Exchange derivatives, and equities across every
5
+ lit exchange and dark pool) over one authenticated connection.
6
+
7
+ ```bash
8
+ pip install qjtrader
9
+ ```
10
+
11
+ - **Free sandbox, no approval.** Create an account at [console.qjtrader.ai](https://console.qjtrader.ai),
12
+ click *Create sandbox credential*, and you get a `client_id` + `client_secret` that stream
13
+ **simulated** data and return **simulated** fills — in the *exact production wire format*, 24/7.
14
+ - **Sandbox → production with one credential swap.** Your code never changes; the credential decides
15
+ sandbox vs. real, server-side.
16
+ - **Stdlib only.** No dependencies — easy to install, easy to audit.
17
+
18
+ ## Quickstart
19
+
20
+ Get a sandbox key from the [console](https://console.qjtrader.ai), then:
21
+
22
+ ```bash
23
+ export QJ_CLIENT_ID="your-client-id"
24
+ export QJ_CLIENT_SECRET="your-client-secret"
25
+ ```
26
+
27
+ ### Send an order
28
+
29
+ ```python
30
+ import qjtrader
31
+
32
+ client = qjtrader.Client() # reads QJ_CLIENT_ID / QJ_CLIENT_SECRET from the environment
33
+
34
+ with client.orders() as oe:
35
+ fill = oe.order_and_wait(
36
+ sym="MX:CRAU26", side="buy", qty=1, price=97.00, account="SIM", tif="ioc",
37
+ )
38
+ print(fill) # {'type': 'exec', 'status': 'filled', 'last_px': 97.0, 'cum_qty': 1, ...}
39
+ ```
40
+
41
+ Lower-level, if you want every message:
42
+
43
+ ```python
44
+ with client.orders() as oe:
45
+ cid = oe.order(sym="MX:CRAU26", side="buy", qty=1, price=97.00, account="SIM")
46
+ for msg in oe.updates(timeout=10):
47
+ print(msg) # accepted -> new -> (partial)* -> filled | canceled | replaced
48
+ oe.cancel(cid)
49
+ print(oe.status()) # open orders + session state
50
+ ```
51
+
52
+ ### Stream market data
53
+
54
+ ```python
55
+ import qjtrader
56
+
57
+ client = qjtrader.Client()
58
+
59
+ with client.market_data() as md:
60
+ md.subscribe(["CA:RY", "CA:RY.PT", "MX:CRAU26"], depth=5)
61
+ for msg in md.messages(timeout=30):
62
+ if msg["type"] == "quote":
63
+ print(msg["symbol"], msg["data"]["bid"], msg["data"]["ask"])
64
+ ```
65
+
66
+ - `CA:RY` is the **consolidated** Canadian equity book (each level tagged with its venue);
67
+ `CA:RY.PT` is **PURE (CSE)** only. Futures like `MX:CRAU26` are venue-native. See the full
68
+ [symbology reference](https://docs.qjtrader.ai/docs/ai/symbology).
69
+
70
+ ## Command line
71
+
72
+ The package installs a `qjtrader` command:
73
+
74
+ ```bash
75
+ qjtrader subscribe CA:RY MX:CRAU26 --watch 30
76
+ qjtrader order --sym MX:CRAU26 --side buy --qty 1 --price 97.00 --account SIM --tif ioc
77
+ qjtrader status
78
+ qjtrader cancel --orig qj-abc123
79
+
80
+ # strategies: the same file runs in backtest and live
81
+ qjtrader backtest examples/strategy_meanreversion.py --symbol MX:CRAU26 --bars 200
82
+ qjtrader run examples/strategy_meanreversion.py --symbols MX:CRAU26 --tag mr1
83
+ ```
84
+
85
+ ## Strategies — one contract, every venue
86
+
87
+ Subclass `Strategy` and the same file runs in the backtest engine, a paper run, or
88
+ live (plan §10). Backtests are offline and deterministic (no network, no secrets);
89
+ `qjtrader run` hosts it against a live/paper credential, tags every order with the
90
+ strategy name (so the journal groups by strategy), and cancels everything on Ctrl-C.
91
+
92
+ ```python
93
+ from qjtrader import Strategy, run_backtest, synthetic_bars
94
+
95
+ class Buy2Percent(Strategy):
96
+ def on_bar(self, ctx, bar):
97
+ if ctx.position(bar["symbol"]) == 0 and bar["close"] < ctx.param("floor", 0):
98
+ ctx.buy(bar["symbol"], 1, bar["close"], tif="ioc")
99
+ def on_fill(self, ctx, fill):
100
+ ctx.log("filled", fill.get("cid"), "@", fill.get("last_px") or fill.get("price"))
101
+
102
+ report = run_backtest(Buy2Percent(), synthetic_bars("MX:CRAU26", 200), params={"floor": 95})
103
+ print(report["total_pnl"], report["positions"])
104
+ ```
105
+
106
+ The bar-level backtester is for **logic**; L2 event-replay with queue-model fills
107
+ (microstructure truth) comes from the paper environment.
108
+
109
+ ## Configuration
110
+
111
+ `Client()` reads these (constructor args override environment):
112
+
113
+ | Setting | Env var | Default |
114
+ |---|---|---|
115
+ | Client ID | `QJ_CLIENT_ID` | — (required) |
116
+ | Client secret | `QJ_CLIENT_SECRET` | — (required) |
117
+ | Token endpoint | `QJ_TOKEN_URL` | QJ Cognito token URL |
118
+ | Market-data host | `QJ_DATA_HOST` | `data-feed.qjtrader.ai:7000` |
119
+ | Order-entry host | `QJ_ORDERS_HOST` | `orders.qjtrader.ai:7001` |
120
+ | Pinned CA/cert | `QJ_CA_FILE` | none (standard public-CA validation) |
121
+
122
+ Tokens are minted for you (OAuth2 client-credentials) and refreshed automatically before they
123
+ expire — you never handle them directly. Need a raw token (e.g. for the WebSocket interface)?
124
+ `client.token(qjtrader.MARKET_DATA_SCOPE)`.
125
+
126
+ > **Pilot note:** while order entry is in private pilot it may be reached by IP with a pinned
127
+ > certificate provided at onboarding — pass `ca_file="pilot-server.pem"` (or `QJ_CA_FILE`). Market
128
+ > data uses a standard public certificate.
129
+
130
+ ## How it works
131
+
132
+ Both APIs speak **NDJSON over TLS** — one JSON object per line, UTF-8, newline-terminated,
133
+ authenticated with an OAuth2 JWT sent on the first line. The order lifecycle is a deterministic,
134
+ journaled state machine (`accepted → new → (partial)* → filled | canceled | replaced`), commands are
135
+ idempotent per client order id (`cid`), and the server enforces pre-trade risk checks +
136
+ cancel-on-disconnect. Full protocol: **[Order Entry](https://docs.qjtrader.ai/docs/ai/order-entry)**
137
+ and **[Market Data](https://docs.qjtrader.ai/docs/ai/market-data)**.
138
+
139
+ ## Use it from an LLM (MCP)
140
+
141
+ Prefer to drive QJ from Claude or another AI assistant? The companion
142
+ [`qjtrader-mcp`](https://github.com/QJTrader/qjtrader-python) server exposes these APIs as Model
143
+ Context Protocol tools — subscribe to quotes and place **simulated** orders in plain language, no
144
+ code. Order tools refuse a live credential by default (sandbox-only unless you opt in). Add it to
145
+ Claude Code with:
146
+
147
+ ```bash
148
+ claude mcp add qjtrader -e QJ_CLIENT_ID=... -e QJ_CLIENT_SECRET=... -e QJ_ENV=sandbox -- uvx qjtrader-mcp
149
+ ```
150
+
151
+ The console's "Connect your AI" panel generates this for you, pre-filled.
152
+
153
+ ## Links
154
+
155
+ - 📚 Docs: https://docs.qjtrader.ai/docs/ai
156
+ - 🔑 Console (get a key): https://console.qjtrader.ai
157
+ - 🔤 Symbology: https://docs.qjtrader.ai/docs/ai/symbology
158
+ - 🐛 Issues: https://github.com/QJTrader/qjtrader-python/issues
159
+
160
+ ## License
161
+
162
+ Apache-2.0. See [LICENSE](LICENSE).