xtrading-models 0.5.0__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.
- xtrading_models-0.5.0/LICENSE +21 -0
- xtrading_models-0.5.0/PKG-INFO +60 -0
- xtrading_models-0.5.0/README.md +40 -0
- xtrading_models-0.5.0/pyproject.toml +34 -0
- xtrading_models-0.5.0/setup.cfg +4 -0
- xtrading_models-0.5.0/src/xtrading_models/__init__.py +22 -0
- xtrading_models-0.5.0/src/xtrading_models/bar.py +38 -0
- xtrading_models-0.5.0/src/xtrading_models/execution_result.py +36 -0
- xtrading_models-0.5.0/src/xtrading_models/fill.py +55 -0
- xtrading_models-0.5.0/src/xtrading_models/order.py +225 -0
- xtrading_models-0.5.0/src/xtrading_models.egg-info/PKG-INFO +60 -0
- xtrading_models-0.5.0/src/xtrading_models.egg-info/SOURCES.txt +16 -0
- xtrading_models-0.5.0/src/xtrading_models.egg-info/dependency_links.txt +1 -0
- xtrading_models-0.5.0/src/xtrading_models.egg-info/requires.txt +4 -0
- xtrading_models-0.5.0/src/xtrading_models.egg-info/top_level.txt +1 -0
- xtrading_models-0.5.0/tests/test_bar.py +153 -0
- xtrading_models-0.5.0/tests/test_fill.py +78 -0
- xtrading_models-0.5.0/tests/test_models.py +540 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yanir Taflev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: xtrading-models
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Shared trading models for XTrading ecosystem
|
|
5
|
+
Author-email: Yanir Taflev <yanirta+xtrading@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: trading,models,finance,algotrading,backtesting
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: pydantic>=2.0
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest; extra == "dev"
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# xtrading-models
|
|
22
|
+
|
|
23
|
+
Shared trading models for the XTrading ecosystem.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install xtrading-models
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from xtrading_models import MarketOrder, LimitOrder, BarData, UNSET_DOUBLE
|
|
35
|
+
|
|
36
|
+
# Create a market order
|
|
37
|
+
order = MarketOrder(action='BUY', totalQuantity=100)
|
|
38
|
+
|
|
39
|
+
# Create bar data
|
|
40
|
+
bar = BarData(
|
|
41
|
+
date=datetime.now(),
|
|
42
|
+
open=Decimal('100.00'),
|
|
43
|
+
high=Decimal('105.00'),
|
|
44
|
+
low=Decimal('99.00'),
|
|
45
|
+
close=Decimal('104.00'),
|
|
46
|
+
volume=1000000
|
|
47
|
+
)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Models
|
|
51
|
+
|
|
52
|
+
- **Order classes**: `Order`, `LimitOrder`, `MarketOrder`, `StopOrder`, `StopLimitOrder`, `TrailingStopMarket`, `TrailingStopLimit`
|
|
53
|
+
- **Bar data**: `BarData` - OHLCV candlestick representation
|
|
54
|
+
- **Execution**: `Execution`, `CommissionReport`, `Fill`
|
|
55
|
+
- **Results**: `ExecutionResult`
|
|
56
|
+
- **Sentinels**: `UNSET_DOUBLE`, `UNSET_INTEGER`
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# xtrading-models
|
|
2
|
+
|
|
3
|
+
Shared trading models for the XTrading ecosystem.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install xtrading-models
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from xtrading_models import MarketOrder, LimitOrder, BarData, UNSET_DOUBLE
|
|
15
|
+
|
|
16
|
+
# Create a market order
|
|
17
|
+
order = MarketOrder(action='BUY', totalQuantity=100)
|
|
18
|
+
|
|
19
|
+
# Create bar data
|
|
20
|
+
bar = BarData(
|
|
21
|
+
date=datetime.now(),
|
|
22
|
+
open=Decimal('100.00'),
|
|
23
|
+
high=Decimal('105.00'),
|
|
24
|
+
low=Decimal('99.00'),
|
|
25
|
+
close=Decimal('104.00'),
|
|
26
|
+
volume=1000000
|
|
27
|
+
)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Models
|
|
31
|
+
|
|
32
|
+
- **Order classes**: `Order`, `LimitOrder`, `MarketOrder`, `StopOrder`, `StopLimitOrder`, `TrailingStopMarket`, `TrailingStopLimit`
|
|
33
|
+
- **Bar data**: `BarData` - OHLCV candlestick representation
|
|
34
|
+
- **Execution**: `Execution`, `CommissionReport`, `Fill`
|
|
35
|
+
- **Results**: `ExecutionResult`
|
|
36
|
+
- **Sentinels**: `UNSET_DOUBLE`, `UNSET_INTEGER`
|
|
37
|
+
|
|
38
|
+
## License
|
|
39
|
+
|
|
40
|
+
MIT
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "xtrading-models"
|
|
3
|
+
version = "0.5.0"
|
|
4
|
+
description = "Shared trading models for XTrading ecosystem"
|
|
5
|
+
authors = [{name = "Yanir Taflev", email = "yanirta+xtrading@gmail.com"}]
|
|
6
|
+
license = {text = "MIT"}
|
|
7
|
+
readme = "README.md"
|
|
8
|
+
classifiers = [
|
|
9
|
+
"Programming Language :: Python :: 3.9",
|
|
10
|
+
"Programming Language :: Python :: 3.10",
|
|
11
|
+
"Programming Language :: Python :: 3.11",
|
|
12
|
+
"License :: OSI Approved :: MIT License",
|
|
13
|
+
"Operating System :: OS Independent"
|
|
14
|
+
]
|
|
15
|
+
keywords = ["trading", "models", "finance", "algotrading", "backtesting"]
|
|
16
|
+
requires-python = ">=3.10"
|
|
17
|
+
dependencies = [
|
|
18
|
+
"pydantic>=2.0"
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
dev = [
|
|
23
|
+
"pytest"
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["setuptools", "wheel"]
|
|
28
|
+
build-backend = "setuptools.build_meta"
|
|
29
|
+
|
|
30
|
+
[tool.setuptools]
|
|
31
|
+
package-dir = {"" = "src"}
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from .order import (
|
|
2
|
+
Order, LimitOrder, MarketOrder, StopOrder, StopLimitOrder,
|
|
3
|
+
TrailingOrder, TrailingStopMarket, TrailingStopLimit,
|
|
4
|
+
UNSET_DOUBLE, UNSET_INTEGER
|
|
5
|
+
)
|
|
6
|
+
from .bar import BarData
|
|
7
|
+
from .fill import Execution, CommissionReport, Fill
|
|
8
|
+
from .execution_result import ExecutionResult
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
# Orders
|
|
12
|
+
'Order', 'LimitOrder', 'MarketOrder', 'StopOrder', 'StopLimitOrder',
|
|
13
|
+
'TrailingOrder', 'TrailingStopMarket', 'TrailingStopLimit',
|
|
14
|
+
# Sentinels
|
|
15
|
+
'UNSET_DOUBLE', 'UNSET_INTEGER',
|
|
16
|
+
# Bar
|
|
17
|
+
'BarData',
|
|
18
|
+
# Fill
|
|
19
|
+
'Execution', 'CommissionReport', 'Fill',
|
|
20
|
+
# Result
|
|
21
|
+
'ExecutionResult'
|
|
22
|
+
]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from decimal import Decimal
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from pydantic import BaseModel, field_validator, model_validator
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BarData(BaseModel):
|
|
7
|
+
"""OHLCV bar data (IB-compatible) with validation."""
|
|
8
|
+
|
|
9
|
+
date: datetime
|
|
10
|
+
open: Decimal = Decimal('0')
|
|
11
|
+
high: Decimal = Decimal('0')
|
|
12
|
+
low: Decimal = Decimal('0')
|
|
13
|
+
close: Decimal = Decimal('0')
|
|
14
|
+
volume: int = 0
|
|
15
|
+
# average: Decimal = Decimal('0')
|
|
16
|
+
# barCount: int = 0
|
|
17
|
+
|
|
18
|
+
@field_validator('date')
|
|
19
|
+
@classmethod
|
|
20
|
+
def date_required(cls, v):
|
|
21
|
+
if v is None:
|
|
22
|
+
raise ValueError('date cannot be null')
|
|
23
|
+
return v
|
|
24
|
+
|
|
25
|
+
@model_validator(mode='after')
|
|
26
|
+
def validate_ohlc(self):
|
|
27
|
+
"""Validate OHLC relationships: High >= all, Low <= all."""
|
|
28
|
+
if self.high < self.low:
|
|
29
|
+
raise ValueError(f'High ({self.high}) must be >= Low ({self.low})')
|
|
30
|
+
if self.high < self.open:
|
|
31
|
+
raise ValueError(f'High ({self.high}) must be >= Open ({self.open})')
|
|
32
|
+
if self.high < self.close:
|
|
33
|
+
raise ValueError(f'High ({self.high}) must be >= Close ({self.close})')
|
|
34
|
+
if self.low > self.open:
|
|
35
|
+
raise ValueError(f'Low ({self.low}) must be <= Open ({self.open})')
|
|
36
|
+
if self.low > self.close:
|
|
37
|
+
raise ValueError(f'Low ({self.low}) must be <= Close ({self.close})')
|
|
38
|
+
return self
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Execution result model for order execution outcomes."""
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
|
|
4
|
+
from .order import Order
|
|
5
|
+
from .fill import Fill
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class ExecutionResult:
|
|
10
|
+
"""Result of executing one or more orders against a bar."""
|
|
11
|
+
fills: list[Fill] = field(default_factory=list)
|
|
12
|
+
pending_orders: list[Order] = field(default_factory=list)
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
def status(self) -> str:
|
|
16
|
+
"""Derive overall status from fills and pending.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
- 'PENDING': No fills yet (order not executed or pending)
|
|
20
|
+
- 'FILLED': All orders filled, nothing pending
|
|
21
|
+
- 'PARTIAL': Some fills with pending orders (e.g., stop triggered, limit pending)
|
|
22
|
+
"""
|
|
23
|
+
has_fills = len(self.fills) > 0
|
|
24
|
+
has_pending = len(self.pending_orders) > 0
|
|
25
|
+
|
|
26
|
+
if not has_fills and not has_pending:
|
|
27
|
+
# Should never happen - at minimum order should be pending
|
|
28
|
+
raise ValueError("Invalid ExecutionResult state: empty result")
|
|
29
|
+
if not has_fills and has_pending:
|
|
30
|
+
return 'PENDING' # Order(s) not executed yet
|
|
31
|
+
if has_fills and not has_pending:
|
|
32
|
+
return 'FILLED' # All done
|
|
33
|
+
if has_fills and has_pending:
|
|
34
|
+
return 'PARTIAL' # Parent filled, children pending
|
|
35
|
+
|
|
36
|
+
raise ValueError("Unexpected ExecutionResult state")
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from decimal import Decimal
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import NamedTuple, Optional
|
|
5
|
+
|
|
6
|
+
from .order import Order
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class Execution:
|
|
11
|
+
"""Record of an order execution."""
|
|
12
|
+
|
|
13
|
+
execId: str = ''
|
|
14
|
+
time: Optional[datetime] = None
|
|
15
|
+
acctNumber: str = ''
|
|
16
|
+
exchange: str = ''
|
|
17
|
+
side: str = ''
|
|
18
|
+
shares: float = 0.0
|
|
19
|
+
price: Decimal = Decimal('0')
|
|
20
|
+
permId: int = 0
|
|
21
|
+
clientId: int = 0
|
|
22
|
+
orderId: int = 0
|
|
23
|
+
liquidation: int = 0
|
|
24
|
+
cumQty: float = 0.0
|
|
25
|
+
avgPrice: Decimal = Decimal('0')
|
|
26
|
+
orderRef: str = ''
|
|
27
|
+
evRule: str = ''
|
|
28
|
+
evMultiplier: float = 0.0
|
|
29
|
+
modelCode: str = ''
|
|
30
|
+
lastLiquidity: int = 0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class CommissionReport:
|
|
35
|
+
"""Commission and P&L information for an execution."""
|
|
36
|
+
|
|
37
|
+
execId: str = ''
|
|
38
|
+
commission: Decimal = Decimal('0')
|
|
39
|
+
currency: str = ''
|
|
40
|
+
realizedPNL: Decimal = Decimal('0')
|
|
41
|
+
yield_: float = 0.0
|
|
42
|
+
yieldRedemptionDate: int = 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Fill(NamedTuple):
|
|
46
|
+
"""
|
|
47
|
+
Combines order, execution, and commission into a single record.
|
|
48
|
+
IB-compatible nested object.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
order: Order
|
|
52
|
+
execution: Execution
|
|
53
|
+
commissionReport: CommissionReport
|
|
54
|
+
time: datetime
|
|
55
|
+
parentId: int = 0
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
from decimal import Decimal
|
|
2
|
+
from typing import Optional, ClassVar
|
|
3
|
+
from pydantic import BaseModel, Field, model_validator, field_validator
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
UNSET_DOUBLE = Decimal('inf')
|
|
7
|
+
UNSET_INTEGER = 2**31 - 1
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Order(BaseModel):
|
|
11
|
+
"""Base order class for trading."""
|
|
12
|
+
|
|
13
|
+
model_config = {
|
|
14
|
+
'arbitrary_types_allowed': True,
|
|
15
|
+
'validate_assignment': True, # Validate on mutation
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
_next_order_id: ClassVar[int] = 1
|
|
19
|
+
|
|
20
|
+
orderId: int = Field(default=0)
|
|
21
|
+
clientId: int = 0
|
|
22
|
+
action: str = ''
|
|
23
|
+
totalQuantity: float = 0.0
|
|
24
|
+
orderType: str = ''
|
|
25
|
+
price: Decimal = Field(default=UNSET_DOUBLE, allow_inf_nan=True)
|
|
26
|
+
tif: str = ''
|
|
27
|
+
goodTillDate: str = ''
|
|
28
|
+
goodAfterTime: str = ''
|
|
29
|
+
ocaGroup: str = ''
|
|
30
|
+
orderRef: str = ''
|
|
31
|
+
parentId: int = UNSET_INTEGER
|
|
32
|
+
transmit: bool = True
|
|
33
|
+
children: list['Order'] = Field(default_factory=list)
|
|
34
|
+
|
|
35
|
+
@field_validator('price', mode='before')
|
|
36
|
+
@classmethod
|
|
37
|
+
def allow_unset_price(cls, v):
|
|
38
|
+
"""Allow UNSET_DOUBLE sentinel value."""
|
|
39
|
+
return v
|
|
40
|
+
|
|
41
|
+
def model_post_init(self, __context) -> None:
|
|
42
|
+
"""Auto-assign orderId after initialization."""
|
|
43
|
+
if self.orderId == 0:
|
|
44
|
+
self.orderId = Order._next_order_id
|
|
45
|
+
Order._next_order_id += 1
|
|
46
|
+
|
|
47
|
+
def add_child(self, child: 'Order') -> None:
|
|
48
|
+
"""Add a child order and set its parentId."""
|
|
49
|
+
child.parentId = self.orderId
|
|
50
|
+
self.children.append(child)
|
|
51
|
+
|
|
52
|
+
class LimitOrder(Order):
|
|
53
|
+
"""Limit order."""
|
|
54
|
+
|
|
55
|
+
@field_validator('price', mode='before')
|
|
56
|
+
@classmethod
|
|
57
|
+
def allow_unset_price(cls, v):
|
|
58
|
+
"""Allow UNSET_DOUBLE sentinel value."""
|
|
59
|
+
return v
|
|
60
|
+
|
|
61
|
+
def __init__(self, action: str, totalQuantity: float, price: Decimal, **kwargs):
|
|
62
|
+
super().__init__(
|
|
63
|
+
orderType='LMT',
|
|
64
|
+
action=action,
|
|
65
|
+
totalQuantity=totalQuantity,
|
|
66
|
+
price=price,
|
|
67
|
+
**kwargs
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
class MarketOrder(Order):
|
|
71
|
+
"""Market order."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, action: str, totalQuantity: float, **kwargs):
|
|
74
|
+
super().__init__(
|
|
75
|
+
orderType='MKT',
|
|
76
|
+
action=action,
|
|
77
|
+
totalQuantity=totalQuantity,
|
|
78
|
+
**kwargs
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
class StopOrder(Order):
|
|
82
|
+
"""Stop order implemented as Stop with Market child."""
|
|
83
|
+
|
|
84
|
+
def __init__(self, action: str, totalQuantity: float, stopPrice: Decimal, **kwargs):
|
|
85
|
+
# Initialize as a Stop order (parent)
|
|
86
|
+
super().__init__(
|
|
87
|
+
orderType='STP',
|
|
88
|
+
action=action,
|
|
89
|
+
totalQuantity=totalQuantity,
|
|
90
|
+
price=stopPrice,
|
|
91
|
+
**kwargs
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# Create Market child order (orderId auto-assigned)
|
|
95
|
+
market_child = MarketOrder(
|
|
96
|
+
action=action,
|
|
97
|
+
totalQuantity=totalQuantity
|
|
98
|
+
)
|
|
99
|
+
self.add_child(market_child)
|
|
100
|
+
|
|
101
|
+
class StopLimitOrder(Order):
|
|
102
|
+
"""Stop limit order implemented as Stop with Limit child."""
|
|
103
|
+
|
|
104
|
+
def __init__(self, action: str, totalQuantity: float, limitPrice: Decimal, stopPrice: Decimal, **kwargs):
|
|
105
|
+
# Initialize as a Stop order (parent)
|
|
106
|
+
super().__init__(
|
|
107
|
+
orderType='STP LMT', # Preserve backward compatibility
|
|
108
|
+
action=action,
|
|
109
|
+
totalQuantity=totalQuantity,
|
|
110
|
+
price=stopPrice,
|
|
111
|
+
**kwargs
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Create Limit child order (orderId auto-assigned)
|
|
115
|
+
limit_child = LimitOrder(
|
|
116
|
+
action=action,
|
|
117
|
+
totalQuantity=totalQuantity,
|
|
118
|
+
price=limitPrice
|
|
119
|
+
)
|
|
120
|
+
self.add_child(limit_child)
|
|
121
|
+
|
|
122
|
+
class TrailingOrder(Order):
|
|
123
|
+
"""Base class for trailing orders."""
|
|
124
|
+
|
|
125
|
+
trailingDistance: Optional[Decimal] = None
|
|
126
|
+
trailingPercent: Optional[Decimal] = None
|
|
127
|
+
stopPrice: Optional[Decimal] = None
|
|
128
|
+
extremePrice: Optional[Decimal] = None
|
|
129
|
+
|
|
130
|
+
@model_validator(mode='after')
|
|
131
|
+
def validate_trailing_params(self):
|
|
132
|
+
"""Validate exactly one of trailingDistance or trailingPercent is set."""
|
|
133
|
+
if (self.trailingDistance is None and self.trailingPercent is None) or \
|
|
134
|
+
(self.trailingDistance is not None and self.trailingPercent is not None):
|
|
135
|
+
raise ValueError("Exactly one of trailingDistance or trailingPercent must be specified")
|
|
136
|
+
return self
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def __init__(self, orderType: str, action: str, totalQuantity: float, trailingDistance: Optional[Decimal] = None, trailingPercent: Optional[Decimal] = None, **kwargs):
|
|
140
|
+
super().__init__(
|
|
141
|
+
orderType=orderType,
|
|
142
|
+
action=action,
|
|
143
|
+
totalQuantity=totalQuantity,
|
|
144
|
+
trailingDistance=trailingDistance, # type: ignore
|
|
145
|
+
trailingPercent=trailingPercent, # type: ignore
|
|
146
|
+
**kwargs
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
class TrailingStopMarket(TrailingOrder):
|
|
150
|
+
"""Trailing stop market order with mutable state tracking.
|
|
151
|
+
|
|
152
|
+
Tracks the extreme price and adjusts stop price as market moves favorably.
|
|
153
|
+
When stop is hit, the child Market order is executed.
|
|
154
|
+
|
|
155
|
+
Supports two modes (exactly one must be specified):
|
|
156
|
+
- trailingDistance: Absolute trailing amount (e.g., trail by $2.00)
|
|
157
|
+
- trailingPercent: Percentage trailing (e.g., trail by 2%)
|
|
158
|
+
|
|
159
|
+
Attributes:
|
|
160
|
+
trailingDistance: Absolute distance from extreme to stop (optional)
|
|
161
|
+
trailingPercent: Percentage distance from extreme to stop (optional)
|
|
162
|
+
currentStopPrice: Current stop trigger price (mutable)
|
|
163
|
+
extremePrice: Best price seen so far (mutable)
|
|
164
|
+
children: Contains one MarketOrder child
|
|
165
|
+
"""
|
|
166
|
+
def __init__(self, action: str, totalQuantity: float, trailingDistance: Optional[Decimal] = None, trailingPercent: Optional[Decimal] = None, **kwargs):
|
|
167
|
+
super().__init__(
|
|
168
|
+
orderType='TRAIL',
|
|
169
|
+
action=action,
|
|
170
|
+
totalQuantity=totalQuantity,
|
|
171
|
+
trailingDistance=trailingDistance,
|
|
172
|
+
trailingPercent=trailingPercent,
|
|
173
|
+
**kwargs
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# Create Market child order (will be executed when stop triggers)
|
|
177
|
+
market_child = MarketOrder(
|
|
178
|
+
action=action,
|
|
179
|
+
totalQuantity=totalQuantity
|
|
180
|
+
)
|
|
181
|
+
self.add_child(market_child)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class TrailingStopLimit(TrailingOrder):
|
|
185
|
+
"""Trailing stop limit order with mutable state tracking.
|
|
186
|
+
|
|
187
|
+
Similar to TrailingStopMarket but the child is a Limit order.
|
|
188
|
+
|
|
189
|
+
Supports two modes (exactly one must be specified):
|
|
190
|
+
- trailingDistance: Absolute trailing amount (e.g., trail by $2.00)
|
|
191
|
+
- trailingPercent: Percentage trailing (e.g., trail by 2%)
|
|
192
|
+
|
|
193
|
+
Attributes:
|
|
194
|
+
trailingDistance: Absolute distance from extreme to stop (optional)
|
|
195
|
+
trailingPercent: Percentage distance from extreme to stop (optional)
|
|
196
|
+
limitOffset: Distance from stop to limit price (always positive)
|
|
197
|
+
currentStopPrice: Current stop trigger price (mutable)
|
|
198
|
+
extremePrice: Best price seen so far (mutable)
|
|
199
|
+
children: Contains one LimitOrder child (price set when triggered)
|
|
200
|
+
"""
|
|
201
|
+
|
|
202
|
+
limitOffset: Decimal = Decimal('0')
|
|
203
|
+
|
|
204
|
+
def __init__(self, action: str, totalQuantity: float,
|
|
205
|
+
limitOffset: Decimal,
|
|
206
|
+
trailingDistance: Optional[Decimal] = None,
|
|
207
|
+
trailingPercent: Optional[Decimal] = None,
|
|
208
|
+
**kwargs):
|
|
209
|
+
super().__init__(
|
|
210
|
+
orderType='TRAIL LIMIT',
|
|
211
|
+
action=action,
|
|
212
|
+
totalQuantity=totalQuantity,
|
|
213
|
+
trailingDistance=trailingDistance,
|
|
214
|
+
trailingPercent=trailingPercent,
|
|
215
|
+
limitOffset=limitOffset,
|
|
216
|
+
**kwargs
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
# Create Limit child order (price will be set when stop triggers)
|
|
220
|
+
limit_child = LimitOrder(
|
|
221
|
+
action=action,
|
|
222
|
+
totalQuantity=totalQuantity,
|
|
223
|
+
price=Decimal('0') # Placeholder, set when stop triggers
|
|
224
|
+
)
|
|
225
|
+
self.add_child(limit_child)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: xtrading-models
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Shared trading models for XTrading ecosystem
|
|
5
|
+
Author-email: Yanir Taflev <yanirta+xtrading@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: trading,models,finance,algotrading,backtesting
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: pydantic>=2.0
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest; extra == "dev"
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# xtrading-models
|
|
22
|
+
|
|
23
|
+
Shared trading models for the XTrading ecosystem.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install xtrading-models
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from xtrading_models import MarketOrder, LimitOrder, BarData, UNSET_DOUBLE
|
|
35
|
+
|
|
36
|
+
# Create a market order
|
|
37
|
+
order = MarketOrder(action='BUY', totalQuantity=100)
|
|
38
|
+
|
|
39
|
+
# Create bar data
|
|
40
|
+
bar = BarData(
|
|
41
|
+
date=datetime.now(),
|
|
42
|
+
open=Decimal('100.00'),
|
|
43
|
+
high=Decimal('105.00'),
|
|
44
|
+
low=Decimal('99.00'),
|
|
45
|
+
close=Decimal('104.00'),
|
|
46
|
+
volume=1000000
|
|
47
|
+
)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Models
|
|
51
|
+
|
|
52
|
+
- **Order classes**: `Order`, `LimitOrder`, `MarketOrder`, `StopOrder`, `StopLimitOrder`, `TrailingStopMarket`, `TrailingStopLimit`
|
|
53
|
+
- **Bar data**: `BarData` - OHLCV candlestick representation
|
|
54
|
+
- **Execution**: `Execution`, `CommissionReport`, `Fill`
|
|
55
|
+
- **Results**: `ExecutionResult`
|
|
56
|
+
- **Sentinels**: `UNSET_DOUBLE`, `UNSET_INTEGER`
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/xtrading_models/__init__.py
|
|
5
|
+
src/xtrading_models/bar.py
|
|
6
|
+
src/xtrading_models/execution_result.py
|
|
7
|
+
src/xtrading_models/fill.py
|
|
8
|
+
src/xtrading_models/order.py
|
|
9
|
+
src/xtrading_models.egg-info/PKG-INFO
|
|
10
|
+
src/xtrading_models.egg-info/SOURCES.txt
|
|
11
|
+
src/xtrading_models.egg-info/dependency_links.txt
|
|
12
|
+
src/xtrading_models.egg-info/requires.txt
|
|
13
|
+
src/xtrading_models.egg-info/top_level.txt
|
|
14
|
+
tests/test_bar.py
|
|
15
|
+
tests/test_fill.py
|
|
16
|
+
tests/test_models.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
xtrading_models
|