simudyne-pulse 0.9.0.dev6__tar.gz → 0.9.0.dev8__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 (25) hide show
  1. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/PKG-INFO +1 -1
  2. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/pyproject.toml +1 -1
  3. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/resources/data.py +99 -14
  4. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/resources/simulation.py +351 -13
  5. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne_pulse.egg-info/PKG-INFO +1 -1
  6. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/tests/test_new_resources.py +103 -0
  7. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/LICENSE +0 -0
  8. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/README.md +0 -0
  9. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/setup.cfg +0 -0
  10. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/__init__.py +0 -0
  11. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/client.py +0 -0
  12. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/exceptions.py +0 -0
  13. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/resources/__init__.py +0 -0
  14. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/resources/api_keys.py +0 -0
  15. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/resources/fix.py +0 -0
  16. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/resources/fm.py +0 -0
  17. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/resources/profile.py +0 -0
  18. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne/resources/validation.py +0 -0
  19. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne_pulse.egg-info/SOURCES.txt +0 -0
  20. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne_pulse.egg-info/dependency_links.txt +0 -0
  21. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne_pulse.egg-info/requires.txt +0 -0
  22. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/src/simudyne_pulse.egg-info/top_level.txt +0 -0
  23. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/tests/test_api_contract.py +0 -0
  24. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/tests/test_retries.py +0 -0
  25. {simudyne_pulse-0.9.0.dev6 → simudyne_pulse-0.9.0.dev8}/tests/test_validation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simudyne-pulse
3
- Version: 0.9.0.dev6
3
+ Version: 0.9.0.dev8
4
4
  Summary: Python SDK for the Simudyne Pulse synthetic market data API
5
5
  Author-email: Simudyne <support@simudyne.com>
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "simudyne-pulse"
7
- version = "0.9.0-dev.6"
7
+ version = "0.9.0-dev.8"
8
8
  description = "Python SDK for the Simudyne Pulse synthetic market data API"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -38,6 +38,23 @@ _FILTERS_DOC = """
38
38
  failure at any stage; the reason is in ``calibration_error``.
39
39
  :meth:`calibrated_data` lists calibrated days only, so there
40
40
  anything but "calibrated" matches nothing.
41
+ min_trades, max_trades, min_messages, max_messages, min_volume,
42
+ max_volume, min_spread_ticks, max_spread_ticks : number, optional
43
+ Bounds on a scanned day's measured stats. Demo tier.
44
+ tick_size, lot_size : float, optional
45
+ Scanned days with exactly this tick or lot size. Demo tier.
46
+ currency, instrument_type : str, optional
47
+ Scanned days in this currency (e.g. "GBp") or of this type
48
+ (e.g. "equity"). Demo tier.
49
+ calibratable : bool, optional
50
+ Scanned days that can (True) or cannot (False) be calibrated: a
51
+ day needs at least one trade and fewer than 10,000,000 messages.
52
+ Demo tier.
53
+ scanned_only : bool, default False
54
+ Only days the catalog has scanned. Demo tier.
55
+ include_stats : bool, default False
56
+ Add each scanned day's measured ``stats``. Demo tier; ``None`` on
57
+ every other tier.
41
58
  """
42
59
 
43
60
  _ROWS_DOC = """
@@ -58,12 +75,26 @@ _ROWS_DOC = """
58
75
  day's LATEST calibration record
59
76
  - calibration_stage, calibration_error, calibration_updated_at,
60
77
  pulse_version, number_of_msgs, volume_traded, reference_price
78
+ - scanned, calibratable, not_calibratable_reason, event_counts,
79
+ stats: figures from the vendor data, demo tier only (None on
80
+ every other tier)
81
+
82
+ Filtering on a demo-tier field from another tier raises 403 rather
83
+ than returning an unfiltered answer.
61
84
  """
62
85
 
63
86
 
87
+ #: On/off flags whose False is the server's default, so False is not sent.
88
+ #: (calibratable is not one: False asks for the days that CANNOT be calibrated.)
89
+ _DEFAULT_OFF_FLAGS = ("scanned_only", "include_stats")
90
+
91
+
64
92
  def _day_params(**filters) -> dict | None:
65
93
  """Query parameters for either catalog call, without unset filters."""
66
- params = {k: v for k, v in filters.items() if v is not None}
94
+ params = {
95
+ k: v for k, v in filters.items()
96
+ if v is not None and not (k in _DEFAULT_OFF_FLAGS and v is False)
97
+ }
67
98
  return params or None
68
99
 
69
100
 
@@ -95,6 +126,21 @@ class DataResource:
95
126
  date_from: str | None = None,
96
127
  date_to: str | None = None,
97
128
  calibration_status: str | None = None,
129
+ min_trades: int | None = None,
130
+ max_trades: int | None = None,
131
+ min_messages: int | None = None,
132
+ max_messages: int | None = None,
133
+ min_volume: float | None = None,
134
+ max_volume: float | None = None,
135
+ min_spread_ticks: float | None = None,
136
+ max_spread_ticks: float | None = None,
137
+ tick_size: float | None = None,
138
+ lot_size: float | None = None,
139
+ currency: str | None = None,
140
+ instrument_type: str | None = None,
141
+ calibratable: bool | None = None,
142
+ scanned_only: bool = False,
143
+ include_stats: bool = False,
98
144
  limit: int | None = None,
99
145
  offset: int | None = None,
100
146
  ):
@@ -134,9 +180,10 @@ class DataResource:
134
180
  Raises
135
181
  ------
136
182
  PulseAPIError
137
- If the key is not pro or demo tier (403); ``model_id`` names a
138
- model that is not registered (404) or matches more than one (400);
139
- a date is not ``YYYY-MM-DD``, ``date`` is combined with a range,
183
+ If the key is not pro or demo tier (403), or filters on a demo-tier
184
+ field from another tier (403); ``model_id`` names a model that is
185
+ not registered (404) or matches more than one (400); a date is not
186
+ ``YYYY-MM-DD``, ``date`` is combined with a range,
140
187
  ``calibration_status`` is not one of the three values, ``limit`` is
141
188
  outside 1-200 or ``offset`` is negative (422); or, with
142
189
  ``model_id``, the model registry (pulse-orchestrator) could not be
@@ -176,12 +223,26 @@ class DataResource:
176
223
  ... exchange="lse", date_from="2025-07-01", date_to="2025-07-31",
177
224
  ... calibration_status="failed",
178
225
  ... )
226
+
227
+ Days that can be calibrated but are not yet (demo tier):
228
+
229
+ >>> page = client.data.available_data(
230
+ ... exchange="lse", date_from="2025-07-01", date_to="2025-07-31",
231
+ ... calibratable=True,
232
+ ... )
179
233
  """
