trading-engine-interface 0.56.25__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- trading_engine_interface/__init__.py +334 -0
- trading_engine_interface/common/__init__.py +0 -0
- trading_engine_interface/common/enums.py +163 -0
- trading_engine_interface/common/errors.py +259 -0
- trading_engine_interface/common/models/__init__.py +3 -0
- trading_engine_interface/common/models/base_api_model.py +14 -0
- trading_engine_interface/common/utils.py +20 -0
- trading_engine_interface/domain/__init__.py +8 -0
- trading_engine_interface/domain/fill_simulator.py +114 -0
- trading_engine_interface/domain/maker_fill.py +138 -0
- trading_engine_interface/domain/position_math.py +386 -0
- trading_engine_interface/examples/__init__.py +1 -0
- trading_engine_interface/examples/touch_bid_strategy.py +131 -0
- trading_engine_interface/py.typed +0 -0
- trading_engine_interface/runtime/__init__.py +32 -0
- trading_engine_interface/runtime/registry.py +298 -0
- trading_engine_interface/runtime/strategy.py +94 -0
- trading_engine_interface/trading_engine/__init__.py +0 -0
- trading_engine_interface/trading_engine/enums.py +284 -0
- trading_engine_interface/trading_engine/models/__init__.py +0 -0
- trading_engine_interface/trading_engine/models/accounting_models.py +412 -0
- trading_engine_interface/trading_engine/models/backtest_models.py +200 -0
- trading_engine_interface/trading_engine/models/market_models.py +452 -0
- trading_engine_interface/trading_engine/models/order_models.py +520 -0
- trading_engine_interface/trading_engine/models/position_breakdown_models.py +130 -0
- trading_engine_interface/trading_engine/models/position_models.py +230 -0
- trading_engine_interface/trading_engine/models/strategy_metrics_models.py +204 -0
- trading_engine_interface/trading_engine/models/strategy_models.py +1360 -0
- trading_engine_interface/trading_engine/order_rules.py +209 -0
- trading_engine_interface-0.56.25.dist-info/LICENSE +21 -0
- trading_engine_interface-0.56.25.dist-info/METADATA +112 -0
- trading_engine_interface-0.56.25.dist-info/RECORD +33 -0
- trading_engine_interface-0.56.25.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Strategy registry — module-level singleton + decorator-based registration.
|
|
2
|
+
|
|
3
|
+
Moved from ``app/strategies/strategy_registry.py`` in Phase 1.8. Strategies
|
|
4
|
+
import the ``@register_strategy`` decorator from here without depending on the
|
|
5
|
+
engine. The engine reads ``STRATEGY_REGISTRY`` to look up classes by name.
|
|
6
|
+
|
|
7
|
+
The registry is stateful (a mutable singleton) but the API is small and
|
|
8
|
+
serves as a shared contract: strategies register themselves; the engine looks
|
|
9
|
+
them up. Putting it in public-interface keeps both consumers on the same
|
|
10
|
+
``trading_engine_interface`` dependency without a cycle.
|
|
11
|
+
|
|
12
|
+
Discovery (the act of walking packages to import strategy modules so their
|
|
13
|
+
``@register_strategy`` decorators fire) stays in engine code — it's startup
|
|
14
|
+
machinery that knows engine-side package namespaces.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from datetime import datetime, timezone
|
|
21
|
+
from typing import Any, Callable, Iterator, KeysView, Optional, Type, Union, overload
|
|
22
|
+
|
|
23
|
+
from trading_engine_interface.runtime.strategy import StrategyProtocol
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class RegistryEntry:
|
|
28
|
+
"""Metadata for a registered strategy class."""
|
|
29
|
+
|
|
30
|
+
name: str
|
|
31
|
+
cls: Type[StrategyProtocol]
|
|
32
|
+
module: str
|
|
33
|
+
source: str # "builtin" today; "external" once Phase 3 plugin loading ships
|
|
34
|
+
registered_at: datetime
|
|
35
|
+
#: Optional config class for the strategy. Populated when registered via
|
|
36
|
+
#: ``@register_strategy(config=...)``. ``None`` for legacy registrations.
|
|
37
|
+
#: Consumed by the engine to look up config classes without importing them
|
|
38
|
+
#: directly (decoupling — see ``app/configs/strategies/real_strategy_config.py``
|
|
39
|
+
#: in inf-trading-engine for the runtime-lookup pattern).
|
|
40
|
+
#:
|
|
41
|
+
#: Typed as ``Any`` rather than ``Type[BaseStrategyConfig]`` because
|
|
42
|
+
#: ``BaseStrategyConfig`` lives in this same package and importing it here
|
|
43
|
+
#: would create a circular import (strategy_models.py imports from runtime.*
|
|
44
|
+
#: for the decorator). Callers cast to the appropriate config type.
|
|
45
|
+
config_cls: Optional[Any] = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class StrategyRegistry:
|
|
49
|
+
"""Mutable registry of strategy classes keyed by name.
|
|
50
|
+
|
|
51
|
+
Backward-compatible with the dict-of-classes shape the prior implementation
|
|
52
|
+
exposed: ``__getitem__``, ``__contains__``, ``__iter__``, ``__len__``, and
|
|
53
|
+
``keys()`` all work the way callers were using them.
|
|
54
|
+
|
|
55
|
+
Not thread-safe. Mutation happens at import time (decorator side-effects)
|
|
56
|
+
and at startup (discovery). Phase 3 (runtime plugin loading via API) will
|
|
57
|
+
add a lock for in-flight mutation.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self) -> None:
|
|
61
|
+
self._entries: dict[str, RegistryEntry] = {}
|
|
62
|
+
#: Function returning the engine's deployment config list given context
|
|
63
|
+
#: (account, app_mode, risk_limit). Registered via the module-level
|
|
64
|
+
#: ``@register_production_configs`` decorator at strategies-wheel load
|
|
65
|
+
#: time. ``None`` until something registers; the engine's
|
|
66
|
+
#: ``RealStrategyConfigFactory`` calls ``get_production_configs()`` and
|
|
67
|
+
#: invokes the result. Only one function can register per engine; a
|
|
68
|
+
#: second registration raises.
|
|
69
|
+
self._production_configs_fn: Optional[Callable[..., list[Any]]] = None
|
|
70
|
+
|
|
71
|
+
def register(
|
|
72
|
+
self,
|
|
73
|
+
name: str,
|
|
74
|
+
cls: Type[StrategyProtocol],
|
|
75
|
+
*,
|
|
76
|
+
source: str = "builtin",
|
|
77
|
+
config_cls: Optional[Any] = None,
|
|
78
|
+
) -> None:
|
|
79
|
+
"""Register a strategy class. Raises if ``name`` is already taken.
|
|
80
|
+
|
|
81
|
+
``config_cls`` is the strategy's Pydantic config class (subclass of
|
|
82
|
+
``BaseStrategyConfig``). Engine consumers retrieve it via
|
|
83
|
+
:meth:`get_config_class` instead of importing the config class directly,
|
|
84
|
+
which avoids a hard build-time dependency on the strategies package.
|
|
85
|
+
"""
|
|
86
|
+
if name in self._entries:
|
|
87
|
+
existing = self._entries[name]
|
|
88
|
+
raise ValueError(
|
|
89
|
+
f"Strategy '{name}' already registered from {existing.module}; cannot register {cls.__module__}"
|
|
90
|
+
)
|
|
91
|
+
self._entries[name] = RegistryEntry(
|
|
92
|
+
name=name,
|
|
93
|
+
cls=cls,
|
|
94
|
+
module=cls.__module__,
|
|
95
|
+
source=source,
|
|
96
|
+
registered_at=datetime.now(timezone.utc),
|
|
97
|
+
config_cls=config_cls,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def unregister(self, name: str) -> None:
|
|
101
|
+
"""Remove a strategy by name. No-op if the name is not registered."""
|
|
102
|
+
self._entries.pop(name, None)
|
|
103
|
+
|
|
104
|
+
def list_entries(self) -> list[RegistryEntry]:
|
|
105
|
+
"""Snapshot of all registered entries with metadata."""
|
|
106
|
+
return list(self._entries.values())
|
|
107
|
+
|
|
108
|
+
def get_config_class(self, name: str) -> Any:
|
|
109
|
+
"""Return the config class registered for a strategy.
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
KeyError: if ``name`` isn't registered.
|
|
113
|
+
ValueError: if the strategy was registered without ``config=...``.
|
|
114
|
+
Migrate the strategy to ``@register_strategy(config=YourConfig)``.
|
|
115
|
+
|
|
116
|
+
Returns the class as ``Any`` to avoid an interface-package circular
|
|
117
|
+
import on ``BaseStrategyConfig``. Engine call sites typically just
|
|
118
|
+
invoke it as a constructor; type-checkers see ``Any`` and don't enforce
|
|
119
|
+
kwarg types — acceptable since the engine's production-config layer
|
|
120
|
+
knows what kwargs each config accepts.
|
|
121
|
+
"""
|
|
122
|
+
entry = self._entries[name]
|
|
123
|
+
if entry.config_cls is None:
|
|
124
|
+
raise ValueError(
|
|
125
|
+
f"Strategy '{name}' has no registered config class. "
|
|
126
|
+
f"Update its registration to use @register_strategy(config=YourConfigClass)."
|
|
127
|
+
)
|
|
128
|
+
return entry.config_cls
|
|
129
|
+
|
|
130
|
+
def register_production_configs(self, fn: Callable[..., list[Any]]) -> None:
|
|
131
|
+
"""Register the deployment-config function for the engine.
|
|
132
|
+
|
|
133
|
+
Strategies repo's ``strategies/production/__init__.py`` calls this via
|
|
134
|
+
the module-level ``@register_production_configs`` decorator at
|
|
135
|
+
wheel-load time. Engine retrieves the function via
|
|
136
|
+
:meth:`get_production_configs` and invokes it with deployment context
|
|
137
|
+
(account, app_mode, risk_limit) to build the per-env strategy config
|
|
138
|
+
list.
|
|
139
|
+
|
|
140
|
+
Raises:
|
|
141
|
+
ValueError: if a function is already registered. Only one
|
|
142
|
+
production-configs function makes sense per engine; a second
|
|
143
|
+
registration usually means two ``strategies/`` packages got
|
|
144
|
+
loaded — investigate.
|
|
145
|
+
"""
|
|
146
|
+
if self._production_configs_fn is not None:
|
|
147
|
+
existing_module = getattr(self._production_configs_fn, "__module__", "?")
|
|
148
|
+
new_module = getattr(fn, "__module__", "?")
|
|
149
|
+
raise ValueError(
|
|
150
|
+
f"@register_production_configs already registered from {existing_module}; "
|
|
151
|
+
f"cannot register a second one from {new_module}."
|
|
152
|
+
)
|
|
153
|
+
self._production_configs_fn = fn
|
|
154
|
+
|
|
155
|
+
def get_production_configs(self) -> Callable[..., list[Any]]:
|
|
156
|
+
"""Return the registered deployment-config function.
|
|
157
|
+
|
|
158
|
+
Raises:
|
|
159
|
+
ValueError: if no ``@register_production_configs`` function has
|
|
160
|
+
been registered. Usually means the strategies wheel hasn't
|
|
161
|
+
been loaded yet, or the strategies repo doesn't ship a
|
|
162
|
+
``strategies/production/`` package (older release).
|
|
163
|
+
"""
|
|
164
|
+
if self._production_configs_fn is None:
|
|
165
|
+
raise ValueError(
|
|
166
|
+
"No @register_production_configs function registered. "
|
|
167
|
+
"Strategies repo's strategies/production/__init__.py should "
|
|
168
|
+
"register one at wheel-load time."
|
|
169
|
+
)
|
|
170
|
+
return self._production_configs_fn
|
|
171
|
+
|
|
172
|
+
def has_production_configs(self) -> bool:
|
|
173
|
+
"""True if a ``@register_production_configs`` function is currently registered.
|
|
174
|
+
|
|
175
|
+
Predicate for code paths that need to branch on registration state without
|
|
176
|
+
triggering :meth:`get_production_configs`'s ``ValueError`` (e.g. hot-reload
|
|
177
|
+
assertions, test fixtures). Symmetric with the dict-protocol ``__contains__``
|
|
178
|
+
for strategy entries.
|
|
179
|
+
"""
|
|
180
|
+
return self._production_configs_fn is not None
|
|
181
|
+
|
|
182
|
+
def unregister_production_configs(self) -> None:
|
|
183
|
+
"""Clear the deployment-config function slot. No-op if nothing is registered.
|
|
184
|
+
|
|
185
|
+
Used by the hot-reload path (:mod:`app.strategies._reload`) before
|
|
186
|
+
``importlib.reload`` re-executes ``strategies/production/__init__.py`` — the
|
|
187
|
+
re-execution re-invokes ``@register_production_configs``, which would
|
|
188
|
+
otherwise raise via :meth:`register_production_configs`'s single-registration
|
|
189
|
+
guard. Symmetric with :meth:`unregister` for strategy entries.
|
|
190
|
+
"""
|
|
191
|
+
self._production_configs_fn = None
|
|
192
|
+
|
|
193
|
+
# ---- Dict-protocol surface for backward compatibility ----
|
|
194
|
+
|
|
195
|
+
def __getitem__(self, name: str) -> Type[StrategyProtocol]:
|
|
196
|
+
return self._entries[name].cls
|
|
197
|
+
|
|
198
|
+
def __contains__(self, name: object) -> bool:
|
|
199
|
+
return isinstance(name, str) and name in self._entries
|
|
200
|
+
|
|
201
|
+
def __iter__(self) -> Iterator[str]:
|
|
202
|
+
return iter(self._entries)
|
|
203
|
+
|
|
204
|
+
def __len__(self) -> int:
|
|
205
|
+
return len(self._entries)
|
|
206
|
+
|
|
207
|
+
def keys(self) -> KeysView[str]:
|
|
208
|
+
return self._entries.keys()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# Module-level singleton. Strategies and engine both reference this.
|
|
212
|
+
STRATEGY_REGISTRY = StrategyRegistry()
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@overload
|
|
216
|
+
def register_strategy(cls: Type[StrategyProtocol]) -> Type[StrategyProtocol]: ...
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@overload
|
|
220
|
+
def register_strategy(
|
|
221
|
+
*,
|
|
222
|
+
name: Optional[str] = None,
|
|
223
|
+
config: Optional[Any] = None,
|
|
224
|
+
) -> Callable[[Type[StrategyProtocol]], Type[StrategyProtocol]]: ...
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def register_strategy(
|
|
228
|
+
cls: Optional[Type[StrategyProtocol]] = None,
|
|
229
|
+
*,
|
|
230
|
+
name: Optional[str] = None,
|
|
231
|
+
config: Optional[Any] = None,
|
|
232
|
+
) -> Union[Type[StrategyProtocol], Callable[[Type[StrategyProtocol]], Type[StrategyProtocol]]]:
|
|
233
|
+
"""Decorator: register a strategy class in :data:`STRATEGY_REGISTRY`.
|
|
234
|
+
|
|
235
|
+
Usage — bare (config-less; legacy)::
|
|
236
|
+
|
|
237
|
+
@register_strategy
|
|
238
|
+
class MyStrategy(BaseStrategy):
|
|
239
|
+
...
|
|
240
|
+
|
|
241
|
+
Recommended — explicit config class so engine can deserialize without
|
|
242
|
+
importing the config class directly::
|
|
243
|
+
|
|
244
|
+
@register_strategy(config=MyStrategyConfig)
|
|
245
|
+
class MyStrategy(BaseStrategy):
|
|
246
|
+
...
|
|
247
|
+
|
|
248
|
+
Explicit registry name (defaults to the class name)::
|
|
249
|
+
|
|
250
|
+
@register_strategy(name="CustomName", config=MyStrategyConfig)
|
|
251
|
+
class MyStrategy(BaseStrategy):
|
|
252
|
+
...
|
|
253
|
+
|
|
254
|
+
The ``config`` arg is the strategy's Pydantic config class. Engine
|
|
255
|
+
retrieves it via ``STRATEGY_REGISTRY.get_config_class(name)`` — see
|
|
256
|
+
``app/configs/strategies/real_strategy_config.py`` for the consumption
|
|
257
|
+
pattern. Strategies registered without ``config`` continue to work but
|
|
258
|
+
can't participate in registry-based config lookup.
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
def wrap(c: Type[StrategyProtocol]) -> Type[StrategyProtocol]:
|
|
262
|
+
STRATEGY_REGISTRY.register(name or c.__name__, c, config_cls=config)
|
|
263
|
+
return c
|
|
264
|
+
|
|
265
|
+
if cls is None:
|
|
266
|
+
return wrap
|
|
267
|
+
return wrap(cls)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def register_production_configs(fn: Callable[..., list[Any]]) -> Callable[..., list[Any]]:
|
|
271
|
+
"""Decorator: register the deployment-config function in :data:`STRATEGY_REGISTRY`.
|
|
272
|
+
|
|
273
|
+
Strategies repo's ``strategies/production/__init__.py`` exposes a single
|
|
274
|
+
function that, given engine deployment context (account, app_mode,
|
|
275
|
+
risk_limit), returns the list of strategy configs to launch. This
|
|
276
|
+
decorator stores the function in the registry; engine retrieves it via
|
|
277
|
+
``STRATEGY_REGISTRY.get_production_configs()`` and invokes it from
|
|
278
|
+
``RealStrategyConfigFactory.get_configs()``.
|
|
279
|
+
|
|
280
|
+
Usage::
|
|
281
|
+
|
|
282
|
+
@register_production_configs
|
|
283
|
+
def configs_for(
|
|
284
|
+
account: AccountPermissionConfig,
|
|
285
|
+
app_mode: AppMode,
|
|
286
|
+
risk_limit: RiskLimitConfig,
|
|
287
|
+
) -> list[BaseStrategyConfig]:
|
|
288
|
+
return [
|
|
289
|
+
MeanReversionStrategyConfig(account_permission=account, ...),
|
|
290
|
+
...
|
|
291
|
+
]
|
|
292
|
+
|
|
293
|
+
Only one function may register per engine — see
|
|
294
|
+
:meth:`StrategyRegistry.register_production_configs`. Returns the original
|
|
295
|
+
function unchanged.
|
|
296
|
+
"""
|
|
297
|
+
STRATEGY_REGISTRY.register_production_configs(fn)
|
|
298
|
+
return fn
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Strategy Protocol — the minimal runtime contract between engine and strategies.
|
|
2
|
+
|
|
3
|
+
Engine code type-checks strategy instances against this Protocol. Concrete
|
|
4
|
+
strategy classes (e.g. ``BaseStrategy``) live in the strategies package and
|
|
5
|
+
structurally implement this contract. The engine never imports ``BaseStrategy``
|
|
6
|
+
directly — only the Protocol.
|
|
7
|
+
|
|
8
|
+
This is the seam that lets strategies live in their own repo (Phase 2) while
|
|
9
|
+
the engine remains strategy-aware via type-checking.
|
|
10
|
+
|
|
11
|
+
Captures exactly what engine code accesses on strategy instances:
|
|
12
|
+
- ``decide(input_data, predictions)`` — main decision entry
|
|
13
|
+
- ``close_position(position, order_book)`` — engine-driven close-position path
|
|
14
|
+
- ``flush_output()`` — engine reads accumulated output after a close
|
|
15
|
+
- ``fees`` — mutable attribute the engine updates on fee changes
|
|
16
|
+
- ``VERSION`` (class attribute) — algorithm version
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any, Optional, Protocol, runtime_checkable
|
|
22
|
+
|
|
23
|
+
from trading_engine_interface.common.enums import Symbol, VenueName
|
|
24
|
+
from trading_engine_interface.trading_engine.enums import OrderType
|
|
25
|
+
from trading_engine_interface.trading_engine.models.market_models import OrderBook, TradeFee
|
|
26
|
+
from trading_engine_interface.trading_engine.models.position_models import Position
|
|
27
|
+
from trading_engine_interface.trading_engine.models.strategy_models import (
|
|
28
|
+
BaseStrategyConfig,
|
|
29
|
+
StrategyInput,
|
|
30
|
+
StrategyOutput,
|
|
31
|
+
StrategyPredictions,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@runtime_checkable
|
|
36
|
+
class StrategyProtocol(Protocol):
|
|
37
|
+
"""Runtime contract for a trading strategy.
|
|
38
|
+
|
|
39
|
+
Anything structurally implementing these members is a Strategy as far as
|
|
40
|
+
the engine cares. The concrete ``BaseStrategy`` ABC in the strategies
|
|
41
|
+
package satisfies this Protocol; so do mock test strategies.
|
|
42
|
+
|
|
43
|
+
Attributes:
|
|
44
|
+
VERSION: Class-level algorithm version. Bumped when the strategy's
|
|
45
|
+
decision logic changes in a way that should produce a fresh DB row
|
|
46
|
+
rather than reusing the previous version's state.
|
|
47
|
+
fees: Per-symbol per-venue trading fees. Engine assigns this when fees
|
|
48
|
+
update mid-run.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
# Note: declared as plain int (not ClassVar) so subclasses can override the
|
|
52
|
+
# default value the conventional way: ``VERSION: int = 5``.
|
|
53
|
+
VERSION: int
|
|
54
|
+
fees: dict[Symbol, dict[VenueName, TradeFee]]
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
config: BaseStrategyConfig,
|
|
59
|
+
order_permissions: Optional[dict[Symbol, dict[VenueName, list[OrderType]]]] = None,
|
|
60
|
+
fees: Optional[dict[Symbol, dict[VenueName, TradeFee]]] = None,
|
|
61
|
+
**kwargs: Any,
|
|
62
|
+
) -> None:
|
|
63
|
+
"""Construct with config + optional order_permissions/fees runtime context."""
|
|
64
|
+
...
|
|
65
|
+
|
|
66
|
+
def decide(
|
|
67
|
+
self,
|
|
68
|
+
input_data: StrategyInput,
|
|
69
|
+
predictions: Optional[StrategyPredictions] = None,
|
|
70
|
+
) -> StrategyOutput:
|
|
71
|
+
"""Make a trading decision and return the resulting actions."""
|
|
72
|
+
...
|
|
73
|
+
|
|
74
|
+
def close_position(
|
|
75
|
+
self,
|
|
76
|
+
position: Position,
|
|
77
|
+
order_book: OrderBook,
|
|
78
|
+
input_data: Optional[StrategyInput] = None,
|
|
79
|
+
exit_type: Any = None,
|
|
80
|
+
) -> Any:
|
|
81
|
+
"""Queue actions to close the given position. Output retrieved via flush_output().
|
|
82
|
+
|
|
83
|
+
Returns ``Any`` because concrete implementations vary (BaseStrategy returns
|
|
84
|
+
``bool``; the engine does not use the return value).
|
|
85
|
+
"""
|
|
86
|
+
...
|
|
87
|
+
|
|
88
|
+
def flush_output(
|
|
89
|
+
self,
|
|
90
|
+
skip_reason: Optional[Any] = None,
|
|
91
|
+
**skip_metrics: float,
|
|
92
|
+
) -> StrategyOutput:
|
|
93
|
+
"""Drain accumulated orders/cancels/logs into a StrategyOutput and reset internal state."""
|
|
94
|
+
...
|
|
File without changes
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
from trading_engine_interface.common.enums import *
|
|
2
|
+
|
|
3
|
+
# --- App --- #
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AppMode(StrValueEnum):
|
|
7
|
+
LIVE = "LIVE"
|
|
8
|
+
SANDBOX = "SANDBOX"
|
|
9
|
+
PAPER = "PAPER"
|
|
10
|
+
BACKTEST = "BACKTEST"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AppStatus(IntEnum):
|
|
14
|
+
# Normal Life Cycle
|
|
15
|
+
INIT = 0
|
|
16
|
+
VERIFYING = 1
|
|
17
|
+
READY = 2
|
|
18
|
+
TRADING = 3
|
|
19
|
+
# Terminate
|
|
20
|
+
INACTIVE = 4
|
|
21
|
+
STOPPING = 5
|
|
22
|
+
SHUTDOWN = 6
|
|
23
|
+
# Abnormal
|
|
24
|
+
NOT_READY = -1
|
|
25
|
+
ERROR = -2
|
|
26
|
+
UNKNOWN = -3
|
|
27
|
+
SAFE_MODE = -5
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class LifecycleEventType(StrValueEnum):
|
|
31
|
+
"""Kind of app-lifecycle event recorded in the durable lifecycle log."""
|
|
32
|
+
|
|
33
|
+
STARTED = "STARTED" # Process started; carries RestartType in metadata.
|
|
34
|
+
STATUS_CHANGE = "STATUS_CHANGE" # App transitioned between stable AppStatus values.
|
|
35
|
+
SHUTDOWN = "SHUTDOWN" # Clean shutdown path completed (lack of this = crash).
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class RestartType(StrValueEnum):
|
|
39
|
+
"""How the current process was started relative to the previous one.
|
|
40
|
+
|
|
41
|
+
Resolved on startup by reading the latest durable lifecycle event:
|
|
42
|
+
- FIRST_START: no previous events on record.
|
|
43
|
+
- DEPLOY: previous event exists but version differs from current.
|
|
44
|
+
- RESTART: previous event is a SHUTDOWN at the same version (clean restart).
|
|
45
|
+
- CRASH_RESTART: previous event is NOT a SHUTDOWN at the same version
|
|
46
|
+
(process died without running the shutdown path).
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
FIRST_START = "FIRST_START"
|
|
50
|
+
DEPLOY = "DEPLOY"
|
|
51
|
+
RESTART = "RESTART"
|
|
52
|
+
CRASH_RESTART = "CRASH_RESTART"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# --- Venue --- #
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class VenueType(StrValueEnum):
|
|
59
|
+
EXCHANGE = "EXCHANGE"
|
|
60
|
+
OTC = "OTC"
|
|
61
|
+
BANK = "BANK"
|
|
62
|
+
WALLET = "WALLET"
|
|
63
|
+
# DEFI = "DEFI"
|
|
64
|
+
# Removed DEFI because it's a broader category:
|
|
65
|
+
# DeFi Spectrum Analysis:
|
|
66
|
+
# DEXs (Hyperliquid, dYdX, etc.) → Same as exchanges
|
|
67
|
+
# AMMs (Uniswap, etc.) → Different interface (no order books, different pricing)
|
|
68
|
+
# Lending (Aave, etc.) → Completely different interface
|
|
69
|
+
# Yield farming → Different interface
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# --- Accounting --- #
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class AccountType(StrValueEnum):
|
|
76
|
+
FUNDING = "FUNDING"
|
|
77
|
+
SPOT = "SPOT"
|
|
78
|
+
MARGIN = "MARGIN"
|
|
79
|
+
FUTURE = "FUTURE"
|
|
80
|
+
OPTION = "OPTION"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class AccountStatus(StrValueEnum):
|
|
84
|
+
ACTIVE = "ACTIVE"
|
|
85
|
+
SUSPENDED = "SUSPENDED"
|
|
86
|
+
CLOSED = "CLOSED"
|
|
87
|
+
ERROR = "ERROR"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class TransactionType(StrValueEnum):
|
|
91
|
+
FILL = "FILL"
|
|
92
|
+
TRANSFER = "TRANSFER"
|
|
93
|
+
FEE = "FEE"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# --- Market --- #
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class MarketStatus(StrValueEnum):
|
|
100
|
+
OPEN = "OPEN"
|
|
101
|
+
CLOSED = "CLOSED"
|
|
102
|
+
HALTED = "HALTED"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# --- Order --- #
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class Side(StrValueEnum):
|
|
109
|
+
BUY = "BUY"
|
|
110
|
+
SELL = "SELL"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class OrderType(StrValueEnum):
|
|
114
|
+
MARKET = "MARKET"
|
|
115
|
+
LIMIT = "LIMIT"
|
|
116
|
+
FOK = "FOK"
|
|
117
|
+
POST_ONLY = "POST_ONLY"
|
|
118
|
+
IOC = "IOC"
|
|
119
|
+
# Venue-side trigger (conditional/algo) orders: the order rests AT THE VENUE
|
|
120
|
+
# and converts when price crosses ``trigger_price`` — no engine-side polling, immune
|
|
121
|
+
# to the load-correlated REST latency tail. STOP_LOSS converts to a market order on
|
|
122
|
+
# trigger; STOP_LOSS_LIMIT converts to a limit order at ``price``. Side + quantity
|
|
123
|
+
# are fully specified at placement (spot semantics — no reduce-only concept); orphan
|
|
124
|
+
# protection is engine-enforced cancel-on-close, not a venue flag. OKX-only initially
|
|
125
|
+
# (POST /trade/order-algo, ordType=conditional).
|
|
126
|
+
STOP_LOSS = "STOP_LOSS"
|
|
127
|
+
STOP_LOSS_LIMIT = "STOP_LOSS_LIMIT"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class OrderStatus(StrValueEnum):
|
|
131
|
+
PENDING_NEW = "PENDING_NEW"
|
|
132
|
+
NEW = "NEW"
|
|
133
|
+
SETTLING = "SETTLING" # Exchange confirmed fill, but fill records not yet received locally
|
|
134
|
+
FILLED = "FILLED"
|
|
135
|
+
PARTIALLY_FILLED = "PARTIALLY_FILLED"
|
|
136
|
+
PENDING_CANCEL = "PENDING_CANCEL"
|
|
137
|
+
CANCELED = "CANCELED"
|
|
138
|
+
REJECTED = "REJECTED"
|
|
139
|
+
UNKNOWN = "UNKNOWN"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class LiquidityType(StrValueEnum):
|
|
143
|
+
MAKER = "MAKER"
|
|
144
|
+
TAKER = "TAKER"
|
|
145
|
+
UNKNOWN = "UNKNOWN"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class RfqQuoteSource(StrValueEnum):
|
|
149
|
+
"""Who asked for an RFQ quote: the venue, or the engine's own synthetic request generator."""
|
|
150
|
+
|
|
151
|
+
VENUE = "VENUE"
|
|
152
|
+
SYNTHETIC = "SYNTHETIC"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# --- Transfer --- #
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class TransferType(StrValueEnum):
|
|
159
|
+
DEPOSIT = "DEPOSIT"
|
|
160
|
+
WITHDRAWAL = "WITHDRAWAL"
|
|
161
|
+
# Earned income credited by the venue outside trading — e.g. Binance daily
|
|
162
|
+
# fee-rebate / asset distributions (assetDistributionHistory). Credits
|
|
163
|
+
# the balance but is EXCLUDED from capital_base (it's performance, not injected
|
|
164
|
+
# capital), so TWR/ROI treat it as return rather than a neutralized flow.
|
|
165
|
+
REBATE = "REBATE"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class TransferStatus(StrValueEnum):
|
|
169
|
+
PENDING = "PENDING"
|
|
170
|
+
APPROVED = "APPROVED"
|
|
171
|
+
PROCESSING = "PROCESSING"
|
|
172
|
+
COMPLETED = "COMPLETED"
|
|
173
|
+
FAILED = "FAILED"
|
|
174
|
+
CANCELLED = "CANCELLED"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class TransferFlowClass(StrValueEnum):
|
|
178
|
+
"""What a transfer is FOR, orthogonal to its direction (TransferType).
|
|
179
|
+
|
|
180
|
+
Direction is fixed by the venue when the transfer is parsed; purpose is only
|
|
181
|
+
knowable once the partner leg of a rebalance arrives, so it lives on its own
|
|
182
|
+
field and can be reclassified after insert.
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
# Capital crossing the book boundary: an injection or a withdrawal to outside.
|
|
186
|
+
# Counts toward capital_base. The default, so an unclassified row keeps the
|
|
187
|
+
# semantics it had before flow classes existed.
|
|
188
|
+
EXTERNAL = "EXTERNAL"
|
|
189
|
+
# One leg of a same-asset move between two in-book accounts (a venue rebalance).
|
|
190
|
+
# Once both legs have landed neither counts toward capital_base, so the amount
|
|
191
|
+
# difference (the network fee) shows as portfolio cost instead of capital withdrawn.
|
|
192
|
+
INTERNAL = "INTERNAL"
|
|
193
|
+
# One leg of a cross-asset pair (e.g. TRX out, converted outside the book, USD back).
|
|
194
|
+
# Both legs keep counting toward capital_base: capital_base is held in native units,
|
|
195
|
+
# and excluding both would leave the old asset in capital after it is gone.
|
|
196
|
+
CONVERSION = "CONVERSION"
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class TransferFlowClassSource(StrValueEnum):
|
|
200
|
+
"""Who set a transfer's flow_class — the durability marker.
|
|
201
|
+
|
|
202
|
+
AUTO rows are re-derived by the pairing pass on every capital_base rebuild;
|
|
203
|
+
OPERATOR rows are never touched by it, so a manual correction survives the next sync.
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
AUTO = "AUTO"
|
|
207
|
+
OPERATOR = "OPERATOR"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# --- Strategy --- #
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class StrategyStatus(StrValueEnum):
|
|
214
|
+
INACTIVE = "INACTIVE"
|
|
215
|
+
ACTIVE = "ACTIVE"
|
|
216
|
+
DISABLED = "DISABLED"
|
|
217
|
+
ERROR = "ERROR"
|
|
218
|
+
KILLED = "KILLED"
|
|
219
|
+
CLOSE_ONLY = "CLOSE_ONLY" # Only allow closing existing positions
|
|
220
|
+
# Operator pause: loop stopped, positions KEPT, orders cancelled.
|
|
221
|
+
# Durable — operator-parked, skipped by the starter and hot-reload
|
|
222
|
+
# restarts; risk kill switch stays armed on the kept exposure. Resume via
|
|
223
|
+
# enable. Distinct from DISABLED, which flattens: PAUSED-with-exposure is
|
|
224
|
+
# intended, DISABLED-with-exposure is an anomaly.
|
|
225
|
+
PAUSED = "PAUSED"
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class StrategyStatusSource(StrValueEnum):
|
|
229
|
+
"""Who last set a strategy's status — the durability marker.
|
|
230
|
+
|
|
231
|
+
OPERATOR-set status is an explicit live decision (kill, disable, enable) and
|
|
232
|
+
must never be clobbered by config-driven reconciliation: a stale-wheel boot
|
|
233
|
+
silently DISABLED promoted LIVE strategies (07-12), and a release reload
|
|
234
|
+
silently re-ACTIVATED a killed arm (07-16).
|
|
235
|
+
CONFIG marks status the engine derived from the wheel's production configs
|
|
236
|
+
(row creation at initial_status, retirement of rows absent from the wheel).
|
|
237
|
+
"""
|
|
238
|
+
|
|
239
|
+
CONFIG = "CONFIG"
|
|
240
|
+
OPERATOR = "OPERATOR"
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class StrategyErrorReason(StrValueEnum):
|
|
244
|
+
"""Classification of the cause when a strategy transitions to ERROR.
|
|
245
|
+
|
|
246
|
+
Used by the auto-resume path (periodic verification success) to distinguish
|
|
247
|
+
recoverable failures (transient fee fetch issue, stop timeout) from operator-
|
|
248
|
+
meaningful quarantine (risk guardrails tripping repeatedly). Non-recoverable
|
|
249
|
+
reasons stay parked in ERROR until an operator manually intervenes.
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
RISK_QUARANTINE = "RISK_QUARANTINE" # Hard risk violations tripped repeatedly
|
|
253
|
+
REJECTION_QUARANTINE = "REJECTION_QUARANTINE" # Order rejections tripped repeatedly
|
|
254
|
+
REJECTION_QUARANTINE_TERMINAL = "REJECTION_QUARANTINE_TERMINAL" # Rejection retries exhausted; operator reset
|
|
255
|
+
FEE_UNAVAILABLE = "FEE_UNAVAILABLE" # Missing venue/symbol fee data at start
|
|
256
|
+
STOP_TIMEOUT = "STOP_TIMEOUT" # Strategy didn't stop within deadline
|
|
257
|
+
CLOSE_ORDERS_FAILED = "CLOSE_ORDERS_FAILED" # Failed to cancel/close on shutdown
|
|
258
|
+
INIT_FAILURE = "INIT_FAILURE" # Strategy failed to initialize at boot
|
|
259
|
+
UNKNOWN = "UNKNOWN" # Uncategorized / catch-all
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class ExecutionMode(StrValueEnum):
|
|
263
|
+
"""Strategy execution mode determining when strategy logic runs"""
|
|
264
|
+
|
|
265
|
+
TIMER = "TIMER" # Execute at fixed time intervals
|
|
266
|
+
MARKET_DRIVEN = "MARKET_DRIVEN" # Execute on market data updates
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# --- State --- #
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
class EntityType(StrValueEnum):
|
|
273
|
+
"""Types of entities that can be validated"""
|
|
274
|
+
|
|
275
|
+
ORDER = "order"
|
|
276
|
+
FILL = "fill"
|
|
277
|
+
TRANSFER = "transfer"
|
|
278
|
+
BALANCE = "balance"
|
|
279
|
+
POSITION = "position"
|
|
280
|
+
STRATEGY = "strategy"
|
|
281
|
+
# Add more as needed
|
|
282
|
+
# create_order_request
|
|
283
|
+
# cancel_order_request
|
|
284
|
+
# transaction
|
|
File without changes
|