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.
Files changed (33) hide show
  1. trading_engine_interface/__init__.py +334 -0
  2. trading_engine_interface/common/__init__.py +0 -0
  3. trading_engine_interface/common/enums.py +163 -0
  4. trading_engine_interface/common/errors.py +259 -0
  5. trading_engine_interface/common/models/__init__.py +3 -0
  6. trading_engine_interface/common/models/base_api_model.py +14 -0
  7. trading_engine_interface/common/utils.py +20 -0
  8. trading_engine_interface/domain/__init__.py +8 -0
  9. trading_engine_interface/domain/fill_simulator.py +114 -0
  10. trading_engine_interface/domain/maker_fill.py +138 -0
  11. trading_engine_interface/domain/position_math.py +386 -0
  12. trading_engine_interface/examples/__init__.py +1 -0
  13. trading_engine_interface/examples/touch_bid_strategy.py +131 -0
  14. trading_engine_interface/py.typed +0 -0
  15. trading_engine_interface/runtime/__init__.py +32 -0
  16. trading_engine_interface/runtime/registry.py +298 -0
  17. trading_engine_interface/runtime/strategy.py +94 -0
  18. trading_engine_interface/trading_engine/__init__.py +0 -0
  19. trading_engine_interface/trading_engine/enums.py +284 -0
  20. trading_engine_interface/trading_engine/models/__init__.py +0 -0
  21. trading_engine_interface/trading_engine/models/accounting_models.py +412 -0
  22. trading_engine_interface/trading_engine/models/backtest_models.py +200 -0
  23. trading_engine_interface/trading_engine/models/market_models.py +452 -0
  24. trading_engine_interface/trading_engine/models/order_models.py +520 -0
  25. trading_engine_interface/trading_engine/models/position_breakdown_models.py +130 -0
  26. trading_engine_interface/trading_engine/models/position_models.py +230 -0
  27. trading_engine_interface/trading_engine/models/strategy_metrics_models.py +204 -0
  28. trading_engine_interface/trading_engine/models/strategy_models.py +1360 -0
  29. trading_engine_interface/trading_engine/order_rules.py +209 -0
  30. trading_engine_interface-0.56.25.dist-info/LICENSE +21 -0
  31. trading_engine_interface-0.56.25.dist-info/METADATA +112 -0
  32. trading_engine_interface-0.56.25.dist-info/RECORD +33 -0
  33. trading_engine_interface-0.56.25.dist-info/WHEEL +4 -0