180
234
  return self._client._request("GET", AVAILABLE_DATA_PATH, params=_day_params(
181
235
  model_id=model_id, symbol=symbol, q=q, provider=provider, exchange=exchange,
182
236
  date=date, date_from=date_from, date_to=date_to,
183
237
  calibration_status=calibration_status,
184
- limit=limit, offset=offset,
238
+ min_trades=min_trades, max_trades=max_trades,
239
+ min_messages=min_messages, max_messages=max_messages,
240
+ min_volume=min_volume, max_volume=max_volume,
241
+ min_spread_ticks=min_spread_ticks, max_spread_ticks=max_spread_ticks,
242
+ tick_size=tick_size, lot_size=lot_size,
243
+ currency=currency, instrument_type=instrument_type,
244
+ calibratable=calibratable, scanned_only=scanned_only,
245
+ include_stats=include_stats, limit=limit, offset=offset,
185
246
  ))
186
247
 
187
248
  def calibrated_data(
@@ -194,6 +255,21 @@ class DataResource:
194
255
  date_from: str | None = None,
195
256
  date_to: str | None = None,
196
257
  calibration_status: str | None = None,
258
+ min_trades: int | None = None,
259
+ max_trades: int | None = None,
260
+ min_messages: int | None = None,
261
+ max_messages: int | None = None,
262
+ min_volume: float | None = None,
263
+ max_volume: float | None = None,
264
+ min_spread_ticks: float | None = None,
265
+ max_spread_ticks: float | None = None,
266
+ tick_size: float | None = None,
267
+ lot_size: float | None = None,
268
+ currency: str | None = None,
269
+ instrument_type: str | None = None,
270
+ calibratable: bool | None = None,
271
+ scanned_only: bool = False,
272
+ include_stats: bool = False,
197
273
  limit: int | None = None,
198
274
  offset: int | None = None,
199
275
  ):
@@ -224,10 +300,11 @@ class DataResource:
224
300
  Raises
225
301
  ------
226
302
  PulseAPIError
227
- If a date is not ``YYYY-MM-DD``, ``date`` is combined with a
228
- range, ``calibration_status`` is not one of the three values,
229
- ``limit`` is outside 1-1000 or ``offset`` is negative (422).
230
- Available on every tier.
303
+ If a filter on a demo-tier field comes from another tier (403), or
304
+ a date is not ``YYYY-MM-DD``, ``date`` is combined with a range,
305
+ ``calibration_status`` is not one of the three values, ``limit`` is
306
+ outside 1-1000 or ``offset`` is negative (422). Available on every
307
+ tier.
231
308
 
232
309
  See Also
233
310
  --------
@@ -260,7 +337,14 @@ class DataResource:
260
337
  symbol=symbol, q=q, provider=provider, exchange=exchange,
261
338
  date=date, date_from=date_from, date_to=date_to,
262
339
  calibration_status=calibration_status,
263
- limit=limit, offset=offset,
340
+ min_trades=min_trades, max_trades=max_trades,
341
+ min_messages=min_messages, max_messages=max_messages,
342
+ min_volume=min_volume, max_volume=max_volume,
343
+ min_spread_ticks=min_spread_ticks, max_spread_ticks=max_spread_ticks,
344
+ tick_size=tick_size, lot_size=lot_size,
345
+ currency=currency, instrument_type=instrument_type,
346
+ calibratable=calibratable, scanned_only=scanned_only,
347
+ include_stats=include_stats, limit=limit, offset=offset,
264
348
  ))
265
349
 
266
350
  # The two calls share their filters and row shape, so their docs share the
@@ -330,10 +414,11 @@ class DataResource:
330
414
  If the key is not demo tier (403); ``provider`` or ``exchange`` is
331
415
  not a recognised value (422); the day has no market data — a
332
416
  weekend, an exchange holiday, a day the vendor did not deliver
