synpath 0.7.2__tar.gz → 0.8.1__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.
- {synpath-0.7.2 → synpath-0.8.1}/PKG-INFO +5 -4
- {synpath-0.7.2 → synpath-0.8.1}/README.md +4 -3
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/src/router.rs +5 -5
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/router.rs +7 -7
- {synpath-0.7.2 → synpath-0.8.1}/pyproject.toml +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/__init__.py +3 -3
- synpath-0.8.1/synpath/_deprecated.py +95 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/bucket.py +4 -2
- {synpath-0.7.2 → synpath-0.8.1}/synpath/client.py +6 -4
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/engine.py +14 -5
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/eod.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/journal.py +54 -9
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/ledger.py +13 -13
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/__init__.py +2 -2
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/base.py +27 -17
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/iceberg.py +4 -4
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/manager.py +8 -7
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/oco.py +22 -22
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/peg.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/routed.py +18 -18
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/stop.py +98 -47
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/taker.py +8 -8
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/twap.py +7 -7
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/paper.py +42 -40
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/reconcile.py +4 -4
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/risk.py +6 -6
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/router.py +46 -40
- {synpath-0.7.2 → synpath-0.8.1}/synpath/history.py +8 -2
- {synpath-0.7.2 → synpath-0.8.1}/synpath/hyperliquid.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/kalshi.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/limitless.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/polymarket.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/predict_fun.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/remote.py +3 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/trading.py +9 -2
- {synpath-0.7.2 → synpath-0.8.1}/synpath/sx_bet.py +2 -2
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/__init__.py +2 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/base.py +7 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/hyperliquid.py +18 -18
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/instruments.py +10 -10
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/kalshi.py +24 -24
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/limitless.py +17 -17
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/money.py +20 -13
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/opinion.py +14 -14
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/polymarket.py +25 -22
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/polymarket_us.py +14 -14
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/polymarket_us_exchange.py +11 -11
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/predict_fun.py +17 -17
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/sx_bet.py +14 -14
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/types.py +60 -12
- {synpath-0.7.2 → synpath-0.8.1}/synpath/types.py +19 -5
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/base.py +4 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/hyperliquid.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/kalshi.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/opinion.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/polymarket.py +1 -1
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/polymarket_us.py +2 -2
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/sx_bet.py +2 -2
- {synpath-0.7.2 → synpath-0.8.1}/Cargo.toml +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/LICENSE +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/Cargo.lock +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/Cargo.toml +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/src/kalshi.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/src/lib.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/src/objects.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/src/polymarket.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/src/pyjson.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/src/signing.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/bindings/python/src/venues.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/build_backend/synpath_build.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/Cargo.lock +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/Cargo.toml +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/examples/decode_timing.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/book.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/kalshi.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/lib.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/opinion.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/polymarket.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/polymarket_us.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/signing.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/crates/synpath-core/src/wire.rs +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/__main__.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/_native.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/base.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/__init__.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/__main__.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/alerts.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/events.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/fair_values.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/feeds.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/engine/orders/day.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/errors.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/hosted.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/hosted_auth.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ids.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/matching.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/opinion.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/polymarket_us.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/__init__.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/__main__.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/api.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/errors.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/local.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/models.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/serve.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/server/store.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/__main__.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/credentials.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/errors.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/hyperliquid_signing.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/init.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/limiter.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/limitless_signing.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/opinion_signing.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/polymarket_signing.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/predict_fun_signing.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/trading/sx_bet_signing.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/__init__.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/grpc.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/limitless.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/polymarket_us_exchange.py +0 -0
- {synpath-0.7.2 → synpath-0.8.1}/synpath/ws/predict_fun.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: synpath
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.8.1
|
|
4
4
|
Classifier: Development Status :: 3 - Alpha
|
|
5
5
|
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
6
6
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -190,7 +190,7 @@ from synpath import KalshiTrading, OrderRequest, Side, load_credentials, require
|
|
|
190
190
|
async with KalshiTrading(require("kalshi", load_credentials())) as kalshi:
|
|
191
191
|
order = await kalshi.create_order(OrderRequest(
|
|
192
192
|
market_id=market.id, side=Side.BUY, # buy takes YES, sell takes NO
|
|
193
|
-
|
|
193
|
+
quantity=Decimal("10"), price=Decimal("0.42"), # always the YES price
|
|
194
194
|
))
|
|
195
195
|
```
|
|
196
196
|
|
|
@@ -210,10 +210,11 @@ async with PolymarketMarketStream() as stream:
|
|
|
210
210
|
|
|
211
211
|
```python
|
|
212
212
|
synpath.match_market("kalshi:KXHIGHTATL-26SEP23-B80") # .matched: the same question on another venue, or None
|
|
213
|
+
synpath.match_market("kalshi:KXMLB-26-LAD", venue="polymarket_us") # on one venue in particular
|
|
213
214
|
synpath.match_event("kalshi:KXHIGHTATL-26SEP23") # each venue's events on the same event
|
|
214
215
|
```
|
|
215
216
|
|
|
216
|
-
Matching is hosted at `api.synpath.dev` and needs a Synpath API key (`synpath login`, then `synpath keys create`). A match is a deterministic parse both listings land on, not a similarity score, and `side_map` says when one venue asks the question the other way round. Crypto up-or-down markets are never matched, since each venue sets its own price to beat. Browse matched events at [synpath.dev](https://www.synpath.dev); API: [match a market](https://www.synpath.dev/docs/api-reference/matching/market), [match an event](https://www.synpath.dev/docs/api-reference/matching/event).
|
|
217
|
+
Matching covers Kalshi, Polymarket, Polymarket US, Opinion, Hyperliquid, predict.fun, Limitless and SX Bet. It is hosted at `api.synpath.dev` and needs a Synpath API key (`synpath login`, then `synpath keys create`). A match is a deterministic parse both listings land on, not a similarity score, and `side_map` says when one venue asks the question the other way round. Crypto up-or-down markets are never matched, since each venue sets its own price to beat. Browse matched events at [synpath.dev](https://www.synpath.dev); API: [match a market](https://www.synpath.dev/docs/api-reference/matching/market), [match an event](https://www.synpath.dev/docs/api-reference/matching/event).
|
|
217
218
|
|
|
218
219
|
**Smart order routing: one order across Kalshi and Polymarket**
|
|
219
220
|
|
|
@@ -232,7 +233,7 @@ async with KalshiTrading(require("kalshi", creds)) as kalshi, \
|
|
|
232
233
|
]))
|
|
233
234
|
# Both order books combined, each level net of fees, filled from the cheapest price outward
|
|
234
235
|
await engine.submit(OrderRequest(
|
|
235
|
-
market_id=bucket.market_id, side=Side.BUY,
|
|
236
|
+
market_id=bucket.market_id, side=Side.BUY, quantity=Decimal("500"),
|
|
236
237
|
type=OrderType.MARKET, price=Decimal("0.45"), # the worst price you accept
|
|
237
238
|
book="alpha",
|
|
238
239
|
))
|
|
@@ -144,7 +144,7 @@ from synpath import KalshiTrading, OrderRequest, Side, load_credentials, require
|
|
|
144
144
|
async with KalshiTrading(require("kalshi", load_credentials())) as kalshi:
|
|
145
145
|
order = await kalshi.create_order(OrderRequest(
|
|
146
146
|
market_id=market.id, side=Side.BUY, # buy takes YES, sell takes NO
|
|
147
|
-
|
|
147
|
+
quantity=Decimal("10"), price=Decimal("0.42"), # always the YES price
|
|
148
148
|
))
|
|
149
149
|
```
|
|
150
150
|
|
|
@@ -164,10 +164,11 @@ async with PolymarketMarketStream() as stream:
|
|
|
164
164
|
|
|
165
165
|
```python
|
|
166
166
|
synpath.match_market("kalshi:KXHIGHTATL-26SEP23-B80") # .matched: the same question on another venue, or None
|
|
167
|
+
synpath.match_market("kalshi:KXMLB-26-LAD", venue="polymarket_us") # on one venue in particular
|
|
167
168
|
synpath.match_event("kalshi:KXHIGHTATL-26SEP23") # each venue's events on the same event
|
|
168
169
|
```
|
|
169
170
|
|
|
170
|
-
Matching is hosted at `api.synpath.dev` and needs a Synpath API key (`synpath login`, then `synpath keys create`). A match is a deterministic parse both listings land on, not a similarity score, and `side_map` says when one venue asks the question the other way round. Crypto up-or-down markets are never matched, since each venue sets its own price to beat. Browse matched events at [synpath.dev](https://www.synpath.dev); API: [match a market](https://www.synpath.dev/docs/api-reference/matching/market), [match an event](https://www.synpath.dev/docs/api-reference/matching/event).
|
|
171
|
+
Matching covers Kalshi, Polymarket, Polymarket US, Opinion, Hyperliquid, predict.fun, Limitless and SX Bet. It is hosted at `api.synpath.dev` and needs a Synpath API key (`synpath login`, then `synpath keys create`). A match is a deterministic parse both listings land on, not a similarity score, and `side_map` says when one venue asks the question the other way round. Crypto up-or-down markets are never matched, since each venue sets its own price to beat. Browse matched events at [synpath.dev](https://www.synpath.dev); API: [match a market](https://www.synpath.dev/docs/api-reference/matching/market), [match an event](https://www.synpath.dev/docs/api-reference/matching/event).
|
|
171
172
|
|
|
172
173
|
**Smart order routing: one order across Kalshi and Polymarket**
|
|
173
174
|
|
|
@@ -186,7 +187,7 @@ async with KalshiTrading(require("kalshi", creds)) as kalshi, \
|
|
|
186
187
|
]))
|
|
187
188
|
# Both order books combined, each level net of fees, filled from the cheapest price outward
|
|
188
189
|
await engine.submit(OrderRequest(
|
|
189
|
-
market_id=bucket.market_id, side=Side.BUY,
|
|
190
|
+
market_id=bucket.market_id, side=Side.BUY, quantity=Decimal("500"),
|
|
190
191
|
type=OrderType.MARKET, price=Decimal("0.45"), # the worst price you accept
|
|
191
192
|
book="alpha",
|
|
192
193
|
))
|
|
@@ -135,17 +135,17 @@ pub(crate) fn router_levels(
|
|
|
135
135
|
#[pymethods]
|
|
136
136
|
impl RouterLevels {
|
|
137
137
|
/// `_walk`'s loop. Returns `(slots, remaining, reason)`, a slot being
|
|
138
|
-
/// `(market_id,
|
|
138
|
+
/// `(market_id, quantity, cost, fee, worst)`, or `None` when the arithmetic
|
|
139
139
|
/// would not be exact.
|
|
140
140
|
fn walk<'py>(
|
|
141
141
|
&self,
|
|
142
142
|
py: Python<'py>,
|
|
143
143
|
buy: bool,
|
|
144
|
-
|
|
144
|
+
quantity: &Bound<'py, PyAny>,
|
|
145
145
|
limit: &Bound<'py, PyAny>,
|
|
146
146
|
excluded: Vec<String>,
|
|
147
147
|
) -> PyResult<Option<Bound<'py, PyTuple>>> {
|
|
148
|
-
let (Ok(
|
|
148
|
+
let (Ok(quantity), Ok(limit)) = (from_py(quantity), from_py(limit)) else {
|
|
149
149
|
return Ok(None);
|
|
150
150
|
};
|
|
151
151
|
let mut skip = vec![false; self.members.len()];
|
|
@@ -154,7 +154,7 @@ impl RouterLevels {
|
|
|
154
154
|
skip[index] = excluded.iter().any(|e| e.as_str() == name.as_ref());
|
|
155
155
|
}
|
|
156
156
|
let Some((slots, remaining, reason)) =
|
|
157
|
-
router::walk(&self.levels, buy,
|
|
157
|
+
router::walk(&self.levels, buy, quantity, limit, &skip)
|
|
158
158
|
else {
|
|
159
159
|
return Ok(None);
|
|
160
160
|
};
|
|
@@ -162,7 +162,7 @@ impl RouterLevels {
|
|
|
162
162
|
for slot in slots {
|
|
163
163
|
rows.append((
|
|
164
164
|
self.members[slot.member].bind(py),
|
|
165
|
-
decimal(py, slot.
|
|
165
|
+
decimal(py, slot.quantity)?,
|
|
166
166
|
decimal(py, slot.cost)?,
|
|
167
167
|
decimal(py, slot.fee)?,
|
|
168
168
|
decimal(py, slot.worst)?,
|
|
@@ -89,7 +89,7 @@ pub fn sort(levels: &mut [Level], buy: bool) {
|
|
|
89
89
|
#[derive(Debug, Clone, PartialEq)]
|
|
90
90
|
pub struct Slot {
|
|
91
91
|
pub member: usize,
|
|
92
|
-
pub
|
|
92
|
+
pub quantity: Decimal,
|
|
93
93
|
/// Sum of net price times contracts.
|
|
94
94
|
pub cost: Decimal,
|
|
95
95
|
/// Sum of the per-contract fee times contracts.
|
|
@@ -117,17 +117,17 @@ impl Reason {
|
|
|
117
117
|
}
|
|
118
118
|
|
|
119
119
|
/// `_walk`'s loop: what each member's levels give, best first, up to
|
|
120
|
-
/// `
|
|
120
|
+
/// `quantity` and no worse than `limit` net. Slots come in the order members
|
|
121
121
|
/// were first taken from. `None` when the arithmetic would not be exact.
|
|
122
122
|
pub fn walk(
|
|
123
123
|
levels: &[Level],
|
|
124
124
|
buy: bool,
|
|
125
|
-
|
|
125
|
+
quantity: Decimal,
|
|
126
126
|
limit: Decimal,
|
|
127
127
|
excluded: &[bool],
|
|
128
128
|
) -> Option<(Vec<Slot>, Decimal, Reason)> {
|
|
129
129
|
let mut slots: Vec<Slot> = Vec::new();
|
|
130
|
-
let mut remaining =
|
|
130
|
+
let mut remaining = quantity;
|
|
131
131
|
let mut reason = Reason::Liquidity;
|
|
132
132
|
let mut stopped = false;
|
|
133
133
|
for level in levels {
|
|
@@ -155,7 +155,7 @@ pub fn walk(
|
|
|
155
155
|
None => {
|
|
156
156
|
slots.push(Slot {
|
|
157
157
|
member: level.member,
|
|
158
|
-
|
|
158
|
+
quantity: Decimal::ZERO,
|
|
159
159
|
cost: Decimal::ZERO,
|
|
160
160
|
fee: Decimal::ZERO,
|
|
161
161
|
worst: level.price,
|
|
@@ -164,7 +164,7 @@ pub fn walk(
|
|
|
164
164
|
}
|
|
165
165
|
};
|
|
166
166
|
let slot = &mut slots[index];
|
|
167
|
-
slot.
|
|
167
|
+
slot.quantity = add(slot.quantity, take)?;
|
|
168
168
|
slot.cost = add(slot.cost, mul(level.net, take)?)?;
|
|
169
169
|
slot.fee = add(slot.fee, mul(sub(level.net, level.price)?.abs(), take)?)?;
|
|
170
170
|
// `max`/`min` keep the first argument on a tie, as Python's do.
|
|
@@ -221,7 +221,7 @@ mod tests {
|
|
|
221
221
|
assert_eq!(reason, Reason::WorstPrice);
|
|
222
222
|
assert_eq!(remaining, d("15"));
|
|
223
223
|
assert_eq!(slots[0].member, 1);
|
|
224
|
-
assert_eq!(slots[1].
|
|
224
|
+
assert_eq!(slots[1].quantity, d("10"));
|
|
225
225
|
assert_eq!(slots[1].fee, d("0.10"));
|
|
226
226
|
}
|
|
227
227
|
|
|
@@ -9,7 +9,7 @@ backend-path = ["build_backend"]
|
|
|
9
9
|
|
|
10
10
|
[project]
|
|
11
11
|
name = "synpath"
|
|
12
|
-
version = "0.
|
|
12
|
+
version = "0.8.1"
|
|
13
13
|
description = "One API for prediction markets. Kalshi and Polymarket, normalized, with every price labelled by source and time."
|
|
14
14
|
readme = "README.md"
|
|
15
15
|
requires-python = ">=3.10"
|
|
@@ -80,7 +80,7 @@ from .types import (
|
|
|
80
80
|
TradesRangeResponse,
|
|
81
81
|
)
|
|
82
82
|
|
|
83
|
-
__version__ = "0.
|
|
83
|
+
__version__ = "0.8.1"
|
|
84
84
|
|
|
85
85
|
exchanges: dict[str, type[Exchange]] = {
|
|
86
86
|
"kalshi": Kalshi,
|
|
@@ -114,7 +114,7 @@ from .trading import (
|
|
|
114
114
|
OpinionTrading, HyperliquidTrading, PredictFunTrading, LimitlessTrading, SxBetTrading,
|
|
115
115
|
Account, Balance, EditRequest, FeeEstimate, Fill, HeldBy, Liquidity,
|
|
116
116
|
Order, OrderRequest, OrderStatus, OrderType, Position, PositionSide,
|
|
117
|
-
Precision, Settlement, SettlementState, Side, TimeInForce,
|
|
117
|
+
Precision, Settlement, SettlementState, Side, TimeInForce, TriggerSource,
|
|
118
118
|
CredentialsMissing, DuplicateClientOrderId, InsufficientFunds, InvalidOrder,
|
|
119
119
|
MarketHalted, OrderNotFound, OrderRejected, PermissionDenied,
|
|
120
120
|
RateBudgetExceeded, RiskRejected,
|
|
@@ -182,7 +182,7 @@ __all__ = [
|
|
|
182
182
|
"OpinionTrading", "HyperliquidTrading", "PredictFunTrading", "LimitlessTrading", "SxBetTrading",
|
|
183
183
|
"Account", "Balance", "EditRequest", "FeeEstimate", "Fill", "HeldBy", "Liquidity",
|
|
184
184
|
"Order", "OrderRequest", "OrderStatus", "OrderType", "Position", "PositionSide",
|
|
185
|
-
"Precision", "Settlement", "SettlementState", "Side", "TimeInForce",
|
|
185
|
+
"Precision", "Settlement", "SettlementState", "Side", "TimeInForce", "TriggerSource",
|
|
186
186
|
"CredentialsMissing", "DuplicateClientOrderId", "InsufficientFunds", "InvalidOrder",
|
|
187
187
|
"MarketHalted", "OrderNotFound", "OrderRejected", "PermissionDenied",
|
|
188
188
|
"RateBudgetExceeded", "RiskRejected",
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Old names kept working for one release, with a `DeprecationWarning`.
|
|
2
|
+
|
|
3
|
+
A number of contracts is `quantity` everywhere; it used to be `amount`. For
|
|
4
|
+
one release a caller who still writes the old name gets the new one and a
|
|
5
|
+
warning:
|
|
6
|
+
|
|
7
|
+
* model input: `OrderRequest(amount=5)` is `OrderRequest(quantity=5)`
|
|
8
|
+
(`renamed_fields`, which also gives the model a read-only `.amount`
|
|
9
|
+
property; `model_dump()` and JSON only ever carry `quantity`);
|
|
10
|
+
* keyword arguments: `fetch_fee_estimate(..., amount=5)`
|
|
11
|
+
(`renamed_kwargs`);
|
|
12
|
+
* plain attribute reads on dataclasses (`deprecated_property`).
|
|
13
|
+
|
|
14
|
+
TODO(0.9): remove this module and every use of it (search for
|
|
15
|
+
`_deprecated`).
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import functools
|
|
20
|
+
import inspect
|
|
21
|
+
import warnings
|
|
22
|
+
from typing import Any, Callable, Mapping, TypeVar
|
|
23
|
+
|
|
24
|
+
T = TypeVar("T")
|
|
25
|
+
|
|
26
|
+
QUANTITY = {"amount": "quantity"}
|
|
27
|
+
"""The rename every contract-count field and argument went through."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def warn(old: str, new: str, *, stacklevel: int = 3) -> None:
|
|
31
|
+
warnings.warn(f"`{old}` is deprecated, use `{new}`; it will be removed in the next release",
|
|
32
|
+
DeprecationWarning, stacklevel=stacklevel)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def rename_input(data: Any, renames: Mapping[str, str]) -> Any:
|
|
36
|
+
"""`data` (a model's raw input) with each old key under its new name."""
|
|
37
|
+
if not renames or not isinstance(data, dict) or not any(old in data for old in renames):
|
|
38
|
+
return data
|
|
39
|
+
data = dict(data)
|
|
40
|
+
for old, new in renames.items():
|
|
41
|
+
if old in data:
|
|
42
|
+
warn(old, new, stacklevel=5)
|
|
43
|
+
value = data.pop(old)
|
|
44
|
+
data.setdefault(new, value)
|
|
45
|
+
return data
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def deprecated_property(old: str, new: str) -> property:
|
|
49
|
+
"""A read-only `old` that returns `new`, with a warning."""
|
|
50
|
+
def read(self: Any) -> Any:
|
|
51
|
+
warn(old, new)
|
|
52
|
+
return getattr(self, new)
|
|
53
|
+
read.__name__ = old
|
|
54
|
+
read.__doc__ = f"Deprecated: use `{new}`."
|
|
55
|
+
return property(read)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def renamed_fields(renames: Mapping[str, str]) -> Callable[[type[T]], type[T]]:
|
|
59
|
+
"""Class decorator for a model whose fields were renamed. The model's
|
|
60
|
+
base runs `rename_input` with `__synpath_renamed__` before validation;
|
|
61
|
+
this adds the read-only old names."""
|
|
62
|
+
def decorate(cls: type[T]) -> type[T]:
|
|
63
|
+
merged = {**getattr(cls, "__synpath_renamed__", {}), **renames}
|
|
64
|
+
setattr(cls, "__synpath_renamed__", merged)
|
|
65
|
+
for old, new in renames.items():
|
|
66
|
+
setattr(cls, old, deprecated_property(old, new))
|
|
67
|
+
return cls
|
|
68
|
+
return decorate
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def renamed_kwargs(**renames: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
72
|
+
"""Function decorator: an old keyword argument is taken as the new one."""
|
|
73
|
+
def decorate(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
74
|
+
def fix(kwargs: dict[str, Any]) -> None:
|
|
75
|
+
for old, new in renames.items():
|
|
76
|
+
if old in kwargs:
|
|
77
|
+
warn(old, new, stacklevel=4)
|
|
78
|
+
value = kwargs.pop(old)
|
|
79
|
+
if new in kwargs:
|
|
80
|
+
raise TypeError(f"{fn.__name__}() got both `{old}` and `{new}`")
|
|
81
|
+
kwargs[new] = value
|
|
82
|
+
|
|
83
|
+
if inspect.iscoroutinefunction(fn):
|
|
84
|
+
@functools.wraps(fn)
|
|
85
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
86
|
+
fix(kwargs)
|
|
87
|
+
return await fn(*args, **kwargs)
|
|
88
|
+
return async_wrapper
|
|
89
|
+
|
|
90
|
+
@functools.wraps(fn)
|
|
91
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
92
|
+
fix(kwargs)
|
|
93
|
+
return fn(*args, **kwargs)
|
|
94
|
+
return wrapper
|
|
95
|
+
return decorate
|
|
@@ -20,6 +20,7 @@ from typing import Literal
|
|
|
20
20
|
from pydantic import Field
|
|
21
21
|
|
|
22
22
|
from . import ids
|
|
23
|
+
from ._deprecated import QUANTITY, renamed_fields
|
|
23
24
|
from .errors import BadRequest
|
|
24
25
|
from .trading.types import Side
|
|
25
26
|
from .types import BookSide, _Base
|
|
@@ -99,6 +100,7 @@ class BucketVenueFill(_Base):
|
|
|
99
100
|
average_price: Decimal | None = Field(description="In bucket terms")
|
|
100
101
|
|
|
101
102
|
|
|
103
|
+
@renamed_fields(QUANTITY) # TODO(0.9): remove
|
|
102
104
|
class BucketOrderReport(_Base):
|
|
103
105
|
"""What an order on a bucket has done, in bucket terms, and where."""
|
|
104
106
|
|
|
@@ -106,14 +108,14 @@ class BucketOrderReport(_Base):
|
|
|
106
108
|
bucket_id: str
|
|
107
109
|
status: str = Field(description="As on the order: `open`, `closed`, `canceled`, ...")
|
|
108
110
|
side: str
|
|
109
|
-
|
|
111
|
+
quantity: Decimal
|
|
110
112
|
worst_price: Decimal = Field(description="The worst price the order accepts, in bucket terms")
|
|
111
113
|
filled: Decimal
|
|
112
114
|
unfilled: Decimal
|
|
113
115
|
average_price: Decimal | None = Field(description="Weighted across every venue, in bucket terms")
|
|
114
116
|
fees_paid: Decimal
|
|
115
117
|
rounds: int = Field(description="Re-allocations that moved a leg")
|
|
116
|
-
stop_reason: str | None = Field(description="`worst_price` (nothing left at or better than it), `liquidity`, `
|
|
118
|
+
stop_reason: str | None = Field(description="`worst_price` (nothing left at or better than it), `liquidity`, `min_quantity`, `max_rounds`, `max_age`, "
|
|
117
119
|
"or null while working or once filled")
|
|
118
120
|
per_venue: list[BucketVenueFill]
|
|
119
121
|
detail: str | None = Field(default=None, description="Why the order was rejected or stopped, in words; "
|
|
@@ -10,7 +10,7 @@ book = client.fetch_order_book("polymarket:2252244", side="no")
|
|
|
10
10
|
client = synpath.Client(synpath.load_credentials()) # KALSHI_*, POLYMARKET_* from .env
|
|
11
11
|
async with client:
|
|
12
12
|
order = await client.create_order(OrderRequest(
|
|
13
|
-
market_id=market.id, side="buy", type="limit", price="0.05",
|
|
13
|
+
market_id=market.id, side="buy", type="limit", price="0.05", quantity=5,
|
|
14
14
|
))
|
|
15
15
|
await client.cancel_order(order.id, market_id=order.market_id)
|
|
16
16
|
```
|
|
@@ -39,6 +39,7 @@ from decimal import Decimal
|
|
|
39
39
|
from typing import Any, Iterable, Mapping
|
|
40
40
|
|
|
41
41
|
from . import ids
|
|
42
|
+
from ._deprecated import renamed_kwargs
|
|
42
43
|
from .base import Exchange
|
|
43
44
|
from .bucket import Bucket, BucketMember, BucketOrderReport, BucketPosition
|
|
44
45
|
from .errors import BadRequest
|
|
@@ -294,10 +295,11 @@ class Client:
|
|
|
294
295
|
market_id=market_id, since=since, limit=limit, cursor=cursor,
|
|
295
296
|
)
|
|
296
297
|
|
|
297
|
-
|
|
298
|
+
@renamed_kwargs(amount="quantity") # TODO(0.9): remove
|
|
299
|
+
async def fetch_fee_estimate(self, market_id: str, side: Side, price: Decimal, quantity: Decimal) -> FeeEstimate:
|
|
298
300
|
if self._remote and not self.credentials:
|
|
299
|
-
return await self._remote.fetch_fee_estimate(market_id, side, price,
|
|
300
|
-
return await self.trading(self._venue(market_id)).fetch_fee_estimate(market_id, side, price,
|
|
301
|
+
return await self._remote.fetch_fee_estimate(market_id, side, price, quantity)
|
|
302
|
+
return await self.trading(self._venue(market_id)).fetch_fee_estimate(market_id, side, price, quantity)
|
|
301
303
|
|
|
302
304
|
# -- housekeeping ---------------------------------------------------------
|
|
303
305
|
|
|
@@ -126,6 +126,9 @@ POST_ONLY_KINDS = ("iceberg", "peg", "twap")
|
|
|
126
126
|
something. A TWAP only in its `limit` style."""
|
|
127
127
|
|
|
128
128
|
|
|
129
|
+
STOP_KINDS = frozenset({"stop_market", "stop_limit", "trailing_stop"})
|
|
130
|
+
|
|
131
|
+
|
|
129
132
|
def check_managed_fields(request: OrderRequest, *, now_ms: int) -> None:
|
|
130
133
|
"""Refuse the order fields an engine-held type cannot honour, rather than
|
|
131
134
|
ignore them. `reduce_only` always passes to the children; `expires_at` is
|
|
@@ -140,6 +143,12 @@ def check_managed_fields(request: OrderRequest, *, now_ms: int) -> None:
|
|
|
140
143
|
f"a {kind} order takes liquidity")
|
|
141
144
|
if request.expires_at is not None and request.expires_at <= now_ms:
|
|
142
145
|
raise BadRequest("expires_at is in the past")
|
|
146
|
+
if kind in STOP_KINDS:
|
|
147
|
+
if "trigger_source" in request.params:
|
|
148
|
+
raise BadRequest("trigger_source is a field of the order, not a param")
|
|
149
|
+
for key in ("max_slippage", "protection"):
|
|
150
|
+
if key in request.params:
|
|
151
|
+
raise BadRequest(f"a {kind} takes no {key}: the engine sets the market child's worst price itself")
|
|
143
152
|
|
|
144
153
|
|
|
145
154
|
class Engine:
|
|
@@ -149,7 +158,7 @@ class Engine:
|
|
|
149
158
|
engine = Engine({"kalshi": kalshi_adapter}, EngineConfig(journal_path="trading.db"))
|
|
150
159
|
async with engine:
|
|
151
160
|
await engine.submit(OrderRequest(market_id="kalshi:KXX", side=Side.BUY,
|
|
152
|
-
|
|
161
|
+
quantity=Decimal("10"), price=Decimal("0.42"), book="alpha"))
|
|
153
162
|
```
|
|
154
163
|
"""
|
|
155
164
|
|
|
@@ -417,7 +426,7 @@ class Engine:
|
|
|
417
426
|
adapter = self._adapter(venue)
|
|
418
427
|
key = f"cancel:{venue}:{order_id}"
|
|
419
428
|
request = OrderRequest(
|
|
420
|
-
market_id=order.market_id, side=order.side,
|
|
429
|
+
market_id=order.market_id, side=order.side, quantity=order.remaining or order.quantity,
|
|
421
430
|
price=order.price, book=order.book, trader=order.trader, client_order_id=key,
|
|
422
431
|
)
|
|
423
432
|
account = order.account or self.accounts.get(venue) or Account(venue=venue)
|
|
@@ -453,7 +462,7 @@ class Engine:
|
|
|
453
462
|
key = request.client_order_id or f"edit:{venue}:{request.order_id}:{uuid.uuid4().hex[:8]}"
|
|
454
463
|
request = request.model_copy(update={"client_order_id": key})
|
|
455
464
|
intent_request = OrderRequest(
|
|
456
|
-
market_id=order.market_id, side=order.side,
|
|
465
|
+
market_id=order.market_id, side=order.side, quantity=request.quantity or order.quantity,
|
|
457
466
|
price=request.price if request.price is not None else order.price, book=order.book, trader=order.trader,
|
|
458
467
|
client_order_id=key,
|
|
459
468
|
)
|
|
@@ -686,9 +695,9 @@ class Engine:
|
|
|
686
695
|
"""A public print."""
|
|
687
696
|
market_id = getattr(event, "market_id", None) or event["market_id"]
|
|
688
697
|
price = getattr(event, "price", None) or event["price"]
|
|
689
|
-
|
|
698
|
+
quantity = getattr(event, "quantity", None) or event.get("quantity", ZERO)
|
|
690
699
|
self.last_trade[market_id] = Decimal(str(price))
|
|
691
|
-
await self.orders.on_trade(market_id, Decimal(str(price)), Decimal(str(
|
|
700
|
+
await self.orders.on_trade(market_id, Decimal(str(price)), Decimal(str(quantity)))
|
|
692
701
|
|
|
693
702
|
async def on_settlement(self, settlement: Settlement) -> None:
|
|
694
703
|
realized = self.ledger.apply_settlement(settlement)
|
|
@@ -81,7 +81,7 @@ class EndOfDay:
|
|
|
81
81
|
since = engine.risk.day_start_ms
|
|
82
82
|
for fill in await engine.journal.fills(since_ts=since):
|
|
83
83
|
report.fills += 1
|
|
84
|
-
report.volume += fill.
|
|
84
|
+
report.volume += fill.quantity
|
|
85
85
|
report.fees += fill.fee or ZERO
|
|
86
86
|
|
|
87
87
|
marks = engine.fair_values.marks()
|
|
@@ -38,7 +38,7 @@ from typing import Any, AsyncIterator, Iterable
|
|
|
38
38
|
|
|
39
39
|
from ..trading.types import Account, Fill, Order, OrderRequest
|
|
40
40
|
|
|
41
|
-
SCHEMA_VERSION =
|
|
41
|
+
SCHEMA_VERSION = 4
|
|
42
42
|
|
|
43
43
|
SCHEMA = """
|
|
44
44
|
CREATE TABLE IF NOT EXISTS meta (
|
|
@@ -87,7 +87,7 @@ CREATE TABLE IF NOT EXISTS orders (
|
|
|
87
87
|
terminal INTEGER NOT NULL DEFAULT 0,
|
|
88
88
|
book TEXT,
|
|
89
89
|
trader TEXT,
|
|
90
|
-
|
|
90
|
+
quantity TEXT NOT NULL,
|
|
91
91
|
filled TEXT NOT NULL,
|
|
92
92
|
price TEXT,
|
|
93
93
|
parent_id TEXT,
|
|
@@ -108,7 +108,7 @@ CREATE TABLE IF NOT EXISTS fills (
|
|
|
108
108
|
market_id TEXT NOT NULL,
|
|
109
109
|
side TEXT NOT NULL,
|
|
110
110
|
price TEXT NOT NULL,
|
|
111
|
-
|
|
111
|
+
quantity TEXT NOT NULL,
|
|
112
112
|
fee TEXT,
|
|
113
113
|
settlement TEXT NOT NULL,
|
|
114
114
|
book TEXT,
|
|
@@ -193,6 +193,21 @@ def _dump(value: Any) -> str:
|
|
|
193
193
|
return json.dumps(value, default=str, separators=(",", ":"))
|
|
194
194
|
|
|
195
195
|
|
|
196
|
+
_RENAMED = {"amount": "quantity", "last_fill_amount": "last_fill_quantity"}
|
|
197
|
+
_VERBATIM = frozenset({"info", "raw", "tags"})
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _quantity_keys(value: Any) -> Any:
|
|
201
|
+
"""A payload written before 4 with this library's own `amount` keys
|
|
202
|
+
named `quantity`. A venue's raw record (`info`, `raw`) is left as the
|
|
203
|
+
venue sent it."""
|
|
204
|
+
if isinstance(value, dict):
|
|
205
|
+
return {_RENAMED.get(k, k): (v if k in _VERBATIM else _quantity_keys(v)) for k, v in value.items()}
|
|
206
|
+
if isinstance(value, list):
|
|
207
|
+
return [_quantity_keys(v) for v in value]
|
|
208
|
+
return value
|
|
209
|
+
|
|
210
|
+
|
|
196
211
|
def _text(value: Decimal | None) -> str | None:
|
|
197
212
|
return None if value is None else str(value)
|
|
198
213
|
|
|
@@ -331,10 +346,17 @@ class Journal:
|
|
|
331
346
|
|
|
332
347
|
2 -> 3: `orders.parent_id` (a child names its parent in a column, not
|
|
333
348
|
only inside its payload) and `managed_orders.account_key` nullable (a
|
|
334
|
-
parent across venues has no single account).
|
|
349
|
+
parent across venues has no single account).
|
|
350
|
+
|
|
351
|
+
3 -> 4: a number of contracts is `quantity`, never `amount`: the
|
|
352
|
+
`orders` and `fills` columns are renamed and the stored payloads
|
|
353
|
+
(orders, fills, intents, engine-held parents) rewritten to the new
|
|
354
|
+
names. The append-only `events` log keeps what it said at the time."""
|
|
335
355
|
orders = await self._columns("orders")
|
|
336
356
|
if "parent_id" not in orders:
|
|
337
357
|
await self._db.execute("ALTER TABLE orders ADD COLUMN parent_id TEXT")
|
|
358
|
+
if "amount" in orders or "amount" in await self._columns("fills"):
|
|
359
|
+
await self._rename_amount_to_quantity()
|
|
338
360
|
managed = await self._columns("managed_orders")
|
|
339
361
|
if managed.get("account_key", {}).get("notnull"):
|
|
340
362
|
# SQLite cannot drop NOT NULL in place: rebuild, copy, swap.
|
|
@@ -366,6 +388,29 @@ class Journal:
|
|
|
366
388
|
await self._db.execute("ROLLBACK")
|
|
367
389
|
raise
|
|
368
390
|
|
|
391
|
+
async def _rename_amount_to_quantity(self) -> None:
|
|
392
|
+
await self._db.execute("BEGIN IMMEDIATE")
|
|
393
|
+
try:
|
|
394
|
+
for table in ("orders", "fills"):
|
|
395
|
+
if "amount" in await self._columns(table):
|
|
396
|
+
await self._db.execute(f"ALTER TABLE {table} RENAME COLUMN amount TO quantity")
|
|
397
|
+
for table, column in (("orders", "payload"), ("fills", "payload"),
|
|
398
|
+
("intents", "request"), ("managed_orders", "payload")):
|
|
399
|
+
async with self._db.execute(f"SELECT rowid, {column} FROM {table}") as cursor:
|
|
400
|
+
rows = await cursor.fetchall()
|
|
401
|
+
for row in rows:
|
|
402
|
+
try:
|
|
403
|
+
before = json.loads(row[column])
|
|
404
|
+
except (TypeError, ValueError):
|
|
405
|
+
continue
|
|
406
|
+
after = _quantity_keys(before)
|
|
407
|
+
if after != before:
|
|
408
|
+
await self._db.execute(f"UPDATE {table} SET {column}=? WHERE rowid=?", (_dump(after), row["rowid"]))
|
|
409
|
+
await self._db.execute("COMMIT")
|
|
410
|
+
except Exception:
|
|
411
|
+
await self._db.execute("ROLLBACK")
|
|
412
|
+
raise
|
|
413
|
+
|
|
369
414
|
async def close(self) -> None:
|
|
370
415
|
if self.lease is not None and self._db is not None:
|
|
371
416
|
await self.release_lease()
|
|
@@ -526,19 +571,19 @@ class Journal:
|
|
|
526
571
|
try:
|
|
527
572
|
await self._db.execute(
|
|
528
573
|
"""INSERT INTO orders(venue, id, client_order_id, account_key, market_id, side,
|
|
529
|
-
status, terminal, book, trader,
|
|
574
|
+
status, terminal, book, trader, quantity, filled, price, parent_id, payload,
|
|
530
575
|
created_ts, updated_ts)
|
|
531
576
|
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
532
577
|
ON CONFLICT(venue, id) DO UPDATE SET
|
|
533
578
|
client_order_id=COALESCE(excluded.client_order_id, orders.client_order_id),
|
|
534
579
|
status=excluded.status, terminal=excluded.terminal, filled=excluded.filled,
|
|
535
|
-
price=excluded.price,
|
|
580
|
+
price=excluded.price, quantity=excluded.quantity, payload=excluded.payload,
|
|
536
581
|
book=COALESCE(excluded.book, orders.book), trader=COALESCE(excluded.trader, orders.trader),
|
|
537
582
|
parent_id=COALESCE(excluded.parent_id, orders.parent_id),
|
|
538
583
|
updated_ts=excluded.updated_ts""",
|
|
539
584
|
(order.venue, order.id, order.client_order_id, account_key, order.market_id,
|
|
540
585
|
_word(order.side), _word(order.status), 1 if order.is_terminal else 0, order.book, order.trader,
|
|
541
|
-
str(order.
|
|
586
|
+
str(order.quantity), str(order.filled), _text(order.price),
|
|
542
587
|
order.parent_id or order.tags.get("parent"), _dump(body),
|
|
543
588
|
order.created_at or stamp, stamp),
|
|
544
589
|
)
|
|
@@ -567,14 +612,14 @@ class Journal:
|
|
|
567
612
|
changed = existing is None or existing["settlement"] != _word(fill.settlement)
|
|
568
613
|
await self._db.execute(
|
|
569
614
|
"""INSERT INTO fills(venue, id, order_id, client_order_id, account_key, market_id,
|
|
570
|
-
side, price,
|
|
615
|
+
side, price, quantity, fee, settlement, book, trader, ts, payload)
|
|
571
616
|
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
572
617
|
ON CONFLICT(venue, id) DO UPDATE SET
|
|
573
618
|
settlement=excluded.settlement, fee=COALESCE(excluded.fee, fills.fee),
|
|
574
619
|
payload=excluded.payload,
|
|
575
620
|
book=COALESCE(fills.book, excluded.book), trader=COALESCE(fills.trader, excluded.trader)""",
|
|
576
621
|
(fill.venue, fill.id, fill.order_id, fill.client_order_id, account_key, fill.market_id,
|
|
577
|
-
_word(fill.side), str(fill.price), str(fill.
|
|
622
|
+
_word(fill.side), str(fill.price), str(fill.quantity), _text(fill.fee),
|
|
578
623
|
_word(fill.settlement), book, trader, fill.timestamp or stamp, _dump(body)),
|
|
579
624
|
)
|
|
580
625
|
if changed:
|
|
@@ -25,7 +25,7 @@ fair values the engine stores per account and instrument (`fair_values.py`),
|
|
|
25
25
|
not from a book this module cannot see. Without a mark a position reports
|
|
26
26
|
its cost and no unrealized number, rather than a made-up one.
|
|
27
27
|
|
|
28
|
-
Settlement closes a position at 1 or 0 and moves the whole remaining
|
|
28
|
+
Settlement closes a position at 1 or 0 and moves the whole remaining quantity
|
|
29
29
|
into realized.
|
|
30
30
|
"""
|
|
31
31
|
from __future__ import annotations
|
|
@@ -99,18 +99,18 @@ class PositionState:
|
|
|
99
99
|
unreal = self.unrealized(mark) or ZERO
|
|
100
100
|
return self.realized + unreal
|
|
101
101
|
|
|
102
|
-
def apply(self, *, side: Side, price: Decimal,
|
|
102
|
+
def apply(self, *, side: Side, price: Decimal, quantity: Decimal, fee: Decimal | None, ts: int | None) -> Decimal:
|
|
103
103
|
"""Apply one fill already converted to the YES leg. Returns the profit
|
|
104
104
|
realized by this fill, fee included."""
|
|
105
|
-
signed =
|
|
105
|
+
signed = quantity if side == Side.BUY else -quantity
|
|
106
106
|
realized = ZERO
|
|
107
107
|
if self.contracts == 0 or (self.contracts > 0) == (signed > 0):
|
|
108
108
|
# Opening or adding: weighted average of what it cost.
|
|
109
|
-
total = abs(self.contracts) +
|
|
110
|
-
self.average_cost = ((self.average_cost * abs(self.contracts)) + (price *
|
|
109
|
+
total = abs(self.contracts) + quantity
|
|
110
|
+
self.average_cost = ((self.average_cost * abs(self.contracts)) + (price * quantity)) / total if total else ZERO
|
|
111
111
|
self.contracts += signed
|
|
112
112
|
else:
|
|
113
|
-
closing = min(
|
|
113
|
+
closing = min(quantity, abs(self.contracts))
|
|
114
114
|
direction = ONE if self.contracts > 0 else -ONE
|
|
115
115
|
realized += (price - self.average_cost) * closing * direction
|
|
116
116
|
self.contracts += signed
|
|
@@ -123,13 +123,13 @@ class PositionState:
|
|
|
123
123
|
self.fees += fee
|
|
124
124
|
realized -= fee
|
|
125
125
|
self.realized += realized
|
|
126
|
-
self.volume +=
|
|
126
|
+
self.volume += quantity
|
|
127
127
|
if side == Side.BUY:
|
|
128
|
-
self.bought +=
|
|
128
|
+
self.bought += quantity
|
|
129
129
|
else:
|
|
130
|
-
self.sold +=
|
|
130
|
+
self.sold += quantity
|
|
131
131
|
held = "yes" if side == Side.BUY else "no"
|
|
132
|
-
self.inventory[held] = self.inventory.get(held, ZERO) +
|
|
132
|
+
self.inventory[held] = self.inventory.get(held, ZERO) + quantity
|
|
133
133
|
self.fills += 1
|
|
134
134
|
if ts is not None:
|
|
135
135
|
self.last_ts = max(ts, self.last_ts or 0)
|
|
@@ -209,7 +209,7 @@ class Ledger:
|
|
|
209
209
|
return ZERO
|
|
210
210
|
state = self.state_for(fill, book=book)
|
|
211
211
|
# Fills arrive on the YES leg already: `sell` is the NO side at the YES price.
|
|
212
|
-
return state.apply(side=fill.side, price=fill.price,
|
|
212
|
+
return state.apply(side=fill.side, price=fill.price, quantity=fill.quantity, fee=fill.fee, ts=fill.timestamp)
|
|
213
213
|
|
|
214
214
|
def apply_fills(self, fills: Iterable[Fill], *, book: str | None = None) -> Decimal:
|
|
215
215
|
return sum((self.apply_fill(f, book=book) for f in fills), ZERO)
|
|
@@ -348,6 +348,6 @@ def _settlement_price(settlement: Settlement, face_value: Decimal) -> Decimal:
|
|
|
348
348
|
return ZERO
|
|
349
349
|
if settlement.won is not None:
|
|
350
350
|
return face_value if settlement.won else ZERO
|
|
351
|
-
if settlement.payout is not None and settlement.
|
|
352
|
-
return Decimal(settlement.payout) / Decimal(settlement.
|
|
351
|
+
if settlement.payout is not None and settlement.quantity:
|
|
352
|
+
return Decimal(settlement.payout) / Decimal(settlement.quantity)
|
|
353
353
|
return ZERO
|