reamer-py 4.13.0__py3-none-win_amd64.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.
reamer-py.pth ADDED
@@ -0,0 +1 @@
1
+ reamer_py
@@ -0,0 +1,50 @@
1
+ """Reamer Research for Python.
2
+
3
+ import reamer_research as rr
4
+
5
+ def on_bar(data):
6
+ fast, slow = data.close[-10:].mean(), data.close[-30:].mean()
7
+ if fast > slow and data.position() == 0:
8
+ return rr.buy_market(10)
9
+ if fast < slow and data.position() > 0:
10
+ return rr.close_position()
11
+
12
+ result = rr.backtest(on_bar, 'AAPL.csv', lookback=30, open_viewer=True)
13
+ print(result)
14
+
15
+ backtest() runs a strategy over bars and returns a Result: every summary
16
+ metric as an attribute, closed_trades, json(), monte_carlo() and
17
+ open_viewer(). The order and action builders (buy_market, sell_limit,
18
+ close_position, modify_position, ...) make what on_bar returns. Relay sends
19
+ the same orders live. load_csv, to_bars, write_bin and read_bin move bars
20
+ between CSV, numpy, pandas and .bin files; write_exogenous makes sidecars.
21
+
22
+ The package finds libreamer_research inside itself when installed from the
23
+ kit's wheel, or in the kit's lib/ when run from the kit; REAMER_RESEARCH_LIB
24
+ overrides both.
25
+ """
26
+
27
+ from ._abi import REAMER_ABI_VERSION
28
+ from ._lib import EvaluationLimit, ReamerError, library_candidates, load_library
29
+ from ._run import DEFAULTS, Result, backtest, make_config, run_backtest
30
+ from .actions import cancel_all, close_all, modify_order, modify_position
31
+ from .bars import BAR_DTYPE, load_csv, read_bin, to_bars, write_bin, write_exogenous
32
+ from .orders import (
33
+ buy_limit, buy_market, buy_stop, cancel_order, close_position, orders,
34
+ sell_limit, sell_market, sell_stop,
35
+ )
36
+ from .relay import Relay
37
+ from . import license
38
+
39
+ BacktestResult = Result # the 4.8 name
40
+
41
+ __version__ = '4.13.0'
42
+
43
+ __all__ = [
44
+ 'backtest', 'run_backtest', 'Result', 'BacktestResult', 'DEFAULTS', 'make_config',
45
+ 'buy_market', 'sell_market', 'buy_limit', 'sell_limit', 'buy_stop', 'sell_stop',
46
+ 'close_position', 'cancel_order', 'orders',
47
+ 'modify_order', 'modify_position', 'close_all', 'cancel_all',
48
+ 'Relay', 'license', 'load_csv', 'to_bars', 'write_bin', 'read_bin', 'write_exogenous', 'BAR_DTYPE',
49
+ 'ReamerError', 'EvaluationLimit', 'load_library', 'library_candidates', 'REAMER_ABI_VERSION',
50
+ ]
@@ -0,0 +1,374 @@
1
+ """ctypes mirrors of reamer_research_abi.h: structs, enums and prototypes.
2
+
3
+ All field orders below must match include/reamer_research_abi.h exactly.
4
+ """
5
+
6
+ import ctypes
7
+
8
+
9
+ # Must match reamer_research_abi.h's #define REAMER_ABI_VERSION exactly --
10
+ # used by the binding to verify the loaded library matches this file's
11
+ # assumed struct layouts before making any call.
12
+ REAMER_ABI_VERSION = 9
13
+
14
+
15
+ # === ctypes struct mirrors (exact field order from reamer_research_abi.h) ===
16
+
17
+ class OhlcvBar(ctypes.Structure):
18
+ """Mirror of reamer::OhlcvBar (64 bytes, padding-free)."""
19
+ _fields_ = [
20
+ ('ts', ctypes.c_int64),
21
+ ('open', ctypes.c_double),
22
+ ('high', ctypes.c_double),
23
+ ('low', ctypes.c_double),
24
+ ('close', ctypes.c_double),
25
+ ('volume', ctypes.c_double),
26
+ ('notional', ctypes.c_double),
27
+ ('tick_count', ctypes.c_int64),
28
+ ]
29
+
30
+
31
+ class ReamerOrderRequest(ctypes.Structure):
32
+ """Mirror of strategy/abi/reamer_research_abi.h ReamerOrderRequest."""
33
+ _fields_ = [
34
+ ('ticker_id', ctypes.c_int),
35
+ ('order_type', ctypes.c_int), # ReamerResearchOrderType
36
+ ('kind', ctypes.c_int), # ReamerResearchOrderKind
37
+ ('side', ctypes.c_int), # ReamerResearchSide
38
+ ('tif', ctypes.c_int), # ReamerResearchTimeInForce
39
+ ('valid', ctypes.c_bool),
40
+ ('is_cancel', ctypes.c_bool),
41
+ ('is_close', ctypes.c_bool),
42
+ ('reject_reason', ctypes.c_char * 256),
43
+ ('expiry_timestamp', ctypes.c_char * 256),
44
+ ('qty', ctypes.c_double),
45
+ ('limit_price', ctypes.c_double),
46
+ ('stop_price', ctypes.c_double),
47
+ ('take_profit', ctypes.c_double),
48
+ ('stop_loss', ctypes.c_double),
49
+ ('cancel_target_id', ctypes.c_uint64),
50
+ ]
51
+
52
+
53
+ class ReamerPositionState(ctypes.Structure):
54
+ """Mirror of strategy/abi/reamer_research_abi.h ReamerPositionState."""
55
+ _fields_ = [
56
+ ('qty', ctypes.c_double), # signed: + long, - short, 0 flat
57
+ ('avg_entry_price', ctypes.c_double),
58
+ ('take_profit', ctypes.c_double),
59
+ ('stop_loss', ctypes.c_double),
60
+ ('unrealized_pnl', ctypes.c_double),
61
+ ('entry_ts', ctypes.c_int64), # epoch seconds UTC; 0 when flat
62
+ ]
63
+
64
+
65
+ class ReamerOpenOrder(ctypes.Structure):
66
+ """Mirror of strategy/abi/reamer_research_abi.h ReamerOpenOrder."""
67
+ _fields_ = [
68
+ ('order_id', ctypes.c_uint64),
69
+ ('ticker_id', ctypes.c_int),
70
+ ('order_type', ctypes.c_int), # ReamerResearchOrderType
71
+ ('kind', ctypes.c_int), # ReamerResearchOrderKind
72
+ ('side', ctypes.c_int), # ReamerResearchSide
73
+ ('tif', ctypes.c_int), # ReamerResearchTimeInForce
74
+ ('qty', ctypes.c_double),
75
+ ('limit_price', ctypes.c_double),
76
+ ('stop_price', ctypes.c_double),
77
+ ('take_profit', ctypes.c_double),
78
+ ('stop_loss', ctypes.c_double),
79
+ ]
80
+
81
+
82
+ class ReamerOrderAction(ctypes.Structure):
83
+ """Mirror of strategy/abi/reamer_research_abi.h ReamerOrderAction."""
84
+ _fields_ = [
85
+ ('kind', ctypes.c_int), # ReamerResearchActionKind
86
+ ('ticker_id', ctypes.c_int),
87
+ ('order_id', ctypes.c_uint64),
88
+ ('price', ctypes.c_double),
89
+ ('take_profit', ctypes.c_double),
90
+ ('stop_loss', ctypes.c_double),
91
+ ('applied', ctypes.c_bool), # output: set by the engine
92
+ ('reject_reason', ctypes.c_char * 256), # output: set by the engine
93
+ ]
94
+
95
+
96
+ class ReamerBacktestConfig(ctypes.Structure):
97
+ """Mirror of strategy/abi/reamer_research_abi.h ReamerBacktestConfig."""
98
+ _fields_ = [
99
+ ('commission_per_unit', ctypes.c_double),
100
+ ('commission_mode', ctypes.c_int), # ReamerResearchCommissionMode
101
+ ('slippage', ctypes.c_double),
102
+ ('price_volatility', ctypes.c_double),
103
+ ('spread', ctypes.c_double),
104
+ ('ohlcv_type', ctypes.c_int), # ReamerResearchOhlcvType
105
+ ('swap_per_unit', ctypes.c_double * 7),
106
+ ('rng_seed', ctypes.c_uint),
107
+ ('roll_cycle_months', ctypes.c_int * 12),
108
+ ('roll_cycle_months_count', ctypes.c_size_t),
109
+ ('roll_days_before_monthend', ctypes.c_int),
110
+ ]
111
+
112
+
113
+ class ReamerBacktestSummary(ctypes.Structure):
114
+ """Mirror of strategy/abi/reamer_research_abi.h ReamerBacktestSummary."""
115
+ _fields_ = [
116
+ ('gross_pnl', ctypes.c_double),
117
+ ('net_pnl', ctypes.c_double),
118
+ ('total_fees', ctypes.c_double),
119
+ ('total_slippage_cost', ctypes.c_double),
120
+ ('total_swap_cost', ctypes.c_double),
121
+ ('trades', ctypes.c_size_t),
122
+ ('closed_trades_count', ctypes.c_size_t),
123
+ ('total_return_pct', ctypes.c_double),
124
+ ('win_rate', ctypes.c_double),
125
+ ('total_orders', ctypes.c_size_t),
126
+ ('filled_orders', ctypes.c_size_t),
127
+ ('expired_orders', ctypes.c_size_t),
128
+ ('cancelled_orders', ctypes.c_size_t),
129
+ ('rejected_orders', ctypes.c_size_t),
130
+ ('gross_profit', ctypes.c_double),
131
+ ('gross_loss', ctypes.c_double),
132
+ ('net_profit', ctypes.c_double),
133
+ ('max_consecutive_wins', ctypes.c_size_t),
134
+ ('max_consecutive_losses', ctypes.c_size_t),
135
+ ('avg_holding_time_seconds', ctypes.c_double),
136
+ ('max_holding_time_seconds', ctypes.c_double),
137
+ ('min_holding_time_seconds', ctypes.c_double),
138
+ ('recovery_factor', ctypes.c_double),
139
+ ('sharpe_ratio', ctypes.c_double),
140
+ ('sortino_ratio', ctypes.c_double),
141
+ ('calmar_ratio', ctypes.c_double),
142
+ ('profit_factor', ctypes.c_double),
143
+ ('net_ev_per_trade', ctypes.c_double),
144
+ ('equity_drawdown_maximal', ctypes.c_double),
145
+ ('equity_drawdown_relative', ctypes.c_double),
146
+ ('roll_event_count', ctypes.c_size_t),
147
+ ]
148
+
149
+
150
+ class ReamerClosedTrade(ctypes.Structure):
151
+ """Mirror of strategy/abi/reamer_research_abi.h ReamerClosedTrade."""
152
+ _fields_ = [
153
+ ('ticker', ctypes.c_char * 256),
154
+ ('open_timestamp', ctypes.c_char * 256),
155
+ ('close_timestamp', ctypes.c_char * 256),
156
+ ('side', ctypes.c_int), # ReamerResearchSide
157
+ ('entry_price', ctypes.c_double),
158
+ ('exit_price', ctypes.c_double),
159
+ ('qty', ctypes.c_double),
160
+ ('gross_pnl', ctypes.c_double),
161
+ ('net_pnl', ctypes.c_double),
162
+ ]
163
+
164
+
165
+ class ReamerBacktestHandle(ctypes.Structure):
166
+ """Opaque result handle from reamer_run_backtest."""
167
+ _fields_ = [('_opaque', ctypes.c_void_p)]
168
+
169
+
170
+ class ReamerMonteCarloConfig(ctypes.Structure):
171
+ """Mirror of reamer_research_abi.h ReamerMonteCarloConfig."""
172
+ _fields_ = [
173
+ ('num_simulations', ctypes.c_size_t), # 0 -> 10000
174
+ ('rng_seed', ctypes.c_uint64), # 0 -> drawn from entropy
175
+ ('n_threads', ctypes.c_size_t), # 0 -> hardware concurrency
176
+ ]
177
+
178
+
179
+ class ReamerMonteCarloStats(ctypes.Structure):
180
+ """Mirror of reamer_research_abi.h ReamerMonteCarloStats."""
181
+ _fields_ = [
182
+ ('mean_final_equity', ctypes.c_double),
183
+ ('median_final_equity', ctypes.c_double),
184
+ ('best_final_equity', ctypes.c_double),
185
+ ('worst_final_equity', ctypes.c_double),
186
+ ('final_equity_p5', ctypes.c_double),
187
+ ('probability_of_loss', ctypes.c_double),
188
+ ('p_final_below_half_initial', ctypes.c_double),
189
+ ('p_final_above_initial', ctypes.c_double),
190
+ ('p_final_below_initial', ctypes.c_double),
191
+ ('max_drawdown_p5', ctypes.c_double),
192
+ ('max_drawdown_p50', ctypes.c_double),
193
+ ('max_drawdown_p95', ctypes.c_double),
194
+ ('per_trade_return_variance', ctypes.c_double),
195
+ ('effective_seed', ctypes.c_uint64),
196
+ ('num_simulations', ctypes.c_size_t),
197
+ ]
198
+
199
+
200
+ class ReamerRelayHandle(ctypes.Structure):
201
+ """Opaque relay handle from reamer_relay_open."""
202
+ _fields_ = [('_opaque', ctypes.c_void_p)]
203
+
204
+
205
+ # CFUNCTYPE signature: on_bar. `positions` (length ticker_count) is the
206
+ # engine's signed position per ticker (positive=long, negative=short,
207
+ # 0.0=flat). `window_valid` (length ticker_count * window_len, row-major)
208
+ # marks real bars (1) vs forward-filled placeholders (0). `exogenous` and
209
+ # `exogenous_len` (length ticker_count) carry the most recent sidecar entry
210
+ # at or before the current bar (NULL/0 where none); the bytes are
211
+ # engine-owned, valid only for the duration of the call, and are not
212
+ # NUL-terminated: slice with exogenous_len[i], never with a C string read.
213
+ # `position_states` (length ticker_count) is each ticker's full position
214
+ # state; `open_orders` (length open_order_count, sorted by order_id) lists
215
+ # every resting order, so a strategy can cancel one by its ID.
216
+ # `out_actions` (up to max_actions) takes modify/close-all/cancel-all actions;
217
+ # the callback stores their count in *out_action_count (0 on entry).
218
+ # See on_bar's doc comment in reamer_research_abi.h.
219
+ OnBarCallback = ctypes.CFUNCTYPE(
220
+ # Pointers come in as plain addresses (int, or None for NULL): a typed
221
+ # POINTER argument costs an object per argument per bar, and _run.py
222
+ # reads only what the strategy asks for.
223
+ ctypes.c_size_t,
224
+ ctypes.c_void_p, # user_data
225
+ ctypes.c_void_p, # window (const OhlcvBar*)
226
+ ctypes.c_void_p, # window_valid (const uint8_t*)
227
+ ctypes.c_size_t, # window_len
228
+ ctypes.c_size_t, # ticker_count
229
+ ctypes.c_void_p, # positions (const double*)
230
+ ctypes.c_void_p, # exogenous (const char* const*; values are not NUL-terminated)
231
+ ctypes.c_void_p, # exogenous_len (const size_t*)
232
+ ctypes.c_void_p, # position_states (const ReamerPositionState*)
233
+ ctypes.c_void_p, # open_orders (const ReamerOpenOrder*)
234
+ ctypes.c_size_t, # open_order_count
235
+ ctypes.c_void_p, # out_orders (ReamerOrderRequest*)
236
+ ctypes.c_size_t, # max_orders
237
+ ctypes.c_void_p, # out_actions (ReamerOrderAction*)
238
+ ctypes.c_size_t, # max_actions
239
+ ctypes.c_void_p, # out_action_count (size_t*)
240
+ )
241
+
242
+
243
+ # CFUNCTYPE signature: on_progress. Optional; return nonzero to stop the run.
244
+ ProgressCallback = ctypes.CFUNCTYPE(
245
+ ctypes.c_int,
246
+ ctypes.c_void_p, # user_data
247
+ ctypes.c_size_t, # steps_done
248
+ ctypes.c_size_t, # steps_total
249
+ )
250
+
251
+
252
+ class ReamerResearchStrategyVtable(ctypes.Structure):
253
+ """Strategy vtable contract. Field order/count must match the C struct
254
+ exactly -- this is passed to the library by pointer, so a missing field
255
+ here means the library reads past the end of this ctypes-allocated
256
+ struct."""
257
+ _fields_ = [
258
+ ('user_data', ctypes.c_void_p),
259
+ ('on_bar', OnBarCallback),
260
+ ('on_progress', ProgressCallback),
261
+ ]
262
+
263
+
264
+ # Enum constants (from reamer_research_abi.h)
265
+ REAMER_RESEARCH_ORDER_TYPE_BUY = 0
266
+ REAMER_RESEARCH_ORDER_TYPE_SELL = 1
267
+ REAMER_RESEARCH_ORDER_TYPE_BUY_LIMIT = 2
268
+ REAMER_RESEARCH_ORDER_TYPE_SELL_LIMIT = 3
269
+ REAMER_RESEARCH_ORDER_TYPE_BUY_STOP = 4
270
+ REAMER_RESEARCH_ORDER_TYPE_SELL_STOP = 5
271
+
272
+ REAMER_RESEARCH_ORDER_KIND_MARKET = 0
273
+ REAMER_RESEARCH_ORDER_KIND_LIMIT = 1
274
+ REAMER_RESEARCH_ORDER_KIND_STOP = 2
275
+
276
+ REAMER_RESEARCH_ACTION_MODIFY_ORDER = 0
277
+ REAMER_RESEARCH_ACTION_MODIFY_POSITION = 1
278
+ REAMER_RESEARCH_ACTION_CLOSE_ALL = 2
279
+ REAMER_RESEARCH_ACTION_CANCEL_ALL = 3
280
+
281
+ REAMER_RESEARCH_SIDE_BUY = 0
282
+ REAMER_RESEARCH_SIDE_SELL = 1
283
+
284
+ REAMER_RESEARCH_TIF_GTC = 0
285
+ REAMER_RESEARCH_TIF_GTD = 1
286
+ REAMER_RESEARCH_TIF_IOC = 2
287
+
288
+ REAMER_RESEARCH_COMMISSION_ROUND_TRIP = 0
289
+ REAMER_RESEARCH_COMMISSION_OPEN_ONLY = 1
290
+ REAMER_RESEARCH_COMMISSION_CLOSE_ONLY = 2
291
+
292
+ REAMER_RESEARCH_OHLCV_BID = 0
293
+ REAMER_RESEARCH_OHLCV_ASK = 1
294
+ REAMER_RESEARCH_OHLCV_MIDPOINT = 2
295
+
296
+ REAMER_RESEARCH_SUCCESS = 0
297
+ REAMER_RESEARCH_ERROR = 1
298
+
299
+ # reamer_run_backtest_files() start_ts / end_ts for "no bound".
300
+ REAMER_RESEARCH_TS_UNBOUNDED_START = -(2 ** 63)
301
+ REAMER_RESEARCH_TS_UNBOUNDED_END = 2 ** 63 - 1
302
+
303
+ # ReamerResearchErrorCode (from reamer_research_abi.h)
304
+ REAMER_RESEARCH_ERROR_NONE = 0
305
+ REAMER_RESEARCH_ERROR_INVALID_VTABLE = 1
306
+ REAMER_RESEARCH_ERROR_INVALID_OUTPUT = 2
307
+ REAMER_RESEARCH_ERROR_INVALID_HANDLE = 4
308
+ REAMER_RESEARCH_ERROR_LICENSE_MISSING = 5
309
+ REAMER_RESEARCH_ERROR_PROCESS_FATAL = 6
310
+ REAMER_RESEARCH_ERROR_INVALID_BAR = 7
311
+ REAMER_RESEARCH_ERROR_INVALID_TICKER_NAME = 8
312
+ REAMER_RESEARCH_ERROR_EXOGENOUS_LOAD = 9
313
+ REAMER_RESEARCH_ERROR_BAR_FILE = 10
314
+ REAMER_RESEARCH_ERROR_CANCELLED = 11
315
+ REAMER_RESEARCH_ERROR_RELAY = 12
316
+ REAMER_RESEARCH_ERROR_LICENSE_ACTIVATION = 13
317
+
318
+ REAMER_ERROR_CODE_NAMES = {
319
+ REAMER_RESEARCH_ERROR_NONE: 'NONE',
320
+ REAMER_RESEARCH_ERROR_INVALID_VTABLE: 'INVALID_VTABLE',
321
+ REAMER_RESEARCH_ERROR_INVALID_OUTPUT: 'INVALID_OUTPUT',
322
+ REAMER_RESEARCH_ERROR_INVALID_HANDLE: 'INVALID_HANDLE',
323
+ REAMER_RESEARCH_ERROR_LICENSE_MISSING: 'LICENSE_MISSING',
324
+ REAMER_RESEARCH_ERROR_PROCESS_FATAL: 'PROCESS_FATAL',
325
+ REAMER_RESEARCH_ERROR_INVALID_BAR: 'INVALID_BAR',
326
+ REAMER_RESEARCH_ERROR_INVALID_TICKER_NAME: 'INVALID_TICKER_NAME',
327
+ REAMER_RESEARCH_ERROR_EXOGENOUS_LOAD: 'EXOGENOUS_LOAD',
328
+ REAMER_RESEARCH_ERROR_BAR_FILE: 'BAR_FILE',
329
+ REAMER_RESEARCH_ERROR_CANCELLED: 'CANCELLED',
330
+ REAMER_RESEARCH_ERROR_RELAY: 'RELAY',
331
+ REAMER_RESEARCH_ERROR_LICENSE_ACTIVATION: 'LICENSE_ACTIVATION',
332
+ }
333
+
334
+
335
+ def bind(lib):
336
+ """Set argtypes/restype on every exported function of a loaded library."""
337
+ P = ctypes.POINTER
338
+ c_size_t, c_int, c_double, c_char_p = ctypes.c_size_t, ctypes.c_int, ctypes.c_double, ctypes.c_char_p
339
+ protos = {
340
+ 'reamer_get_abi_version': ([], c_size_t),
341
+ 'reamer_get_last_error': ([P(c_int), c_char_p, c_size_t], None),
342
+ 'reamer_run_backtest': ([
343
+ P(P(OhlcvBar)), P(c_size_t), P(c_char_p), P(P(ReamerBacktestConfig)), P(c_char_p),
344
+ c_size_t, P(ReamerResearchStrategyVtable), c_size_t, P(ReamerBacktestConfig),
345
+ c_double, c_double, P(ReamerBacktestHandle)], c_int),
346
+ 'reamer_run_backtest_files': ([
347
+ P(c_char_p), P(c_char_p), P(P(ReamerBacktestConfig)), P(c_char_p), c_size_t,
348
+ ctypes.c_int64, ctypes.c_int64, P(ReamerResearchStrategyVtable), c_size_t,
349
+ P(ReamerBacktestConfig), c_double, c_double, P(ReamerBacktestHandle)], c_int),
350
+ 'reamer_write_bin': ([c_char_p, P(OhlcvBar), c_size_t], c_int),
351
+ 'reamer_get_summary': ([ReamerBacktestHandle, c_double, P(ReamerBacktestSummary)], c_int),
352
+ 'reamer_get_result_json': ([ReamerBacktestHandle, ctypes.c_void_p, c_size_t, P(c_size_t)], c_int),
353
+ 'reamer_write_result_json': ([ReamerBacktestHandle, c_char_p], c_int),
354
+ 'reamer_get_closed_trades': ([ReamerBacktestHandle, P(ReamerClosedTrade), c_size_t, P(c_size_t)], c_int),
355
+ 'reamer_run_monte_carlo': ([ReamerBacktestHandle, P(ReamerMonteCarloConfig), P(ReamerMonteCarloStats)], c_int),
356
+ 'reamer_free_result': ([ReamerBacktestHandle], None),
357
+ 'reamer_relay_open': ([c_char_p, c_char_p, P(c_char_p), c_size_t, P(ReamerRelayHandle)], c_int),
358
+ 'reamer_relay_send': ([ReamerRelayHandle, P(ReamerOrderRequest), c_size_t], c_int),
359
+ 'reamer_relay_send_batch': ([ReamerRelayHandle, P(ReamerOrderRequest), c_size_t,
360
+ P(ReamerOrderAction), c_size_t], c_int),
361
+ 'reamer_relay_get_counts': ([ReamerRelayHandle, P(ctypes.c_uint64), P(ctypes.c_uint64)], c_int),
362
+ 'reamer_relay_poll': ([ReamerRelayHandle, c_int], c_int),
363
+ 'reamer_relay_get_positions': ([ReamerRelayHandle, P(ReamerPositionState), c_size_t], c_int),
364
+ 'reamer_relay_is_connected': ([ReamerRelayHandle], ctypes.c_bool),
365
+ 'reamer_relay_close': ([ReamerRelayHandle], None),
366
+ 'reamer_license_status': ([ctypes.c_char_p, c_size_t, P(c_size_t)], c_int),
367
+ 'reamer_license_activate': ([c_char_p, c_char_p, c_int], c_int),
368
+ 'reamer_license_deactivate': ([c_char_p], c_int),
369
+ }
370
+ for name, (argtypes, restype) in protos.items():
371
+ fn = getattr(lib, name)
372
+ fn.argtypes = argtypes
373
+ fn.restype = restype
374
+ return lib
@@ -0,0 +1,206 @@
1
+ """The on_bar bridge: turns the engine's on_bar callback into a strategy's
2
+ on_bar(data) call and its return value into order requests and actions."""
3
+
4
+ import ctypes
5
+
6
+ from . import _abi
7
+ from .actions import action_result, is_action, marshal_order_action
8
+ from .data import _BacktestData, _TickerView
9
+ from .orders import marshal_order_request
10
+
11
+
12
+ # === The on_bar bridge ===
13
+
14
+ _BAR_SIZE = ctypes.sizeof(_abi.OhlcvBar)
15
+ _POSITION_STATE_FIELDS = tuple(n for n, _ in _abi.ReamerPositionState._fields_)
16
+ _OPEN_ORDER_FIELDS = tuple(n for n, _ in _abi.ReamerOpenOrder._fields_)
17
+ _TS_OFFSET = _abi.OhlcvBar.ts.offset
18
+
19
+
20
+ def _strategy_object(strategy, lookback):
21
+ """(object with on_bar, lookback) from a class, an instance or a function."""
22
+ if isinstance(strategy, type):
23
+ obj = strategy()
24
+ elif hasattr(strategy, 'on_bar'):
25
+ obj = strategy
26
+ elif callable(strategy):
27
+ fn = strategy
28
+
29
+ class _Fn:
30
+ def on_bar(self, data):
31
+ return fn(data)
32
+ obj = _Fn()
33
+ else:
34
+ raise TypeError('strategy must be a class or object with on_bar(data), or a function')
35
+ if lookback is None:
36
+ lookback = getattr(obj, 'lookback', getattr(strategy, 'lookback', 1))
37
+ return obj, int(lookback)
38
+
39
+
40
+ class _Bridge:
41
+ """The vtable for one run, and the state carried between on_bar calls.
42
+
43
+ A ctypes callback must not raise into C, so an exception in the strategy
44
+ is kept, the remaining bars are skipped, the run is stopped at the
45
+ engine's next progress check, and the exception is raised again from
46
+ backtest() once the engine returns.
47
+ """
48
+
49
+ def __init__(self, strategy, ticker_names, capture):
50
+ self.strategy = strategy
51
+ self.names = list(ticker_names)
52
+ self.ids = {n: i for i, n in enumerate(self.names)}
53
+ self.capture = capture
54
+ self.action_count = 0
55
+ self.error = None
56
+ self._data = None
57
+ self._cur = None
58
+ self._on_bar_cb = _abi.OnBarCallback(self._call)
59
+ self._on_progress_cb = _abi.ProgressCallback(self._progress)
60
+ self.vtable = _abi.ReamerResearchStrategyVtable()
61
+ self.vtable.user_data = None
62
+ self.vtable.on_bar = self._on_bar_cb
63
+ self.vtable.on_progress = self._on_progress_cb
64
+
65
+ def _progress(self, _user, done, total):
66
+ if self.error is not None:
67
+ return 1
68
+ cb = getattr(self.strategy, 'on_progress', None)
69
+ if cb is None:
70
+ return 0
71
+ try:
72
+ return 1 if cb(done, total) else 0
73
+ except BaseException as e: # noqa: BLE001 -- raised again after the run
74
+ self.error = e
75
+ return 1
76
+
77
+ def _call(self, _user, window, valid, window_len, ticker_count, positions, exo, exo_len,
78
+ states, open_orders, open_order_count, out_orders, max_orders,
79
+ out_actions, max_actions, out_action_count):
80
+ if self.error is not None:
81
+ return 0
82
+ try:
83
+ return self._on_bar(window, valid, window_len, positions, exo, exo_len, states,
84
+ open_orders, open_order_count, out_orders, max_orders,
85
+ out_actions, max_actions, out_action_count)
86
+ except BaseException as e: # noqa: BLE001 -- raised again after the run
87
+ self.error = e
88
+ ctypes.c_size_t.from_address(out_action_count).value = 0
89
+ self.action_count = 0
90
+ return 0
91
+ finally:
92
+ self._data = None
93
+ if self.capture:
94
+ self.capture.end_bar()
95
+
96
+ # The pointers arrive as plain addresses (OnBarCallback); what the
97
+ # strategy does not read is never turned into Python objects. These
98
+ # readers run on first use, while the call is still live.
99
+
100
+ def live(self, data):
101
+ return data is self._data
102
+
103
+ def position_0(self):
104
+ return ctypes.c_double.from_address(self._cur[0]).value
105
+
106
+ def positions(self):
107
+ n = len(self.names)
108
+ return dict(zip(self.names, (ctypes.c_double * n).from_address(self._cur[0])))
109
+
110
+ def position_states(self):
111
+ n = len(self.names)
112
+ states = (_abi.ReamerPositionState * n).from_address(self._cur[1])
113
+ return {name: {f: getattr(st, f) for f in _POSITION_STATE_FIELDS}
114
+ for name, st in zip(self.names, states)}
115
+
116
+ def open_orders(self):
117
+ addr, count = self._cur[2], self._cur[3]
118
+ if not count:
119
+ return []
120
+ orders = []
121
+ for o in (_abi.ReamerOpenOrder * count).from_address(addr):
122
+ d = {f: getattr(o, f) for f in _OPEN_ORDER_FIELDS}
123
+ d['ticker'] = self.names[o.ticker_id]
124
+ orders.append(d)
125
+ return orders
126
+
127
+ def exogenous(self):
128
+ exo, exo_len = self._cur[4], self._cur[5]
129
+ if not exo:
130
+ return {}
131
+ n = len(self.names)
132
+ ptrs = (ctypes.c_void_p * n).from_address(exo)
133
+ lens = (ctypes.c_size_t * n).from_address(exo_len)
134
+ return {name: ctypes.string_at(ptrs[i], lens[i])
135
+ for i, name in enumerate(self.names) if ptrs[i]}
136
+
137
+ def _on_bar(self, window, valid, window_len, positions, exo, exo_len, states,
138
+ open_orders, open_order_count, out_orders, max_orders,
139
+ out_actions, max_actions, out_action_count):
140
+ names = self.names
141
+ # window and valid are row-major (ticker_count, window_len): ticker i's
142
+ # row starts at i * window_len and its current bar is the row's last.
143
+ views, ts = {}, None
144
+ if window_len:
145
+ row = window_len * _BAR_SIZE
146
+ for i, name in enumerate(names):
147
+ start = window + i * row
148
+ fresh = ctypes.c_uint8.from_address(valid + i * window_len + window_len - 1).value != 0
149
+ if fresh:
150
+ bar_ts = ctypes.c_int64.from_address(start + row - _BAR_SIZE + _TS_OFFSET).value
151
+ ts = bar_ts if ts is None or bar_ts > ts else ts
152
+ views[name] = _TickerView(start, window_len, i, fresh)
153
+ else:
154
+ for i, name in enumerate(names):
155
+ views[name] = _TickerView(None, 0, i, False)
156
+ if self.capture:
157
+ self.capture.ts = ts
158
+ # The engine leaves the previous call's action results in out_actions.
159
+ results = []
160
+ if self.action_count:
161
+ done = (_abi.ReamerOrderAction * self.action_count).from_address(out_actions)
162
+ results = [action_result(a) for a in done]
163
+ self.action_count = 0
164
+ self._cur = (positions, states, open_orders, open_order_count, exo, exo_len)
165
+ data = self._data = _BacktestData(views, action_results=results, ts=ts, source=self)
166
+
167
+ out = self.strategy.on_bar(data)
168
+ if out is None:
169
+ return 0
170
+ if isinstance(out, dict):
171
+ out = [out]
172
+ elif not isinstance(out, (list, tuple)):
173
+ raise TypeError('on_bar must return None, an order or action dict, or a list of '
174
+ f'them, not {type(out).__name__}')
175
+ count = n_actions = 0
176
+ orders_out = actions_out = None
177
+ only = names[0] if len(names) == 1 else None
178
+ for item in out:
179
+ if item is None:
180
+ continue
181
+ ticker = item.get('ticker') or only
182
+ if ticker is not None and ticker not in self.ids:
183
+ raise KeyError(f'unknown ticker {ticker!r}; this run has {names}')
184
+ if is_action(item):
185
+ if n_actions >= max_actions:
186
+ raise RuntimeError(f'on_bar returned more than {max_actions} actions')
187
+ if actions_out is None:
188
+ actions_out = (_abi.ReamerOrderAction * max_actions).from_address(out_actions)
189
+ actions_out[n_actions] = marshal_order_action(item, self.ids.get(ticker, -1))
190
+ n_actions += 1
191
+ continue
192
+ if ticker is None:
193
+ raise ValueError(f'{item} needs ticker=: this run has {len(names)} tickers')
194
+ if count >= max_orders:
195
+ raise RuntimeError(f'on_bar returned more than {max_orders} orders')
196
+ req = marshal_order_request(item, self.ids[ticker])
197
+ if not req.valid:
198
+ raise ValueError(f'malformed order {item}')
199
+ if orders_out is None:
200
+ orders_out = (_abi.ReamerOrderRequest * max_orders).from_address(out_orders)
201
+ orders_out[count] = req
202
+ count += 1
203
+ if n_actions:
204
+ ctypes.c_size_t.from_address(out_action_count).value = n_actions
205
+ self.action_count = n_actions
206
+ return count