pitbridge 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.
Files changed (67) hide show
  1. pitbridge-0.1.0/.gitignore +30 -0
  2. pitbridge-0.1.0/LICENSE +202 -0
  3. pitbridge-0.1.0/NOTICE +31 -0
  4. pitbridge-0.1.0/PKG-INFO +60 -0
  5. pitbridge-0.1.0/README.md +23 -0
  6. pitbridge-0.1.0/pyproject.toml +71 -0
  7. pitbridge-0.1.0/src/pitbridge/__init__.py +7 -0
  8. pitbridge-0.1.0/src/pitbridge/accounts.py +253 -0
  9. pitbridge-0.1.0/src/pitbridge/adapter.py +53 -0
  10. pitbridge-0.1.0/src/pitbridge/addonlink.py +369 -0
  11. pitbridge-0.1.0/src/pitbridge/audit.py +255 -0
  12. pitbridge-0.1.0/src/pitbridge/cli.py +394 -0
  13. pitbridge-0.1.0/src/pitbridge/config.py +147 -0
  14. pitbridge-0.1.0/src/pitbridge/denylist.py +46 -0
  15. pitbridge-0.1.0/src/pitbridge/executor.py +309 -0
  16. pitbridge-0.1.0/src/pitbridge/guardrails/__init__.py +68 -0
  17. pitbridge-0.1.0/src/pitbridge/guardrails/calendar.py +109 -0
  18. pitbridge-0.1.0/src/pitbridge/guardrails/cooldown.py +38 -0
  19. pitbridge-0.1.0/src/pitbridge/guardrails/daily_loss_halt.py +40 -0
  20. pitbridge-0.1.0/src/pitbridge/guardrails/duplicate_protection.py +38 -0
  21. pitbridge-0.1.0/src/pitbridge/guardrails/engine.py +214 -0
  22. pitbridge-0.1.0/src/pitbridge/guardrails/human_confirm.py +44 -0
  23. pitbridge-0.1.0/src/pitbridge/guardrails/instrument_allowlist.py +24 -0
  24. pitbridge-0.1.0/src/pitbridge/guardrails/kill_switch.py +22 -0
  25. pitbridge-0.1.0/src/pitbridge/guardrails/link_down.py +21 -0
  26. pitbridge-0.1.0/src/pitbridge/guardrails/position_caps.py +38 -0
  27. pitbridge-0.1.0/src/pitbridge/guardrails/profit_lock.py +36 -0
  28. pitbridge-0.1.0/src/pitbridge/guardrails/rate_limit.py +57 -0
  29. pitbridge-0.1.0/src/pitbridge/guardrails/registry.py +72 -0
  30. pitbridge-0.1.0/src/pitbridge/guardrails/trading_window.py +65 -0
  31. pitbridge-0.1.0/src/pitbridge/mcp_server.py +211 -0
  32. pitbridge-0.1.0/src/pitbridge/modes.py +103 -0
  33. pitbridge-0.1.0/src/pitbridge/notify.py +66 -0
  34. pitbridge-0.1.0/src/pitbridge/pipeline.py +402 -0
  35. pitbridge-0.1.0/src/pitbridge/protocol.py +302 -0
  36. pitbridge-0.1.0/src/pitbridge/rest.py +270 -0
  37. pitbridge-0.1.0/src/pitbridge/runtime.py +135 -0
  38. pitbridge-0.1.0/src/pitbridge/timeutil.py +28 -0
  39. pitbridge-0.1.0/tests/conftest.py +9 -0
  40. pitbridge-0.1.0/tests/hardening_harness.py +97 -0
  41. pitbridge-0.1.0/tests/test_account_deny.py +251 -0
  42. pitbridge-0.1.0/tests/test_accounts.py +245 -0
  43. pitbridge-0.1.0/tests/test_adapter_seam.py +66 -0
  44. pitbridge-0.1.0/tests/test_audit.py +208 -0
  45. pitbridge-0.1.0/tests/test_audit_anchor.py +142 -0
  46. pitbridge-0.1.0/tests/test_calendar.py +88 -0
  47. pitbridge-0.1.0/tests/test_cli_m3.py +177 -0
  48. pitbridge-0.1.0/tests/test_config.py +206 -0
  49. pitbridge-0.1.0/tests/test_e2e.py +389 -0
  50. pitbridge-0.1.0/tests/test_executor.py +209 -0
  51. pitbridge-0.1.0/tests/test_fake_addon_runner.py +40 -0
  52. pitbridge-0.1.0/tests/test_guardrails.py +438 -0
  53. pitbridge-0.1.0/tests/test_hardening_confirm.py +63 -0
  54. pitbridge-0.1.0/tests/test_hardening_exec_dedup.py +66 -0
  55. pitbridge-0.1.0/tests/test_hardening_live_point_value.py +55 -0
  56. pitbridge-0.1.0/tests/test_hardening_risk_gate.py +41 -0
  57. pitbridge-0.1.0/tests/test_hardening_staleness.py +25 -0
  58. pitbridge-0.1.0/tests/test_mcp_no_bypass.py +220 -0
  59. pitbridge-0.1.0/tests/test_mcp_server.py +111 -0
  60. pitbridge-0.1.0/tests/test_notify.py +31 -0
  61. pitbridge-0.1.0/tests/test_pipeline.py +243 -0
  62. pitbridge-0.1.0/tests/test_protocol.py +134 -0
  63. pitbridge-0.1.0/tests/test_rest.py +261 -0
  64. pitbridge-0.1.0/tests/test_schemas.py +70 -0
  65. pitbridge-0.1.0/tests/test_sticky_halt.py +126 -0
  66. pitbridge-0.1.0/tests/test_version.py +20 -0
  67. pitbridge-0.1.0/uv.lock +887 -0