333
- (422); or the calibration service is unreachable (503). A day that
334
- is queued and then fails shows up in :meth:`available_data` with
335
- ``calibration_status`` "failed" and the reason in
336
- ``calibration_error``.
417
+ (422); the catalog has scanned the day and it cannot be calibrated,
418
+ e.g. it has no trades (422, with the reason); or the calibration
419
+ service is unreachable (503). A day that is queued and then fails
420
+ shows up in :meth:`available_data` with ``calibration_status``
421
+ "failed" and the reason in ``calibration_error``.
337
422
 
338
423
  See Also
339
424
  --------
@@ -18,6 +18,7 @@ Calibration is not here — it is a data operation, at
18
18
  """
19
19
 
20
20
  import io
21
+ from pathlib import Path
21
22
 
22
23
 
23
24
  RUN_PATH = "/simulation/run"
@@ -79,6 +80,29 @@ SCENARIO_DEFAULTS = {
79
80
  }
80
81
 
81
82
 
83
+
84
+ def _csv_text(value) -> str:
85
+ """``rows_csv`` as CSV text: text as given, a ``.csv`` path (str or
86
+ Path) read from disk, a polars or pandas DataFrame written without its
87
+ index (missing values as empty cells)."""
88
+ if isinstance(value, Path) or (
89
+ isinstance(value, str) and "\n" not in value and value.strip().lower().endswith(".csv")
90
+ ):
91
+ path = Path(value).expanduser()
92
+ if not path.is_file():
93
+ raise ValueError(f"rows_csv: no such file {str(path)!r}")
94
+ return path.read_text(encoding="utf-8-sig")
95
+ if isinstance(value, str):
96
+ return value
97
+ if hasattr(value, "write_csv"): # polars
98
+ return value.write_csv()
99
+ if hasattr(value, "to_csv"): # pandas
100
+ return value.to_csv(index=False)
101
+ raise TypeError(
102
+ "rows_csv must be CSV text, a path to a .csv file, or a pandas / polars DataFrame, "
103
+ f"not {type(value).__name__}"
104
+ )
105
+
82
106
  class SimulationResource:
83
107
  """Run agent-based market simulations and read their results.
84
108
 
@@ -230,10 +254,55 @@ class SimulationResource:
230
254
  - horizon: execution window in SECONDS, e.g. 3600 (required)
231
255
  - start_time: e.g. "09:30:00" (optional, defaults to market open)
232
256
 
233
- For CSS (custom static schedule):
234
-
235
- - type: "css" (required)
236
- - orders: dict mapping timestamps to quantities (required)
257
+ For a custom schedule of individual orders:
258
+
259
+ - type: "order_schedule" (required). It replaces ``"css"``, which
260
+ is refused (422); a list of market orders is now rows with
261
+ ``order_type`` "market", one order per row. There is no
262
+ schedule-level ``side``: each row carries its own, and a
263
+ ``side`` on the algo is a 422.
264
+ - rows: a list of individual orders, each a dict with
265
+ ``time`` (exchange-local, to the millisecond), ``ref`` (unique
266
+ per order; no "," or "#"), ``order_type`` ("market", "limit",
267
+ "ioc", "cancel", "stop", "stop_limit" or "amend"), ``side``
268
+ ("buy"/"sell") and ``size`` (lots). Optional: ``price_ref``
269
+ ("near", "far" or "mid") and ``offset_ticks`` (positive = less
270
+ aggressive), ``peg``, ``peg_limit_ticks``, ``peak``,
271
+ ``peak_random_pct``, ``lifetime_s``, ``stop_offset_ticks``.
272
+ ``peg_limit_ticks`` (>= 0, pegged limit orders only) gives a peg
273
+ a limit: its reference when entered, moved that many ticks in
274
+ the aggressive direction. While the reference is past the limit
275
+ the order is pulled; it comes back at the back of the queue, as
276
+ ``<ref>#<n>``, when the reference returns (LSE MIT201 6.1).
277
+ A ``cancel`` row names an earlier ``ref``. An ``amend`` row
278
+ names an earlier limit or stop_limit ``ref`` that no earlier
279
+ row cancels, and gives a new price (``price_ref`` and
280
+ ``offset_ticks``, priced at the amend time), a new remaining
281
+ visible ``size``, or both. A price change loses queue
282
+ priority, a size change alone keeps it, and an amend of an
283
+ order that has already filled or been cancelled does nothing.
284
+ A price amend of a pegged order is a 422. A ``ref`` of the form
285
+ ``<role>-<n>`` (e.g. "spoof-3") names the order's role for
286
+ :meth:`get_sim_events`. Or
287
+ - rows_csv: the same rows as CSV, given as CSV text,
288
+ a path to a ``.csv`` file (str or ``pathlib.Path``), or a
289
+ pandas / polars DataFrame; the SDK sends CSV text. The header
290
+ names the columns used (the row keys above, any order); an
291
+ empty cell is a field not set; ``peg`` is 0/1/true/false.
292
+ Errors name the CSV line (header = line 1) and column, and the
293
+ run's schedule report (:meth:`get_sim_schedule_report`) refers
294
+ to the same lines. Give ``rows`` or ``rows_csv``, not both.
295
+
296
+ An ``order_schedule`` takes only ``rows`` or ``rows_csv``: any
297
+ other key (``side``, ``random_offset``, ...) is a 422. Its rows
298
+ run at exactly their times; ``random_offset`` is a TWAP / VWAP
299
+ option.
300
+
301
+ Execution metrics are for the side with the most volume; for a
302
+ two-sided schedule read the schedule report per order
303
+ (:meth:`get_sim_schedule_report`). With ``engine="fm"`` a
304
+ schedule must be market orders on one side only; anything else
305
+ is a 422 naming why.
237
306
 
