-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdiogrid.py
1562 lines (1426 loc) · 66.2 KB
/
diogrid.py
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import time
import hmac
import base64
import hashlib
import asyncio
import aiohttp
import websockets
import traceback
import urllib.parse
from dotenv import load_dotenv
import random
# TRADING CONFIGURATION
PASSIVE_INCOME = 0
KRAKEN_FEE = 0.002
STARTING_PORTFOLIO_INVESTMENT = 3000.0
PROFIT_INCREMENT = 10
TRADING_PAIRS = {
pair: {
'size': size,
'grid_interval': grid,
'trail_interval': trail,
'precision': precision,
'sell_multiplier': sell_multiplier
}
for pair, (size, grid, trail, precision, sell_multiplier) in {
"BTC/USD": (0.000875, 0.75, 0.75, 1, 0.999), # $87.50 @ 3.5x (0.00025 @ 1.0x @ $100k)
"SOL/USD": (0.06, 2.5, 2.5, 2, 0.999), # 13-16% # need to unstake 0.1199636 and append to top sell order
"XRP/USD": (5.0, 3.0, 3.0, 5, 0.999), # 0%
"ADA/USD": (18.0, 3.0, 3.0, 6, 0.999), # 2-5%
"ETH/USD": (0.0045, 3.0, 3.0, 2, 0.999), # 2-7%
"TRX/USD": (55.0, 3.0, 3.0, 6, 0.999), # 4-7%
"DOT/USD": (2.5, 3.0, 3.0, 4, 0.999), # 12-18%
"INJ/USD": (0.81, 3.0, 3.0, 3, 0.999), # 7-11% pair appear broken on kraken end, balance doesn't update
"KSM/USD": (0.6, 3.0, 3.0, 2, 0.999), # 16-24%
}.items()
}
SHORT_SLEEP_TIME = 0.1
LONG_SLEEP_TIME = 3
GRID_DECAY_TIME = 5
MAX_AMEND_RETRIES = 3
AMEND_RETRY_DELAY = 5
AMEND_RESPONSE_TIMEOUT = 10
load_dotenv()
class Logger:
ERROR = '\033[91m'
WARNING = '\033[93m'
INFO = '\033[96m'
SUCCESS = '\033[92m'
RESET = '\033[0m'
@staticmethod
def error(msg: str, exc_info: Exception = None):
CURRENT_TIME = time.strftime('%H:%M:%S')
error_msg = f"{Logger.ERROR}[{CURRENT_TIME}][ERROR] {msg}{Logger.RESET}"
if exc_info:
error_msg += f"\n{Logger.ERROR}Exception: {str(exc_info)}{Logger.RESET}"
print(error_msg)
@staticmethod
def warning(msg: str):
CURRENT_TIME = time.strftime('%H:%M:%S')
print(f"{Logger.WARNING}[{CURRENT_TIME}][WARNING] {msg}{Logger.RESET}")
@staticmethod
def info(msg: str):
CURRENT_TIME = time.strftime('%H:%M:%S')
print(f"{Logger.INFO}[{CURRENT_TIME}][INFO] {msg}{Logger.RESET}")
@staticmethod
def success(msg: str):
CURRENT_TIME = time.strftime('%H:%M:%S')
print(f"{Logger.SUCCESS}[{CURRENT_TIME}][SUCCESS] {msg}{Logger.RESET}")
class KrakenAPIError(Exception):
"""Custom exception class for Kraken API errors"""
def __init__(self, error_code, message=None):
self.error_code = error_code
self.message = message or error_code
super().__init__(f"{error_code}: {self.message}")
class KrakenWebSocketClient:
def __init__(self):
self.api_key = os.getenv('KRAKEN_API_KEY')
self.api_secret = os.getenv('KRAKEN_API_SECRET')
self.ws_auth_url = "wss://ws-auth.kraken.com/v2"
self.ws_public_url = "wss://ws.kraken.com/v2"
self.rest_url = "https://api.kraken.com"
self.websocket = None
self.public_websocket = None
self.running = True
self.connection_status = {
'private': {'connected': False, 'last_ping': time.time(), 'last_pong': time.time()},
'public': {'connected': False, 'last_ping': time.time(), 'last_pong': time.time()}
}
self.last_ticker_time = time.time()
self.ping_interval = 15
self.pong_timeout = 5
self.reconnect_delay = 3
self.max_reconnect_attempts = 10
self.execution_rate_limit = None
self.subscriptions = {}
self.handlers = {}
self.balances = {}
self.orders = {}
self.maintenance_task = None
self.message_task = None
self.ticker_data = {}
self.active_trading_pairs = set()
self.portfolio_value = 0.0
self.last_portfolio_update = 0
self.update_interval = 5
self.last_profit_take_time = 0
self.profit_take_cooldown = 300
self.highest_portfolio_value = STARTING_PORTFOLIO_INVESTMENT
self.ticker_subscriptions = {}
self.public_message_task = None
self.earn_balances = {}
self.subscribed_channels = set()
self.subscription_lock = asyncio.Lock()
self.subscription_retry_delay = 1
self.ws_timeout = 30
self.ws_options = {
"ping_interval": None,
"ping_timeout": None,
"close_timeout": 5,
"max_size": 2**23,
"max_queue": 2**10
}
# Rate limiting parameters
self.initial_backoff = 1 # Start with 1 second
self.max_backoff = 300 # Max 5 minutes
self.backoff_factor = 2 # Double the delay each time
self.jitter = 0.1 # Add 10% random jitter
self.earn_strategies = {}
self.strategy_ids = {}
self. _public_ping_lock = asyncio.Lock()
"""
Generates a Kraken API signature for authentication.
Args:
urlpath (str): The API endpoint path
data (dict): The request data to be signed
Returns:
str: Base64 encoded signature for API authentication
"""
def get_kraken_signature(self, urlpath, data):
post_data = urllib.parse.urlencode(data)
encoded = (data['nonce'] + post_data).encode('utf-8')
message = urlpath.encode('utf-8') + hashlib.sha256(encoded).digest()
mac = hmac.new(base64.b64decode(self.api_secret), message, hashlib.sha512)
return base64.b64encode(mac.digest()).decode()
"""
Retrieves a WebSocket authentication token from Kraken's REST API.
Returns:
str: Authentication token for WebSocket connection
Raises:
KrakenAPIError: If token retrieval fails
"""
async def get_ws_token(self):
"""Get WebSocket authentication token from REST API"""
path = "/0/private/GetWebSocketsToken"
url = self.rest_url + path
nonce = str(int(time.time() * 1000))
post_data = {"nonce": nonce}
headers = {
"API-Key": self.api_key,
"API-Sign": self.get_kraken_signature(path, post_data),
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, data=post_data) as response:
if response.status != 200:
raise KrakenAPIError('EService:Unavailable', f"HTTP request failed: {response.status}")
result = await response.json()
if 'error' in result and result['error']:
error_code = result['error'][0]
raise KrakenAPIError(error_code)
return result.get("result", {}).get("token")
except aiohttp.ClientError as e:
raise KrakenAPIError('EService:Unavailable', f"HTTP request failed: {str(e)}")
except Exception as e:
raise KrakenAPIError('EGeneral:Internal error', str(e))
"""
Establishes WebSocket connections to Kraken's authenticated and public endpoints.
Initializes message handling and maintenance tasks.
Returns:
str: Authentication token from successful connection
Raises:
Exception: If connection fails
"""
async def connect_with_backoff(self):
"""Connect to WebSocket with exponential backoff."""
current_backoff = self.initial_backoff
attempt = 0
while attempt < self.max_reconnect_attempts:
try:
# First try to get the auth token
token = await self.get_ws_token()
if not token:
raise KrakenAPIError('EAPI:Invalid key', 'Failed to obtain WebSocket token')
# Try private connection first
try:
self.websocket = await asyncio.wait_for(
websockets.connect(self.ws_auth_url, **self.ws_options),
timeout=self.ws_timeout
)
self.connection_status['private']['connected'] = True
Logger.success("CONNECTION: PRIVATE - 200 - OK")
except Exception as e:
Logger.error(f"Private WebSocket connection failed: {str(e)}")
raise
# Add delay before public connection attempt
await asyncio.sleep(1)
# Then try public connection
try:
self.public_websocket = await asyncio.wait_for(
websockets.connect(self.ws_public_url, **self.ws_options),
timeout=self.ws_timeout
)
self.connection_status['public']['connected'] = True
Logger.success("CONNECTION: PUBLIC - 200 - OK")
except Exception as e:
Logger.error(f"Public WebSocket connection failed: {str(e)}")
# Close private connection if public fails
if self.websocket:
await self.websocket.close()
raise
return token
except websockets.exceptions.InvalidStatus as e:
if "HTTP 429" in str(e):
Logger.warning(f"Rate limit hit. Backing off for {current_backoff} seconds...")
jitter_amount = random.uniform(-self.jitter, self.jitter)
backoff_with_jitter = current_backoff * (1 + jitter_amount)
await asyncio.sleep(backoff_with_jitter)
current_backoff = min(current_backoff * self.backoff_factor, self.max_backoff)
attempt += 1
continue
else:
raise
except Exception as e:
Logger.error(f"Connection attempt {attempt + 1} failed: {str(e)}")
await asyncio.sleep(self.reconnect_delay)
attempt += 1
# Reset connection status
self.connection_status['private']['connected'] = False
self.connection_status['public']['connected'] = False
raise Exception(f"Failed to connect after {self.max_reconnect_attempts} attempts")
"""
Establishes initial WebSocket connection with backoff retry logic.
Creates and starts maintenance tasks for connection monitoring and message handling.
Returns:
str: Authentication token from successful connection
Raises:
Exception: If initial connection fails
"""
async def connect(self):
"""Initial connection with backoff."""
try:
token = await self.connect_with_backoff()
# Start maintenance tasks
self.maintenance_task = asyncio.create_task(self.maintain_connection())
self.message_task = asyncio.create_task(self.handle_messages())
self.public_message_task = asyncio.create_task(self.handle_public_messages())
return token
except Exception as e:
Logger.error(f"Initial connection failed: {str(e)}")
await self.disconnect()
raise
"""
Closes all WebSocket connections and cancels maintenance tasks.
Raises:
Exception: If error occurs during disconnect process
"""
async def disconnect(self):
"""Disconnect from both WebSocket connections."""
self.running = False
# Cancel all tasks if they exist
tasks = [self.maintenance_task, self.message_task, self.public_message_task]
for task in tasks:
if task is not None:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# Reset task attributes
self.maintenance_task = None
self.message_task = None
self.public_message_task = None
# Close connections if they exist and are open
try:
if self.websocket:
await self.websocket.close()
if self.public_websocket:
await self.public_websocket.close()
except Exception as e:
Logger.error(f"Error during disconnect: {str(e)}")
"""
Monitors WebSocket connection health and handles reconnection attempts.
Sends periodic ping messages and checks for pong responses.
Reconnects if connection is lost or unresponsive.
Raises:
Exception: If maintenance encounters an error
"""
async def maintain_connection(self):
"""Monitor and maintain WebSocket connection health."""
reconnect_attempts = 0
try:
while self.running:
current_time = time.time()
needs_reconnect = False
# Check private connection health
if self.connection_status['private']['connected']:
time_since_pong = current_time - self.connection_status['private']['last_pong']
if current_time - self.connection_status['private']['last_ping'] >= self.ping_interval:
try:
await self.ping()
self.connection_status['private']['last_ping'] = current_time
except Exception as e:
Logger.warning(f"Failed to send private ping: {str(e)}")
needs_reconnect = True
# Check public connection health using last ticker time instead of explicit ping
if self.connection_status['public']['connected']:
time_since_ticker = current_time - self.last_ticker_time
if time_since_ticker > self.ping_interval * 2: # Allow more time before triggering reconnect
Logger.warning("No recent ticker updates, connection may be stale")
needs_reconnect = True
if needs_reconnect:
if reconnect_attempts < self.max_reconnect_attempts:
reconnect_attempts += 1
Logger.warning(f"Connection issues detected. Attempting reconnection (attempt {reconnect_attempts}/{self.max_reconnect_attempts})")
try:
await self.reconnect()
reconnect_attempts = 0
continue
except Exception as e:
Logger.error(f"Reconnection attempt failed: {str(e)}")
await asyncio.sleep(self.backoff_factor ** reconnect_attempts)
else:
Logger.error("Max reconnection attempts reached")
self.running = False
break
await asyncio.sleep(LONG_SLEEP_TIME)
except asyncio.CancelledError:
pass
except Exception as e:
Logger.error(f"Connection maintenance error: {str(e)}")
self.running = False
"""
Sends a ping message to verify connection health.
Raises:
Exception: If ping message fails to send
"""
async def ping(self):
"""Send a ping message to the private connection."""
current_time = int(time.time() * 1000)
ping_message = {
"method": "ping",
"req_id": current_time
}
try:
await self.websocket.send(json.dumps(ping_message))
except Exception as e:
Logger.error("Error sending ping", e)
"""
Attempts to reestablish lost WebSocket connections.
Handles reconnection to both private and public endpoints.
Raises:
Exception: If reconnection fails
"""
async def reconnect(self):
"""Reconnect to WebSocket endpoints with backoff."""
Logger.info("Starting reconnection process...")
try:
# Cancel existing tasks
tasks = [self.maintenance_task, self.message_task, self.public_message_task]
for task in tasks:
if task is not None:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# Reset task attributes
self.maintenance_task = None
self.message_task = None
self.public_message_task = None
# Close existing connections if they exist
if hasattr(self.websocket, 'close') and self.websocket:
try:
await self.websocket.close()
except Exception as e:
Logger.warning(f"Error closing private connection: {str(e)}")
if hasattr(self.public_websocket, 'close') and self.public_websocket:
try:
await self.public_websocket.close()
except Exception as e:
Logger.warning(f"Error closing public connection: {str(e)}")
# Reset websocket objects
self.websocket = None
self.public_websocket = None
# Reset connection status
self.connection_status['private']['connected'] = False
self.connection_status['public']['connected'] = False
# Wait before attempting reconnection
await asyncio.sleep(self.reconnect_delay)
# Connect with backoff
token = await self.connect_with_backoff()
# Reset connection status timestamps
current_time = time.time()
self.connection_status['private'].update({
'last_ping': current_time,
'last_pong': current_time
})
self.connection_status['public'].update({
'last_ping': current_time,
'last_pong': current_time
})
self.last_ticker_time = current_time
# Restart message handling tasks
self.message_task = asyncio.create_task(self.handle_messages())
self.public_message_task = asyncio.create_task(self.handle_public_messages())
self.maintenance_task = asyncio.create_task(self.maintain_connection())
# Resubscribe to channels
await self.subscribe(['balances', 'executions'], token)
if self.active_trading_pairs:
await self.subscribe_ticker(list(self.active_trading_pairs))
Logger.success("Reconnection successful")
return True
except Exception as e:
Logger.error(f"Reconnection failed: {str(e)}")
# Reset websocket objects on failure
self.websocket = None
self.public_websocket = None
self.connection_status['private']['connected'] = False
self.connection_status['public']['connected'] = False
raise
"""
Processes incoming messages from the private WebSocket connection.
Handles various message types including order updates and system messages.
Raises:
websockets.exceptions.ConnectionClosed: If connection is lost
Exception: For other processing errors
"""
async def handle_messages(self):
"""Handle incoming messages from the WebSocket."""
while self.running:
try:
# Add timeout to receive operation
message = await asyncio.wait_for(
self.websocket.recv(),
timeout=self.ws_timeout
)
await self.handle_message(message)
except asyncio.TimeoutError:
Logger.warning("Message receive timeout, checking connection...")
if not self.websocket.open:
Logger.warning("WebSocket connection lost")
await self.reconnect()
break
except websockets.exceptions.ConnectionClosed:
Logger.warning("Private WebSocket connection closed")
await self.reconnect()
break
except Exception as e:
Logger.error(f"Error in message handling: {str(e)}")
await asyncio.sleep(LONG_SLEEP_TIME)
"""
Processes incoming messages from the public WebSocket connection.
Handles ticker updates and heartbeat messages.
Raises:
websockets.exceptions.ConnectionClosed: If connection is lost
Exception: For other processing errors
"""
async def handle_public_messages(self):
"""Handle messages from public WebSocket."""
while self.running:
try:
# Add timeout to receive operation
message = await asyncio.wait_for(
self.public_websocket.recv(),
timeout=self.ws_timeout
)
data = json.loads(message)
# Update last ticker time for any valid message
self.last_ticker_time = time.time()
if isinstance(data, dict):
if data.get('event') == 'error':
Logger.error(f"WebSocket error: {data.get('error')}")
continue
elif data.get('method') == 'pong':
continue
elif data.get('method') in ['subscribe', 'unsubscribe']:
if not data.get('success') and data.get('error'):
Logger.error(f"WebSocket subscription error: {data.get('error')}")
continue
if data.get('channel') == 'ticker':
await self.handle_ticker(data)
except asyncio.TimeoutError:
Logger.warning("Public message receive timeout, checking connection...")
if not self.public_websocket.open:
Logger.warning("Public WebSocket connection lost")
await self.reconnect()
break
except websockets.exceptions.ConnectionClosed:
Logger.warning("Public WebSocket connection closed")
await self.reconnect()
break
except Exception as e:
Logger.error(f"Error in public message handling: {str(e)}")
await asyncio.sleep(LONG_SLEEP_TIME)
"""
Processes a single WebSocket message.
Handles response matching, pong messages, and channel-specific data.
Args:
message (str): The raw message received from WebSocket
Raises:
json.JSONDecodeError: If message is not valid JSON
Exception: For other processing errors
"""
async def handle_message(self, message):
"""Process a single message from the WebSocket."""
try:
data = json.loads(message)
# Handle subscription responses
if isinstance(data, dict) and data.get('method') in ['subscribe', 'unsubscribe']:
if data.get('success') is False:
error_msg = data.get('error', 'Unknown error')
if 'Already subscribed' not in error_msg:
Logger.error(f"WebSocket subscription error: {error_msg}")
return
if isinstance(data, dict) and 'req_id' in data:
req_id = data['req_id']
if hasattr(self, '_response_futures') and req_id in self._response_futures:
if not self._response_futures[req_id].done():
self._response_futures[req_id].set_result(data)
return
if isinstance(data, dict) and (data.get('event') == 'pong' or data.get('method') == 'pong'):
self.connection_status['private']['last_pong'] = time.time()
return
if isinstance(data, dict) and data.get('method') == 'edit_order':
return
if 'channel' in data:
channel = data['channel']
if channel in self.handlers:
await self.handlers[channel](data)
elif 'event' in data:
if data.get('event') == 'systemStatus' and data.get('status') != 'online':
Logger.warning(f"System status: {data}")
except json.JSONDecodeError as e:
Logger.error("Invalid JSON message", e)
except Exception as e:
Logger.error("Error handling message", e)
"""
Subscribes to specified WebSocket channels.
Args:
channels (list): List of channel names to subscribe to
token (str): Authentication token for private channels
Raises:
Exception: If subscription fails
"""
async def subscribe(self, channels, token):
"""Subscribe to the specified channels with duplicate protection."""
async with self.subscription_lock:
for channel in channels:
if channel in self.subscribed_channels:
continue
subscribe_message = {
"method": "subscribe",
"params": {
"channel": channel,
"token": token,
}
}
if channel == 'executions':
subscribe_message["params"].update({
"snap_orders": True,
"snap_trades": False
})
elif channel == 'balances':
subscribe_message["params"]["snapshot"] = True
try:
await self.websocket.send(json.dumps(subscribe_message))
self.subscribed_channels.add(channel)
await asyncio.sleep(self.subscription_retry_delay)
except Exception as e:
Logger.error(f"Error subscribing to {channel}: {str(e)}")
"""
Unsubscribes from specified WebSocket channels.
Args:
channels (list): List of channel names to unsubscribe from
Raises:
websockets.exceptions.ConnectionClosed: If connection is lost
Exception: If unsubscribe fails
"""
async def unsubscribe(self, channels):
"""Unsubscribe from the specified channels."""
if not self.websocket or self.websocket.close:
return
for channel in channels:
try:
unsubscribe_message = {
"method": "unsubscribe",
"params": {
"channel": channel,
"token": await self.get_ws_token()
}
}
await self.websocket.send(json.dumps(unsubscribe_message))
Logger.warning(f"Unsubscribed from {channel} channel")
await asyncio.sleep(SHORT_SLEEP_TIME)
except websockets.exceptions.ConnectionClosed:
Logger.warning(f"Connection closed while unsubscribing from {channel}")
break
except Exception as e:
Logger.error(f"Error unsubscribing from {channel}", e)
"""
Registers a handler function for a specific channel.
Args:
channel (str): Channel name to register handler for
handler (callable): Function to handle channel messages
"""
def set_handler(self, channel, handler):
"""Set a handler function for a specific channel."""
self.handlers[channel] = handler
"""
Calculates total portfolio value across all assets.
Updates internal portfolio tracking and checks profit targets.
Raises:
Exception: If calculation fails
"""
async def calculate_portfolio_value(self):
"""Calculate total portfolio value in USD."""
total_value = 0.0
for asset, balance in self.balances.items():
if balance <= 0:
continue
if asset == 'USD':
total_value += balance
elif asset == 'USDC':
# Use USDC/USD ticker if available, otherwise assume 1:1
ticker = self.ticker_data.get('USDC/USD', {})
price = float(ticker.get('last', 1.0))
total_value += balance * price
else:
ticker_symbol = f"{asset}/USD"
ticker = self.ticker_data.get(ticker_symbol)
if ticker and ticker.get('last'):
price = float(ticker['last'])
value = balance * price
total_value += value
self.portfolio_value = total_value
Logger.success(f"BALANCE: 200 - OK")
# Check if we should take profit
if PASSIVE_INCOME == 1:
await self.check_and_take_profit()
else:
return
"""
Monitors portfolio value and executes profit-taking orders when targets are met.
"""
async def check_and_take_profit(self):
"""Check if we should take profit and execute USDC order if needed."""
current_time = time.time()
# Check if we're still in cooldown
if current_time - self.last_profit_take_time < self.profit_take_cooldown:
return
usdc_balance = self.balances.get('USDC', 0)
profit_threshold = self.highest_portfolio_value + PROFIT_INCREMENT + usdc_balance
if self.portfolio_value >= profit_threshold:
# Update highest portfolio value
self.highest_portfolio_value = self.portfolio_value - PROFIT_INCREMENT
# Create market order for USDC
order_message = {
"method": "add_order",
"params": {
"order_type": "market",
"side": "buy",
"cash_order_qty": PROFIT_INCREMENT,
"symbol": "USDC/USD",
"token": await self.get_ws_token()
},
"req_id": int(time.time() * 1000)
}
try:
await self.websocket.send(json.dumps(order_message))
Logger.success(f"PROFIT: Taking profit of ${PROFIT_INCREMENT:.2f} USDC at portfolio value ${self.portfolio_value:.2f}")
self.last_profit_take_time = current_time
except Exception as e:
Logger.error(f"Error taking profit: {str(e)}")
"""
Processes balance updates and manages ticker subscriptions.
Updates internal balance tracking and adjusts subscriptions based on holdings.
Args:
data (dict): Balance update data from WebSocket
Raises:
Exception: If update processing fails
"""
async def handle_balance_updates(self, data):
"""Handle incoming balance updates and manage ticker subscriptions."""
if data.get('type') in ['snapshot', 'update']:
# Keep track of all assets with non-zero balances
assets_with_balance = set()
# First, process all wallet data to ensure accurate earn balances
for asset_data in data.get('data', []):
asset_code = asset_data.get('asset')
# Initialize earn balance for this asset
self.earn_balances[asset_code] = 0.0
# Process wallets
wallets = asset_data.get('wallets', [])
if wallets:
# Sum up all earn-related wallet balances
earn_balance = sum(
float(wallet.get('balance', 0))
for wallet in wallets
if wallet.get('type') in ['earn', 'bonded', 'locked']
)
self.earn_balances[asset_code] = earn_balance
# Now process total balances and check for staking opportunities
for asset_data in data.get('data', []):
asset_code = asset_data.get('asset')
# Process wallets
wallets = asset_data.get('wallets', [])
total_balance = 0.0
if wallets:
# Sum up all wallet balances
total_balance = sum(float(wallet.get('balance', 0)) for wallet in wallets)
else:
# Fallback to legacy format if no wallets field
total_balance = float(asset_data.get('balance', 0))
# Update total balance
self.balances[asset_code] = total_balance
# Add to tracking set if non-zero balance and not USD
if total_balance > 0 and asset_code != 'USD':
assets_with_balance.add(asset_code)
# Convert assets to trading pairs
new_trading_pairs = {f"{asset}/USD" for asset in assets_with_balance}
# Handle subscription changes if needed
pairs_to_remove = self.active_trading_pairs - new_trading_pairs
pairs_to_add = new_trading_pairs - self.active_trading_pairs
if pairs_to_remove:
await self.unsubscribe_ticker(list(pairs_to_remove))
if pairs_to_add:
await self.subscribe_ticker(list(pairs_to_add))
self.active_trading_pairs = new_trading_pairs
# Calculate portfolio value after balance update
await self.calculate_portfolio_value()
"""
Subscribes to ticker data for specified trading pairs.
Args:
symbols (list): List of trading pair symbols to subscribe to
Raises:
Exception: If subscription fails
"""
async def subscribe_ticker(self, symbols):
"""Subscribe to ticker data with duplicate protection."""
if not symbols:
return
async with self.subscription_lock:
for symbol in symbols:
if symbol in self.ticker_subscriptions:
continue
subscribe_message = {
"method": "subscribe",
"params": {
"channel": "ticker",
"symbol": [symbol]
}
}
try:
await self.public_websocket.send(json.dumps(subscribe_message))
self.ticker_subscriptions[symbol] = True
await asyncio.sleep(self.subscription_retry_delay)
except Exception as e:
Logger.error(f"Error subscribing to ticker for {symbol}: {str(e)}")
"""
Unsubscribes from ticker data for specified trading pairs.
Args:
symbols (list): List of trading pair symbols to unsubscribe from
Raises:
websockets.exceptions.ConnectionClosed: If connection is lost
Exception: If unsubscribe fails
"""
async def unsubscribe_ticker(self, symbols):
"""Unsubscribe from ticker data for specified symbols."""
if not symbols or not self.public_websocket:
return
try:
unsubscribe_message = {
"method": "unsubscribe",
"params": {
"channel": "ticker",
"symbol": symbols
}
}
await self.public_websocket.send(json.dumps(unsubscribe_message))
for symbol in symbols:
self.ticker_subscriptions.pop(symbol, None)
await asyncio.sleep(SHORT_SLEEP_TIME)
except websockets.exceptions.ConnectionClosed:
Logger.warning("Public connection closed while unsubscribing from tickers")
except Exception as e:
Logger.error(f"Error unsubscribing from tickers", e)
"""
Processes incoming ticker updates and updates portfolio values.
Args:
data (dict): Ticker update data from WebSocket
Raises:
Exception: If ticker processing fails
"""
async def handle_ticker(self, data):
"""Handle incoming ticker updates."""
if data.get('channel') == 'ticker':
self.last_ticker_time = time.time()
update_portfolio = False
current_time = time.time()
for ticker_data in data.get('data', []):
symbol = ticker_data.get('symbol')
self.ticker_data[symbol] = {
'last': ticker_data.get('last'),
'bid': ticker_data.get('bid'),
'ask': ticker_data.get('ask'),
'volume': ticker_data.get('volume'),
'vwap': ticker_data.get('vwap')
}
update_portfolio = True
# Update portfolio value if enough time has passed
if update_portfolio and (current_time - self.last_portfolio_update) >= self.update_interval:
await self.calculate_portfolio_value()
self.last_portfolio_update = current_time
"""
Processes execution updates for orders.
Updates internal order tracking and handles various execution types.
Args:
data (dict): Execution update data from WebSocket
Raises:
Exception: If execution processing fails
"""
async def handle_execution_updates(self, data):
"""Handle incoming execution updates."""
if data.get('type') == 'snapshot':
self.orders = {}
for execution in data.get('data', []):
if execution.get('order_status') in ['new', 'partially_filled']:
order_id = execution.get('order_id')
if order_id:
self.orders[order_id] = execution
elif data.get('type') == 'update':
for execution in data.get('data', []):
order_id = execution.get('order_id')
if not order_id:
continue
exec_type = execution.get('exec_type')
order_status = execution.get('order_status')
symbol = execution.get('symbol')
if exec_type in ['filled', 'canceled', 'expired']:
if order_id in self.orders:
removed_order = self.orders.pop(order_id)
elif exec_type in ['new', 'pending_new']:
if order_id in self.orders:
self.orders[order_id].update(execution)
else:
self.orders[order_id] = execution
Logger.info(f"ORDER: NEW {symbol} - {order_id}")
elif order_id in self.orders:
self.orders[order_id].update(execution)
"""
Waits for a response to a specific request with timeout.
Args:
req_id: Request ID to wait for
timeout (int): Maximum time to wait in seconds
Returns:
dict: Response data if received
None: If timeout occurs
Raises:
Exception: If waiting fails
"""
async def wait_for_response(self, req_id, timeout=5):
"""Wait for a response to a specific request."""
# Create response future if it doesn't exist
if not hasattr(self, '_response_futures'):
self._response_futures = {}
# Create future for this request
future = asyncio.Future()
self._response_futures[req_id] = future
try:
# Wait for response with timeout
return await asyncio.wait_for(future, timeout)
except asyncio.TimeoutError:
Logger.warning(f"Timeout waiting for response to request {req_id}")
return None
finally:
# Clean up future
self._response_futures.pop(req_id, None)
"""
Fetch available earn strategies from Kraken.
Makes an authenticated POST request to Kraken's Earn/Strategies endpoint to retrieve
available staking and earn opportunities.
Returns:
dict: Dictionary mapping asset codes to their earn strategy details including:
- id: Strategy identifier
- apr_estimate: Estimated annual percentage rate
- lock_type: Type of lock period (if any)
- can_allocate: Whether user can allocate funds
- min_allocation: Minimum allocation amount
- user_cap: Maximum allocation cap per user
Raises:
KrakenAPIError: If the API request fails, returns error, or service is unavailable
Exception: For any other unexpected errors
"""
async def get_earn_strategies(self):
path = "/0/private/Earn/Strategies"
url = self.rest_url + path
nonce = str(int(time.time() * 1000))
post_data = {
"nonce": nonce,
}
headers = {
"API-Key": self.api_key,
"API-Sign": self.get_kraken_signature(path, post_data),
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, data=post_data) as response:
if response.status != 200:
raise KrakenAPIError('EService:Unavailable', f"HTTP request failed: {response.status}")
result = await response.json()
if 'error' in result and result['error']:
error_code = result['error'][0]
raise KrakenAPIError(error_code)
# Process and store strategies
strategies = result.get('result', {}).get('items', [])
for strategy in strategies: