bijective-strategy 0.1.2__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,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,32 @@
1
+ # bijective-strategy
2
+
3
+ The strategy protocol for Python strategies. Standard library only.
4
+
5
+ ```python
6
+ from bijective_strategy import Book, EndOfWindow, answered, events, propose
7
+
8
+ for event in events():
9
+ if isinstance(event, Book):
10
+ if int(event.ask_price) - int(event.bid_price) < 200:
11
+ propose(desk="alpha", instrument=event.instrument, side="buy",
12
+ quantity_scaled="1", price_scaled=event.bid_price,
13
+ client_id="c1", decided_at_ns="1")
14
+ answered()
15
+ elif isinstance(event, EndOfWindow):
16
+ break
17
+ ```
18
+
19
+ See [Strategies](../../docs/concepts/strategies.md).
20
+
21
+ ## Reference strategies
22
+
23
+ `examples/reference/` holds strategies that exercise the platform end to end: the order path, the
24
+ risk gate and the record. They are not recommendations.
25
+
26
+ | File | Rule |
27
+ |---|---|
28
+ | `zscore_reversion.py` | Short above two standard deviations of the minute mid, long below, flat within half of one |
29
+ | `momentum.py` | Long one unit when the 15-minute move clears one standard deviation, sold after 15 minutes |
30
+
31
+ Each keeps its decision core free of input and output so it is tested without the platform, and
32
+ each runs as a set over one window: `bijective-backtest examples/reference/`.
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bijective-strategy"
7
+ version = "0.1.2"
8
+ description = "The protocol a strategy speaks, for strategies written in Python."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+
12
+ requires-python = ">=3.12,<3.15"
13
+
14
+ # No dependencies: the strategy sandbox has no network, so this is standard library only.
15
+ dependencies = []
16
+
17
+ [project.optional-dependencies]
18
+ test = ["pytest>=8"]
19
+
20
+ [tool.setuptools.packages.find]
21
+ where = ["src"]
22
+
23
+ [tool.pytest.ini_options]
24
+ testpaths = ["tests"]
25
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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,10 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/bijective_strategy/__init__.py
4
+ src/bijective_strategy.egg-info/PKG-INFO
5
+ src/bijective_strategy.egg-info/SOURCES.txt
6
+ src/bijective_strategy.egg-info/dependency_links.txt
7
+ src/bijective_strategy.egg-info/requires.txt
8
+ src/bijective_strategy.egg-info/top_level.txt
9
+ tests/test_protocol.py
10
+ tests/test_reference.py
@@ -0,0 +1 @@
1
+ bijective_strategy
@@ -0,0 +1,269 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Bijective Labs
3
+
4
+ """What a strategy written in Python reads and writes.
5
+
6
+ Assertions are on the wire bytes, since a round trip through this module could be wrong on both halves.
7
+ """
8
+
9
+ import io
10
+ import json
11
+
12
+ from bijective_strategy import Book, EndOfWindow, Resumed, Unrecognised, answered, events, propose, read_event
13
+
14
+ BOOK = (
15
+ '{"event":"book","position":"7","instrument":"btc-perp","venue_sequence":"3",'
16
+ '"venue_ts_ms":"1788000000000","bid_price":"2654375","bid_quantity":"1500",'
17
+ '"ask_price":"2654500","ask_quantity":"900","bid_depth":5,"ask_depth":5}'
18
+ )
19
+
20
+
21
+ def test_a_book_arrives_with_every_number_still_text():
22
+ event = read_event(BOOK)
23
+ assert isinstance(event, Book)
24
+ assert event.position == "7"
25
+ assert event.bid_price == "2654375"
26
+ # Scaled integers cross as decimal strings. A float here would be the platform's one prohibited conversion.
27
+ assert isinstance(event.bid_price, str)
28
+ assert event.bid_depth == 5
29
+
30
+
31
+ def test_an_event_this_version_does_not_know_is_returned_not_raised():
32
+ event = read_event('{"event":"something_added_later","detail":"x"}')
33
+ assert isinstance(event, Unrecognised)
34
+
35
+
36
+ def test_a_book_missing_a_field_is_not_half_a_book():
37
+ partial = '{"event":"book","position":"7","instrument":"btc-perp"}'
38
+ assert isinstance(read_event(partial), Unrecognised)
39
+
40
+
41
+ def test_the_two_events_that_are_not_books():
42
+ assert isinstance(read_event('{"event":"end_of_window"}'), EndOfWindow)
43
+ resumed = read_event('{"event":"resumed","from_position":"12","missed":{"missed":"not_recorded"}}')
44
+ assert isinstance(resumed, Resumed)
45
+ assert resumed.from_position == "12"
46
+
47
+
48
+ def test_a_line_that_is_not_json_is_not_an_exception():
49
+ assert isinstance(read_event("a strategy logged where it should not"), Unrecognised)
50
+
51
+
52
+ def test_events_skips_blank_lines_and_keeps_order():
53
+ stream = io.StringIO(BOOK + "\n\n" + '{"event":"end_of_window"}' + "\n")
54
+ read = list(events(stream))
55
+ assert [type(e) for e in read] == [Book, EndOfWindow]
56
+
57
+
58
+ def test_a_proposal_carries_what_was_given_and_nothing_else():
59
+ out = io.StringIO()
60
+ propose(
61
+ desk="alpha",
62
+ instrument="btc-perp",
63
+ side="buy",
64
+ quantity_scaled="1",
65
+ price_scaled="3000000",
66
+ client_id="c1",
67
+ decided_at_ns="1",
68
+ out=out,
69
+ )
70
+ written = json.loads(out.getvalue())
71
+ assert written == {
72
+ "emit": "proposal",
73
+ "desk": "alpha",
74
+ "instrument": "btc-perp",
75
+ "side": "buy",
76
+ "quantity_scaled": "1",
77
+ "price_scaled": "3000000",
78
+ "client_id": "c1",
79
+ "decided_at_ns": "1",
80
+ }
81
+ # Absent stays absent: null is not the same as a field that was not sent.
82
+ assert "cap_scaled" not in written
83
+ assert "decided_at_position" not in written
84
+
85
+
86
+ def test_a_decision_can_name_the_event_it_was_made_on():
87
+ out = io.StringIO()
88
+ propose(
89
+ desk="alpha",
90
+ instrument="btc-perp",
91
+ side="buy",
92
+ quantity_scaled="1",
93
+ price_scaled="3000000",
94
+ client_id="c1",
95
+ decided_at_ns="1",
96
+ decided_at_position="7",
97
+ out=out,
98
+ )
99
+ assert json.loads(out.getvalue())["decided_at_position"] == "7"
100
+
101
+
102
+ def test_the_turn_marker_is_exactly_what_the_supervisor_waits_for():
103
+ out = io.StringIO()
104
+ answered(out=out)
105
+ assert out.getvalue() == '{"emit":"answered"}\n'
106
+
107
+
108
+ def test_every_line_ends_with_a_newline_because_a_message_is_a_whole_line():
109
+ out = io.StringIO()
110
+ propose(
111
+ desk="alpha",
112
+ instrument="btc-perp",
113
+ side="buy",
114
+ quantity_scaled="1",
115
+ price_scaled="1",
116
+ client_id="c1",
117
+ decided_at_ns="1",
118
+ out=out,
119
+ )
120
+ answered(out=out)
121
+ assert out.getvalue().count("\n") == 2
122
+ for line in out.getvalue().splitlines():
123
+ json.loads(line)
124
+
125
+
126
+ def test_a_top_carries_its_venue_and_a_proposal_may_name_one() -> None:
127
+ import io
128
+
129
+ from bijective_strategy import Book, propose, read_event
130
+
131
+ line = (
132
+ '{"event":"book","position":"1","instrument":"btc-perp","venue":"venue-a",'
133
+ '"venue_ts_ms":"1","bid_price":"9","bid_quantity":"1","ask_price":"11",'
134
+ '"ask_quantity":"1","bid_depth":1,"ask_depth":1}'
135
+ )
136
+ top = read_event(line)
137
+ assert isinstance(top, Book) and top.venue == "venue-a"
138
+ out = io.StringIO()
139
+ propose(desk="d", instrument="btc-perp", side="buy", quantity_scaled="1", price_scaled="9",
140
+ client_id="c", decided_at_ns="1", venue="venue-b", out=out)
141
+ assert '"venue": "venue-b"' in out.getvalue() or '"venue":"venue-b"' in out.getvalue()
142
+
143
+
144
+ def test_the_venue_line_carries_fees_and_unsaid_fees_stay_absent() -> None:
145
+ from bijective_strategy import Venue, read_event
146
+
147
+ line = (
148
+ '{"event":"venue","venue":"venue-a","taker_fee_bps_scaled":"550000000",'
149
+ '"maker_fee_bps_scaled":"-100000000","fee_source":"venue fee page, read 2026-11-04"}'
150
+ )
151
+ opened = read_event(line)
152
+ assert isinstance(opened, Venue)
153
+ assert (opened.venue, opened.taker_fee_bps_scaled) == ("venue-a", "550000000")
154
+ unsaid = read_event('{"event":"venue","venue":"venue-a"}')
155
+ assert isinstance(unsaid, Venue) and unsaid.taker_fee_bps_scaled is None
156
+
157
+
158
+ def test_an_order_update_carries_a_fill_and_a_refusal_names_no_order() -> None:
159
+ from bijective_strategy import OrderUpdate, read_event
160
+
161
+ filled = read_event(
162
+ '{"event":"order","proposal_position":"12","client_id":"c-1","status":"filled",'
163
+ '"fill_id":"f-9","fill_quantity_scaled":"1500","fill_price_scaled":"2654375"}'
164
+ )
165
+ assert isinstance(filled, OrderUpdate)
166
+ assert (filled.status, filled.fill_quantity_scaled) == ("filled", "1500")
167
+ refused = read_event('{"event":"order","proposal_position":"13","status":"refused","reason":"x"}')
168
+ assert isinstance(refused, OrderUpdate) and refused.client_id is None and refused.reason == "x"
169
+
170
+
171
+ def test_the_venue_line_carries_each_instruments_increments() -> None:
172
+ from bijective_strategy import Venue, read_event
173
+
174
+ opened = read_event(
175
+ '{"event":"venue","venue":"venue-a","instruments":[{"instrument":"btc-perp",'
176
+ '"price_scale":1,"quantity_scale":3,"price_tick":"5","quantity_lot":"1",'
177
+ '"minimum_size":"1","minimum_notional":"50","trading":true}]}'
178
+ )
179
+ assert isinstance(opened, Venue)
180
+ assert opened.instruments[0].price_tick == "5" and opened.instruments[0].trading
181
+
182
+
183
+ def test_a_top_carries_when_it_arrived_and_an_old_top_says_nothing() -> None:
184
+ from bijective_strategy import Book, read_event
185
+
186
+ base = (
187
+ "{\"event\":\"book\",\"position\":\"1\",\"instrument\":\"btc-perp\",\"venue\":\"venue-a\","
188
+ "\"venue_ts_ms\":\"1\",\"bid_price\":\"9\",\"bid_quantity\":\"1\",\"ask_price\":\"11\","
189
+ "\"ask_quantity\":\"1\",\"bid_depth\":1,\"ask_depth\":1"
190
+ )
191
+ stamped = read_event(base + ",\"received_at_ns\":\"1788000000001000000\"}")
192
+ assert isinstance(stamped, Book) and stamped.received_at_ns == "1788000000001000000"
193
+ old = read_event(base + "}")
194
+ assert isinstance(old, Book) and old.received_at_ns is None
195
+
196
+
197
+ def test_an_instrument_says_what_it_is_and_a_session_of_several_venues_resumes_per_venue() -> None:
198
+ from bijective_strategy import Resumed, Venue, read_event
199
+
200
+ opened = read_event(
201
+ "{\"event\":\"venue\",\"venue\":\"venue-a\",\"instruments\":[{\"instrument\":\"btc-perp\","
202
+ "\"price_scale\":1,\"quantity_scale\":3,\"price_tick\":\"5\",\"quantity_lot\":\"1\","
203
+ "\"minimum_size\":\"1\",\"minimum_notional\":\"50\",\"trading\":true,"
204
+ "\"kind\":\"perpetual\",\"quote_currency\":\"usdt\",\"settlement_currency\":\"usdt\",\"base_currency\":\"btc\"}]}"
205
+ )
206
+ assert isinstance(opened, Venue)
207
+ rules = opened.instruments[0]
208
+ assert (rules.kind, rules.quote_currency, rules.settlement_currency) == (
209
+ "perpetual",
210
+ "usdt",
211
+ "usdt",
212
+ )
213
+ resumed = read_event(
214
+ "{\"event\":\"resumed\",\"from_position\":\"3\",\"missed\":{\"missed\":\"not_recorded\"},"
215
+ "\"venue\":\"venue-b\"}"
216
+ )
217
+ assert isinstance(resumed, Resumed) and resumed.venue == "venue-b"
218
+
219
+
220
+ def test_a_fact_of_any_kind_reads_as_one_event_with_its_values() -> None:
221
+ from bijective_strategy import Fact, read_event
222
+
223
+ trade = read_event(
224
+ '{"event":"fact","kind":"trade","fact_position":"4","instrument":"btc-perp",'
225
+ '"venue":"venue-a","received_at_ns":"9","trade_id":"t-1","aggressor":"seller",'
226
+ '"price_scaled":"2654375","quantity_scaled":"1500"}'
227
+ )
228
+ assert isinstance(trade, Fact)
229
+ assert (trade.kind, trade.fact_position, trade.venue) == ("trade", "4", "venue-a")
230
+ assert trade.values == {
231
+ "trade_id": "t-1",
232
+ "aggressor": "seller",
233
+ "price_scaled": "2654375",
234
+ "quantity_scaled": "1500",
235
+ }
236
+ later = read_event('{"event":"fact","kind":"basis","instrument":"btc-perp","basis":"3"}')
237
+ assert isinstance(later, Fact) and later.kind == "basis" and later.values == {"basis": "3"}
238
+
239
+
240
+ def test_a_proposal_states_its_terms_only_when_asked() -> None:
241
+ import io
242
+ import json
243
+
244
+ from bijective_strategy import propose
245
+
246
+ plain, stated = io.StringIO(), io.StringIO()
247
+ common = dict(desk="alpha", instrument="i", side="buy", quantity_scaled="1",
248
+ price_scaled="100", client_id="c", decided_at_ns="1")
249
+ propose(**common, out=plain)
250
+ propose(**common, time_in_force="ioc", post_only=True, out=stated)
251
+ assert "time_in_force" not in json.loads(plain.getvalue())
252
+ assert "post_only" not in json.loads(plain.getvalue())
253
+ line = json.loads(stated.getvalue())
254
+ assert (line["time_in_force"], line["post_only"]) == ("ioc", True)
255
+ stop = io.StringIO()
256
+ propose(**common, stop_price_scaled="90", reduce_only=True, out=stop)
257
+ line = json.loads(stop.getvalue())
258
+ assert (line["stop_price_scaled"], line["reduce_only"]) == ("90", True)
259
+ assert "reduce_only" not in json.loads(plain.getvalue())
260
+ child = io.StringIO()
261
+ propose(**common, reduce_only=True, parent="entry-1", oco="bracket", out=child)
262
+ line = json.loads(child.getvalue())
263
+ assert (line["parent"], line["oco"]) == ("entry-1", "bracket")
264
+ assert "parent" not in json.loads(plain.getvalue())
265
+ assert "oco" not in json.loads(plain.getvalue())
266
+ dated = io.StringIO()
267
+ propose(**common, expire_at_ns="1800000000000000000", out=dated)
268
+ assert json.loads(dated.getvalue())["expire_at_ns"] == "1800000000000000000"
269
+ assert "expire_at_ns" not in json.loads(plain.getvalue())
@@ -0,0 +1,116 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Bijective Labs
3
+
4
+ """The reference strategies decide what their rules say, and decide it the same way every time."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib.util
9
+ import io
10
+ import subprocess
11
+ import sys
12
+ from decimal import Decimal
13
+ from pathlib import Path
14
+ from types import ModuleType
15
+
16
+ from bijective_strategy import Book
17
+
18
+ REFERENCE = Path(__file__).resolve().parent.parent / "examples" / "reference"
19
+ MINUTE_MS = 60_000
20
+
21
+
22
+ def load(name: str) -> ModuleType:
23
+ spec = importlib.util.spec_from_file_location(name, REFERENCE / f"{name}.py")
24
+ assert spec is not None and spec.loader is not None
25
+ module = importlib.util.module_from_spec(spec)
26
+ # Registered first: a dataclass resolves its annotations through its module.
27
+ sys.modules[name] = module
28
+ spec.loader.exec_module(module)
29
+ return module
30
+
31
+
32
+ def book(minute: int, mid: int, position: int = 0) -> Book:
33
+ return Book(
34
+ position=str(position),
35
+ instrument="btc-perp",
36
+ venue_sequence=None,
37
+ venue_ts_ms=str(1_788_000_000_000 + minute * MINUTE_MS),
38
+ bid_price=str(mid - 1),
39
+ bid_quantity="5",
40
+ ask_price=str(mid + 1),
41
+ ask_quantity="5",
42
+ bid_depth=1,
43
+ ask_depth=1,
44
+ )
45
+
46
+
47
+ def minutes(mids: list[int]) -> list[Book]:
48
+ """One top per minute, plus one more so the last minute closes."""
49
+ tops = [book(m, mid, m) for m, mid in enumerate(mids)]
50
+ return tops + [book(len(mids), mids[-1], len(mids))]
51
+
52
+
53
+ def decided(core: object, tops: list[Book]) -> list[tuple[str, int, int]]:
54
+ out = []
55
+ for top in tops:
56
+ order = core.on_book(top) # type: ignore[attr-defined]
57
+ if order is not None:
58
+ out.append((order.side, order.quantity_scaled, order.limit_price_scaled))
59
+ return out
60
+
61
+
62
+ def test_zscore_sells_a_spike_at_the_ask_and_buys_back_when_it_reverts() -> None:
63
+ module = load("zscore_reversion")
64
+ core = module.ZScoreReversion(unit_quantity_scaled=10, lookback=5)
65
+ noise = [1000, 1002, 1000, 1002, 1000]
66
+ orders = decided(core, minutes(noise + [1050, 1001]))
67
+ # Decided on the first top of the next minute, at that top: the spike closed, the price moved on.
68
+ assert orders == [("sell", 10, 1002), ("buy", 10, 1000)]
69
+
70
+
71
+ def test_zscore_refuses_thresholds_that_cannot_be_ordered() -> None:
72
+ module = load("zscore_reversion")
73
+ try:
74
+ module.ZScoreReversion(unit_quantity_scaled=1, entry_z=Decimal(1), exit_z=Decimal(2))
75
+ except ValueError:
76
+ return
77
+ raise AssertionError("an exit wider than the entry was accepted")
78
+
79
+
80
+ def test_momentum_buys_a_rise_and_sells_after_its_hold() -> None:
81
+ module = load("momentum")
82
+ core = module.Momentum(unit_quantity_scaled=10, horizon=2, window=6, hold=2)
83
+ noise = [1000, 1001, 1000, 1001, 1000, 1001, 1000]
84
+ orders = decided(core, minutes(noise + [1020, 1040, 1041, 1042]))
85
+ assert orders[0] == ("buy", 10, 1039)
86
+ assert orders[1][0] == "sell"
87
+ assert len(orders) == 2
88
+
89
+
90
+ def run_main(name: str, lines: str) -> str:
91
+ library = Path(__file__).resolve().parent.parent / "src"
92
+ done = subprocess.run(
93
+ [sys.executable, str(REFERENCE / f"{name}.py")],
94
+ input=lines,
95
+ capture_output=True,
96
+ text=True,
97
+ env={"PYTHONPATH": str(library)},
98
+ check=True,
99
+ )
100
+ return done.stdout
101
+
102
+
103
+ def test_each_reference_strategy_answers_every_event_and_is_deterministic() -> None:
104
+ stream = io.StringIO()
105
+ for top in minutes([1000, 1002, 1000, 1002, 1000, 1050, 1001] * 3):
106
+ stream.write(
107
+ '{"event":"book","position":"%s","instrument":"btc-perp","venue_ts_ms":"%s",'
108
+ '"bid_price":"%s","bid_quantity":"5","ask_price":"%s","ask_quantity":"5",'
109
+ '"bid_depth":1,"ask_depth":1}\n'
110
+ % (top.position, top.venue_ts_ms, top.bid_price, top.ask_price)
111
+ )
112
+ stream.write('{"event":"end_of_window"}\n')
113
+ for name in ("zscore_reversion", "momentum"):
114
+ first = run_main(name, stream.getvalue())
115
+ assert first == run_main(name, stream.getvalue()), name
116
+ assert first.count('"emit":"answered"') == 22, name