@@ -0,0 +1,30 @@
1
+ # secrets — never commit
2
+ .env
3
+ *.env
4
+ !*.env.example
5
+
6
+ # python
7
+ __pycache__/
8
+ *.pyc
9
+ .venv/
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ dist/
13
+ *.egg-info/
14
+
15
+ # node / astro
16
+ node_modules/
17
+ sites/**/dist/
18
+ sites/**/.astro/
19
+
20
+ # c#
21
+ addon/**/bin/
22
+ addon/**/obj/
23
+ *.user
24
+
25
+ # os / editor
26
+ .DS_Store
27
+
28
+ # wrangler local state
29
+ .wrangler/
30
+ sites/**/.wrangler/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
pitbridge-0.1.0/NOTICE ADDED
@@ -0,0 +1,31 @@
1
+ PitBridge
2
+ Copyright 2026 PitBridge
3
+
4
+ This product includes software developed by the PitBridge project.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not
7
+ use these files except in compliance with the License. You may obtain a copy
8
+ of the License in the LICENSE file at the root of this repository or at
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ ---
12
+
13
+ Open-core notice
14
+ ================
15
+ The code in this repository — the daemon (guardrail engine, MCP/REST/WS
16
+ surface, paper + read-only execution), the NinjaTrader 8 AddOn, the protocol
17
+ schemas, and the developer tools — is the OPEN CORE and is licensed under
18
+ Apache-2.0 above. You may run, modify, and redistribute it, including
19
+ commercially, subject to the License.
20
+
21
+ The following are NOT part of this repository and are distributed separately
22
+ as closed-source commercial components (PitBridge Pro):
23
+ - the live-execution provider (the `pitbridge.plugins` entry point that
24
+ `arm-live` requires before any real-money order can be submitted),
25
+ - the prop-firm rule packs,
26
+ - multi-account fan-out,
27
+ - tamper-evident audit export.
28
+
29
+ Without a Pro component installed, the daemon runs paper/read-only only:
30
+ `arm-live` refuses by design. This boundary is intentional (open-core), not a
31
+ limitation of the Apache-2.0 grant on the core.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: pitbridge
3
+ Version: 0.1.0
4
+ Summary: Local-first, guardrailed MCP bridge for NinjaTrader 8 — hard risk limits your AI agent cannot bypass.
5
+ Project-URL: Homepage, https://pitbridge.com
6
+ Project-URL: Documentation, https://pitbridge.com/docs/
7
+ Project-URL: Repository, https://github.com/ToolstackVault/pitbridge
8
+ Project-URL: Changelog, https://pitbridge.com/changelog/
9
+ Author: PitBridge
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Keywords: ai-agent,algo-trading,futures,guardrails,local-first,mcp,model-context-protocol,ninjatrader,risk-management,trading
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: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Office/Business :: Financial :: Investment
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: fastapi>=0.115
23
+ Requires-Dist: httpx>=0.27
24
+ Requires-Dist: mcp>=1.0
25
+ Requires-Dist: pydantic>=2.7
26
+ Requires-Dist: typer>=0.12
27
+ Requires-Dist: tzdata>=2024.1
28
+ Requires-Dist: uvicorn>=0.30
29
+ Requires-Dist: websockets>=12.0
30
+ Provides-Extra: dev
31
+ Requires-Dist: httpx>=0.27; extra == 'dev'
32
+ Requires-Dist: jsonschema>=4.21; extra == 'dev'
33
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
34
+ Requires-Dist: pytest>=8.0; extra == 'dev'
35
+ Requires-Dist: ruff>=0.6; extra == 'dev'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # pitbridge (daemon)
39
+
40
+ Python 3.12 daemon that sits between AI agents (MCP / REST / WS) and the
41
+ NinjaTrader 8 AddOn (outbound WebSocket, port 8873). Binding spec:
42
+ `../docs/architecture.md`.
43
+
44
+ ## Dev setup
45
+
46
+ ```sh
47
+ cd daemon
48
+ uv venv --python 3.12
49
+ uv pip install -e ".[dev]"
50
+ uv run pytest
51
+ uv run ruff check .
52
+ ```
53
+
54
+ Status: M2 daemon-core — protocol models (14 message types, schema-mirrored),
55
+ guardrail engine (M1), the AddOn WS link (hello/auth/heartbeat/snapshot/
56
+ reconnect-reconcile, reconcile-first hard), executor (idempotent pending-order
57
+ table + ack timeouts), the frozen pipeline (schema -> permission -> guardrails
58
+ -> confirm gate -> submit -> audit) as the single order path, the /v1 REST + WS
59
+ surfaces, and `tools/fake_addon.py` for chaos tests. `pitbridge run --config`
60
+ serves it. MCP surface + C# AddOn land in M3/M4.
@@ -0,0 +1,23 @@
1
+ # pitbridge (daemon)
2
+
3
+ Python 3.12 daemon that sits between AI agents (MCP / REST / WS) and the
4
+ NinjaTrader 8 AddOn (outbound WebSocket, port 8873). Binding spec:
5
+ `../docs/architecture.md`.
6
+
7
+ ## Dev setup
8
+
9
+ ```sh
10
+ cd daemon
11
+ uv venv --python 3.12
12
+ uv pip install -e ".[dev]"
13
+ uv run pytest
14
+ uv run ruff check .
15
+ ```
16
+
17
+ Status: M2 daemon-core — protocol models (14 message types, schema-mirrored),
18
+ guardrail engine (M1), the AddOn WS link (hello/auth/heartbeat/snapshot/
19
+ reconnect-reconcile, reconcile-first hard), executor (idempotent pending-order
20
+ table + ack timeouts), the frozen pipeline (schema -> permission -> guardrails
21
+ -> confirm gate -> submit -> audit) as the single order path, the /v1 REST + WS
22
+ surfaces, and `tools/fake_addon.py` for chaos tests. `pitbridge run --config`
23
+ serves it. MCP surface + C# AddOn land in M3/M4.
@@ -0,0 +1,71 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pitbridge"
7
+ version = "0.1.0"
8
+ description = "Local-first, guardrailed MCP bridge for NinjaTrader 8 — hard risk limits your AI agent cannot bypass."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [{ name = "PitBridge" }]
14
+ keywords = [
15
+ "mcp", "model-context-protocol", "ninjatrader", "trading", "futures",
16
+ "ai-agent", "guardrails", "risk-management", "local-first", "algo-trading",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Intended Audience :: Developers",
21
+ "Intended Audience :: Financial and Insurance Industry",
22
+ "License :: OSI Approved :: Apache Software License",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Topic :: Office/Business :: Financial :: Investment",
26
+ ]
27
+ dependencies = [
28
+ "fastapi>=0.115",
29
+ "uvicorn>=0.30",
30
+ "mcp>=1.0",
31
+ "pydantic>=2.7",
32
+ "websockets>=12.0",
33
+ "typer>=0.12",
34
+ "httpx>=0.27",
35
+ # Windows (and any host lacking the system IANA tz database) needs this for
36
+ # zoneinfo.ZoneInfo(...) used by the trading-window guardrail. Runtime dep,
37
+ # not dev-only: a Windows user running the daemon would otherwise crash.
38
+ "tzdata>=2024.1",
39
+ ]
40
+
41
+ [project.optional-dependencies]
42
+ dev = [
43
+ "pytest>=8.0",
44
+ "pytest-asyncio>=0.24",
45
+ "httpx>=0.27",
46
+ "ruff>=0.6",
47
+ "jsonschema>=4.21",
48
+ ]
49
+
50
+ [project.urls]
51
+ Homepage = "https://pitbridge.com"
52
+ Documentation = "https://pitbridge.com/docs/"
53
+ Repository = "https://github.com/ToolstackVault/pitbridge"
54
+ Changelog = "https://pitbridge.com/changelog/"
55
+
56
+ [project.scripts]
57
+ pitbridge = "pitbridge.cli:app"
58
+
59
+ [tool.hatch.build.targets.wheel]
60
+ packages = ["src/pitbridge"]
61
+
62
+ [tool.pytest.ini_options]
63
+ testpaths = ["tests"]
64
+ asyncio_mode = "auto"
65
+
66
+ [tool.ruff]
67
+ target-version = "py312"
68
+ line-length = 100
69
+
70
+ [tool.ruff.lint]
71
+ select = ["E", "F", "W", "I", "UP", "B"]
@@ -0,0 +1,7 @@
1
+ """PitBridge daemon package.
2
+
3
+ Guardrailed bridge between AI agents (MCP / REST / WS) and a NinjaTrader 8
4
+ AddOn. Binding architecture: docs/architecture.md at the repo root.
5
+ """
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,253 @@
1
+ """Per-account state + day ledger.
2
+
3
+ Contract (architecture.md sections 3 and 4): the mutable bookkeeping behind
4
+ the pure guardrail engine. `AccountBook` ingests executions (realized P&L,
5
+ average-cost) and account_state updates (unrealized P&L straight from the
6
+ AddOn's AccountItem events — no market-data feed needed), applies the ET
7
+ day-ledger rollover, and produces the frozen `AccountSnapshot` the engine
8
+ checks against.
9
+
10
+ Rollover semantics are the Crucible live-loop semantics (live/run.py,
11
+ pinned by tests/test_live_run.py): on the first activity of a new ET date,
12
+ yesterday's realized folds into the balance, the best-day marker updates,
13
+ and — for the eval profile — the EOD trailing floor ratchets to
14
+ max(floor, balance - trailing_drawdown). The funded profile keeps a static
15
+ floor. Because the day P&L resets to zero, a daily-loss halt or profit lock
16
+ from yesterday automatically lifts (no sticky flag; the engine recomputes).
17
+
18
+ Import-pure and I/O-free: state lives in memory; the M2 link layer feeds it.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass
24
+ from datetime import date, datetime, timedelta
25
+ from typing import Literal
26
+
27
+ from pitbridge.guardrails.engine import AccountSnapshot, OrderEvent, Side
28
+ from pitbridge.timeutil import et_date, require_aware
29
+
30
+ Profile = Literal["eval", "funded"]
31
+
32
+ _EVENT_RETENTION = timedelta(hours=24) # covers the largest rolling rate-limit window
33
+
34
+
35
+ @dataclass(slots=True)
36
+ class _Position:
37
+ qty: int = 0 # signed net contracts
38
+ avg_px: float = 0.0
39
+
40
+
41
+ class AccountBook:
42
+ """Mutable per-account ledger. Not thread-safe; the daemon owns one per
43
+ account on its single event loop."""
44
+
45
+ def __init__(
46
+ self,
47
+ account: str,
48
+ *,
49
+ profile: Profile = "eval",
50
+ starting_balance: float = 0.0,
51
+ trailing_drawdown: float = 0.0,
52
+ point_value: float = 1.0,
53
+ day_halt_sticky: bool = False,
54
+ daily_loss_halt: float | None = None,
55
+ profit_lock: float | None = None,
56
+ ) -> None:
57
+ self.account = account
58
+ self.profile: Profile = profile
59
+ self.point_value = point_value
60
+ self.trailing_drawdown = trailing_drawdown
61
+ self.balance = starting_balance
62
+ self.trailing_floor = starting_balance - trailing_drawdown
63
+ self.max_day_profit = 0.0
64
+ self.day_date: date | None = None
65
+ self.day_realized = 0.0
66
+ self.unrealized = 0.0
67
+ self.link_up = True
68
+ self.first_order_done = False
69
+ self.max_order_qty = 0
70
+ self.last_loss_ts: datetime | None = None
71
+ self.last_order_ts: datetime | None = None
72
+ self._positions: dict[str, _Position] = {}
73
+ self._order_events: list[OrderEvent] = []
74
+ # exec_ids already booked into the ledger — the link dedups inbound
75
+ # frames by envelope id, but an execution redelivered with a fresh
76
+ # envelope id and the same broker exec_id (M4 reconnect/replay) would
77
+ # otherwise double-count. Ledger booking is idempotent by exec_id.
78
+ self._booked_exec_ids: set[str] = set()
79
+ # Sticky day-halt latch (M2 follow-up). The thresholds mirror the
80
+ # per-account guardrail config; the daemon wires them in. When sticky
81
+ # halting is on, the latch trips on observation (any account_state /
82
+ # execution) and holds until the ET rollover — recovery cannot re-open
83
+ # trading. With sticky off it stays dormant (M1 recompute-per-check).
84
+ self.day_halt_sticky = day_halt_sticky
85
+ self.daily_loss_halt = daily_loss_halt
86
+ self.profit_lock = profit_lock
87
+ self.day_halted = False
88
+ self.day_halt_reason: str | None = None
89
+ self._pending_halt_notice: str | None = None
90
+
91
+ # ------------------------------------------------------------- rollover
92
+
93
+ def roll_if_needed(self, now: datetime) -> bool:
94
+ """Apply the ET day-ledger rollover if `now` is on a new ET date.
95
+ Returns True when a rollover happened (Crucible EOD fold)."""
96
+ today = et_date(require_aware(now))
97
+ if self.day_date == today:
98
+ return False
99
+ rolled = self.day_date is not None
100
+ if rolled:
101
+ self.balance += self.day_realized
102
+ self.max_day_profit = max(self.max_day_profit, self.day_realized)
103
+ if self.profile == "eval":
104
+ # EOD trailing: floor ratchets with the end-of-day high-water
105
+ self.trailing_floor = max(
106
+ self.trailing_floor, self.balance - self.trailing_drawdown
107
+ )
108
+ self.day_date = today
109
+ self.day_realized = 0.0
110
+ cutoff = now - _EVENT_RETENTION
111
+ self._order_events = [e for e in self._order_events if e.ts > cutoff]
112
+ if rolled:
113
+ # A fresh ET day clears the sticky latch (and any pending flatten
114
+ # notice for it): yesterday's halt does not carry into today.
115
+ self.day_halted = False
116
+ self.day_halt_reason = None
117
+ self._pending_halt_notice = None
118
+ return rolled
119
+
120
+ # --------------------------------------------------------- sticky halt
121
+
122
+ def _evaluate_halt(self) -> None:
123
+ """Latch the sticky day-halt if a loss-halt or profit-lock threshold is
124
+ breached. No-op when sticky is off or the latch is already set."""
125
+ if not self.day_halt_sticky or self.day_halted:
126
+ return
127
+ pnl = self.day_pnl
128
+ if self.daily_loss_halt is not None and pnl <= -self.daily_loss_halt:
129
+ self._latch("DAILY_LOSS_HALT")
130
+ elif self.profit_lock is not None and pnl >= self.profit_lock:
131
+ self._latch("PROFIT_LOCK")
132
+
133
+ def _latch(self, reason: str) -> None:
134
+ self.day_halted = True
135
+ self.day_halt_reason = reason
136
+ self._pending_halt_notice = reason
137
+
138
+ def consume_halt_notice(self) -> str | None:
139
+ """Pop the reason of a *newly* latched sticky halt (for flatten_on_halt /
140
+ notifier), or None if nothing new latched since the last call."""
141
+ notice = self._pending_halt_notice
142
+ self._pending_halt_notice = None
143
+ return notice
144
+
145
+ # ------------------------------------------------------------- ingestion
146
+
147
+ def record_order(self, ts: datetime, instrument: str, side: Side, qty: int) -> None:
148
+ """Book a submitted order (feeds rate-limit / duplicate / cooldown)."""
149
+ require_aware(ts, "ts")
150
+ self.roll_if_needed(ts)
151
+ self._order_events.append(OrderEvent(ts=ts, instrument=instrument, side=side, qty=qty))
152
+ self.last_order_ts = ts
153
+ self.first_order_done = True
154
+ self.max_order_qty = max(self.max_order_qty, qty)
155
+
156
+ def record_execution(
157
+ self,
158
+ ts: datetime,
159
+ instrument: str,
160
+ side: Side,
161
+ qty: int,
162
+ price: float,
163
+ *,
164
+ commission: float = 0.0,
165
+ exec_id: str | None = None,
166
+ ) -> float:
167
+ """Book a fill. Average-cost method: a position-reducing fill books
168
+ (price - avg) * closed_qty * point_value (sign-adjusted) into the day
169
+ ledger; a flip re-opens the remainder at the fill price. Commission
170
+ is subtracted from realized (Crucible's approximation). Returns the
171
+ realized P&L delta. A realized loss on a closing fill stamps
172
+ `last_loss_ts` (cooldown guardrail); pure opens do not.
173
+
174
+ Idempotent by `exec_id` (FIX 3): a redelivered execution with an
175
+ already-booked exec_id is a no-op (returns 0.0), so a replayed fill
176
+ cannot double-count position or realized P&L. exec_id=None disables
177
+ dedup (direct test bookings)."""
178
+ require_aware(ts, "ts")
179
+ if qty <= 0:
180
+ raise ValueError(f"qty must be positive (got {qty})")
181
+ if exec_id is not None:
182
+ if exec_id in self._booked_exec_ids:
183
+ return 0.0
184
+ self._booked_exec_ids.add(exec_id)
185
+ self.roll_if_needed(ts)
186
+
187
+ pos = self._positions.setdefault(instrument, _Position())
188
+ signed = qty if side == "BUY" else -qty
189
+ realized = 0.0
190
+ closed_qty = 0
191
+
192
+ if pos.qty != 0 and (pos.qty > 0) != (signed > 0):
193
+ closed_qty = min(abs(signed), abs(pos.qty))
194
+ direction = 1.0 if pos.qty > 0 else -1.0
195
+ realized = (price - pos.avg_px) * closed_qty * self.point_value * direction
196
+
197
+ new_qty = pos.qty + signed
198
+ if pos.qty == 0 or (pos.qty > 0) == (signed > 0):
199
+ # opening / adding: volume-weighted average price
200
+ total = abs(pos.qty) + qty
201
+ pos.avg_px = (pos.avg_px * abs(pos.qty) + price * qty) / total
202
+ elif abs(signed) > abs(pos.qty):
203
+ pos.avg_px = price # flip: remainder opens at the fill price
204
+ elif new_qty == 0:
205
+ pos.avg_px = 0.0
206
+ pos.qty = new_qty
207
+
208
+ realized -= commission
209
+ self.day_realized += realized
210
+ if closed_qty > 0 and realized < 0:
211
+ self.last_loss_ts = ts
212
+ self._evaluate_halt()
213
+ return realized
214
+
215
+ def set_unrealized(self, value: float) -> None:
216
+ """Unrealized P&L as reported by the AddOn's account_state message."""
217
+ self.unrealized = value
218
+ self._evaluate_halt()
219
+
220
+ def set_link(self, up: bool) -> None:
221
+ self.link_up = up
222
+
223
+ # ------------------------------------------------------------- reads
224
+
225
+ def position(self, instrument: str) -> int:
226
+ pos = self._positions.get(instrument)
227
+ return pos.qty if pos is not None else 0
228
+
229
+ @property
230
+ def day_pnl(self) -> float:
231
+ return self.day_realized + self.unrealized
232
+
233
+ def snapshot(self, now: datetime, *, kill_engaged: bool = False) -> AccountSnapshot:
234
+ """The frozen per-account snapshot the guardrail engine checks
235
+ against. Rolls the ledger first, so a stale book can never leak
236
+ yesterday's P&L into today's decisions."""
237
+ self.roll_if_needed(now)
238
+ self._evaluate_halt()
239
+ return AccountSnapshot(
240
+ account=self.account,
241
+ kill_engaged=kill_engaged,
242
+ link_up=self.link_up,
243
+ day_realized=self.day_realized,
244
+ unrealized=self.unrealized,
245
+ positions={k: p.qty for k, p in self._positions.items() if p.qty != 0},
246
+ order_events=tuple(self._order_events),
247
+ last_loss_ts=self.last_loss_ts,
248
+ last_order_ts=self.last_order_ts,
249
+ first_order_done=self.first_order_done,
250
+ max_order_qty=self.max_order_qty,
251
+ day_halted=self.day_halted,
252
+ day_halt_reason=self.day_halt_reason,
253
+ )