bijective-strategy 0.1.2__py3-none-any.whl

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,360 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Bijective Labs
3
+
4
+ """The protocol a strategy speaks: one JSON object per line in both directions.
5
+
6
+ A convenience over stdin and stdout; the supervisor decides what a proposal may say.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from dataclasses import dataclass
14
+ from typing import Iterator, TextIO
15
+
16
+ __all__ = [
17
+ "Book",
18
+ "EndOfWindow",
19
+ "Fact",
20
+ "Resumed",
21
+ "Unrecognised",
22
+ "answered",
23
+ "events",
24
+ "propose",
25
+ "read_event",
26
+ ]
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Book:
31
+ """A book update with its position in the market's history.
32
+
33
+ Fields stay as sent: scaled integers are decimal strings, never floats.
34
+ """
35
+
36
+ position: str
37
+ instrument: str
38
+ venue_sequence: str | None
39
+ venue_ts_ms: str
40
+ bid_price: str
41
+ bid_quantity: str
42
+ ask_price: str
43
+ ask_quantity: str
44
+ bid_depth: int
45
+ ask_depth: int
46
+ #: The venue the top was quoted on. None where the stream names no venue.
47
+ venue: str | None = None
48
+ #: UTC nanoseconds on this node's clock when the top arrived: one clock for every venue.
49
+ #: None on a top recorded before receive times were kept.
50
+ received_at_ns: str | None = None
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class InstrumentRules:
55
+ """One instrument's rules on the session's venue, at the instrument's own scales, as strings.
56
+
57
+ A limit price must be a multiple of `price_tick` and a quantity a multiple of `quantity_lot`,
58
+ or the order is refused before it leaves.
59
+ """
60
+
61
+ instrument: str
62
+ price_scale: int
63
+ quantity_scale: int
64
+ price_tick: str
65
+ quantity_lot: str
66
+ minimum_size: str
67
+ minimum_notional: str
68
+ trading: bool
69
+ #: What the instrument is (spot, perpetual, ...). None where the venue declared none.
70
+ kind: str | None = None
71
+ quote_currency: str | None = None
72
+ settlement_currency: str | None = None
73
+ #: The asset a quantity is counted in. None where the venue's declaration predates it.
74
+ base_currency: str | None = None
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Venue:
79
+ """The venue a session reads and what it charges, sent once before the first top.
80
+
81
+ Fees are basis points at the platform's 8-decimal scale, as strings. None means no fee
82
+ declaration stands for the venue, which is not a fee of zero.
83
+ """
84
+
85
+ venue: str
86
+ taker_fee_bps_scaled: str | None = None
87
+ maker_fee_bps_scaled: str | None = None
88
+ fee_source: str | None = None
89
+ instruments: tuple[InstrumentRules, ...] = ()
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class OrderUpdate:
94
+ """What became of one of this strategy's proposals, in a live session.
95
+
96
+ `proposal_position` is where the proposal landed in the proposal stream. `status` is one of
97
+ refused, submitted, accepted, rejected, unknown, filled, cancel_requested, canceled, expired or
98
+ reconciling. `unknown` means the order may or may not be at the venue: neither placed nor failed.
99
+ A fill carries its quantity and price at the venue's scales, as strings.
100
+ """
101
+
102
+ proposal_position: str
103
+ status: str
104
+ #: UTC nanoseconds on the platform clock. From submitted to the venue's answer is its latency.
105
+ recorded_at_ns: str = ""
106
+ client_id: str | None = None
107
+ reason: str = ""
108
+ fill_id: str | None = None
109
+ fill_quantity_scaled: str | None = None
110
+ fill_price_scaled: str | None = None
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class Fact:
115
+ """A fact about an instrument besides its top of book: a trade, liquidation, funding rate,
116
+ open interest, mark or index price or long/short ratio, named by `kind`.
117
+
118
+ `fact_position` is a position on the venue's facts stream, not one a decision names. `values`
119
+ holds the kind's own fields as sent: scaled figures as strings, each `_scale` as a number.
120
+ """
121
+
122
+ kind: str
123
+ fact_position: str
124
+ instrument: str
125
+ venue: str | None
126
+ exchange_ts_ns: str | None
127
+ received_at_ns: str
128
+ values: dict[str, object]
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class EndOfWindow:
133
+ """A bounded run's window is exhausted. A live session is never sent this."""
134
+
135
+
136
+ @dataclass(frozen=True)
137
+ class Resumed:
138
+ """Where a live session's events pick up, and what ran while nothing was listening."""
139
+
140
+ from_position: str
141
+ missed: object
142
+ #: The venue whose market this resume point is on. A session of several markets is sent one
143
+ #: per market. None where the stream names no venue.
144
+ venue: str | None = None
145
+ #: The stream the position is on (`market-<venue>` or `facts-<venue>`).
146
+ stream: str | None = None
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class Unrecognised:
151
+ """An event this version does not know. Returned, not raised, so an older strategy keeps running.
152
+
153
+ """
154
+
155
+ raw: str
156
+
157
+
158
+ def read_event(
159
+ line: str,
160
+ ) -> Book | Venue | OrderUpdate | Fact | EndOfWindow | Resumed | Unrecognised:
161
+ """One line the supervisor sent, read."""
162
+ try:
163
+ message = json.loads(line)
164
+ except ValueError:
165
+ return Unrecognised(line)
166
+ if not isinstance(message, dict):
167
+ return Unrecognised(line)
168
+
169
+ match message.get("event"):
170
+ case "book":
171
+ try:
172
+ return Book(
173
+ position=message["position"],
174
+ instrument=message["instrument"],
175
+ venue_sequence=message.get("venue_sequence"),
176
+ venue_ts_ms=message["venue_ts_ms"],
177
+ bid_price=message["bid_price"],
178
+ bid_quantity=message["bid_quantity"],
179
+ ask_price=message["ask_price"],
180
+ ask_quantity=message["ask_quantity"],
181
+ bid_depth=message["bid_depth"],
182
+ ask_depth=message["ask_depth"],
183
+ venue=message.get("venue"),
184
+ received_at_ns=message.get("received_at_ns"),
185
+ )
186
+ except KeyError:
187
+ # A partial book is not half a book. Deciding on one would be a guess.
188
+ return Unrecognised(line)
189
+ case "venue" if isinstance(message.get("venue"), str):
190
+ try:
191
+ return Venue(
192
+ venue=message["venue"],
193
+ taker_fee_bps_scaled=message.get("taker_fee_bps_scaled"),
194
+ maker_fee_bps_scaled=message.get("maker_fee_bps_scaled"),
195
+ fee_source=message.get("fee_source"),
196
+ instruments=tuple(_rules(r) for r in message.get("instruments", [])),
197
+ )
198
+ except (KeyError, TypeError, ValueError):
199
+ # Partial rules are not rules. A price placed on a guessed increment is refused anyway.
200
+ return Unrecognised(line)
201
+ case "order" if isinstance(message.get("proposal_position"), str):
202
+ return OrderUpdate(
203
+ proposal_position=message["proposal_position"],
204
+ status=message.get("status", ""),
205
+ recorded_at_ns=message.get("recorded_at_ns", ""),
206
+ client_id=message.get("client_id"),
207
+ reason=message.get("reason", ""),
208
+ fill_id=message.get("fill_id"),
209
+ fill_quantity_scaled=message.get("fill_quantity_scaled"),
210
+ fill_price_scaled=message.get("fill_price_scaled"),
211
+ )
212
+ case "end_of_window":
213
+ return EndOfWindow()
214
+ case "resumed":
215
+ return Resumed(
216
+ from_position=message.get("from_position", ""),
217
+ missed=message.get("missed"),
218
+ venue=message.get("venue"),
219
+ stream=message.get("stream"),
220
+ )
221
+ case "fact" if isinstance(message.get("kind"), str):
222
+ return _fact(message)
223
+ case _:
224
+ return Unrecognised(line)
225
+
226
+
227
+ _FACT_COMMON = ("event", "kind", "fact_position", "instrument", "venue", "exchange_ts_ns",
228
+ "received_at_ns")
229
+
230
+
231
+ def _fact(message: dict[str, object]) -> Fact:
232
+ """Every kind reads the same way, so a kind added later reaches a strategy without a release."""
233
+ return Fact(
234
+ kind=str(message["kind"]),
235
+ fact_position=str(message.get("fact_position", "")),
236
+ instrument=str(message.get("instrument", "")),
237
+ venue=_text(message.get("venue")),
238
+ exchange_ts_ns=_text(message.get("exchange_ts_ns")),
239
+ received_at_ns=str(message.get("received_at_ns", "")),
240
+ values={k: v for k, v in message.items() if k not in _FACT_COMMON},
241
+ )
242
+
243
+
244
+ def _rules(rules: dict[str, object]) -> InstrumentRules:
245
+ """Named fields only: a field a later platform adds is ignored, not a reason to fail."""
246
+ return InstrumentRules(
247
+ instrument=str(rules["instrument"]),
248
+ price_scale=int(str(rules["price_scale"])),
249
+ quantity_scale=int(str(rules["quantity_scale"])),
250
+ price_tick=str(rules["price_tick"]),
251
+ quantity_lot=str(rules["quantity_lot"]),
252
+ minimum_size=str(rules["minimum_size"]),
253
+ minimum_notional=str(rules["minimum_notional"]),
254
+ trading=bool(rules["trading"]),
255
+ kind=_text(rules.get("kind")),
256
+ quote_currency=_text(rules.get("quote_currency")),
257
+ settlement_currency=_text(rules.get("settlement_currency")),
258
+ base_currency=_text(rules.get("base_currency")),
259
+ )
260
+
261
+
262
+ def _text(value: object) -> str | None:
263
+ return None if value is None else str(value)
264
+
265
+
266
+ def events(
267
+ stream: TextIO | None = None,
268
+ ) -> Iterator[Book | Venue | OrderUpdate | Fact | EndOfWindow | Resumed | Unrecognised]:
269
+ """Every event, as it arrives."""
270
+ for line in stream if stream is not None else sys.stdin:
271
+ line = line.strip()
272
+ if line:
273
+ yield read_event(line)
274
+
275
+
276
+ def propose(
277
+ *,
278
+ desk: str,
279
+ instrument: str,
280
+ side: str,
281
+ quantity_scaled: str,
282
+ price_scaled: str | None = None,
283
+ cap_scaled: str | None = None,
284
+ client_id: str,
285
+ decided_at_ns: str,
286
+ decided_at_position: str | None = None,
287
+ venue: str | None = None,
288
+ time_in_force: str | None = None,
289
+ post_only: bool = False,
290
+ stop_price_scaled: str | None = None,
291
+ expire_at_ns: str | None = None,
292
+ reduce_only: bool = False,
293
+ parent: str | None = None,
294
+ oco: str | None = None,
295
+ out: TextIO | None = None,
296
+ ) -> None:
297
+ """Say what to do. Keyword-only, because seven positional strings is how the wrong two swap.
298
+
299
+ `venue` names the venue the decision was made for (an arbitrage leg, a venue's fee or
300
+ liquidity); the order is admitted there or refused, never moved to another. Left out, the
301
+ desk's venue preference decides. `time_in_force` is `gtc` (left out), `ioc`, `fok`, `day`,
302
+ `at_the_open` or `at_the_close`; `post_only` asks for an order that only rests. A venue that
303
+ cannot honour them refuses the order rather than send it under other terms.
304
+ `stop_price_scaled` makes it a stop: held until the price reaches it (a buy when it rises to
305
+ it, a sell when it falls), then a limit order at `price_scaled` or, without one, a market
306
+ order bounded by `cap_scaled`. `reduce_only` asks for an order that only reduces what is held:
307
+ an exit or a protective stop, which a halted platform leaves working. `expire_at_ns` (UTC
308
+ nanoseconds) has the node cancel the order if it still works then; it needs a time in force
309
+ that rests.
310
+ `parent` names the `client_id` of an earlier proposal: this one is held until that one's
311
+ orders fill, then placed for the quantity filled, and must be `reduce_only`. `oco` names a
312
+ group under the same parent: once one member's order fills, the others are cancelled. A
313
+ bracket is an entry and two reduce-only children, a stop and a take-profit, in one group.
314
+ """
315
+ message: dict[str, object] = {
316
+ "emit": "proposal",
317
+ "desk": desk,
318
+ "instrument": instrument,
319
+ "side": side,
320
+ "quantity_scaled": quantity_scaled,
321
+ "client_id": client_id,
322
+ "decided_at_ns": decided_at_ns,
323
+ }
324
+ # Absent stays absent: null is not the same as a field that was not sent.
325
+ if price_scaled is not None:
326
+ message["price_scaled"] = price_scaled
327
+ if cap_scaled is not None:
328
+ message["cap_scaled"] = cap_scaled
329
+ if decided_at_position is not None:
330
+ message["decided_at_position"] = decided_at_position
331
+ if venue is not None:
332
+ message["venue"] = venue
333
+ if time_in_force is not None:
334
+ message["time_in_force"] = time_in_force
335
+ if post_only:
336
+ message["post_only"] = True
337
+ if stop_price_scaled is not None:
338
+ message["stop_price_scaled"] = stop_price_scaled
339
+ if expire_at_ns is not None:
340
+ message["expire_at_ns"] = expire_at_ns
341
+ if reduce_only:
342
+ message["reduce_only"] = True
343
+ if parent is not None:
344
+ message["parent"] = parent
345
+ if oco is not None:
346
+ message["oco"] = oco
347
+ _write(message, out)
348
+
349
+
350
+ def answered(out: TextIO | None = None) -> None:
351
+ """This event is finished with. The stepwise exchange waits for it."""
352
+ _write({"emit": "answered"}, out)
353
+
354
+
355
+ def _write(message: dict[str, object], out: TextIO | None) -> None:
356
+ stream = out if out is not None else sys.stdout
357
+ stream.write(json.dumps(message, separators=(",", ":")))
358
+ stream.write("\n")
359
+ # Flushed on every line. A buffered answer leaves the supervisor waiting until the wall bound.
360
+ stream.flush()
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: bijective-strategy
3
+ Version: 0.1.2
4
+ Summary: The protocol a strategy speaks, for strategies written in Python.
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: <3.15,>=3.12
7
+ Description-Content-Type: text/markdown
8
+ Provides-Extra: test
9
+ Requires-Dist: pytest>=8; extra == "test"
10
+
11
+ # bijective-strategy
12
+
13
+ The strategy protocol for Python strategies. Standard library only.
14
+
15
+ ```python
16
+ from bijective_strategy import Book, EndOfWindow, answered, events, propose
17
+
18
+ for event in events():
19
+ if isinstance(event, Book):
20
+ if int(event.ask_price) - int(event.bid_price) < 200:
21
+ propose(desk="alpha", instrument=event.instrument, side="buy",
22
+ quantity_scaled="1", price_scaled=event.bid_price,
23
+ client_id="c1", decided_at_ns="1")
24
+ answered()
25
+ elif isinstance(event, EndOfWindow):
26
+ break
27
+ ```
28
+
29
+ See [Strategies](../../docs/concepts/strategies.md).
30
+
31
+ ## Reference strategies
32
+
33
+ `examples/reference/` holds strategies that exercise the platform end to end: the order path, the
34
+ risk gate and the record. They are not recommendations.
35
+
36
+ | File | Rule |
37
+ |---|---|
38
+ | `zscore_reversion.py` | Short above two standard deviations of the minute mid, long below, flat within half of one |
39
+ | `momentum.py` | Long one unit when the 15-minute move clears one standard deviation, sold after 15 minutes |
40
+
41
+ Each keeps its decision core free of input and output so it is tested without the platform, and
42
+ each runs as a set over one window: `bijective-backtest examples/reference/`.
@@ -0,0 +1,5 @@
1
+ bijective_strategy/__init__.py,sha256=c3CNtD552csmjX2v3Ho08aKJIl3s6-ekQUupyfYY2bk,13265
2
+ bijective_strategy-0.1.2.dist-info/METADATA,sha256=p-gw5WGYbecmQZNF8rCM0cGUOYBF65hAkAv9Sot8YGM,1542
3
+ bijective_strategy-0.1.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ bijective_strategy-0.1.2.dist-info/top_level.txt,sha256=xfPQYkGPkGL94zEpFC4zYyC1uxiFnCKK6FG4uWhLaYk,19
5
+ bijective_strategy-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ bijective_strategy