-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecution.py
More file actions
389 lines (344 loc) · 13.8 KB
/
Copy pathexecution.py
File metadata and controls
389 lines (344 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
"""
execution.py
------------
Handles all order execution against the Hyperliquid REST API.
Responsibilities:
- Place market orders (entry).
- Place limit orders (TP/SL as reduce-only orders).
- Cancel open orders.
- Query open positions and account equity.
- Wrap Hyperliquid SDK calls with error handling and logging.
"""
import logging
import time
from dataclasses import dataclass
from typing import Optional
from config import Config
from strategy_flip import Direction
from responses import (
FillResponse, CancelResponse, AccountState,
ResponseStatus, TradeResponse,
)
logger = logging.getLogger(__name__)
# Hyperliquid Python SDK imports
try:
from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from hyperliquid.utils import constants
import eth_account
HL_SDK_AVAILABLE = True
except ImportError:
logger.warning("[Execution] hyperliquid-python-sdk not installed. Running in mock mode.")
HL_SDK_AVAILABLE = False
@dataclass
class OrderResult:
"""
Legacy shim — kept for backward compatibility with controller.py.
New code should use FillResponse from responses.py directly.
"""
success: bool
order_id: Optional[str]
filled_price: Optional[float]
filled_size: Optional[float]
error: Optional[str] = None
raw_response: Optional[dict] = None
fill: Optional[FillResponse] = None # ← the typed response object
@classmethod
def from_fill(cls, fill: FillResponse) -> "OrderResult":
"""Convert a FillResponse into an OrderResult."""
return cls(
success=fill.is_ok() or fill.status == ResponseStatus.DRY_RUN,
order_id=fill.order_id,
filled_price=fill.filled_price,
filled_size=fill.filled_size,
error=fill.error,
raw_response=fill.raw,
fill=fill,
)
@dataclass
class Position:
symbol: str
direction: Direction
size: float
entry_price: float
unrealized_pnl: float
leverage: float
class ExecutionEngine:
"""
Wraps Hyperliquid SDK for order placement and account queries.
Falls back to mock/dry-run mode if SDK is unavailable or DRY_RUN=true.
"""
def __init__(self, config: Config, data_feed=None):
self.config = config
self.dry_run = config.DRY_RUN
self._exchange: Optional[object] = None
self._info: Optional[object] = None
self._wallet_address = config.HL_WALLET_ADDRESS
self._data_feed = data_feed # used for live price in dry-run mode
if not self.dry_run and HL_SDK_AVAILABLE:
self._init_sdk()
else:
mode = "DRY RUN" if self.dry_run else "MOCK (SDK missing)"
logger.warning(f"[Execution] Running in {mode} mode — no real orders will be placed.")
# ------------------------------------------------------------------
# SDK Initialization
# ------------------------------------------------------------------
def _init_sdk(self) -> None:
"""Initialize Hyperliquid SDK with wallet credentials."""
try:
account = eth_account.Account.from_key(self.config.HL_API_SECRET)
self._info = Info(self.config.HL_REST_URL, skip_ws=True)
self._exchange = Exchange(
account,
self.config.HL_REST_URL,
account_address=self.config.HL_WALLET_ADDRESS,
)
logger.info(f"[Execution] Hyperliquid SDK initialized. Wallet: {self.config.HL_WALLET_ADDRESS[:8]}...")
except Exception as e:
logger.error(f"[Execution] SDK initialization failed: {e}")
self._exchange = None
self._info = None
# ------------------------------------------------------------------
# Account Queries
# ------------------------------------------------------------------
def get_account_equity(self) -> float:
"""Return current account equity in USD."""
if self.dry_run or not self._info:
logger.debug("[Execution] Mock equity: $10,000.00")
return 10_000.0
try:
state = self._info.user_state(self._wallet_address)
equity = float(state.get("marginSummary", {}).get("accountValue", 0))
logger.debug(f"[Execution] Account equity: ${equity:.2f}")
return equity
except Exception as e:
logger.error(f"[Execution] Failed to fetch account equity: {e}")
return 0.0
def get_open_positions(self) -> list[Position]:
"""Return list of currently open positions."""
if self.dry_run or not self._info:
return []
try:
state = self._info.user_state(self._wallet_address)
positions = []
for pos in state.get("assetPositions", []):
p = pos.get("position", {})
size = float(p.get("szi", 0))
if size == 0:
continue
direction = Direction.LONG if size > 0 else Direction.SHORT
positions.append(Position(
symbol=p.get("coin", ""),
direction=direction,
size=abs(size),
entry_price=float(p.get("entryPx", 0)),
unrealized_pnl=float(p.get("unrealizedPnl", 0)),
leverage=float(p.get("leverage", {}).get("value", 1)),
))
return positions
except Exception as e:
logger.error(f"[Execution] Failed to fetch positions: {e}")
return []
def get_open_position_count(self) -> int:
return len(self.get_open_positions())
# ------------------------------------------------------------------
# Order Placement
# ------------------------------------------------------------------
def set_leverage(self, leverage: int) -> bool:
"""Set leverage for the trading symbol."""
if self.dry_run or not self._exchange:
logger.info(f"[Execution] [DRY RUN] Set leverage {leverage}x for {self.config.SYMBOL}")
return True
try:
result = self._exchange.update_leverage(leverage, self.config.SYMBOL, is_cross=True)
logger.info(f"[Execution] Leverage set to {leverage}x for {self.config.SYMBOL}")
return True
except Exception as e:
logger.error(f"[Execution] Failed to set leverage: {e}")
return False
def place_market_order(
self,
direction: Direction,
size_contracts: float,
) -> OrderResult:
"""
Place a market order.
Args:
direction: LONG or SHORT.
size_contracts: Number of contracts to trade.
Returns:
OrderResult wrapping a FillResponse.
Access the full typed response via result.fill
"""
is_buy = direction == Direction.LONG
action_str = "BUY" if is_buy else "SELL"
if self.dry_run or not self._exchange:
mock_price = 0.0
if self._data_feed is not None:
mock_price = self._data_feed.get_latest_price() or 0.0
if mock_price <= 0:
logger.warning("[Execution] [DRY RUN] Could not get live price — using 0.0 as fill price.")
fill = FillResponse.dry_run(
order_type="market_entry",
direction=direction.value,
symbol=self.config.SYMBOL,
mock_price=mock_price,
size=size_contracts,
)
logger.info(f"[Execution] {fill.summary()}")
return OrderResult.from_fill(fill)
try:
result = self._exchange.market_open(
self.config.SYMBOL,
is_buy,
size_contracts,
slippage=0.001,
)
logger.debug(f"[Execution] Raw market order response: {result}")
fill = FillResponse.from_hl_response(
raw=result,
order_type="market_entry",
direction=direction.value,
symbol=self.config.SYMBOL,
)
logger.info(f"[Execution] {fill.summary()}")
return OrderResult.from_fill(fill)
except Exception as e:
logger.error(f"[Execution] Market order exception: {e}")
fill = FillResponse(
status=ResponseStatus.FAILED,
order_type="market_entry",
direction=direction.value,
symbol=self.config.SYMBOL,
error=str(e),
)
return OrderResult.from_fill(fill)
def place_stop_loss(
self,
direction: Direction,
size_contracts: float,
stop_price: float,
) -> OrderResult:
"""
Place a stop-loss order (reduce-only).
Response is available via result.fill (FillResponse).
"""
is_buy = direction == Direction.SHORT
action_str = "SL-SELL" if direction == Direction.LONG else "SL-BUY"
if self.dry_run or not self._exchange:
fill = FillResponse.dry_run(
order_type="stop_loss",
direction=direction.value,
symbol=self.config.SYMBOL,
mock_price=stop_price,
size=size_contracts,
)
logger.info(f"[Execution] {fill.summary()}")
return OrderResult.from_fill(fill)
try:
order_type = {
"trigger": {
"triggerPx": stop_price,
"isMarket": True,
"tpsl": "sl",
}
}
result = self._exchange.order(
self.config.SYMBOL, is_buy, size_contracts,
stop_price, order_type, reduce_only=True,
)
logger.debug(f"[Execution] Raw SL response: {result}")
fill = FillResponse.from_hl_response(
raw=result,
order_type="stop_loss",
direction=direction.value,
symbol=self.config.SYMBOL,
)
logger.info(f"[Execution] {fill.summary()}")
return OrderResult.from_fill(fill)
except Exception as e:
logger.error(f"[Execution] Stop-loss placement failed: {e}")
fill = FillResponse(
status=ResponseStatus.FAILED,
order_type="stop_loss",
direction=direction.value,
symbol=self.config.SYMBOL,
error=str(e),
)
return OrderResult.from_fill(fill)
def place_take_profit(
self,
direction: Direction,
size_contracts: float,
tp_price: float,
) -> OrderResult:
"""
Place a take-profit limit order (reduce-only).
Response is available via result.fill (FillResponse).
"""
is_buy = direction == Direction.SHORT
action_str = "TP-SELL" if direction == Direction.LONG else "TP-BUY"
if self.dry_run or not self._exchange:
fill = FillResponse.dry_run(
order_type="take_profit",
direction=direction.value,
symbol=self.config.SYMBOL,
mock_price=tp_price,
size=size_contracts,
)
logger.info(f"[Execution] {fill.summary()}")
return OrderResult.from_fill(fill)
try:
order_type = {
"trigger": {
"triggerPx": tp_price,
"isMarket": False,
"tpsl": "tp",
}
}
result = self._exchange.order(
self.config.SYMBOL, is_buy, size_contracts,
tp_price, order_type, reduce_only=True,
)
logger.debug(f"[Execution] Raw TP response: {result}")
fill = FillResponse.from_hl_response(
raw=result,
order_type="take_profit",
direction=direction.value,
symbol=self.config.SYMBOL,
)
logger.info(f"[Execution] {fill.summary()}")
return OrderResult.from_fill(fill)
except Exception as e:
logger.error(f"[Execution] Take-profit placement failed: {e}")
fill = FillResponse(
status=ResponseStatus.FAILED,
order_type="take_profit",
direction=direction.value,
symbol=self.config.SYMBOL,
error=str(e),
)
return OrderResult.from_fill(fill)
def cancel_all_orders(self) -> bool:
"""Cancel all open orders for the trading symbol."""
if self.dry_run or not self._exchange:
logger.info(f"[Execution] [DRY RUN] Cancel all orders for {self.config.SYMBOL}")
return True
try:
open_orders = self._info.open_orders(self._wallet_address)
symbol_orders = [o for o in open_orders if o.get("coin") == self.config.SYMBOL]
if not symbol_orders:
logger.debug("[Execution] No open orders to cancel.")
return True
cancels = [{"coin": o["coin"], "oid": o["oid"]} for o in symbol_orders]
result = self._exchange.bulk_cancel(cancels)
logger.info(f"[Execution] Cancelled {len(cancels)} orders: {result}")
return True
except Exception as e:
logger.error(f"[Execution] Cancel all orders failed: {e}")
return False
def close_position(self, direction: Direction, size_contracts: float) -> OrderResult:
"""Close an existing position with a market order."""
close_direction = Direction.SHORT if direction == Direction.LONG else Direction.LONG
logger.info(f"[Execution] Closing {direction.value} position: {size_contracts:.6f} contracts")
return self.place_market_order(close_direction, size_contracts)