238
307
  An FM job accepts at most one algo and needs a real market day —
239
308
  a testdata run cannot carry one.
@@ -286,8 +355,10 @@ class SimulationResource:
286
355
  ``exchange`` is not a recognised value; ``n_runs`` is below 1, or
287
356
  above 8 with ``engine="fm"``; ``engine="fm"`` without
288
357
  ``model_id``; or an ``exec_algos`` entry has a ``start_time``
289
- that is not "HH:MM" / "HH:MM:SS" or a ``side`` that is not "buy"
290
- or "sell".
358
+ that is not "HH:MM" / "HH:MM:SS", a ``type`` of ``"css"`` (replaced
359
+ by ``"order_schedule"``), or an ``order_schedule`` with a
360
+ key other than ``rows`` / ``rows_csv`` (such as ``side`` or
361
+ ``random_offset``) or with both ``rows`` and ``rows_csv``.
291
362
 
292
363
  If the named data is unusable (422). The market identity is checked
293
364
  against the catalogue before submission:
@@ -367,6 +438,38 @@ class SimulationResource:
367
438
  ... }],
368
439
  ... )
369
440
 
441
+ A list of market orders, one row per order:
442
+
443
+ >>> job = client.simulation.run(
444
+ ... symbol="700.HK", cal_date="2025-09-02",
445
+ ... provider="omd", exchange="hkex_securities",
446
+ ... exec_algos=[{"type": "order_schedule", "rows": [
447
+ ... {"time": "2025-09-02 10:00:00.000", "ref": "buy-1",
448
+ ... "order_type": "market", "side": "buy", "size": 200},
449
+ ... {"time": "2025-09-02 10:05:00.000", "ref": "buy-2",
450
+ ... "order_type": "market", "side": "buy", "size": 200},
451
+ ... ]}],
452
+ ... )
453
+
454
+ A schedule of individual orders as CSV (text, a .csv path or a
455
+ DataFrame):
456
+
457
+ >>> schedule = (
458
+ ... "time,ref,order_type,side,size,price_ref,offset_ticks,lifetime_s\n"
459
+ ... "2025-09-02 10:00:00.000,spoof-1,limit,buy,5000,near,2,4\n"
460
+ ... "2025-09-02 10:00:01.500,genuine-1,market,sell,200,,,\n"
461
+ ... )
462
+ >>> job = client.simulation.run(
463
+ ... symbol="700.HK", cal_date="2025-09-02",
464
+ ... provider="omd", exchange="hkex_securities",
465
+ ... exec_algos=[{"type": "order_schedule", "rows_csv": schedule}],
466
+ ... )
467
+ >>> job = client.simulation.run(
468
+ ... symbol="700.HK", cal_date="2025-09-02",
469
+ ... provider="omd", exchange="hkex_securities",
470
+ ... exec_algos=[{"type": "order_schedule", "rows_csv": "my_schedule.csv"}],
471
+ ... )
472
+
370
473
  Both engines are polled and read identically:
371
474
 
372
475
  >>> import time
@@ -417,14 +520,13 @@ class SimulationResource:
417
520
 
418
521
  @staticmethod
419
522
  def _serialize_exec_algos(exec_algos: list) -> list:
420
- """Convert pd.Series orders in CSS configs to JSON-serializable dicts."""
523
+ """Make schedule configs JSON: ``rows_csv`` (a path or a DataFrame)
524
+ becomes CSV text. Everything else is sent as given."""
421
525
  result = []
422
526
  for algo in exec_algos:
423
527
  algo = dict(algo)
424
- if algo.get("type") == "css" and "orders" in algo:
425
- orders = algo["orders"]
426
- if hasattr(orders, "items"):
427
- algo["orders"] = {str(k): int(v) for k, v in orders.items()}
528
+ if "rows_csv" in algo:
529
+ algo["rows_csv"] = _csv_text(algo["rows_csv"])
428
530
  result.append(algo)
429
531
  return result
430
532
 
@@ -909,6 +1011,9 @@ class SimulationResource:
909
1011
  - has_exec_schedule (bool): Whether exec_schedule.parquet exists
910
1012
  - has_schedule_by_min (bool): Whether schedule_by_min.parquet exists
911
1013
  - has_exec_results (bool): Whether exec_results.parquet exists
1014
+ - has_schedule_report (bool): Whether schedule_report.parquet
1015
+ exists (runs with an order schedule; see
1016
+ :meth:`get_sim_schedule_report`)
912
1017
 
913
1018
  Raises
914
1019
  ------