@@ -0,0 +1,259 @@
1
+ from datetime import datetime, timezone
2
+ from enum import Enum, auto
3
+ from typing import Any, Dict, Optional
4
+
5
+ from httpx import ConnectError, ConnectTimeout, HTTPError, ReadTimeout
6
+
7
+
8
+ # TODO: consider the usage of error types;
9
+ # it seems we spend a lot of time defining and categorizing errors without clear usage
10
+ class ErrorType(Enum):
11
+ """Classification of domain error types."""
12
+
13
+ # TODO: consider split VALIDATION into: INPUT and OUTPUT or use STATE for output
14
+ VALIDATION = auto() # Input validation failed
15
+ # INVALID_RESPONSE = auto()
16
+ STATE = auto() # Invalid state for operation
17
+ NOT_FOUND = auto() # Resource doesn't exist
18
+ DECISION = auto() # Decision algorithm failed
19
+ EXECUTION = auto() # Operation execution failed
20
+ SYSTEM = auto() # System/infrastructure error
21
+ TEMPORARY = auto()
22
+
23
+
24
+ # --- Base --- #
25
+
26
+
27
+ class BaseError(Exception):
28
+ """Common base for all custom errors."""
29
+
30
+ def __init__(
31
+ self,
32
+ message: str,
33
+ *,
34
+ retry_after: Optional[float] = None,
35
+ cause: Optional[Exception] = None,
36
+ ) -> None:
37
+ super().__init__(message)
38
+ self.message = message
39
+ self.retry_after = retry_after
40
+ self.cause = cause
41
+ self.timestamp = datetime.now(timezone.utc)
42
+
43
+ @property
44
+ def is_retryable(self) -> bool:
45
+ return self.retry_after is not None
46
+
47
+
48
+ class DomainError(BaseError):
49
+ """Base class for all domain errors."""
50
+
51
+ def __init__(self, message: str, error_type: ErrorType, **kwargs: Any) -> None:
52
+ super().__init__(message, **kwargs)
53
+ self.error_type = error_type
54
+
55
+ def __str__(self) -> str:
56
+ parts = [f"{self.__class__.__name__}[{self.error_type.name}]: {self.message}"]
57
+ if self.retry_after is not None:
58
+ parts.append(f"retry_after={self.retry_after}s")
59
+ if self.cause:
60
+ parts.append(f"cause={repr(self.cause)}")
61
+ return " | ".join(parts)
62
+
63
+
64
+ class ApiError(BaseError):
65
+ """Base error for HTTP/DB API operations."""
66
+
67
+ def __init__(
68
+ self,
69
+ message: str,
70
+ *,
71
+ status_code: Optional[int] = None,
72
+ request: Optional[Dict[str, Any]] = None,
73
+ response: Optional[Dict[str, Any]] = None,
74
+ **kwargs: Any,
75
+ ) -> None:
76
+ super().__init__(message, **kwargs)
77
+ self.status_code = status_code
78
+ self.request = request
79
+ self.response = response
80
+
81
+ def __str__(self) -> str:
82
+ parts = [self.__class__.__name__]
83
+ if self.status_code:
84
+ parts[0] += f"[{self.status_code}]"
85
+ if self.request:
86
+ parts.append(f"request={self.request}")
87
+ if self.response:
88
+ parts.append(f"response={self.response}")
89
+ parts.append(f"message={self.message}")
90
+ if self.retry_after is not None:
91
+ parts.append(f"retry_after={self.retry_after}s")
92
+ if self.cause:
93
+ parts.append(f"cause={repr(self.cause)}")
94
+ return "\n".join(parts)
95
+
96
+
97
+ class ServiceError(Exception):
98
+ pass
99
+
100
+
101
+ # --- Generic API Request Errors --- #
102
+
103
+
104
+ class ApiRequestError(ApiError):
105
+ """API request validation error (4xx)."""
106
+
107
+ default_status = 400
108
+
109
+ def __init__(
110
+ self,
111
+ message: str,
112
+ *,
113
+ status_code: Optional[int] = default_status,
114
+ response: Optional[Dict[str, Any]] = None,
115
+ **kwargs: Any,
116
+ ) -> None:
117
+ super().__init__(message, status_code=status_code, response=response, **kwargs)
118
+
119
+
120
+ class ApiResponseError(ApiError):
121
+ """API response validation or parsing error."""
122
+
123
+ def __init__(self, message: str, response: Optional[Dict[str, Any]] = None, **kwargs: Any) -> None:
124
+ super().__init__(message, response=response, **kwargs)
125
+
126
+
127
+ class ApiConnectTimeout(ApiError):
128
+ """API connection timeout."""
129
+
130
+ default_status = 408
131
+ default_retry = 5.0
132
+
133
+ def __init__(
134
+ self,
135
+ message: str = "Connection timeout",
136
+ status_code: Optional[int] = default_status,
137
+ retry_after: Optional[float] = None,
138
+ **kwargs: Any,
139
+ ) -> None:
140
+ super().__init__(message, status_code=status_code, retry_after=retry_after, **kwargs)
141
+
142
+
143
+ class ApiReadTimeout(ApiError):
144
+ """API read timeout - request sent but response not received."""
145
+
146
+ default_status = 408
147
+
148
+ def __init__(
149
+ self,
150
+ message: str = "Read timeout",
151
+ status_code: Optional[int] = default_status,
152
+ **kwargs: Any,
153
+ ) -> None:
154
+ super().__init__(message, status_code=status_code, **kwargs)
155
+
156
+
157
+ class ApiConnectionError(ApiError):
158
+ """API connection failed."""
159
+
160
+ default_retry = 5.0
161
+
162
+ def __init__(
163
+ self,
164
+ message: str = "Connection failed",
165
+ retry_after: Optional[float] = default_retry,
166
+ **kwargs: Any,
167
+ ) -> None:
168
+ super().__init__(message, retry_after=retry_after, **kwargs)
169
+
170
+
171
+ class ApiRateLimitError(ApiError):
172
+ """API rate limit exceeded (429)."""
173
+
174
+ default_status = 429
175
+ default_retry = 60.0
176
+
177
+ def __init__(
178
+ self,
179
+ message: str = "Rate limit exceeded",
180
+ status_code: Optional[int] = default_status,
181
+ retry_after: Optional[float] = default_retry,
182
+ **kwargs: Any,
183
+ ) -> None:
184
+ super().__init__(message, status_code=status_code, retry_after=retry_after, **kwargs)
185
+
186
+
187
+ class ApiTemporaryError(ApiError):
188
+ """API temporary error that failed a valid request."""
189
+
190
+ default_status = 425
191
+ default_retry = 5.0
192
+
193
+ def __init__(
194
+ self,
195
+ message: str = "Temporary error",
196
+ status_code: Optional[int] = default_status,
197
+ retry_after: Optional[float] = default_retry,
198
+ **kwargs: Any,
199
+ ) -> None:
200
+ super().__init__(message, status_code=status_code, retry_after=retry_after, **kwargs)
201
+
202
+
203
+ class ApiServerError(ApiError):
204
+ """API server error (5xx)."""
205
+
206
+ default_status = 500
207
+
208
+ def __init__(
209
+ self,
210
+ message: str = "Internal server error",
211
+ *,
212
+ status_code: Optional[int] = default_status,
213
+ **kwargs: Any,
214
+ ) -> None:
215
+ super().__init__(message, status_code=status_code, **kwargs)
216
+
217
+
218
+ class ApiUnavailableError(ApiServerError):
219
+ """API service unavailable (503)."""
220
+
221
+ default_status = 503
222
+ default_retry = 30.0
223
+
224
+ def __init__(
225
+ self,
226
+ message: str = "Service unavailable",
227
+ status_code: Optional[int] = default_status,
228
+ retry_after: Optional[float] = default_retry,
229
+ **kwargs: Any,
230
+ ) -> None:
231
+ super().__init__(message, status_code=status_code, retry_after=retry_after, **kwargs)
232
+
233
+
234
+ def map_api_error(error: Exception, cls: str, method: str) -> ApiError:
235
+ """Map external errors to API errors with context."""
236
+ message = f"{cls}.{method}: {str(error)}"
237
+
238
+ if isinstance(error, ConnectTimeout):
239
+ return ApiConnectTimeout(message, cause=error)
240
+ elif isinstance(error, ReadTimeout):
241
+ return ApiReadTimeout(message, cause=error)
242
+ elif isinstance(error, ConnectError):
243
+ return ApiConnectionError(message, cause=error)
244
+ elif isinstance(error, HTTPError):
245
+ return ApiServerError(message, cause=error)
246
+ elif isinstance(error, ValueError):
247
+ return ApiRequestError(message, cause=error)
248
+ elif isinstance(error, ApiError):
249
+ # Preserve API error properties but update message with context
250
+ return error.__class__(
251
+ message,
252
+ status_code=error.status_code,
253
+ request=error.request,
254
+ response=error.response,
255
+ retry_after=error.retry_after,
256
+ cause=error.cause,
257
+ )
258
+ else:
259
+ return ApiServerError(message, cause=error)
@@ -0,0 +1,3 @@
1
+
2
+ __all__ = [
3
+ ]
@@ -0,0 +1,14 @@
1
+ from datetime import datetime
2
+ from typing import Optional
3
+
4
+ from pydantic import BaseModel, ConfigDict
5
+
6
+
7
+ class BaseApiModel(BaseModel):
8
+ id: Optional[int] = None
9
+ created_at: Optional[datetime] = None
10
+ updated_at: Optional[datetime] = None
11
+
12
+ model_config = ConfigDict(
13
+ from_attributes=True,
14
+ )
@@ -0,0 +1,20 @@
1
+ from datetime import datetime, timezone
2
+ from uuid import uuid4
3
+
4
+ """
5
+ This module should only contains utility using python built-in library
6
+ Don't include any business logic or state related code
7
+ """
8
+
9
+ # ID
10
+
11
+
12
+ def gen_id() -> str:
13
+ return uuid4().hex
14
+
15
+
16
+ # Time
17
+
18
+
19
+ def now() -> datetime:
20
+ return datetime.now(timezone.utc)
@@ -0,0 +1,8 @@
1
+ """Shared trading-domain computation (position math, fill/maker simulation).
2
+
3
+ Single source of truth for logic used by BOTH the live engine (accounting /
4
+ position / paper order services) and the backtest package — previously duplicated
5
+ byte-for-byte and guarded by parity tests. Lives in the interface package so
6
+ every consumer imports the same code, no sync. Modules import interface models from
7
+ their defining submodules (not the top-level package) to avoid a circular import.
8
+ """
@@ -0,0 +1,114 @@
1
+ """Shared fill simulation functions for backtest and paper trading.
2
+
3
+ Stateless computation: given (order params, order book, config), produce fill prices
4
+ and order book queries. Used by both BacktestGateway and SimulatedOrderService.
5
+ """
6
+
7
+ from decimal import Decimal
8
+
9
+ from trading_engine_interface.trading_engine.enums import Side
10
+ from trading_engine_interface.trading_engine.models.market_models import OrderBook
11
+
12
+
13
+ def compute_vwap_price(
14
+ side: Side,
15
+ quantity: Decimal,
16
+ order_book: OrderBook,
17
+ fallback_price: Decimal = Decimal("0"),
18
+ ) -> Decimal:
19
+ """Compute volume-weighted average fill price across order book depth levels.
20
+
21
+ For BUY: consume ask levels (ascending price) until quantity is filled.
22
+ For SELL: consume bid levels (descending price) until quantity is filled.
23
+ If OB depth is insufficient, averages all available liquidity.
24
+
25
+ Args:
26
+ side: Order side (BUY consumes asks, SELL consumes bids)
27
+ quantity: Quantity to fill
28
+ order_book: Current order book snapshot
29
+ fallback_price: Price to return when no liquidity exists at all
30
+
31
+ Returns:
32
+ Volume-weighted average price across consumed levels
33
+ """
34
+ remaining = quantity
35
+ cost = Decimal("0")
36
+
37
+ if side == Side.BUY:
38
+ levels = sorted(order_book.asks, key=lambda e: e.price)
39
+ else:
40
+ levels = sorted(order_book.bids, key=lambda e: e.price, reverse=True)
41
+
42
+ for level in levels:
43
+ take = min(remaining, level.quantity)
44
+ cost += take * level.price
45
+ remaining -= take
46
+ if remaining <= Decimal("0"):
47
+ break
48
+
49
+ filled = quantity - remaining
50
+ if filled <= Decimal("0"):
51
+ # No liquidity — use best price or fallback
52
+ if side == Side.BUY:
53
+ return order_book.best_ask_price or fallback_price
54
+ else:
55
+ return order_book.best_bid_price or fallback_price
56
+
57
+ return cost / filled
58
+
59
+
60
+ def apply_slippage(price: Decimal, side: Side, slippage_bps: int) -> Decimal:
61
+ """Apply slippage to a fill price. Worsens execution for the taker.
62
+
63
+ Args:
64
+ price: Base fill price
65
+ side: Order side (BUY slips up, SELL slips down)
66
+ slippage_bps: Slippage in basis points (1 bp = 0.01%)
67
+
68
+ Returns:
69
+ Price adjusted for slippage
70
+ """
71
+ if slippage_bps == 0:
72
+ return price
73
+ factor = Decimal(slippage_bps) / Decimal("10000")
74
+ if side == Side.BUY:
75
+ return price * (Decimal("1") + factor)
76
+ else:
77
+ return price * (Decimal("1") - factor)
78
+
79
+
80
+ def would_cross_book(side: Side, price: Decimal, order_book: OrderBook) -> bool:
81
+ """Check if a limit order at the given price would immediately match (cross the spread).
82
+
83
+ Args:
84
+ side: Order side
85
+ price: Limit price
86
+ order_book: Current order book snapshot
87
+
88
+ Returns:
89
+ True if the order would cross and fill immediately
90
+ """
91
+ if side == Side.BUY:
92
+ return any(ask.price <= price for ask in order_book.asks)
93
+ else:
94
+ return any(bid.price >= price for bid in order_book.bids)
95
+
96
+
97
+ def check_sufficient_liquidity(side: Side, quantity: Decimal, price: Decimal, order_book: OrderBook) -> bool:
98
+ """Check if order book has sufficient liquidity to fill the full quantity at the given price.
99
+
100
+ Args:
101
+ side: Order side
102
+ quantity: Required fill quantity
103
+ price: Limit price (only liquidity at or better than this price counts)
104
+ order_book: Current order book snapshot
105
+
106
+ Returns:
107
+ True if sufficient liquidity exists
108
+ """
109
+ if side == Side.BUY:
110
+ available_liquidity = sum(entry.quantity for entry in order_book.asks if entry.price <= price)
111
+ else:
112
+ available_liquidity = sum(entry.quantity for entry in order_book.bids if entry.price >= price)
113
+
114
+ return available_liquidity >= quantity
@@ -0,0 +1,138 @@
1
+ """Trade-through maker-fill kernel — when does a resting maker order fill?
2
+
3
+ A resting maker order at price ``P`` fills only when a *counter-side trade prints
4
+ through ``P``* — not when an order-book snapshot crosses it (the old, unrealistic
5
+ criterion). This module is the single source of that predicate, shared by:
6
+
7
+ - the backtest agg-trade path (trade-replay over a CSV tape), and
8
+ - the deployed paper ``SimulatedOrderService`` (replay over the live
9
+ public-trade buffer).
10
+
11
+ It lives in the domain tier (``app/domain/``) — below both ``app/services`` (live)
12
+ and the backtest harness — so neither depends "up" into the other. The backtest
13
+ package carries its own byte-identical copy (a parity test guards drift), exactly
14
+ like ``position_math``.
15
+
16
+ Pure functions over interface models. No service state, no I/O.
17
+
18
+ The irreducible uncertainty is **queue position**: a trade touching ``P`` does not
19
+ guarantee *our* fill — orders ahead of us in the queue fill first. We don't pretend
20
+ a point estimate; the caller picks a ``MakerFillAssumption`` and the result comes
21
+ with that assumption attached, so backtest output can report a band (optimistic ↔
22
+ conservative) rather than a false single number.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from dataclasses import dataclass
28
+ from decimal import Decimal
29
+ from typing import Iterable
30
+
31
+ from trading_engine_interface.common.enums import StrValueEnum
32
+ from trading_engine_interface.trading_engine.enums import Side
33
+
34
+
35
+ class MakerFillAssumption(StrValueEnum):
36
+ """Queue-position assumption for resting maker fills.
37
+
38
+ OPTIMISTIC: we are at the front of the queue — fill on the FIRST trade that
39
+ prints at/through our price. Upper bound on fill likelihood / earliest fill.
40
+ CONSERVATIVE: we are at the back — fill only once the cumulative volume that
41
+ traded at/through our price (after we rested) exceeds our order size, i.e.
42
+ the tape clearly traded *through* us, not merely *to* us. Lower bound.
43
+ """
44
+
45
+ OPTIMISTIC = "optimistic"
46
+ CONSERVATIVE = "conservative"
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class TradePrint:
51
+ """One executed trade from the tape, reduced to what the fill predicate needs.
52
+
53
+ ``price`` / ``quantity`` are the print's price and base size. Adapters build
54
+ these from their own tape type (backtest ``AggTrade``, paper public-trade
55
+ buffer) so the kernel stays dependency-free of either.
56
+ """
57
+
58
+ price: Decimal
59
+ quantity: Decimal
60
+
61
+
62
+ def _prints_through(order_side: Side, order_price: Decimal, trade_price: Decimal) -> bool:
63
+ """Does a trade at ``trade_price`` print through a resting order at ``order_price``?
64
+
65
+ A resting maker BUY at P is a bid; it fills when a SELL trade prints at/below P
66
+ (someone hit the bid). A resting maker SELL at P is an ask; it fills when a BUY
67
+ trade prints at/above P (someone lifted the ask). We don't carry the taker side
68
+ on the print — the price relation alone determines a through-print for a resting
69
+ order, which is what matters for fill eligibility:
70
+
71
+ - BUY (bid) at P → through when ``trade_price <= P``
72
+ - SELL (ask) at P → through when ``trade_price >= P``
73
+ """
74
+ if order_side == Side.BUY:
75
+ return trade_price <= order_price
76
+ return trade_price >= order_price
77
+
78
+
79
+ def through_volume(order_side: Side, order_price: Decimal, trades: Iterable[TradePrint]) -> Decimal:
80
+ """Total base volume in ``trades`` that prints THROUGH a resting order at
81
+ ``order_price`` (the rest is irrelevant to that order). Callers accumulate this
82
+ across match passes to drive ``maker_fill_quantity``'s ``prior_through``."""
83
+ return sum((t.quantity for t in trades if _prints_through(order_side, order_price, t.price)), Decimal(0))
84
+
85
+
86
+ def maker_fill_quantity(
87
+ order_side: Side,
88
+ order_price: Decimal,
89
+ order_quantity: Decimal,
90
+ trades: Iterable[TradePrint],
91
+ assumption: MakerFillAssumption,
92
+ queue_ahead: Decimal = Decimal(0),
93
+ prior_through: Decimal = Decimal(0),
94
+ ) -> Decimal:
95
+ """Return how much of a resting maker order fills given the trades that printed
96
+ while it rested.
97
+
98
+ All-or-nothing: the order either fully fills (``order_quantity``)
99
+ or does not (``Decimal(0)``). Partial-by-size fills are a deferred refinement.
100
+
101
+ ``queue_ahead`` is the base volume resting AHEAD of this order at its price
102
+ level — size at better prices plus size already queued at the same price — which
103
+ must trade through FIRST (FIFO) before our order is reached. Measured from a live
104
+ order book on the paper path; defaults to 0 where no real depth is
105
+ available (the backtest's synthetic 1-level book), which preserves the prior
106
+ behavior exactly.
107
+
108
+ ``prior_through`` is the through-volume already accumulated on earlier match
109
+ passes (callers track it via ``through_volume``). It seeds the cumulative count,
110
+ so a queue that needs more than one pass' worth of volume to clear still fills —
111
+ without it, a per-pass caller (the paper fill loop feeds only trades since its
112
+ cursor) could never accumulate past ``queue_ahead``. Defaults to 0 (single-shot
113
+ callers like the backtest, which feed a whole tick's trades at once).
114
+
115
+ - OPTIMISTIC: fills (full) once cumulative through-volume exceeds ``queue_ahead``
116
+ — i.e. as soon as the queue ahead clears (with ``queue_ahead=0``, the first
117
+ trade that prints through ``order_price``).
118
+ - CONSERVATIVE: fills (full) once cumulative through-volume exceeds
119
+ ``queue_ahead + order_quantity`` — the queue ahead AND our own size have to
120
+ trade through (the tape goes past us). Strictly greater: equal volume could be
121
+ consumed entirely by the queue + our resting size without trading beyond us.
122
+
123
+ ``trades`` must be in time order (the order they printed). Returns the filled
124
+ base quantity (0 or ``order_quantity``).
125
+ """
126
+ if order_quantity <= 0:
127
+ return Decimal(0)
128
+
129
+ # Volume that must print THROUGH our price before we're considered filled.
130
+ threshold = queue_ahead if assumption == MakerFillAssumption.OPTIMISTIC else queue_ahead + order_quantity
131
+ cumulative_through = prior_through
132
+ for t in trades:
133
+ if not _prints_through(order_side, order_price, t.price):
134
+ continue
135
+ cumulative_through += t.quantity
136
+ if cumulative_through > threshold:
137
+ return order_quantity
138
+ return Decimal(0)