-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdiogrid.py
1571 lines (1312 loc) · 63.3 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 urllib.parse
from dotenv import load_dotenv
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# TRADING CONFIGURATION
KRAKEN_FEE = 0.002 # current Kraken maker fee
STARTING_PORTFOLIO_INVESTMENT = 2500.0 # Starting USD portfolio balance
PROFIT_INCREMENT = 10 # Dollar amount in realized portfolio value to take profit in USDC
TRADING_PAIRS = {
pair: {
'size': size,
'grid_interval': grid,
'grid_spacing': spacing,
'trail_interval': spacing,
'precision': precision
}
for pair, (size, grid, spacing, precision) in {
"BTC/USD": (0.00072, 0.75, 0.75, 1), # $70.00 @ 2.8x
"ETH/USD": (0.0035, 2.5, 2.5, 2),
"SOL/USD": (0.06, 2.5, 1.5, 2),
"XRP/USD": (5.0, 2.5, 1.5, 5),
"ADA/USD": (12.0, 2.5, 2.5, 6),
"TRX/USD": (50.0, 2.5, 2.5, 6),
"AVAX/USD": (0.35, 2.5, 2.5, 2),
"LINK/USD": (0.5, 2.5, 2.5, 5),
#"XLM/USD": (27.0, 2.5, 2.5, 6),
#"SUI/USD": (2.5, 2.5, 2.5, 4),
}.items()
}
# SLEEP TIMES
SHORT_SLEEP_TIME = 0.1
LONG_SLEEP_TIME = 3
GRID_DECAY_TIME = 5 # 5 second decay time
load_dotenv()
class Logger:
ERROR = '\033[91m' # Red
WARNING = '\033[93m' # Yellow
INFO = '\033[94m' # Blue
SUCCESS = '\033[92m' # Green
RESET = '\033[0m' # Reset color
@staticmethod
def error(msg: str, exc_info: Exception = None):
error_msg = f"{Logger.ERROR}[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):
print(f"{Logger.WARNING}[WARNING] {msg}{Logger.RESET}")
@staticmethod
def info(msg: str):
print(f"{Logger.INFO}[INFO] {msg}{Logger.RESET}")
@staticmethod
def success(msg: str):
print(f"{Logger.SUCCESS}[SUCCESS] {msg}{Logger.RESET}")
class KrakenAPIError(Exception):
"""Custom exception class for Kraken API errors"""
"""
Initializes a new DioGridError instance.
Args:
error_code (str): The error code identifier
message (str, optional): Custom error message. If not provided,
a default message is fetched based on the error code.
"""
def __init__(self, error_code, message=None):
self.error_code = error_code
self.message = message or self._get_error_description(error_code)
super().__init__(f"{error_code}: {self.message}")
def _get_error_description(self, error_code):
error_descriptions = {
# General Errors
'EGeneral:Invalid arguments': 'The request payload is malformed, incorrect or ambiguous',
'EGeneral:Invalid arguments:Index unavailable': 'Index pricing is unavailable for stop/profit orders on this pair',
'EGeneral:Temporary lockout': 'Too many sequential EAPI:Invalid key errors',
'EGeneral:Permission denied': 'API key lacks required permissions',
'EGeneral:Internal error': 'Internal error. Please contact support',
# Service Errors
'EService:Unavailable': 'The matching engine or API is offline',
'EService:Market in cancel_only mode': 'Request cannot be made at this time',
'EService:Market in post_only mode': 'Request cannot be made at this time',
'EService:Deadline elapsed': 'The request timed out according to the default or specified deadline',
# API Authentication Errors
'EAPI:Invalid key': 'Invalid API key provided',
'EAPI:Invalid signature': 'Invalid API signature',
'EAPI:Invalid nonce': 'Invalid nonce value',
# Order Errors
'EOrder:Cannot open opposing position': 'User/tier is ineligible for margin trading',
'EOrder:Cannot open position': 'User/tier is ineligible for margin trading',
'EOrder:Margin allowance exceeded': 'User has exceeded their margin allowance',
'EOrder:Margin level too low': 'Client has insufficient equity or collateral',
'EOrder:Margin position size exceeded': 'Client would exceed the maximum position size for this pair',
'EOrder:Insufficient margin': 'Exchange does not have available funds for this margin trade',
'EOrder:Insufficient funds': 'Client does not have the necessary funds',
'EOrder:Order minimum not met': 'Order size does not meet ordermin',
'EOrder:Cost minimum not met': 'Cost (price * volume) does not meet costmin',
'EOrder:Tick size check failed': 'Price submitted is not a valid multiple of the pair\'s tick_size',
'EOrder:Orders limit exceeded': 'Order rate limit exceeded',
'EOrder:Rate limit exceeded': 'Rate limit exceeded',
'EOrder:Invalid price': 'Invalid price specified',
'EOrder:Domain rate limit exceeded': 'Domain-specific rate limit exceeded',
'EOrder:Positions limit exceeded': 'Maximum positions limit exceeded',
'EOrder:Reduce only:Non-PC': 'Invalid reduce-only order',
'EOrder:Reduce only:No position exists': 'Cannot submit reduce-only order when no position exists',
'EOrder:Reduce only:Position is closed': 'Reduce-only order would flip position',
'EOrder:Scheduled orders limit exceeded': 'Maximum scheduled orders limit exceeded',
'EOrder:Unknown position': 'Position not found',
# Account Errors
'EAccount:Invalid permissions': 'Account has invalid permissions',
# Authentication Errors
'EAuth:Account temporary disabled': 'Account is temporarily disabled',
'EAuth:Account unconfirmed': 'Account is not confirmed',
'EAuth:Rate limit exceeded': 'Authentication rate limit exceeded',
'EAuth:Too many requests': 'Too many authentication requests',
# Trade Errors
'ETrade:Invalid request': 'Invalid trade request',
# Business/Regulatory Errors
'EBM:limit exceeded:CAL': 'Exceeded Canadian Acquisition Limits',
# Funding Errors
'EFunding:Max fee exceeded': 'Processed fee exceeds max_fee set in Withdraw request'
}
return error_descriptions.get(error_code, 'Unknown error')
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" # For private data
self.ws_public_url = "wss://ws.kraken.com/v2" # For public data
self.rest_url = "https://api.kraken.com"
self.websocket = None
self.public_websocket = None # Add new websocket connection
self.running = True
# Only track private connection status
self.connection_status = {
'private': {'last_ping': time.time(), 'last_pong': time.time()},
}
self.last_ticker_time = time.time() # Track last ticker message
self.ping_interval = 30
self.pong_timeout = 10 # Time to wait for pong response
self.reconnect_delay = 5 # Seconds to wait before reconnecting
self.max_reconnect_attempts = 3
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() # Track active trading pairs
self.portfolio_value = 0.0
self.last_portfolio_update = 0
self.update_interval = 5 # Update portfolio value every 5 seconds
self.last_profit_take_time = 0
self.profit_take_cooldown = 300 # 5 minutes in seconds
self.highest_portfolio_value = STARTING_PORTFOLIO_INVESTMENT
self.ticker_subscriptions = {} # Track individual ticker subscriptions
self.public_message_task = None
self.email_manager = EmailManager()
"""
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(self):
"""Connect to Kraken's WebSocket APIs."""
try:
# Connect to authenticated endpoint
token = await self.get_ws_token()
if not token:
raise KrakenAPIError('EAPI:Invalid key', 'Failed to obtain WebSocket token')
self.websocket = await websockets.connect(self.ws_auth_url)
# Connect to public endpoint
self.public_websocket = await websockets.connect(self.ws_public_url)
# 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"Error during connection: {str(e)}")
# Clean up any partially created tasks/connections
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
status = self.connection_status['private']
time_since_pong = current_time - status['last_pong']
if current_time - status['last_ping'] >= self.ping_interval:
await self.ping()
status['last_ping'] = current_time
if time_since_pong > self.ping_interval + self.pong_timeout:
Logger.warning(f"Missing pong response for private connection (last pong was {time_since_pong:.1f}s ago)")
needs_reconnect = True
time_since_ticker = current_time - self.last_ticker_time
if time_since_ticker > self.ping_interval + self.pong_timeout:
Logger.warning(f"No ticker data received for {time_since_ticker:.1f}s")
needs_reconnect = True
if needs_reconnect:
if reconnect_attempts < self.max_reconnect_attempts:
reconnect_attempts += 1
Logger.warning(f"Connection lost. Attempting reconnection (attempt {reconnect_attempts}/{self.max_reconnect_attempts})")
await self.reconnect()
continue
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."""
Logger.info("Reconnecting to WebSocket...")
# Close existing connections
if self.websocket:
await self.websocket.close()
if self.public_websocket:
await self.public_websocket.close()
# Wait before reconnecting
await asyncio.sleep(self.reconnect_delay)
try:
# Reconnect and resubscribe
token = await self.connect()
await self.subscribe(['balances', 'executions'], token)
# Resubscribe to active trading pairs
if self.active_trading_pairs:
await self.subscribe_ticker(list(self.active_trading_pairs))
Logger.success("Successfully reconnected to WebSocket")
except Exception as e:
Logger.error("Error during reconnection", e)
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."""
try:
while self.running:
message = await self.websocket.recv()
await self.handle_message(message)
except asyncio.CancelledError:
pass
except websockets.exceptions.ConnectionClosed:
Logger.warning("WebSocket connection closed")
self.running = False
except Exception as e:
Logger.error("Error in message handling", e)
self.running = False
"""
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."""
try:
while self.running:
message = await self.public_websocket.recv()
data = json.loads(message)
if isinstance(data, dict) and data.get('event') == 'error':
Logger.error(f"WebSocket error: {data.get('error')}")
continue
# Handle other message types
if data.get('channel') == 'heartbeat':
continue
if data.get('channel') == 'status':
continue
if isinstance(data, dict) and 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.CancelledError:
pass
except websockets.exceptions.ConnectionClosed:
Logger.warning("Public WebSocket connection closed")
except Exception as e:
Logger.error("Error in public message handling", e)
"""
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)
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':
Logger.info(f"Order edit response: {data}")
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."""
for channel in channels:
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
await self.websocket.send(json.dumps(subscribe_message))
Logger.info(f"Subscribed to {channel} channel")
"""
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.info(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
current_time = time.strftime('%H:%M:%S')
Logger.info(f"Portfolio Value: ${total_value:,.2f} ({current_time})")
# Check if we should take profit
# IMPORTANT DO NOT DELETE THIS, commented out for compounding returns, will be used in future
#await self.check_and_take_profit()
"""
Monitors portfolio value and executes profit-taking orders when targets are met.
Sends email notifications for profit-taking attempts.
Raises:
Exception: If profit-taking order fails
"""
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
email_body = (
f"Attempting to take profit of ${PROFIT_INCREMENT:.2f} USDC\n"
f"Amount: ${PROFIT_INCREMENT:.2f} USDC\n"
f"Portfolio Value: ${self.portfolio_value:.2f}\n"
f"Previous High: ${self.highest_portfolio_value:.2f}"
)
#TODO: Fix email sending, not currently working from docker environment
await self.email_manager.send_email(
subject=f"Diophant Grid Bot - Profit Take Attempt {current_time}",
body=email_body,
notification_type="profit_taking",
cooldown_minutes=15
)
# Create market order for USDC
order_message = {
"method": "add_order",
"params": {
"order_type": "market",
"side": "buy",
"cash_order_qty": PROFIT_INCREMENT, # Buy $5 worth of USDC
"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()
# Process all balances in the update
for asset in data.get('data', []):
asset_code = asset.get('asset')
balance = float(asset.get('balance', 0))
self.balances[asset_code] = balance
# Add to tracking set if non-zero balance and not USD
if balance > 0 and asset_code != 'USD':
assets_with_balance.add(asset_code)
# Now check all known balances for non-zero amounts
# This ensures we don't lose tracking of assets not included in this update
for asset_code, balance in self.balances.items():
if 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 for specified symbols."""
if not symbols:
return
for symbol in symbols:
subscribe_message = {
"method": "subscribe",
"params": {
"channel": "ticker",
"symbol": [symbol]
}
}
try:
Logger.info(f"DEBUG: Attempting to subscribe to ticker for {symbol}")
await self.public_websocket.send(json.dumps(subscribe_message))
self.ticker_subscriptions[symbol] = True
Logger.info(f"Subscribed to ticker for: {symbol}")
await asyncio.sleep(SHORT_SLEEP_TIME)
except Exception as e:
Logger.error(f"Error subscribing to ticker for {symbol}", 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)
Logger.info(f"Unsubscribed from ticker for: {symbol}")
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 ticker timestamp
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')
}
#print(f"TICKER: {symbol} Last={ticker_data.get('last')} Bid={ticker_data.get('bid')} Ask={ticker_data.get('ask')}")
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)
Logger.info(f"Order {order_id} for {removed_order.get('symbol')} {exec_type}")
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"New order {order_id} for {symbol}")
elif order_id in self.orders:
self.orders[order_id].update(execution)
"""
Formats and prints execution details for logging purposes.
Args:
execution (dict): Execution data to print
"""
def print_execution(self, execution):
"""Print execution details."""
exec_type = execution.get('exec_type')
if exec_type in ['trade', 'filled']:
print(f"ORDER: Trade {execution.get('symbol')} {execution.get('side')} {execution.get('last_qty')}@{execution.get('last_price')} ID={execution.get('order_id')} Status={execution.get('order_status')}")
else:
# Filter out fields that are N/A
details = {
'symbol': execution.get('symbol'),
'side': execution.get('side'),
'qty': execution.get('order_qty'),
'price': execution.get('limit_price'),
'status': execution.get('order_status'),
'id': execution.get('order_id')
}
# Remove None or N/A values
details = {k: v for k, v in details.items() if v not in [None, 'N/A']}
details_str = ' '.join(f"{k}={v}" for k, v in details.items())
print(f"ORDER: {details_str}")
"""
Processes execution messages for order updates.
Maintains order state and handles various execution types.
Args:
message (dict): Execution message from WebSocket
"""
async def handle_execution_message(self, message):
"""Handle execution messages for order updates."""
if message['type'] == 'snapshot':
self.orders = {}
for execution in message['data']:
if execution['order_status'] not in ['filled', 'canceled', 'expired']:
self.orders[execution['order_id']] = execution
elif message['type'] == 'update':
for execution in message['data']:
order_id = execution['order_id']
if execution['exec_type'] in ['filled', 'canceled', 'expired']:
# Remove completed orders
self.orders.pop(order_id, None)
else:
# Update or add order
if order_id in self.orders:
self.orders[order_id].update(execution)
else:
self.orders[order_id] = 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)
class KrakenGridBot:
def __init__(self, client: KrakenWebSocketClient):
self.client = client
self.active_grids = {} # Dictionary to track active grid trades per trading pair
self.email_manager = EmailManager()
self.grid_settings = {
pair: {
'buy_order_size': settings['size'],
'sell_order_size': settings['size'],
'grid_interval': settings['grid_interval'],
'trail_interval': settings['trail_interval'],
'active_orders': set(), # Track order IDs for this grid
'last_order_time': 0 # Add tracking for last order time
}
for pair, settings in TRADING_PAIRS.items()
}
self.grid_orders = {
pair: {'buy': None, 'sell': None}
for pair in TRADING_PAIRS.keys()
}
def format_price_for_pair(self, trading_pair: str, price: float) -> float: