tribulnation-evedex 0.1.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.
- tribulnation_evedex-0.1.0/LICENSE +21 -0
- tribulnation_evedex-0.1.0/PKG-INFO +74 -0
- tribulnation_evedex-0.1.0/README.md +61 -0
- tribulnation_evedex-0.1.0/pyproject.toml +16 -0
- tribulnation_evedex-0.1.0/setup.cfg +4 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/__init__.py +5 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/__init__.pyi +4 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/core.py +213 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/__init__.py +5 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/account.py +157 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/books.py +109 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/common.py +102 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/exchanges.py +180 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/history.py +173 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/markets.py +348 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/orders.py +157 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/market/venue.py +70 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/py.typed +0 -0
- tribulnation_evedex-0.1.0/src/tribulnation/evedex/report.py +125 -0
- tribulnation_evedex-0.1.0/src/tribulnation_evedex.egg-info/PKG-INFO +74 -0
- tribulnation_evedex-0.1.0/src/tribulnation_evedex.egg-info/SOURCES.txt +22 -0
- tribulnation_evedex-0.1.0/src/tribulnation_evedex.egg-info/dependency_links.txt +1 -0
- tribulnation_evedex-0.1.0/src/tribulnation_evedex.egg-info/requires.txt +2 -0
- tribulnation_evedex-0.1.0/src/tribulnation_evedex.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Tribulnation
|
|
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,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tribulnation-evedex
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tribulnation SDK implementation for EVEDEX perpetuals.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/tribulnation/sdk.git
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: tribulnation-sdk>=4.1.0
|
|
11
|
+
Requires-Dist: typed-evedex>=0.1.0
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
<p align="center">
|
|
15
|
+
<a href="https://tribulnation.com/sdk/docs/market/implementations/evedex">
|
|
16
|
+
<picture>
|
|
17
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://tribulnation.com/media/lockups/evedex-dark.svg">
|
|
18
|
+
<source media="(prefers-color-scheme: light)" srcset="https://tribulnation.com/media/lockups/evedex-light.svg">
|
|
19
|
+
<img alt="Tribulnation SDK EVEDEX" src="https://tribulnation.com/media/lockups/evedex-light.svg" width="520">
|
|
20
|
+
</picture>
|
|
21
|
+
</a>
|
|
22
|
+
</p>
|
|
23
|
+
|
|
24
|
+
<p align="center">
|
|
25
|
+
<em>Tribulnation SDK implementation for EVEDEX perpetuals.</em>
|
|
26
|
+
</p>
|
|
27
|
+
|
|
28
|
+
Perpetual Market and Report support for [EVEDEX](https://evedex.com/), built on
|
|
29
|
+
`typed-evedex`. Install with `pip install tribulnation-evedex`.
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from tribulnation.evedex import EvedexMarket
|
|
33
|
+
|
|
34
|
+
async with EvedexMarket.new() as venue:
|
|
35
|
+
perp = await venue.perp_exchange('perp')
|
|
36
|
+
market = await perp.market('BTCUSD')
|
|
37
|
+
book = await market.depth(levels=5)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
An API key reads the account; the wallet's private key also signs orders and opens the
|
|
41
|
+
private fills stream:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
venue = EvedexMarket.new(api_key='…') # account reads only
|
|
45
|
+
venue = EvedexMarket.new(private_key='0x…') # reads and trading
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`MarketSDK` resolves `EVEDEX_API_KEY` and `EVEDEX_PRIVATE_KEY`; `typed-evedex` also
|
|
49
|
+
fills an unset key from them when the other one is given.
|
|
50
|
+
|
|
51
|
+
1. One exchange, `perp`, on the production exchange (evedex.com). Market ids are
|
|
52
|
+
instrument names (`BTCUSD`); the collateral, fee and funding coin is `usdt`.
|
|
53
|
+
2. Public data: discovery, tickers (best bid and ask, last price, 24h volumes), rules,
|
|
54
|
+
depth, a shared book stream, candles in the six SDK intervals, index, `perp_stats`
|
|
55
|
+
and the next hourly funding settlement. No funding-rate history is published.
|
|
56
|
+
3. Account and trading: fees, order queries, open orders, trade history, positions,
|
|
57
|
+
collateral, leverage, available notional and remaining position limit with an API
|
|
58
|
+
key; `set_leverage` too. The fills stream, `MARKET` (an IOC limit) and `LIMIT`
|
|
59
|
+
orders and every cancellation method with the private key. EVEDEX refuses post-only
|
|
60
|
+
orders, so `POST_ONLY` raises `NotImplementedError`. Stream fills carry no fee, and
|
|
61
|
+
their ids differ from `trades_history`'s. Refusals
|
|
62
|
+
raise `OrderRejected`. Funding payments are not supported.
|
|
63
|
+
|
|
64
|
+
`Report` snapshots one account, its trading balance and positions and its wallet:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from tribulnation.evedex import Report
|
|
68
|
+
|
|
69
|
+
async with Report.new(api_key='…') as report:
|
|
70
|
+
record = await report.snapshot()
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
See [EVEDEX Market](../../../docs/market/implementations/evedex.md) for account
|
|
74
|
+
configuration through `MarketSDK` and venue-specific semantics.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://tribulnation.com/sdk/docs/market/implementations/evedex">
|
|
3
|
+
<picture>
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://tribulnation.com/media/lockups/evedex-dark.svg">
|
|
5
|
+
<source media="(prefers-color-scheme: light)" srcset="https://tribulnation.com/media/lockups/evedex-light.svg">
|
|
6
|
+
<img alt="Tribulnation SDK EVEDEX" src="https://tribulnation.com/media/lockups/evedex-light.svg" width="520">
|
|
7
|
+
</picture>
|
|
8
|
+
</a>
|
|
9
|
+
</p>
|
|
10
|
+
|
|
11
|
+
<p align="center">
|
|
12
|
+
<em>Tribulnation SDK implementation for EVEDEX perpetuals.</em>
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
Perpetual Market and Report support for [EVEDEX](https://evedex.com/), built on
|
|
16
|
+
`typed-evedex`. Install with `pip install tribulnation-evedex`.
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from tribulnation.evedex import EvedexMarket
|
|
20
|
+
|
|
21
|
+
async with EvedexMarket.new() as venue:
|
|
22
|
+
perp = await venue.perp_exchange('perp')
|
|
23
|
+
market = await perp.market('BTCUSD')
|
|
24
|
+
book = await market.depth(levels=5)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
An API key reads the account; the wallet's private key also signs orders and opens the
|
|
28
|
+
private fills stream:
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
venue = EvedexMarket.new(api_key='…') # account reads only
|
|
32
|
+
venue = EvedexMarket.new(private_key='0x…') # reads and trading
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`MarketSDK` resolves `EVEDEX_API_KEY` and `EVEDEX_PRIVATE_KEY`; `typed-evedex` also
|
|
36
|
+
fills an unset key from them when the other one is given.
|
|
37
|
+
|
|
38
|
+
1. One exchange, `perp`, on the production exchange (evedex.com). Market ids are
|
|
39
|
+
instrument names (`BTCUSD`); the collateral, fee and funding coin is `usdt`.
|
|
40
|
+
2. Public data: discovery, tickers (best bid and ask, last price, 24h volumes), rules,
|
|
41
|
+
depth, a shared book stream, candles in the six SDK intervals, index, `perp_stats`
|
|
42
|
+
and the next hourly funding settlement. No funding-rate history is published.
|
|
43
|
+
3. Account and trading: fees, order queries, open orders, trade history, positions,
|
|
44
|
+
collateral, leverage, available notional and remaining position limit with an API
|
|
45
|
+
key; `set_leverage` too. The fills stream, `MARKET` (an IOC limit) and `LIMIT`
|
|
46
|
+
orders and every cancellation method with the private key. EVEDEX refuses post-only
|
|
47
|
+
orders, so `POST_ONLY` raises `NotImplementedError`. Stream fills carry no fee, and
|
|
48
|
+
their ids differ from `trades_history`'s. Refusals
|
|
49
|
+
raise `OrderRejected`. Funding payments are not supported.
|
|
50
|
+
|
|
51
|
+
`Report` snapshots one account, its trading balance and positions and its wallet:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from tribulnation.evedex import Report
|
|
55
|
+
|
|
56
|
+
async with Report.new(api_key='…') as report:
|
|
57
|
+
record = await report.snapshot()
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
See [EVEDEX Market](../../../docs/market/implementations/evedex.md) for account
|
|
61
|
+
configuration through `MarketSDK` and venue-specific semantics.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tribulnation-evedex"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Tribulnation SDK implementation for EVEDEX perpetuals."
|
|
9
|
+
license = "MIT"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["tribulnation-sdk>=4.1.0", "typed-evedex>=0.1.0"]
|
|
13
|
+
readme = {file = "README.md", content-type = "text/markdown"}
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Repository = "https://github.com/tribulnation/sdk.git"
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""EVEDEX client ownership, request middleware, venue constants and cached instruments."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
import asyncio
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from typing_extensions import (
|
|
10
|
+
AsyncContextManager,
|
|
11
|
+
Awaitable,
|
|
12
|
+
Callable,
|
|
13
|
+
Iterable,
|
|
14
|
+
Literal,
|
|
15
|
+
Mapping,
|
|
16
|
+
TypeVar,
|
|
17
|
+
cast,
|
|
18
|
+
)
|
|
19
|
+
from typed_evedex import BadRequest as ClientBadRequest, Evedex
|
|
20
|
+
from typed_evedex.core import order_id
|
|
21
|
+
from typed_evedex.exchange.market.instruments import InstrumentInfo
|
|
22
|
+
from typed_evedex.schemas import Instrument
|
|
23
|
+
from typed_evedex.streams.account.fills import OrderFillUpdate
|
|
24
|
+
from tribulnation.sdk import SDK
|
|
25
|
+
from tribulnation.sdk.core import (
|
|
26
|
+
AuthError,
|
|
27
|
+
BadRequest,
|
|
28
|
+
ManagedResource,
|
|
29
|
+
SharedReads,
|
|
30
|
+
Subscription,
|
|
31
|
+
exception_wrapper,
|
|
32
|
+
)
|
|
33
|
+
from tribulnation.sdk.market import Book
|
|
34
|
+
|
|
35
|
+
T = TypeVar('T')
|
|
36
|
+
VenueId = Literal['evedex']
|
|
37
|
+
"""EVEDEX's venue ID: the production exchange (evedex.com)."""
|
|
38
|
+
|
|
39
|
+
wrap_exceptions = exception_wrapper()
|
|
40
|
+
|
|
41
|
+
COLLATERAL = 'usdt'
|
|
42
|
+
"""The one collateral coin, as the venue writes it: margin, PnL, trading fees and
|
|
43
|
+
funding all settle in it."""
|
|
44
|
+
FUNDING_SETTLEMENT = timedelta(hours=1)
|
|
45
|
+
"""EVEDEX settles funding every hour, each settlement a pro-rated share of the rate it
|
|
46
|
+
computes every `fundingRateInterval` hours (8 on every instrument, 2026-11-19)."""
|
|
47
|
+
DEFAULT_LEVERAGE = 1
|
|
48
|
+
"""The leverage the venue applies on an instrument the account never set one on."""
|
|
49
|
+
FILLS = 'fills'
|
|
50
|
+
"""The key of the account's fills upstream in `Shared.fills`."""
|
|
51
|
+
ORDER_ID = re.compile(r'^\d{5}:[0-9a-f]{26}$')
|
|
52
|
+
"""A v2 order id, `DDDDD:<26 hex>`: days since 2025-07-24, then random hex."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def random_client_order_id() -> str:
|
|
56
|
+
"""A fresh order id the venue accepts as the order's own id (`DDDDD:<26 hex>`)."""
|
|
57
|
+
return order_id()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def listed(instrument: InstrumentInfo | Instrument) -> bool:
|
|
61
|
+
"""Whether an instrument is listed: visible to every account (`visibility: all`).
|
|
62
|
+
|
|
63
|
+
Delisted instruments (`LDOUSD`, `WIFUSD`, ...) are `visibility: none`, `trading: none`.
|
|
64
|
+
"""
|
|
65
|
+
return instrument['visibility'] == 'all'
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def tradable(instrument: InstrumentInfo) -> bool:
|
|
69
|
+
"""Whether an instrument takes orders from any account through the API now."""
|
|
70
|
+
return (
|
|
71
|
+
instrument['trading'] in ('all', 'schedule')
|
|
72
|
+
and instrument['marketState'] == 'OPEN'
|
|
73
|
+
and instrument['matcherState'] == 'active'
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def venue_label(exc: BadRequest) -> str | None:
|
|
78
|
+
"""The venue's error `label` behind a translated `BadRequest`, if it sent one
|
|
79
|
+
(`mark_price_limit_exceeded_error`, `order_not_found_error`, ...)."""
|
|
80
|
+
cause = exc.__cause__
|
|
81
|
+
if isinstance(cause, ClientBadRequest) and len(cause.args) >= 2:
|
|
82
|
+
payload: object = cause.args[1]
|
|
83
|
+
if isinstance(payload, dict):
|
|
84
|
+
label = cast(dict[str, object], payload).get('label')
|
|
85
|
+
if isinstance(label, str):
|
|
86
|
+
return label
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True, kw_only=True)
|
|
90
|
+
class Shared(SDK):
|
|
91
|
+
"""Own one client for one account; cache instruments and share reads and streams."""
|
|
92
|
+
|
|
93
|
+
client: Evedex
|
|
94
|
+
account_id: str | None = None
|
|
95
|
+
"""Root SDK account key; `None` when built directly, reporting `venue_id` instead."""
|
|
96
|
+
instruments: dict[str, InstrumentInfo] = field(
|
|
97
|
+
default_factory=dict[str, InstrumentInfo]
|
|
98
|
+
)
|
|
99
|
+
"""Every instrument, delisted ones included, by `name`."""
|
|
100
|
+
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
|
101
|
+
books: dict[str, Subscription[Book]] = field(
|
|
102
|
+
default_factory=dict[str, Subscription[Book]]
|
|
103
|
+
)
|
|
104
|
+
"""One shared upstream book per instrument, on the client's one connection."""
|
|
105
|
+
fills: dict[str, Subscription[OrderFillUpdate]] = field(
|
|
106
|
+
default_factory=dict[str, Subscription[OrderFillUpdate]]
|
|
107
|
+
)
|
|
108
|
+
"""The account's one `orderFills` upstream (every instrument), under `FILLS`, once
|
|
109
|
+
opened."""
|
|
110
|
+
reads: SharedReads = field(default_factory=SharedReads)
|
|
111
|
+
"""Account reads shared between markets and concurrent callers."""
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def new(
|
|
115
|
+
cls,
|
|
116
|
+
*,
|
|
117
|
+
private_key: str | None = None,
|
|
118
|
+
api_key: str | None = None,
|
|
119
|
+
validate: bool = True,
|
|
120
|
+
account_id: str | None = None,
|
|
121
|
+
):
|
|
122
|
+
"""Build a client for one account from explicit credentials.
|
|
123
|
+
|
|
124
|
+
With neither key the client is public. `typed-evedex` fills an unset key from
|
|
125
|
+
`EVEDEX_PRIVATE_KEY`/`EVEDEX_API_KEY` when the other one is given.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
private_key: The wallet's private key: every read, orders and private channels.
|
|
129
|
+
api_key: An API key: every REST account read, without the wallet.
|
|
130
|
+
validate: Validate responses.
|
|
131
|
+
account_id: Root SDK account key, the first segment of every market ID;
|
|
132
|
+
defaults to the venue ID.
|
|
133
|
+
"""
|
|
134
|
+
if private_key or api_key:
|
|
135
|
+
client = Evedex.new(
|
|
136
|
+
env='prod', private_key=private_key, api_key=api_key, validate=validate
|
|
137
|
+
)
|
|
138
|
+
else:
|
|
139
|
+
client = Evedex.new(env='prod', public=True, validate=validate)
|
|
140
|
+
return cls(client=client, account_id=account_id)
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def venue_id(self) -> VenueId:
|
|
144
|
+
"""The venue ID."""
|
|
145
|
+
return 'evedex'
|
|
146
|
+
|
|
147
|
+
@cached_property
|
|
148
|
+
def client_resource(self) -> ManagedResource[object]:
|
|
149
|
+
"""Own the client with the SDK's exception translation on entry and exit."""
|
|
150
|
+
return ManagedResource(
|
|
151
|
+
resource=self.client, wrap_enter=wrap_exceptions, wrap_exit=wrap_exceptions
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
def resources(self) -> Iterable[AsyncContextManager[object]]:
|
|
155
|
+
"""The client root owns every transport."""
|
|
156
|
+
yield self.client_resource
|
|
157
|
+
|
|
158
|
+
@SDK.method
|
|
159
|
+
@wrap_exceptions
|
|
160
|
+
async def call(self, fn: Callable[[], Awaitable[T]]) -> T:
|
|
161
|
+
"""Translate one request, or one page: the unit SDK retries apply to."""
|
|
162
|
+
return await fn()
|
|
163
|
+
|
|
164
|
+
def require_account(self):
|
|
165
|
+
"""Check the client can read the account, before an account read.
|
|
166
|
+
|
|
167
|
+
Raises:
|
|
168
|
+
AuthError: The client is public.
|
|
169
|
+
"""
|
|
170
|
+
if self.client.credentials is None:
|
|
171
|
+
raise AuthError(
|
|
172
|
+
'EVEDEX account reads need an `api_key` or the wallet `private_key`'
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
def require_wallet(self):
|
|
176
|
+
"""Check the client holds the wallet key, before an order or a private stream.
|
|
177
|
+
|
|
178
|
+
Raises:
|
|
179
|
+
AuthError: The client has no wallet key (public, or an API key alone).
|
|
180
|
+
"""
|
|
181
|
+
credentials = self.client.credentials
|
|
182
|
+
if credentials is None or credentials.account is None:
|
|
183
|
+
raise AuthError(
|
|
184
|
+
'EVEDEX orders and private streams are signed by the wallet: configure the '
|
|
185
|
+
'`private_key` (an API key only reads)'
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
async def load_instruments(
|
|
189
|
+
self, *, refetch: bool = False
|
|
190
|
+
) -> Mapping[str, InstrumentInfo]:
|
|
191
|
+
"""Every instrument, from one request, cached until `refetch`."""
|
|
192
|
+
async with self.lock:
|
|
193
|
+
if refetch or not self.instruments:
|
|
194
|
+
rows = await self.call(self.client.exchange.market.instruments)
|
|
195
|
+
# Without `fields` the venue sends full records; the declared return is the
|
|
196
|
+
# union of every `fields` shape (typed-client-issues.md).
|
|
197
|
+
self.instruments.clear()
|
|
198
|
+
self.instruments.update(
|
|
199
|
+
(r['name'], r) for r in cast(list[InstrumentInfo], rows)
|
|
200
|
+
)
|
|
201
|
+
return self.instruments
|
|
202
|
+
|
|
203
|
+
async def instrument(self, name: str, *, refetch: bool = False) -> InstrumentInfo:
|
|
204
|
+
"""One instrument's cached record, delisted ones included.
|
|
205
|
+
|
|
206
|
+
Raises:
|
|
207
|
+
ValueError: The venue has no instrument of that name.
|
|
208
|
+
"""
|
|
209
|
+
rows = await self.load_instruments(refetch=refetch)
|
|
210
|
+
row = rows.get(name)
|
|
211
|
+
if row is None:
|
|
212
|
+
raise ValueError(f'Unknown EVEDEX instrument: {name!r}')
|
|
213
|
+
return row
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Positions, leverage, position limits and the account's cross-margin bucket.
|
|
2
|
+
|
|
3
|
+
Every read here works with an API key alone, and is shared between markets and
|
|
4
|
+
concurrent callers for their `ttl`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from datetime import timedelta
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
import asyncio
|
|
10
|
+
|
|
11
|
+
from typing_extensions import Sequence
|
|
12
|
+
from typed_evedex.exchange.account.available_balance import AvailableBalance
|
|
13
|
+
from typed_evedex.schemas import Instrument, Position, User
|
|
14
|
+
from tribulnation.sdk.market import PerpCollateral, PerpPosition, RemainingPositionLimit
|
|
15
|
+
from tribulnation.sdk.util import whole_leverage
|
|
16
|
+
|
|
17
|
+
from ..core import DEFAULT_LEVERAGE, Shared
|
|
18
|
+
from .common import signed
|
|
19
|
+
|
|
20
|
+
OVERRIDE_UNOBSERVED = (
|
|
21
|
+
'EVEDEX per-account leverage limits (`riskFactorOverride.leverageLimit`) are not '
|
|
22
|
+
'supported yet: which instruments they apply to is undocumented'
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
async def positions(shared: Shared, *, ttl: timedelta | None) -> Sequence[Position]:
|
|
27
|
+
"""Every position record of the account (`positions.list`), flat ones included: a
|
|
28
|
+
record keeps an instrument's leverage setting at zero quantity."""
|
|
29
|
+
shared.require_account()
|
|
30
|
+
result = await shared.reads.read(
|
|
31
|
+
('positions',),
|
|
32
|
+
lambda: shared.call(shared.client.exchange.positions.list),
|
|
33
|
+
ttl=ttl,
|
|
34
|
+
)
|
|
35
|
+
return result['list']
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def record(rows: Sequence[Position], instrument: str) -> Position | None:
|
|
39
|
+
"""The account's position record on an instrument, if it has one."""
|
|
40
|
+
for p in rows:
|
|
41
|
+
if p['instrument'] == instrument:
|
|
42
|
+
return p
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def perp_position(
|
|
46
|
+
shared: Shared, instrument: str, *, ttl: timedelta | None
|
|
47
|
+
) -> PerpPosition:
|
|
48
|
+
"""The signed position and entry price; `quantity` is unsigned beside `side`. The
|
|
49
|
+
venue publishes a bankruptcy price, not a liquidation price, so none is reported."""
|
|
50
|
+
p = record(await positions(shared, ttl=ttl), instrument)
|
|
51
|
+
if p is None or p['quantity'] == 0:
|
|
52
|
+
return PerpPosition()
|
|
53
|
+
return PerpPosition(size=signed(p['side'], p['quantity']), entry_price=p['avgPrice'])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def leverage(shared: Shared, instrument: str, *, ttl: timedelta | None) -> int:
|
|
57
|
+
"""The account's leverage on the instrument: its position record's, which keeps the
|
|
58
|
+
setting while flat, else the venue's default of 1 for an instrument never set."""
|
|
59
|
+
p = record(await positions(shared, ttl=ttl), instrument)
|
|
60
|
+
return DEFAULT_LEVERAGE if p is None else p['leverage']
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def set_leverage(shared: Shared, name: str, value: Decimal):
|
|
64
|
+
"""Set the account's leverage on the instrument (`positions.set_leverage`), checked
|
|
65
|
+
against the instrument's `maxLeverage` first. Not signed: an API key suffices. The
|
|
66
|
+
shared positions read is dropped, so the next `leverage()` reads the new setting.
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
ValueError: `value` is not a positive whole number, or is above the instrument's
|
|
70
|
+
maximum.
|
|
71
|
+
AuthError: The client is public.
|
|
72
|
+
"""
|
|
73
|
+
row = await shared.instrument(name)
|
|
74
|
+
whole = whole_leverage(value)
|
|
75
|
+
if whole > row['maxLeverage']:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f'EVEDEX {name} allows leverage up to {row["maxLeverage"]}, got {value}'
|
|
78
|
+
)
|
|
79
|
+
shared.require_account()
|
|
80
|
+
await shared.call(
|
|
81
|
+
lambda: shared.client.exchange.positions.set_leverage(name, leverage=whole)
|
|
82
|
+
)
|
|
83
|
+
shared.reads.forget(('positions',))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def available_balance(
|
|
87
|
+
shared: Shared, *, ttl: timedelta | None
|
|
88
|
+
) -> AvailableBalance:
|
|
89
|
+
"""The account's margin summary, shared for the caller's `ttl`."""
|
|
90
|
+
shared.require_account()
|
|
91
|
+
return await shared.reads.read(
|
|
92
|
+
('available_balance',),
|
|
93
|
+
lambda: shared.call(shared.client.exchange.account.available_balance),
|
|
94
|
+
ttl=ttl,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def bucket(summary: AvailableBalance, rows: Sequence[Position]) -> PerpCollateral:
|
|
99
|
+
"""The account's one cross bucket.
|
|
100
|
+
|
|
101
|
+
Equity is the trading balance (`funding.balance`) plus every position's
|
|
102
|
+
`unRealizedPnL`; free collateral is the venue's `availableBalance` (the balance less
|
|
103
|
+
the initial margin of positions and open orders and less negative unrealized PnL);
|
|
104
|
+
the initial margin is the positions' (open orders' reservations show in free
|
|
105
|
+
collateral only); the maintenance margin the positions' `maintenanceMargin`; and
|
|
106
|
+
leverage the positions' `volume` (notional) over equity.
|
|
107
|
+
"""
|
|
108
|
+
equity = summary['funding']['balance'] + sum(
|
|
109
|
+
(p['unRealizedPnL'] for p in rows), Decimal(0)
|
|
110
|
+
)
|
|
111
|
+
notional = sum((p['volume'] for p in summary['position']), Decimal(0))
|
|
112
|
+
return PerpCollateral(
|
|
113
|
+
equity=equity,
|
|
114
|
+
free_collateral=summary['availableBalance'],
|
|
115
|
+
initial_margin=sum((p['initialMargin'] for p in summary['position']), Decimal(0)),
|
|
116
|
+
maintenance_margin=sum((p['maintenanceMargin'] for p in rows), Decimal(0)),
|
|
117
|
+
leverage=notional / equity if notional and equity > 0 else Decimal(0),
|
|
118
|
+
margin_mode='cross',
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def collateral(shared: Shared, *, ttl: timedelta | None) -> PerpCollateral:
|
|
123
|
+
"""The account's one cross bucket, whatever the market."""
|
|
124
|
+
summary, rows = await asyncio.gather(
|
|
125
|
+
available_balance(shared, ttl=ttl), positions(shared, ttl=ttl)
|
|
126
|
+
)
|
|
127
|
+
return bucket(summary, rows)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
async def me(shared: Shared, *, ttl: timedelta | None) -> User:
|
|
131
|
+
"""The account's user record (fee rates, risk overrides), shared for `ttl`."""
|
|
132
|
+
shared.require_account()
|
|
133
|
+
return await shared.reads.read(
|
|
134
|
+
('me',), lambda: shared.call(shared.client.exchange.account.me), ttl=ttl
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def remaining_position_limit(
|
|
139
|
+
instrument: Instrument, *, user: User, size: Decimal, leverage: int
|
|
140
|
+
) -> RemainingPositionLimit:
|
|
141
|
+
"""The room per direction under the instrument's `leverageLimit` tier for the
|
|
142
|
+
account's leverage, as notional at the mark price.
|
|
143
|
+
|
|
144
|
+
`leverageLimit` maps a leverage to the largest position notional allowed at it; a
|
|
145
|
+
leverage the table does not name has no published limit (`None`). The venue
|
|
146
|
+
publishes no open-interest cap.
|
|
147
|
+
|
|
148
|
+
Raises:
|
|
149
|
+
NotImplementedError: The account has its own leverage limits.
|
|
150
|
+
"""
|
|
151
|
+
if 'leverageLimit' in user['riskFactorOverride']:
|
|
152
|
+
raise NotImplementedError(OVERRIDE_UNOBSERVED)
|
|
153
|
+
mark = instrument['markPrice']
|
|
154
|
+
return RemainingPositionLimit.capped(
|
|
155
|
+
max_notional=instrument['leverageLimit'].get(str(leverage)),
|
|
156
|
+
position=size * mark,
|
|
157
|
+
)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Order books: REST snapshots and one shared WebSocket book per instrument.
|
|
2
|
+
|
|
3
|
+
Both serve the aggregated book, at most 100 levels per side, stamped with the venue's
|
|
4
|
+
book time. Every `orderBook-<instrument>-<round>` publication is the whole book, not a
|
|
5
|
+
delta. The grouping step `0.1` is the venue's finest: it leaves every instrument's
|
|
6
|
+
levels at its own tick (XRPUSD's `0.0001` levels, ETHUSD's `0.01`), identical to the
|
|
7
|
+
REST book (2026-11-19).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from contextlib import AsyncExitStack, asynccontextmanager
|
|
11
|
+
|
|
12
|
+
from typing_extensions import AsyncIterator, Sequence
|
|
13
|
+
from typed_evedex.exchange.market.order_book import OrderBookAsk, OrderBookBid
|
|
14
|
+
from typed_evedex.streams.order_book import (
|
|
15
|
+
OrderBookLevelAsksItem,
|
|
16
|
+
OrderBookLevelBidsItem,
|
|
17
|
+
OrderBookUpdate,
|
|
18
|
+
)
|
|
19
|
+
from tribulnation.sdk.core import OverflowPolicy, Subscription
|
|
20
|
+
from tribulnation.sdk.market import Book, detached_books
|
|
21
|
+
|
|
22
|
+
from ..core import Shared, wrap_exceptions
|
|
23
|
+
|
|
24
|
+
ROUND = '0.1'
|
|
25
|
+
"""The book channel's finest grouping step."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def entries(
|
|
29
|
+
rows: Sequence[OrderBookAsk]
|
|
30
|
+
| Sequence[OrderBookBid]
|
|
31
|
+
| Sequence[OrderBookLevelAsksItem]
|
|
32
|
+
| Sequence[OrderBookLevelBidsItem],
|
|
33
|
+
) -> list[Book.Entry]:
|
|
34
|
+
"""Book entries from aggregated price levels."""
|
|
35
|
+
return [Book.Entry(r['price'], r['quantity']) for r in rows]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def frame_book(frame: OrderBookUpdate) -> Book:
|
|
39
|
+
"""A channel publication as the whole book."""
|
|
40
|
+
book = frame['orderBook']
|
|
41
|
+
return Book(bids=entries(book['bids']), asks=entries(book['asks']), time=book['t'])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def depth(shared: Shared, instrument: str, *, levels: int | None = None) -> Book:
|
|
45
|
+
"""The aggregated REST book, best first, at most 100 levels per side.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
shared: The owner of the client.
|
|
49
|
+
instrument: The instrument's name.
|
|
50
|
+
levels: Keep at most this many levels per side.
|
|
51
|
+
"""
|
|
52
|
+
await shared.instrument(instrument)
|
|
53
|
+
raw = await shared.call(
|
|
54
|
+
lambda: shared.client.exchange.market.order_book(instrument=instrument)
|
|
55
|
+
)
|
|
56
|
+
book = Book(bids=entries(raw['bids']), asks=entries(raw['asks']), time=raw['t'])
|
|
57
|
+
return book if levels is None else book.limit(levels)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def subscription(shared: Shared, instrument: str) -> Subscription[Book]:
|
|
61
|
+
"""One upstream book per instrument, on the client's one connection."""
|
|
62
|
+
if instrument not in shared.books:
|
|
63
|
+
|
|
64
|
+
@wrap_exceptions
|
|
65
|
+
async def connect() -> Subscription.Context[Book]:
|
|
66
|
+
"""Subscribe to the instrument's book channel."""
|
|
67
|
+
manager = shared.client.streams.order_book(instrument, round=ROUND)
|
|
68
|
+
stack = AsyncExitStack()
|
|
69
|
+
stream = await stack.enter_async_context(manager)
|
|
70
|
+
|
|
71
|
+
@wrap_exceptions
|
|
72
|
+
async def frames() -> AsyncIterator[Book]:
|
|
73
|
+
"""Every publication of the channel, as a book."""
|
|
74
|
+
async for frame in stream:
|
|
75
|
+
yield frame_book(frame).frozen()
|
|
76
|
+
|
|
77
|
+
@wrap_exceptions
|
|
78
|
+
async def close():
|
|
79
|
+
"""Unsubscribe."""
|
|
80
|
+
await stack.aclose()
|
|
81
|
+
|
|
82
|
+
return Subscription.Context(frames(), close)
|
|
83
|
+
|
|
84
|
+
shared.books[instrument] = Subscription(connect)
|
|
85
|
+
return shared.books[instrument]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@asynccontextmanager
|
|
89
|
+
async def depth_stream(
|
|
90
|
+
shared: Shared,
|
|
91
|
+
instrument: str,
|
|
92
|
+
*,
|
|
93
|
+
levels: int | None = None,
|
|
94
|
+
queue_size: int = 1,
|
|
95
|
+
overflow: OverflowPolicy = 'latest',
|
|
96
|
+
):
|
|
97
|
+
"""Fan out the shared book; each subscriber gets its own copy, trimmed to `levels`.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
shared: The owner of the fan-outs.
|
|
101
|
+
instrument: The instrument's name.
|
|
102
|
+
levels: Keep at most this many levels per side.
|
|
103
|
+
queue_size: Books buffered for this subscriber.
|
|
104
|
+
overflow: What to do when the buffer is full.
|
|
105
|
+
"""
|
|
106
|
+
await shared.instrument(instrument)
|
|
107
|
+
upstream = subscription(shared, instrument)
|
|
108
|
+
async with upstream.subscribe(queue_size=queue_size, overflow=overflow) as stream:
|
|
109
|
+
yield detached_books(stream, levels)
|