perkbridge-connect 1.0.0b1__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.
- perkbridge_connect-1.0.0b1/.gitignore +14 -0
- perkbridge_connect-1.0.0b1/CHANGELOG.md +32 -0
- perkbridge_connect-1.0.0b1/LICENSE +202 -0
- perkbridge_connect-1.0.0b1/PKG-INFO +348 -0
- perkbridge_connect-1.0.0b1/README.md +316 -0
- perkbridge_connect-1.0.0b1/docs/SPEC.md +495 -0
- perkbridge_connect-1.0.0b1/examples/breakout.properties +16 -0
- perkbridge_connect-1.0.0b1/examples/breakout.py +48 -0
- perkbridge_connect-1.0.0b1/pyproject.toml +79 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/__init__.py +99 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/__main__.py +5 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/_version.py +1 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/cli.py +218 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/client.py +1369 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/config.py +602 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/errors.py +142 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/http.py +411 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/logs.py +93 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/models.py +640 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/py.typed +0 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/runner.py +511 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/schedule.py +362 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/storage.py +534 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/strategy.py +287 -0
- perkbridge_connect-1.0.0b1/src/perkbridge/timemachine.py +859 -0
- perkbridge_connect-1.0.0b1/tests/__init__.py +0 -0
- perkbridge_connect-1.0.0b1/tests/contract/__init__.py +0 -0
- perkbridge_connect-1.0.0b1/tests/contract/conftest.py +69 -0
- perkbridge_connect-1.0.0b1/tests/contract/nile-sim.sh +127 -0
- perkbridge_connect-1.0.0b1/tests/contract/test_contract.py +319 -0
- perkbridge_connect-1.0.0b1/tests/contract/test_safety_review.py +246 -0
- perkbridge_connect-1.0.0b1/tests/unit/__init__.py +0 -0
- perkbridge_connect-1.0.0b1/tests/unit/conftest.py +67 -0
- perkbridge_connect-1.0.0b1/tests/unit/fakeapi.py +473 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_cli_and_logs.py +98 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_client.py +322 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_config.py +196 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_examples.py +27 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_journal.py +150 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_models.py +73 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_runner.py +385 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_safety_review.py +644 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_schedule.py +117 -0
- perkbridge_connect-1.0.0b1/tests/unit/test_timemachine.py +111 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.0b1 (unreleased)
|
|
4
|
+
|
|
5
|
+
First beta.
|
|
6
|
+
|
|
7
|
+
- `Config`: properties file, `[strategy.<name>]` sections, environment and `_FILE` secrets, and validation that reports every problem at once.
|
|
8
|
+
- `Connect`: reads, orders, modifies, cancels and closes. Includes the idempotency journal with recovery on restart, refused/rejected/unknown outcomes, the local envelope, and retries with `Retry-After`.
|
|
9
|
+
- `Strategy`, `run`, `run_once`: interval, at, cron and manual schedules with time zones and daylight saving time, market hours, the event feed with a saved cursor, and persisted `ctx.state`.
|
|
10
|
+
- Time Machine: replays a past window with a local fill simulator. Nothing is sent.
|
|
11
|
+
- `perkbridge-run` command line.
|
|
12
|
+
- Review fixes, trading safety:
|
|
13
|
+
- The same intent after an ambiguous answer reuses its key.
|
|
14
|
+
- The one-in-flight rule holds after a wait timeout and after a restart.
|
|
15
|
+
- `close_all` stops at an ambiguous close.
|
|
16
|
+
- `then_stops` is journaled and applied once after a late fill.
|
|
17
|
+
- `then_stops` counts as set only when the modify is `done`.
|
|
18
|
+
- Refused or failed stop modifies are retried with backoff, then reported.
|
|
19
|
+
- The same key with different `then_stops` is refused.
|
|
20
|
+
- `pending_stops()` lists stops that are not set yet.
|
|
21
|
+
- `stops_status()` and `stops_needing_attention()` keep failed stop
|
|
22
|
+
protection visible until the position closes.
|
|
23
|
+
- The local envelope is checked inside the submission lock, after the
|
|
24
|
+
same-key replay check.
|
|
25
|
+
- An abandoned or aged unanswered key is never sent late.
|
|
26
|
+
- Derived keys use a digest of the whole key.
|
|
27
|
+
- A stops watcher thread (`order.stops_watch_s`) sets delayed-fill stops
|
|
28
|
+
with no further calls.
|
|
29
|
+
- `StopsNotSet` carries the placed order; a same-intent retry never opens
|
|
30
|
+
a second position.
|
|
31
|
+
- The watcher's exit is serialized with its start.
|
|
32
|
+
- Pruning keeps unresolved stop intents and orders that are not final.
|
|
@@ -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.
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: perkbridge-connect
|
|
3
|
+
Version: 1.0.0b1
|
|
4
|
+
Summary: Python client for the PerkBridge Connect Trading API: idempotent orders, strategies on a schedule, events.
|
|
5
|
+
Project-URL: Homepage, https://perkbridge.eu
|
|
6
|
+
Project-URL: Source, https://github.com/perkbridge/connect-python-client
|
|
7
|
+
Author: PerkBridge
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api-client,metatrader,mt5,perkbridge,trading
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: httpx<1,>=0.27
|
|
25
|
+
Requires-Dist: tzdata; sys_platform == 'win32'
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
29
|
+
Requires-Dist: pyyaml>=6; extra == 'dev'
|
|
30
|
+
Requires-Dist: ruff==0.17.3; extra == 'dev'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# perkbridge-connect
|
|
34
|
+
|
|
35
|
+
The Python library for the PerkBridge Connect Trading API (`/v1/trading`).
|
|
36
|
+
Write a strategy as a small class, keep the connection in a properties file,
|
|
37
|
+
and run it. The library takes care of authentication, idempotency, duplicate
|
|
38
|
+
prevention, scheduling, reconnects, events and errors.
|
|
39
|
+
|
|
40
|
+
Status: **1.0.0b1, beta.** It has been tested against a real Control Plane with
|
|
41
|
+
simulator accounts. It has not yet been run against a real MT5 terminal.
|
|
42
|
+
Use demo accounts.
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
pip install perkbridge-connect # once published; import name: perkbridge
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Python 3.10 to 3.13. The only runtime dependency is `httpx` (plus `tzdata` on Windows).
|
|
49
|
+
|
|
50
|
+
## Five rules the library never breaks
|
|
51
|
+
|
|
52
|
+
1. **Every order is idempotent.** The library generates the `client_order_id` and
|
|
53
|
+
fsyncs it to a local journal before the request leaves the process. Any retry,
|
|
54
|
+
including one after a crash and restart, reuses that key, so the same order is
|
|
55
|
+
never placed twice.
|
|
56
|
+
2. **No invented outcomes.** An order ends in the state the API reports. When an
|
|
57
|
+
answer is lost, the order is reported as `unknown` while the platform checks
|
|
58
|
+
with the broker. It is never re-sent under a new key.
|
|
59
|
+
3. **Config is data, code is strategy.** The connection, the account, the local
|
|
60
|
+
risk envelope and the schedule come from a properties file or environment
|
|
61
|
+
variables. Tokens are never logged.
|
|
62
|
+
4. **One run at a time.** `on_run` is never called twice at once for the same
|
|
63
|
+
strategy.
|
|
64
|
+
5. **Closing always works.** `close()` and `cancel_order()` are sent during a
|
|
65
|
+
halt and after a risk rule trips, exactly as the API allows. The library adds
|
|
66
|
+
no block of its own.
|
|
67
|
+
|
|
68
|
+
## Quick start
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from perkbridge import Config, Connect
|
|
72
|
+
|
|
73
|
+
conf = Config.load() # ./perkbridge.properties, $PERKBRIDGE_CONFIG, env
|
|
74
|
+
pb = Connect(conf) # checks the token and the account
|
|
75
|
+
|
|
76
|
+
print(pb.account().balance, pb.quote("EURUSD").ask)
|
|
77
|
+
order = pb.buy("EURUSD", volume="0.01", then_stops=("1.0800", None))
|
|
78
|
+
print(order.status) # filled, placed, refused, rejected, ... or unknown
|
|
79
|
+
pb.close(pb.position("EURUSD"))
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
A strategy:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from perkbridge import Context, Strategy, run
|
|
86
|
+
|
|
87
|
+
class Breakout(Strategy):
|
|
88
|
+
config = {"schedule.mode": "interval", "schedule.every": "1h",
|
|
89
|
+
"schedule.market_hours": "Mon-Fri 08:00-20:00"}
|
|
90
|
+
|
|
91
|
+
def on_run(self, ctx: Context) -> None:
|
|
92
|
+
bars = ctx.bars("EURUSD", "H1", limit=21)
|
|
93
|
+
if ctx.position("EURUSD") is None and bars[-1].close > max(b.high for b in bars[:-1]):
|
|
94
|
+
ctx.buy("EURUSD")
|
|
95
|
+
|
|
96
|
+
run(Breakout)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
or from the command line:
|
|
100
|
+
|
|
101
|
+
```
|
|
102
|
+
perkbridge-run examples/breakout.py:Breakout --config examples/breakout.properties
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
See [examples/breakout.py](examples/breakout.py) for a complete strategy.
|
|
106
|
+
|
|
107
|
+
## Configuration
|
|
108
|
+
|
|
109
|
+
Settings are layered: the strategy's `config` defaults, then the file, then
|
|
110
|
+
`[strategy.<name>]` sections, then environment variables. Values set in code
|
|
111
|
+
with `Config.update()` win over all of these. Unknown keys and invalid values
|
|
112
|
+
are all reported at start, with a hint.
|
|
113
|
+
|
|
114
|
+
```properties
|
|
115
|
+
connection.url = https://connect.example.com
|
|
116
|
+
connection.account = tac-7f3k2m9q
|
|
117
|
+
# connection.token: prefer PERKBRIDGE_CONNECTION_TOKEN or ..._TOKEN_FILE
|
|
118
|
+
order.default_volume = 0.01
|
|
119
|
+
order.max_open_positions = 3 # local envelope, refused before sending
|
|
120
|
+
order.max_volume = 0.10
|
|
121
|
+
order.allowed_symbols = EURUSD, GBPUSD
|
|
122
|
+
state.dir = ~/.perkbridge/state
|
|
123
|
+
|
|
124
|
+
[strategy.breakout]
|
|
125
|
+
schedule.mode = interval
|
|
126
|
+
schedule.every = 1h
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
- **Environment variables.** Every key has one: `connection.token` becomes
|
|
130
|
+
`PERKBRIDGE_CONNECTION_TOKEN`. A `_FILE` suffix reads the value from a file,
|
|
131
|
+
which suits Docker secrets. A value written `${env:NAME}` in the file reads
|
|
132
|
+
the variable `NAME`.
|
|
133
|
+
- **File permissions.** A file that holds a token must not be readable by other
|
|
134
|
+
users; the library refuses it and suggests `chmod 600`.
|
|
135
|
+
- **Plain HTTP.** Accepted only for `localhost`.
|
|
136
|
+
- **Checking a config.** `perkbridge-run --show-config` prints the merged
|
|
137
|
+
settings and where each one came from, with the token masked.
|
|
138
|
+
|
|
139
|
+
| Group | Keys |
|
|
140
|
+
|---|---|
|
|
141
|
+
| `connection.` | `url`, `token`, `account`, `timeout_s`, `verify_tls`, `ca_file` |
|
|
142
|
+
| `order.` | `default_volume`, `expires_in_ms`, `wait_for_outcome`, `wait_timeout_s`, `strict`, `stops_watch_s`, `max_open_positions`, `max_volume`, `allowed_symbols`, `max_orders_per_run`, `duplicate_check`, `replay_window_s` |
|
|
143
|
+
| `state.` | `dir` |
|
|
144
|
+
| `schedule.` | `mode` (manual, interval, at, cron), `every`, `at`, `cron`, `timezone`, `align`, `market_hours`, `skip_if_running`, `catch_up`, `jitter_s`, `max_consecutive_errors` |
|
|
145
|
+
| `events.` | `enabled`, `poll_interval_s` |
|
|
146
|
+
| `log.` | `level`, `format` (text, json) |
|
|
147
|
+
|
|
148
|
+
## Orders and outcomes
|
|
149
|
+
|
|
150
|
+
- **Order calls.** `buy`, `sell`, `buy_limit`, `sell_limit`, `buy_stop`,
|
|
151
|
+
`sell_stop`, `buy_stop_limit` and `sell_stop_limit` return an `Order`. By
|
|
152
|
+
default the call waits until the order is final, placed or `unknown`.
|
|
153
|
+
`close`, `close_all`, `modify_position`, `modify_order` and `cancel_order`
|
|
154
|
+
work the same way. For modifies, `KEEP` leaves a value unchanged and `None`
|
|
155
|
+
removes it.
|
|
156
|
+
- **Refusals and rejections.** The platform refusing an order raises
|
|
157
|
+
`OrderRefused`, with `.code` and a hint. The broker rejecting it raises
|
|
158
|
+
`OrderRejected`, with `.retcode`. Both carry the stored order.
|
|
159
|
+
- **Stops on market orders.** When a symbol does not support stops on a market
|
|
160
|
+
order, the order is refused before it is sent (`StopsNotSupported`). Use
|
|
161
|
+
`then_stops=(sl, tp)` instead: it places the order, then modifies the
|
|
162
|
+
position. The stops are journaled with the order. If the order has not
|
|
163
|
+
filled when the call returns, they are set once it fills, and exactly once,
|
|
164
|
+
with the key `<key>-s`. This is checked on start, after `wait()`, on order
|
|
165
|
+
events, before each strategy run, and by `pb.apply_pending_stops()`. An order
|
|
166
|
+
that ends without a fill drops its stops.
|
|
167
|
+
|
|
168
|
+
While stops are waiting, a background watcher thread (a daemon) retries
|
|
169
|
+
every `order.stops_watch_s` (2 s by default), so a direct `Connect` user
|
|
170
|
+
needs no further call. The watcher stops when nothing is pending or on
|
|
171
|
+
`close_session()`. Closing, or the process ending, with stops still pending
|
|
172
|
+
logs a warning: those positions are not protected until a `Connect` for the
|
|
173
|
+
same account and `state.dir` starts again and resumes them. With
|
|
174
|
+
`order.stops_watch_s = 0`, the caller must call `apply_pending_stops()` or
|
|
175
|
+
`wait()` itself.
|
|
176
|
+
|
|
177
|
+
If the stops fail during the `buy()` call itself, the call raises
|
|
178
|
+
`StopsNotSet`, whose `.order` is the order that WAS placed. Do not place it
|
|
179
|
+
again. Inside a strategy, the same intent returns that order instead of
|
|
180
|
+
opening a second position. Stop intents that are not resolved, and orders
|
|
181
|
+
that are not final yet, are never pruned from the journal, however old they
|
|
182
|
+
are.
|
|
183
|
+
|
|
184
|
+
The stops count as set only when the platform reports the modify as
|
|
185
|
+
`done`. While the modify is queued, sending or unknown, it stays pending
|
|
186
|
+
and is followed up with the same key. These cases are handled as follows:
|
|
187
|
+
|
|
188
|
+
- **Nothing sent.** Another order was in flight, or the platform rate
|
|
189
|
+
limited the request. The modify is retried later.
|
|
190
|
+
- **Refused, rejected or expired.** The modify was definitely not applied. It
|
|
191
|
+
is retried with a fresh key (`<key>-s2`, `-s3`, ...), waiting 5 s, 15 s,
|
|
192
|
+
60 s, then 300 s between attempts.
|
|
193
|
+
- **Permanent refusal.** For example `stops_invalid` or
|
|
194
|
+
`position_not_found`. The library gives up and logs an error saying the
|
|
195
|
+
position is open without its stops.
|
|
196
|
+
- **Too many attempts.** After 20 attempts it also gives up with that error.
|
|
197
|
+
- **Position already closed.** The stops are dropped.
|
|
198
|
+
|
|
199
|
+
- `pb.pending_stops()` lists the stops that are still being worked on.
|
|
200
|
+
- `pb.stops_status()` lists every intent with its state: `pending`,
|
|
201
|
+
`failed`, `set`, `dropped` or `resolved`.
|
|
202
|
+
- `pb.stops_needing_attention()` lists positions left open without the
|
|
203
|
+
stops the library gave up setting. Each one stays listed, across restarts
|
|
204
|
+
and journal pruning, until its position is seen closed. Each one is also
|
|
205
|
+
logged as an error on start and before every strategy run.
|
|
206
|
+
Reusing a `client_order_id` with different `then_stops` raises
|
|
207
|
+
`IdempotencyConflict`.
|
|
208
|
+
- **Unknown outcomes.** An `unknown` outcome is returned as an order with
|
|
209
|
+
`.unknown` true, or raised as `OutcomeUnknown` when `order.strict = true`. The
|
|
210
|
+
platform settles it, and `pb.wait(order)` or the events follow it.
|
|
211
|
+
- **Duplicate intents.** Inside one strategy run, the same intent made twice
|
|
212
|
+
returns the first order (`order.duplicate_check`). If the first call ended
|
|
213
|
+
without a known outcome (`ConnectionLost`, `OutcomeUnknown`), the same intent
|
|
214
|
+
reuses the first call's key, so the platform answers with that order instead
|
|
215
|
+
of placing a second one. Only a definite "not placed" (refused, rejected,
|
|
216
|
+
never sent) frees the intent for a new order.
|
|
217
|
+
- **Local envelope.** The envelope is checked inside the account's submission
|
|
218
|
+
lock, so two threads cannot both pass `order.max_open_positions`. It applies
|
|
219
|
+
only to a new intent: a replay of a `client_order_id` that is already
|
|
220
|
+
journaled returns the stored order even when the limit has been reached.
|
|
221
|
+
- **One order in flight.** While an order of the account is still `sending`
|
|
222
|
+
or `queued`, the next order raises `InFlight` instead of queueing. This also
|
|
223
|
+
applies after `wait()` times out and after a restart, because the journal
|
|
224
|
+
remembers the order. An `unknown` outcome is left to the platform, which
|
|
225
|
+
refuses new orders with `reconciliation_pending` while it checks.
|
|
226
|
+
- **`close_all`.** It closes positions one by one and stops at the first
|
|
227
|
+
close whose outcome is not known (a lost answer, or `unknown`). That close
|
|
228
|
+
stays journaled and is resolved with its key before anything else is sent.
|
|
229
|
+
- **Keys that are never reused.** A journaled key whose request never got an
|
|
230
|
+
answer follows the restart rules even when it is reused at once: it is
|
|
231
|
+
looked up by key, replayed only while it is younger than
|
|
232
|
+
`order.replay_window_s`, and abandoned otherwise. An abandoned key raises
|
|
233
|
+
`OrderError` (`intent_abandoned`) and is never sent again; a new order needs
|
|
234
|
+
a new key. Derived keys, such as `<key>-s` for stops, stay unique for keys
|
|
235
|
+
near the 128-character limit, because they include a digest of the whole
|
|
236
|
+
key.
|
|
237
|
+
- **Restarts.** On start, `Connect` reads the journal. An entry that never got
|
|
238
|
+
an answer is looked up by its key first. It is replayed with the same key only
|
|
239
|
+
if it is younger than `order.replay_window_s` (120 s by default); otherwise it
|
|
240
|
+
is reported and abandoned.
|
|
241
|
+
|
|
242
|
+
## Strategies and the scheduler
|
|
243
|
+
|
|
244
|
+
`Strategy` has four callbacks: `on_start`, `on_run`, `on_event(ev)` and
|
|
245
|
+
`on_stop`.
|
|
246
|
+
|
|
247
|
+
- **The context.** `ctx` exposes the reads and orders, scoped to the
|
|
248
|
+
strategy's own positions unless `all=True`. It also has `ctx.state`, a dict
|
|
249
|
+
persisted between runs, plus `ctx.run_number`, `ctx.now` and `ctx.log`.
|
|
250
|
+
- **Schedules.** `interval` (aligned to the clock by default), `at` (fixed
|
|
251
|
+
times), `cron` (five fields) and `manual`. All of them honour
|
|
252
|
+
`schedule.timezone` and daylight saving time, and can be limited with
|
|
253
|
+
`schedule.market_hours`.
|
|
254
|
+
- **Missed and failing ticks.** A tick that overruns is skipped, not stacked.
|
|
255
|
+
Missed ticks after a sleep run once at most, or are skipped. After
|
|
256
|
+
`schedule.max_consecutive_errors` errors in a row, the strategy pauses with a
|
|
257
|
+
clear log line.
|
|
258
|
+
- **Control Plane unreachable.** The tick is skipped with one log line. Nothing
|
|
259
|
+
is closed or retried blindly.
|
|
260
|
+
- **Events.** They come from the account's event feed, with a saved cursor, so
|
|
261
|
+
none are lost across restarts. A cursor that is too old resynchronises and
|
|
262
|
+
delivers a `sync.resumed` event.
|
|
263
|
+
|
|
264
|
+
## Time Machine
|
|
265
|
+
|
|
266
|
+
Replay a strategy over a past window with `ctx.now` set to each past tick:
|
|
267
|
+
|
|
268
|
+
```
|
|
269
|
+
perkbridge-run examples/breakout.py:Breakout -c examples/breakout.properties \
|
|
270
|
+
--time-machine from=2026-10-01 to=2026-10-31 step=1h
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
- **Data.** Bars come from the API, and only bars closed before `ctx.now` are
|
|
274
|
+
visible. Quotes are synthetic, built from the last M1 close plus the live
|
|
275
|
+
spread.
|
|
276
|
+
- **Fills.** A local simulator fills market, limit, stop and stop-limit orders
|
|
277
|
+
and SL/TP on M1, M15 or H1 bars, depending on the window length.
|
|
278
|
+
- **No real orders.** Nothing is sent to the platform. `orders=none` only logs
|
|
279
|
+
the intents.
|
|
280
|
+
- **Output.** The report is written to
|
|
281
|
+
`state/<account>/strategies/<name>/time-machine/<from>_<to>/report.json`.
|
|
282
|
+
|
|
283
|
+
It is a sanity replay, not a backtester: there are no swaps, commissions or
|
|
284
|
+
slippage model.
|
|
285
|
+
|
|
286
|
+
## Command line
|
|
287
|
+
|
|
288
|
+
```
|
|
289
|
+
perkbridge-run TARGET [--config FILE] [--set KEY=VALUE ...]
|
|
290
|
+
[--check | --show-config | --once | --time-machine ... | --reset-state --yes]
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
- **Target.** `TARGET` is `module:Class` or `file.py:Class`, with
|
|
294
|
+
`Class1,Class2` for several strategies.
|
|
295
|
+
- **Exit codes.** 0 means OK, 1 an error, 2 a configuration error and 130
|
|
296
|
+
interrupted.
|
|
297
|
+
- **Logs.** They are JSON when stdout is not a terminal.
|
|
298
|
+
- **Tokens.** `--set connection.token=...` is refused: tokens do not belong on
|
|
299
|
+
command lines.
|
|
300
|
+
|
|
301
|
+
## Running in a container
|
|
302
|
+
|
|
303
|
+
The library is built to run in a container later, with no code change:
|
|
304
|
+
|
|
305
|
+
```yaml
|
|
306
|
+
services:
|
|
307
|
+
breakout:
|
|
308
|
+
image: python:3.12-slim # an official image will follow
|
|
309
|
+
command: perkbridge-run /app/breakout.py:Breakout
|
|
310
|
+
environment:
|
|
311
|
+
PERKBRIDGE_CONFIG: /app/perkbridge.properties
|
|
312
|
+
PERKBRIDGE_CONNECTION_TOKEN_FILE: /run/secrets/perkbridge_token
|
|
313
|
+
PERKBRIDGE_STATE_DIR: /state
|
|
314
|
+
volumes: ["./app:/app:ro", "state:/state"]
|
|
315
|
+
secrets: [perkbridge_token]
|
|
316
|
+
stop_grace_period: 30s
|
|
317
|
+
volumes: {state: {}}
|
|
318
|
+
secrets: {perkbridge_token: {file: ./token}}
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Keep `state.dir` on a volume: the idempotency journal is what makes a restart
|
|
322
|
+
safe. The library warns when it runs in a container with the default `state.dir`.
|
|
323
|
+
|
|
324
|
+
## Low-level API
|
|
325
|
+
|
|
326
|
+
`pb.api` is a thin typed client with one method per public operation of the
|
|
327
|
+
Trading API, for example `pb.api.list_orders(...)` and
|
|
328
|
+
`pb.api.place_order(body)`. It handles authentication and retries but adds no
|
|
329
|
+
journal.
|
|
330
|
+
|
|
331
|
+
## Development
|
|
332
|
+
|
|
333
|
+
```
|
|
334
|
+
python -m venv .venv && . .venv/bin/activate
|
|
335
|
+
pip install -e '.[dev]'
|
|
336
|
+
ruff check . && ruff format --check . && mypy src && pytest
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
- **Unit tests** (`tests/unit`) use an in-process fake API and run anywhere.
|
|
340
|
+
- **Contract tests** (`tests/contract`) run against a real Control Plane with
|
|
341
|
+
simulator accounts, built from the private `perkbridge/nile` source with
|
|
342
|
+
`tests/contract/nile-sim.sh`. They are skipped unless `PB_CONTRACT_URL` is
|
|
343
|
+
set.
|
|
344
|
+
- **Specification.** See [docs/SPEC.md](docs/SPEC.md).
|
|
345
|
+
|
|
346
|
+
## Licence
|
|
347
|
+
|
|
348
|
+
Apache-2.0
|