@@ -1026,6 +1131,231 @@ class SimulationResource:
1026
1131
  """
1027
1132
  return self._client._request("GET", f"{RESULTS_PATH}/{sim_id}/metrics")
1028
1133
 
1134
+ def get_sim_events(self, sim_id: str):
1135
+ """Market-quality events and source-backed manipulation patterns in one run.
1136
+
1137
+ Runs the same event detector the platform uses on real market data
1138
+ over this run's order book. Computed on first request, then cached.
1139
+
1140
+ Types that run on any data: market quality (``liquidity_withdrawal``,
1141
+ ``spread_blowout``, ``price_jump``, ``volume_burst``, ``cliff``,
1142
+ ``auction``) and manipulation (``spoofing_like``, ``layering``,
1143
+ ``quote_stuffing``, ``ping_orders``, ``advancing_bid``,
1144
+ ``momentum_ignition``, ``smoking``, ``marking_close``,
1145
+ ``auction_cancel``). Simulation only, because they need the account:
1146
+ ``wash_trade`` and ``painting_tape``, plus the account form of
1147
+ ``marking_close`` (``features["form"] == "account"``). The account is
1148
+ the run's own scheduled orders, and these rules need the aggressor of
1149
+ each trade (``aggressor_order_id`` on newer runs' TRADE rows); an
1150
+ older run gets none of them.
1151
+
1152
+ Parameters
1153
+ ----------
1154
+ sim_id : str
1155
+ The simulation ID (an agent-based run; foundation-model runs have
1156
+ no order lifecycle to scan).
1157
+
1158
+ Returns
1159
+ -------
1160
+ dict
1161
+ ``{"sim_id", "symbol", "date", "detector_version", "stats",
1162
+ "events": [...]}``. Each event has:
1163
+
1164
+ - event_id (str): pass to :meth:`get_sim_event`
1165
+ - type (str), side (str or None: "bid"/"ask", "buy"/"sell" for
1166
+ marking_close, "up"/"down" for price moves)
1167
+ - ts, ts_end, duration_ms, severity (0-100), score,
1168
+ severity_basis
1169
+ - features (dict): the type's measurements
1170
+ - checks (list of dict): every rule applied, each ``{label,
1171
+ value, rule, passed, basis, source}``; ``basis`` is "doc" (a
1172
+ qualifying source states the figure: legislation, official
1173
+ guidance, a final enforcement finding, or a peer-reviewed
1174
+ article in its published version), "default" (Pulse's
1175
+ calibration, including figures derived from a source) or
1176
+ None for context rows, ``source`` a short citation
1177
+ - order_ids (list of str): for an order-level type
1178
+ (spoofing_like, layering, ping_orders, advancing_bid, smoking,
1179
+ auction_cancel, wash_trade, painting_tape) the orders behind
1180
+ the event; for a window-level type (quote_stuffing,
1181
+ momentum_ignition, marking_close) the base refs of the
1182
+ scheduled orders placed inside [ts, ts_end]
1183
+ - thumb: a small normalised picture
1184
+
1185
+ An order from a schedule (``order_schedule``) keeps its row's
1186
+ ``ref`` as its id, with ``#<k>`` added for an iceberg's later
1187
+ peaks and a limited peg's re-entries. A ref is ``<role>-<n>``;
1188
+ the role (spoof, layer, stuff, probe, advance, ignite, smoke,
1189
+ close, wash, paint; anything else is genuine) names the type the
1190
+ order was planted for, and a planted order is caught when an
1191
+ event of that type lists its base ref (a layer is also caught by
1192
+ spoofing_like).
1193
+
1194
+ Raises
1195
+ ------
1196
+ PulseAPIError
1197
+ 404 if ``sim_id`` is unknown or the run wrote no order book; 422
1198
+ for a foundation-model run.
1199
+
1200
+ See Also
1201
+ --------
1202
+ get_sim_event : One event with its full signature picture.
1203
+ get_sim_schedule_orders : The schedule's orders and the rules of
1204
+ their roles measured on each.
1205
+
1206
+ Examples
1207
+ --------
1208
+ >>> events = client.simulation.get_sim_events(sim_id)["events"]
1209
+ >>> spoofs = [e for e in events if e["type"] == "spoofing_like"]
1210
+ >>> caught = {i.split("#")[0] for e in spoofs for i in e["order_ids"]}
1211
+ """
1212
+ return self._client._request("GET", f"{RESULTS_PATH}/{sim_id}/events")
1213
+
1214
+ def get_sim_event(self, sim_id: str, event_id: str):
1215
+ """One event from :meth:`get_sim_events`, with its full signature picture.
1216
+
1217
+ The same fields as an event in :meth:`get_sim_events`, plus
1218
+ ``signature``: a normalised depth picture around the event with
1219
+ spread, imbalance and activity traces.
1220
+ """
1221
+ return self._client._request("GET", f"{RESULTS_PATH}/{sim_id}/events/{event_id}")
1222
+
1223
+ def get_sim_schedule_orders(self, sim_id: str):
1224
+ """Every order a schedule placed in one run, and how it measured
1225
+ against the rules of its role.
1226
+
1227
+ Orders are the ones an ``order_schedule`` placed, found by
1228
+ their ``ref`` (iceberg peaks and a limited peg's re-entries,
1229
+ ``<ref>#<k>``, are folded into one order). Genuine orders are listed
1230
+ too. A planted order that :meth:`get_sim_events` did not catch says
1231
+ here which rule it failed. Computed with the events, then cached.
1232
+
1233
+ Parameters
1234
+ ----------
1235
+ sim_id : str
1236
+ The simulation ID (an agent-based run).
1237
+
1238
+ Returns
1239
+ -------
1240
+ dict
1241
+ ``{"thresholds", "orders"}``.
1242
+
1243
+ - thresholds (dict): the run's ``median_size``,
1244
+ ``size_quantile``, ``size_floor``, ``small_size``, ``tick``,
1245
+ ``aggressor_ids`` (whether the run records the aggressor of
1246
+ each trade) and each role's parameters (``spoof``, ``layer``,
1247
+ ``probe``, ``advance``, ``smoke``, ``wash``, ``paint``)
1248
+ - orders (list of dict), each:
1249
+
1250
+ - ref (str), role (str): genuine, spoof, layer, stuff, probe,
1251
+ advance, ignite, smoke, close, wash or paint
1252
+ - side (str): "bid" or "ask"
1253
+ - t_place, t_end, end: placed, and filled or cancelled;
1254
+ ``end`` is "filled", "cancelled" or "open". An order that
1255
+ filled on arrival is placed at its first fill.
1256
+ - price, size, filled, peaks
1257
+ - ticks_behind_touch, ticks_from_mid: where it rested when
1258
+ placed
1259
+ - tested_against (str or None): the event type its role is
1260
+ planted for; None for genuine
1261
+ - rules (dict): ``{rule_key: {label, value, need, passed,
1262
+ basis, source}}``, that type's rules measured on the order;
1263
+ empty for genuine orders and the window-level roles stuff,
1264
+ ignite and close. On a run without aggressor ids, wash and
1265
+ paint orders carry one rule, ``aggressor_ids``.
1266
+ - meets_rules (bool or None): whether every rule passed; None
1267
+ where ``rules`` is empty or the run has no aggressor ids
1268
+ - amends (list of dict): ``{t, price, size}`` per amend the
1269
+ schedule made to it
1270
+
1271
+ Raises
1272
+ ------
1273
+ PulseAPIError
1274
+ 404 if ``sim_id`` is unknown or the run wrote no order book; 422
1275
+ for a foundation-model run.
1276
+
1277
+ See Also
1278
+ --------
1279
+ get_sim_events : The events that caught (or missed) these orders.
1280
+
1281
+ Examples
1282
+ --------
1283
+ >>> report = client.simulation.get_sim_schedule_orders(sim_id)
1284
+ >>> for o in report["orders"]:
1285
+ ... if o["role"] == "spoof" and o["meets_rules"] is False:
1286
+ ... print(o["ref"], [r["label"] for r in o["rules"].values() if not r["passed"]])
1287
+ """
1288
+ return self._client._request("GET", f"{RESULTS_PATH}/{sim_id}/schedule-orders")
1289
+
1290
+ def get_sim_schedule_report(self, sim_id: str) -> list:
1291
+ """The run's schedule report: what happened to each order schedule row.
1292
+
1293
+ One row per schedule row, written by the engine: whether the row was
1294
+ released or skipped as invalid (and why), when and where it was
1295
+ placed, and how it ended. The same data as
1296
+ ``get_sim_data(sim_id, "schedule_report.parquet")``, as plain dicts.
1297
+
1298
+ Parameters
1299
+ ----------
1300
+ sim_id : str
1301
+ The simulation ID (an agent-based run with an order schedule).
1302
+
1303
+ Returns
1304
+ -------
1305
+ list of dict
1306
+ One dict per schedule row, in time order (rows with the same
1307
+ time keep their file order), with these keys:
1308
+
1309
+ - line (int): 1-based CSV line, header = 1 (for rows given
1310
+ inline, the row index)
1311
+ - ref (str): the row's ORDER_ID
1312
+ - ord_type (str): Limit, Market, IOC, Cancel, Stop, StopLimit or
1313
+ Amend
1314
+ - side (str): Buy or Sell
1315
+ - symbol (str)
1316
+ - t_scheduled (str): exchange-local ISO time with ms
1317
+ - t_placed (str): ISO time, empty if never placed
1318
+ - price_placed (float or None): price units; None for market
1319
+ orders and orders never placed
1320
+ - size (int): visible size
1321
+ - total_size (int)
1322
+ - engine_ids (str): ";"-joined engine order ids (ref, ref#2, ...)
1323
+ - amends (int): amends applied
1324
+ - repegs (int)
1325
+ - filled_qty (int), avg_fill_price (float or None),
1326
+ n_fills (int): from the trader's own execution reports
1327
+ - end (str): "filled", "cancelled", "expired", "open_at_close",
1328
+ "not_placed", "applied" (amend/cancel rows) or "skipped"
1329
+ - end_reason (str): "lifetime", "cancel_row",
1330
+ "cancel_on_fill:<target ref>", "peg_limit", "end_of_day",
1331
+ "no_valid_book", "outside_hours", "run_ended", "elected" (a stop
1332
+ elected; its child order's outcome is on the same row) or "";
1333
+ for a skipped row (end "skipped") the reason text, e.g.
1334
+ "column PEG_LIMIT: applies only to pegged Limit orders"
1335
+ - t_end (str): ISO time, empty if none
1336
+
1337
+ Raises
1338
+ ------
1339
+ PulseAPIError
1340
+ 404 if ``sim_id`` is unknown, or the run has no report (it had no
1341
+ schedule, or it predates the report).
1342
+
1343
+ See Also
1344
+ --------
1345
+ get_sim_data : ``exec_results.parquet`` counts the skipped rows
1346
+ (``schedule_rows_skipped``, ``schedule_skip_reasons``).
1347
+ get_job_logs : The engine log, with a line per skipped row.
1348
+
1349
+ Examples
1350
+ --------
1351
+ >>> rows = client.simulation.get_sim_schedule_report(sim_id)
1352
+ >>> for r in rows:
1353
+ ... if r["end"] == "skipped":
1354
+ ... print(r["line"], r["ref"], r["end_reason"])
1355
+ """
1356
+ report = self._client._request("GET", f"{RESULTS_PATH}/{sim_id}/schedule-report")
1357
+ return report.get("rows", []) if isinstance(report, dict) else report
1358
+
1029
1359
  def get_sim_data(self, sim_id: str, filename: str = "sim_data.parquet"):
1030
1360
  """Download simulation data as a Polars DataFrame.
1031
1361
 
@@ -1048,7 +1378,15 @@ class SimulationResource:
1048
1378
  - "l2_by_second.parquet": L2 order book, 10 levels, per second
1049
1379
  - "exec_schedule.parquet": execution schedule, if an algo ran
1050
1380
  - "schedule_by_min.parquet": algo schedule by minute, if an algo ran
1051
- - "exec_results.parquet": execution cost metrics, if an algo ran
1381
+ - "exec_results.parquet": execution cost metrics, if an algo ran.
1382
+ One row; besides the cost columns it carries
1383
+ ``schedule_rows_skipped`` (int, order schedule rows the engine
1384
+ skipped as invalid, 0 if none) and ``schedule_skip_reasons``
1385
+ (str, up to 5 reasons joined with " | ", "+N more" if more).
1386
+ Runs that predate these columns do not have them: read them as
1387
+ 0 and "". :meth:`get_job_logs` has every skipped line.
1388
+ - "schedule_report.parquet": one row per order schedule row, if
1389
+ the run had a schedule (see :meth:`get_sim_schedule_report`)
1052
1390
 
1053
1391
  Returns
1054
1392
  -------
@@ -1058,7 +1396,7 @@ class SimulationResource:
1058
1396
  Raises
1059
1397
  ------
1060
1398
  PulseAPIError
1061
- If ``filename`` is not one of the six names above (400);
1399
+ If ``filename`` is not one of the seven names above (400);
1062
1400
  ``sim_id`` is unknown, or the file was not written by this run
1063
1401
  (404); or the free-tier download allowance is exhausted (429,
1064
1402
  raised at once: the allowance rolls over in hours, not seconds).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simudyne-pulse
3
- Version: 0.9.0.dev6
3
+ Version: 0.9.0.dev8
4
4
  Summary: Python SDK for the Simudyne Pulse synthetic market data API
5
5
  Author-email: Simudyne <support@simudyne.com>
6
6
  License-Expression: MIT
@@ -141,6 +141,20 @@ class TestDataResource:
141
141
  with pytest.raises(TypeError):
142
142
  DataResource(FakeClient([{}])).available_data(include_calibration_state=True)
143
143
 
144
+ def test_false_flags_are_omitted_true_ones_sent(self):
145
+ client = FakeClient([{}, {}])
146
+ DataResource(client).available_data(symbol="700")
147
+ DataResource(client).available_data(symbol="700", include_stats=True, scanned_only=True)
148
+ assert client.calls[0][2]["params"] == {"symbol": "700"}
149
+ assert client.calls[1][2]["params"] == {"symbol": "700", "include_stats": True, "scanned_only": True}
150
+
151
+ def test_calibratable_false_is_sent(self):
152
+ # calibratable is tri-state: False asks for the days that CANNOT be
153
+ # calibrated, so it must reach the server rather than read as unset.
154
+ client = FakeClient([{}])
155
+ DataResource(client).available_data(calibratable=False)
156
+ assert client.calls[0][2]["params"] == {"calibratable": False}
157
+
144
158
  def test_both_calls_take_the_same_filters(self):
145
159
  import inspect
146
160
  available = set(inspect.signature(DataResource.available_data).parameters)
@@ -155,6 +169,7 @@ class TestDataResource:
155
169
  assert "{filters}" not in method.__doc__ and "{rows}" not in method.__doc__
156
170
  assert "calibration_status : " in method.__doc__
157
171
  assert "calibration_error" in method.__doc__
172
+ assert "calibratable : bool" in method.__doc__
158
173
 
159
174
  def test_calibrated_data_path(self):
160
175
  client = FakeClient([{}])
@@ -252,3 +267,91 @@ class TestSimulationAdditions:
252
267
  out = SimulationResource(client).get_job_logs("job-1")
253
268
  assert out == "engine log line"
254
269
  assert client.calls[0][1].endswith("/simulation/jobs/job-1/logs")
270
+
271
+
272
+ class TestSimEvents:
273
+ def test_events_path(self):
274
+ client = FakeClient([{"events": []}])
275
+ SimulationResource(client).get_sim_events("a:b:c")
276
+ assert client.calls[0][:2] == ("GET", "/simulation/results/a:b:c/events")
277
+
278
+ def test_event_path(self):
279
+ client = FakeClient([{}])
280
+ SimulationResource(client).get_sim_event("a:b:c", "ev1")
281
+ assert client.calls[0][:2] == ("GET", "/simulation/results/a:b:c/events/ev1")
282
+
283
+ def test_schedule_orders_path(self):
284
+ client = FakeClient([{"thresholds": {}, "orders": []}])
285
+ out = SimulationResource(client).get_sim_schedule_orders("a:b:c")
286
+ assert client.calls[0][:2] == ("GET", "/simulation/results/a:b:c/schedule-orders")
287
+ assert out == {"thresholds": {}, "orders": []}
288
+
289
+ def test_schedule_report_returns_rows(self):
290
+ rows = [{"line": 2, "ref": "genuine-1", "status": "released", "skip_reason": ""},
291
+ {"line": 3, "ref": "spoof-1", "status": "skipped", "skip_reason": "column SIZE: negative"}]
292
+ client = FakeClient([{"sim_id": "a:b:c", "n_rows": 2, "n_skipped": 1, "rows": rows}])
293
+ out = SimulationResource(client).get_sim_schedule_report("a:b:c")
294
+ assert client.calls[0][:2] == ("GET", "/simulation/results/a:b:c/schedule-report")
295
+ assert out == rows
296
+
297
+ def test_order_schedule_rows_pass_through_unchanged(self):
298
+ rows = [{"time": "2025-09-02 10:00:00", "ref": "spoof-0", "order_type": "limit",
299
+ "side": "buy", "size": 500, "price_ref": "near", "offset_ticks": 2, "lifetime_s": 4},
300
+ {"time": "2025-09-02 10:00:01", "ref": "genuine-0", "order_type": "market",
301
+ "side": "sell", "size": 200}]
302
+ out = SimulationResource._serialize_exec_algos([{"type": "order_schedule", "rows": rows}])
303
+ assert out == [{"type": "order_schedule", "rows": rows}]
304
+
305
+ def test_no_orders_conversion(self):
306
+ # The time -> quantity "orders" form is gone; the SDK no longer
307
+ # rewrites it, so the API's 422 reaches the caller unchanged.
308
+ orders = {"2025-09-02 10:00:00": 100}
309
+ out = SimulationResource._serialize_exec_algos([{"type": "order_schedule", "orders": orders}])
310
+ assert out == [{"type": "order_schedule", "orders": orders}]
311
+
312
+
313
+ class TestScheduleCsv:
314
+ CSV = ("time,ref,order_type,side,size,price_ref,offset_ticks,peg\n"
315
+ "2025-09-02 10:00:00,spoof-1,limit,buy,5000,near,2,\n"
316
+ "2025-09-02 10:00:01,genuine-1,limit,sell,200,mid,,true\n")
317
+
318
+ def _sent(self, rows_csv):
319
+ client = FakeClient([{"job_id": "j"}])
320
+ SimulationResource(client).run(symbol="700.HK", cal_date="2025-09-02", provider="omd",
321
+ exchange="hkex_securities", exec_algos=[{"type": "order_schedule", "rows_csv": rows_csv}])
322
+ algo = client.calls[0][2]["json"]["exec_algos"][0]
323
+ assert set(algo) == {"type", "rows_csv"}
324
+ return algo["rows_csv"]
325
+
326
+ def test_text_is_sent_as_is(self):
327
+ assert self._sent(self.CSV) == self.CSV
328
+
329
+ def test_path_str_and_path_are_read(self, tmp_path):
330
+ from pathlib import Path
331
+ f = tmp_path / "sched.csv"
332
+ f.write_text(self.CSV)
333
+ assert self._sent(str(f)) == self.CSV
334
+ assert self._sent(Path(f)) == self.CSV
335
+
336
+ def test_missing_file_is_refused_before_sending(self, tmp_path):
337
+ with pytest.raises(ValueError, match="no such file"):
338
+ SimulationResource._serialize_exec_algos([{"type": "order_schedule", "rows_csv": str(tmp_path / "nope.csv")}])
339
+
340
+ def test_polars_dataframe(self):
341
+ import polars as pl
342
+ df = pl.DataFrame({"time": ["2025-09-02 10:00:00", "2025-09-02 10:00:01"], "ref": ["spoof-1", "genuine-1"],
343
+ "order_type": ["limit", "limit"], "side": ["buy", "sell"], "size": [5000, 200],
344
+ "peg": [None, True]})
345
+ assert self._sent(df) == ("time,ref,order_type,side,size,peg\n"
346
+ "2025-09-02 10:00:00,spoof-1,limit,buy,5000,\n"
347
+ "2025-09-02 10:00:01,genuine-1,limit,sell,200,true\n")
348
+
349
+ def test_pandas_dataframe(self):
350
+ pd = pytest.importorskip("pandas")
351
+ df = pd.DataFrame({"time": ["2025-09-02 10:00:00"], "ref": ["spoof-1"], "order_type": ["limit"],
352
+ "side": ["buy"], "size": [5000], "offset_ticks": [None]})
353
+ assert self._sent(df) == "time,ref,order_type,side,size,offset_ticks\n2025-09-02 10:00:00,spoof-1,limit,buy,5000,\n"
354
+
355
+ def test_other_types_are_refused(self):
356
+ with pytest.raises(TypeError, match="rows_csv must be"):
357
+ SimulationResource._serialize_exec_algos([{"type": "order_schedule", "rows_csv": [{"ref": "a"}]}])