capitalcom-cli 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- capital_cli/__init__.py +3 -0
- capital_cli/__main__.py +6 -0
- capital_cli/cli/__init__.py +1 -0
- capital_cli/cli/account_cmds.py +189 -0
- capital_cli/cli/app.py +88 -0
- capital_cli/cli/context.py +45 -0
- capital_cli/cli/live_guard.py +12 -0
- capital_cli/cli/market_cmds.py +165 -0
- capital_cli/cli/output.py +125 -0
- capital_cli/cli/runner.py +96 -0
- capital_cli/cli/session_cmds.py +127 -0
- capital_cli/cli/stream_cmds.py +263 -0
- capital_cli/cli/trade_cmds.py +549 -0
- capital_cli/cli/watchlist_cmds.py +132 -0
- capital_cli/core/__init__.py +1 -0
- capital_cli/core/config.py +152 -0
- capital_cli/core/errors.py +233 -0
- capital_cli/core/http_client.py +297 -0
- capital_cli/core/models.py +328 -0
- capital_cli/core/rate_limit.py +173 -0
- capital_cli/core/risk.py +417 -0
- capital_cli/core/session.py +219 -0
- capital_cli/core/state.py +97 -0
- capital_cli/core/utils.py +87 -0
- capital_cli/core/websocket_client.py +480 -0
- capitalcom_cli-0.4.0.dist-info/METADATA +433 -0
- capitalcom_cli-0.4.0.dist-info/RECORD +32 -0
- capitalcom_cli-0.4.0.dist-info/WHEEL +5 -0
- capitalcom_cli-0.4.0.dist-info/entry_points.txt +2 -0
- capitalcom_cli-0.4.0.dist-info/licenses/LICENSE +202 -0
- capitalcom_cli-0.4.0.dist-info/licenses/NOTICE +18 -0
- capitalcom_cli-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""Core data models for Capital.com CLI."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Any
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, Field
|
|
9
|
+
|
|
10
|
+
# ============================================================
|
|
11
|
+
# Enums
|
|
12
|
+
# ============================================================
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Direction(str, Enum):
|
|
16
|
+
"""Trade direction."""
|
|
17
|
+
|
|
18
|
+
BUY = "BUY"
|
|
19
|
+
SELL = "SELL"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class WorkingOrderType(str, Enum):
|
|
23
|
+
"""Working order type."""
|
|
24
|
+
|
|
25
|
+
LIMIT = "LIMIT"
|
|
26
|
+
STOP = "STOP"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PriceResolution(str, Enum):
|
|
30
|
+
"""Price resolution for historical data."""
|
|
31
|
+
|
|
32
|
+
MINUTE = "MINUTE"
|
|
33
|
+
MINUTE_5 = "MINUTE_5"
|
|
34
|
+
MINUTE_15 = "MINUTE_15"
|
|
35
|
+
MINUTE_30 = "MINUTE_30"
|
|
36
|
+
HOUR = "HOUR"
|
|
37
|
+
HOUR_4 = "HOUR_4"
|
|
38
|
+
DAY = "DAY"
|
|
39
|
+
WEEK = "WEEK"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ============================================================
|
|
43
|
+
# Standard Result Wrapper
|
|
44
|
+
# ============================================================
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ToolMeta(BaseModel):
|
|
48
|
+
"""Metadata for tool results."""
|
|
49
|
+
|
|
50
|
+
request_id: str = Field(default_factory=lambda: str(uuid4()))
|
|
51
|
+
ts: str = Field(default_factory=lambda: datetime.utcnow().isoformat() + "Z")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ToolError(BaseModel):
|
|
55
|
+
"""Error information."""
|
|
56
|
+
|
|
57
|
+
code: str = Field(..., description="Error code")
|
|
58
|
+
message: str = Field(..., description="Human-readable error message")
|
|
59
|
+
details: dict[str, Any] | None = Field(default=None, description="Additional error details")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ToolResult(BaseModel):
|
|
63
|
+
"""Standard tool result wrapper."""
|
|
64
|
+
|
|
65
|
+
ok: bool = Field(..., description="Success status")
|
|
66
|
+
data: dict[str, Any] | None = Field(default=None, description="Result data")
|
|
67
|
+
error: ToolError | None = Field(default=None, description="Error information")
|
|
68
|
+
meta: ToolMeta = Field(default_factory=ToolMeta)
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def success(cls, data: dict[str, Any]) -> "ToolResult":
|
|
72
|
+
"""Create a successful result."""
|
|
73
|
+
return cls(ok=True, data=data, error=None)
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def failure(cls, code: str, message: str, details: dict[str, Any] | None = None) -> "ToolResult":
|
|
77
|
+
"""Create a failed result."""
|
|
78
|
+
return cls(ok=False, data=None, error=ToolError(code=code, message=message, details=details))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# ============================================================
|
|
82
|
+
# Session Models
|
|
83
|
+
# ============================================================
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class SessionTokens(BaseModel):
|
|
87
|
+
"""Session authentication tokens."""
|
|
88
|
+
|
|
89
|
+
cst: str = Field(..., description="CST authorization token")
|
|
90
|
+
x_security_token: str = Field(..., description="X-SECURITY-TOKEN account token")
|
|
91
|
+
last_used_at: datetime = Field(default_factory=datetime.utcnow)
|
|
92
|
+
|
|
93
|
+
def is_expired(self, max_age_seconds: int = 540) -> bool:
|
|
94
|
+
"""Check if session is likely expired (9 minutes default)."""
|
|
95
|
+
age = (datetime.utcnow() - self.last_used_at).total_seconds()
|
|
96
|
+
return age >= max_age_seconds
|
|
97
|
+
|
|
98
|
+
def update_last_used(self) -> None:
|
|
99
|
+
"""Update the last used timestamp."""
|
|
100
|
+
self.last_used_at = datetime.utcnow()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class SessionStatus(BaseModel):
|
|
104
|
+
"""Session status information."""
|
|
105
|
+
|
|
106
|
+
env: str
|
|
107
|
+
base_url: str
|
|
108
|
+
logged_in: bool
|
|
109
|
+
account_id: str | None = None
|
|
110
|
+
last_used_at: str | None = None
|
|
111
|
+
expires_in_s_estimate: int | None = None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ============================================================
|
|
115
|
+
# Market Data Models
|
|
116
|
+
# ============================================================
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class MarketSearchRequest(BaseModel):
|
|
120
|
+
"""Request for market search."""
|
|
121
|
+
|
|
122
|
+
search_term: str | None = Field(default=None, description="Search term")
|
|
123
|
+
epics: list[str] | None = Field(default=None, description="List of EPICs to filter")
|
|
124
|
+
limit: int = Field(default=50, ge=1, le=1000, description="Max results")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class MarketGetRequest(BaseModel):
|
|
128
|
+
"""Request for market details."""
|
|
129
|
+
|
|
130
|
+
epic: str = Field(..., description="Market EPIC")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class PricesRequest(BaseModel):
|
|
134
|
+
"""Request for historical prices."""
|
|
135
|
+
|
|
136
|
+
epic: str = Field(..., description="Market EPIC")
|
|
137
|
+
resolution: PriceResolution = Field(default=PriceResolution.MINUTE_15)
|
|
138
|
+
max: int = Field(default=200, ge=1, le=1000, description="Max candles")
|
|
139
|
+
from_date: str | None = Field(default=None, alias="from")
|
|
140
|
+
to_date: str | None = Field(default=None, alias="to")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ============================================================
|
|
144
|
+
# Trading Models
|
|
145
|
+
# ============================================================
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class PreviewPositionRequest(BaseModel):
|
|
149
|
+
"""Request to preview a position."""
|
|
150
|
+
|
|
151
|
+
epic: str = Field(..., description="Market EPIC")
|
|
152
|
+
direction: Direction = Field(..., description="Trade direction")
|
|
153
|
+
size: float = Field(..., gt=0, description="Position size")
|
|
154
|
+
guaranteed_stop: bool = Field(default=False, description="Use guaranteed stop")
|
|
155
|
+
trailing_stop: bool = Field(default=False, description="Use trailing stop")
|
|
156
|
+
stop_level: float | None = Field(default=None, description="Stop loss level")
|
|
157
|
+
stop_distance: float | None = Field(default=None, description="Stop loss distance")
|
|
158
|
+
stop_amount: float | None = Field(default=None, description="Stop loss amount")
|
|
159
|
+
profit_level: float | None = Field(default=None, description="Take profit level")
|
|
160
|
+
profit_distance: float | None = Field(default=None, description="Take profit distance")
|
|
161
|
+
profit_amount: float | None = Field(default=None, description="Take profit amount")
|
|
162
|
+
auto_normalize_size: bool = Field(
|
|
163
|
+
default=False, description="Round size to the broker increment instead of failing"
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class PreviewWorkingOrderRequest(BaseModel):
|
|
168
|
+
"""Request to preview a working order."""
|
|
169
|
+
|
|
170
|
+
epic: str = Field(..., description="Market EPIC")
|
|
171
|
+
direction: Direction = Field(..., description="Trade direction")
|
|
172
|
+
type: WorkingOrderType = Field(..., description="Order type")
|
|
173
|
+
level: float = Field(..., description="Order trigger level")
|
|
174
|
+
size: float = Field(..., gt=0, description="Order size")
|
|
175
|
+
guaranteed_stop: bool = Field(default=False, description="Use guaranteed stop")
|
|
176
|
+
trailing_stop: bool = Field(default=False, description="Use trailing stop")
|
|
177
|
+
stop_level: float | None = Field(default=None, description="Stop loss level")
|
|
178
|
+
stop_distance: float | None = Field(default=None, description="Stop loss distance")
|
|
179
|
+
stop_amount: float | None = Field(default=None, description="Stop loss amount")
|
|
180
|
+
profit_level: float | None = Field(default=None, description="Take profit level")
|
|
181
|
+
profit_distance: float | None = Field(default=None, description="Take profit distance")
|
|
182
|
+
profit_amount: float | None = Field(default=None, description="Take profit amount")
|
|
183
|
+
good_till_date: str | None = Field(default=None, description="Good till date (ISO 8601)")
|
|
184
|
+
auto_normalize_size: bool = Field(
|
|
185
|
+
default=False, description="Round size to the broker increment instead of failing"
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class RiskCheck(BaseModel):
|
|
190
|
+
"""Individual risk check result."""
|
|
191
|
+
|
|
192
|
+
check: str = Field(..., description="Check name")
|
|
193
|
+
passed: bool = Field(..., description="Check passed")
|
|
194
|
+
message: str = Field(..., description="Check message")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class PreviewResult(BaseModel):
|
|
198
|
+
"""Result of a preview operation."""
|
|
199
|
+
|
|
200
|
+
preview_id: str = Field(default_factory=lambda: str(uuid4()))
|
|
201
|
+
normalized_request: dict[str, Any] = Field(..., description="Normalized request data")
|
|
202
|
+
checks: list[RiskCheck] = Field(..., description="Risk checks performed")
|
|
203
|
+
all_checks_passed: bool = Field(..., description="All checks passed")
|
|
204
|
+
estimated_entry: float | None = Field(default=None, description="Estimated entry price")
|
|
205
|
+
estimated_risk_notes: str | None = Field(
|
|
206
|
+
default=None, description="Risk estimation notes"
|
|
207
|
+
)
|
|
208
|
+
created_at: datetime = Field(default_factory=datetime.utcnow)
|
|
209
|
+
|
|
210
|
+
def is_expired(self, ttl_seconds: int = 120) -> bool:
|
|
211
|
+
"""Check if preview has expired (2 minutes default)."""
|
|
212
|
+
age = (datetime.utcnow() - self.created_at).total_seconds()
|
|
213
|
+
return age >= ttl_seconds
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class ExecutePositionRequest(BaseModel):
|
|
217
|
+
"""Request to execute a position."""
|
|
218
|
+
|
|
219
|
+
preview_id: str = Field(..., description="Preview ID from preview operation")
|
|
220
|
+
confirm: bool = Field(default=False, description="Explicit confirmation")
|
|
221
|
+
wait_for_confirm: bool = Field(default=True, description="Wait for broker confirmation")
|
|
222
|
+
timeout_s: float = Field(default=15.0, gt=0, description="Confirmation timeout")
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class ExecuteWorkingOrderRequest(BaseModel):
|
|
226
|
+
"""Request to execute a working order."""
|
|
227
|
+
|
|
228
|
+
preview_id: str = Field(..., description="Preview ID from preview operation")
|
|
229
|
+
confirm: bool = Field(default=False, description="Explicit confirmation")
|
|
230
|
+
wait_for_confirm: bool = Field(default=True, description="Wait for broker confirmation")
|
|
231
|
+
timeout_s: float = Field(default=15.0, gt=0, description="Confirmation timeout")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class ConfirmWaitRequest(BaseModel):
|
|
235
|
+
"""Request to wait for confirmation."""
|
|
236
|
+
|
|
237
|
+
deal_reference: str = Field(..., description="Deal reference from trade operation")
|
|
238
|
+
timeout_s: float = Field(default=15.0, gt=0, description="Timeout in seconds")
|
|
239
|
+
poll_interval_ms: int = Field(default=500, ge=100, le=5000, description="Poll interval in ms")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# ============================================================
|
|
243
|
+
# Account Models
|
|
244
|
+
# ============================================================
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class AccountPreferencesSetRequest(BaseModel):
|
|
248
|
+
"""Request to set account preferences."""
|
|
249
|
+
|
|
250
|
+
hedging_mode: bool | None = Field(default=None, description="Enable hedging mode")
|
|
251
|
+
leverages: dict[str, int | None] | None = Field(
|
|
252
|
+
default=None, description="Leverage settings per asset class"
|
|
253
|
+
)
|
|
254
|
+
confirm: bool = Field(default=False, description="Explicit confirmation")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class DemoTopUpRequest(BaseModel):
|
|
258
|
+
"""Request to top up demo account."""
|
|
259
|
+
|
|
260
|
+
amount: float = Field(..., gt=0, description="Amount to add")
|
|
261
|
+
confirm: bool = Field(default=False, description="Explicit confirmation")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# ============================================================
|
|
265
|
+
# Watchlist Models
|
|
266
|
+
# ============================================================
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class WatchlistCreateRequest(BaseModel):
|
|
270
|
+
"""Request to create a watchlist."""
|
|
271
|
+
|
|
272
|
+
name: str = Field(..., min_length=1, max_length=100, description="Watchlist name")
|
|
273
|
+
confirm: bool = Field(default=False, description="Explicit confirmation")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class WatchlistAddMarketRequest(BaseModel):
|
|
277
|
+
"""Request to add market to watchlist."""
|
|
278
|
+
|
|
279
|
+
watchlist_id: str = Field(..., description="Watchlist ID")
|
|
280
|
+
epic: str = Field(..., description="Market EPIC")
|
|
281
|
+
confirm: bool = Field(default=False, description="Explicit confirmation")
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# ============================================================
|
|
285
|
+
# WebSocket Streaming Models
|
|
286
|
+
# ============================================================
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class PriceTick(BaseModel):
|
|
290
|
+
"""WebSocket price update."""
|
|
291
|
+
|
|
292
|
+
epic: str = Field(..., description="Market EPIC")
|
|
293
|
+
bid: float = Field(..., description="Bid price")
|
|
294
|
+
offer: float = Field(..., description="Offer/ask price")
|
|
295
|
+
timestamp: str = Field(..., description="Update timestamp (ISO 8601)")
|
|
296
|
+
change_percent: float | None = Field(default=None, description="Price change percentage")
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class OHLCBar(BaseModel):
|
|
300
|
+
"""WebSocket OHLC candlestick update."""
|
|
301
|
+
|
|
302
|
+
epic: str = Field(..., description="Market EPIC")
|
|
303
|
+
resolution: str = Field(..., description="Candle resolution, e.g. MINUTE, HOUR, DAY")
|
|
304
|
+
type: str = Field(default="classic", description="Bar type: classic or heikin-ashi")
|
|
305
|
+
price_type: str = Field(default="bid", description="Price type the bar is built from")
|
|
306
|
+
timestamp: str = Field(..., description="Candle timestamp (ISO 8601)")
|
|
307
|
+
open: float = Field(..., description="Open price")
|
|
308
|
+
high: float = Field(..., description="High price")
|
|
309
|
+
low: float = Field(..., description="Low price")
|
|
310
|
+
close: float = Field(..., description="Close price")
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class StreamAlert(BaseModel):
|
|
314
|
+
"""Alert trigger event."""
|
|
315
|
+
|
|
316
|
+
epic: str = Field(..., description="Market EPIC")
|
|
317
|
+
condition: str = Field(..., description="Alert condition (LEVEL_ABOVE, LEVEL_BELOW, BREAKOUT)")
|
|
318
|
+
trigger_price: float = Field(..., description="Price that triggered the alert")
|
|
319
|
+
current_price: float = Field(..., description="Current market price")
|
|
320
|
+
timestamp: str = Field(..., description="Alert timestamp (ISO 8601)")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class PortfolioSnapshot(BaseModel):
|
|
324
|
+
"""Real-time portfolio state."""
|
|
325
|
+
|
|
326
|
+
positions: list[dict[str, Any]] = Field(..., description="List of open positions")
|
|
327
|
+
total_pnl: float = Field(..., description="Total portfolio P&L")
|
|
328
|
+
timestamp: str = Field(..., description="Snapshot timestamp (ISO 8601)")
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Rate limiting implementation using token bucket algorithm."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TokenBucket:
|
|
8
|
+
"""Token bucket rate limiter (async-safe)."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, capacity: float, refill_rate: float):
|
|
11
|
+
"""
|
|
12
|
+
Initialize token bucket.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
capacity: Maximum number of tokens in the bucket
|
|
16
|
+
refill_rate: Tokens added per second
|
|
17
|
+
"""
|
|
18
|
+
self.capacity = capacity
|
|
19
|
+
self.refill_rate = refill_rate
|
|
20
|
+
self.tokens = capacity
|
|
21
|
+
self.last_refill = time.monotonic()
|
|
22
|
+
self._lock = asyncio.Lock()
|
|
23
|
+
|
|
24
|
+
async def _refill(self) -> None:
|
|
25
|
+
"""Refill tokens based on elapsed time."""
|
|
26
|
+
now = time.monotonic()
|
|
27
|
+
elapsed = now - self.last_refill
|
|
28
|
+
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
|
|
29
|
+
self.last_refill = now
|
|
30
|
+
|
|
31
|
+
async def acquire(self, tokens: float = 1.0, timeout: float | None = None) -> bool:
|
|
32
|
+
"""
|
|
33
|
+
Acquire tokens from the bucket.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
tokens: Number of tokens to acquire
|
|
37
|
+
timeout: Maximum time to wait (None = wait forever)
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
True if tokens acquired, False if timeout
|
|
41
|
+
"""
|
|
42
|
+
start_time = time.monotonic()
|
|
43
|
+
|
|
44
|
+
while True:
|
|
45
|
+
async with self._lock:
|
|
46
|
+
await self._refill()
|
|
47
|
+
|
|
48
|
+
if self.tokens >= tokens:
|
|
49
|
+
self.tokens -= tokens
|
|
50
|
+
return True
|
|
51
|
+
|
|
52
|
+
# Check timeout
|
|
53
|
+
if timeout is not None:
|
|
54
|
+
elapsed = time.monotonic() - start_time
|
|
55
|
+
if elapsed >= timeout:
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
# Wait a bit before retrying
|
|
59
|
+
await asyncio.sleep(0.01)
|
|
60
|
+
|
|
61
|
+
async def try_acquire(self, tokens: float = 1.0) -> bool:
|
|
62
|
+
"""
|
|
63
|
+
Try to acquire tokens without blocking.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
tokens: Number of tokens to acquire
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
True if tokens acquired, False otherwise
|
|
70
|
+
"""
|
|
71
|
+
async with self._lock:
|
|
72
|
+
await self._refill()
|
|
73
|
+
|
|
74
|
+
if self.tokens >= tokens:
|
|
75
|
+
self.tokens -= tokens
|
|
76
|
+
return True
|
|
77
|
+
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
async def available_tokens(self) -> float:
|
|
81
|
+
"""Get current number of available tokens."""
|
|
82
|
+
async with self._lock:
|
|
83
|
+
await self._refill()
|
|
84
|
+
return self.tokens
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class RateLimiter:
|
|
88
|
+
"""
|
|
89
|
+
Multi-tier rate limiter for Capital.com API.
|
|
90
|
+
|
|
91
|
+
Enforces:
|
|
92
|
+
- Global: 10 requests/second per user
|
|
93
|
+
- Session: 1 request/second for POST /session
|
|
94
|
+
- Trading: 1 request per 0.1 seconds for POST /positions, POST /workingorders
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
def __init__(self):
|
|
98
|
+
# Global rate limit: 10 req/s
|
|
99
|
+
self.global_limiter = TokenBucket(capacity=10.0, refill_rate=10.0)
|
|
100
|
+
|
|
101
|
+
# Session rate limit: 1 req/s
|
|
102
|
+
self.session_limiter = TokenBucket(capacity=1.0, refill_rate=1.0)
|
|
103
|
+
|
|
104
|
+
# Trading rate limit: 1 req per 0.1s = 10 req/s
|
|
105
|
+
self.trading_limiter = TokenBucket(capacity=10.0, refill_rate=10.0)
|
|
106
|
+
|
|
107
|
+
async def acquire_global(self, timeout: float | None = 10.0) -> bool:
|
|
108
|
+
"""
|
|
109
|
+
Acquire global rate limit token.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
timeout: Maximum wait time in seconds
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
True if acquired, False if timeout
|
|
116
|
+
"""
|
|
117
|
+
return await self.global_limiter.acquire(tokens=1.0, timeout=timeout)
|
|
118
|
+
|
|
119
|
+
async def acquire_session(self, timeout: float | None = 10.0) -> bool:
|
|
120
|
+
"""
|
|
121
|
+
Acquire session rate limit token (for POST /session).
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
timeout: Maximum wait time in seconds
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
True if acquired, False if timeout
|
|
128
|
+
"""
|
|
129
|
+
# Must also pass global limit
|
|
130
|
+
if not await self.global_limiter.acquire(tokens=1.0, timeout=timeout):
|
|
131
|
+
return False
|
|
132
|
+
return await self.session_limiter.acquire(tokens=1.0, timeout=timeout)
|
|
133
|
+
|
|
134
|
+
async def acquire_trading(self, timeout: float | None = 10.0) -> bool:
|
|
135
|
+
"""
|
|
136
|
+
Acquire trading rate limit token (for POST /positions, POST /workingorders).
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
timeout: Maximum wait time in seconds
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
True if acquired, False if timeout
|
|
143
|
+
"""
|
|
144
|
+
# Must also pass global limit
|
|
145
|
+
if not await self.global_limiter.acquire(tokens=1.0, timeout=timeout):
|
|
146
|
+
return False
|
|
147
|
+
return await self.trading_limiter.acquire(tokens=1.0, timeout=timeout)
|
|
148
|
+
|
|
149
|
+
async def get_state(self) -> dict[str, float]:
|
|
150
|
+
"""Get current state of all limiters."""
|
|
151
|
+
return {
|
|
152
|
+
"global_tokens": await self.global_limiter.available_tokens(),
|
|
153
|
+
"session_tokens": await self.session_limiter.available_tokens(),
|
|
154
|
+
"trading_tokens": await self.trading_limiter.available_tokens(),
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# Global rate limiter instance
|
|
159
|
+
_rate_limiter: RateLimiter | None = None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def get_rate_limiter() -> RateLimiter:
|
|
163
|
+
"""Get or create the global rate limiter instance."""
|
|
164
|
+
global _rate_limiter
|
|
165
|
+
if _rate_limiter is None:
|
|
166
|
+
_rate_limiter = RateLimiter()
|
|
167
|
+
return _rate_limiter
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def reset_rate_limiter() -> None:
|
|
171
|
+
"""Reset the global rate limiter (mainly for testing)."""
|
|
172
|
+
global _rate_limiter
|
|
173
|
+
_rate_limiter = None
|