forked from Endogen/Telegram-Kraken-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram_kraken_bot.py
1675 lines (1248 loc) · 55.8 KB
/
telegram_kraken_bot.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
#!/usr/bin/python3
import json
import logging
import os
import sys
import time
import threading
import datetime
import krakenex
import requests
from enum import Enum, auto
from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, ParseMode
from telegram.ext import Updater, CommandHandler, ConversationHandler, RegexHandler, MessageHandler
from telegram.ext.filters import Filters
# Check if file 'config.json' exists. Exit if not.
if os.path.isfile("config.json"):
# Read configuration
with open("config.json") as config_file:
config = json.load(config_file)
else:
exit("No configuration file 'config.json' found")
# Set up logging
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(name)s - %(message)s")
logger = logging.getLogger()
# Add a file handlers to the logger
if config["log_to_file"]:
# Create a file handler for logging
handler = logging.FileHandler('debug.log')
handler.setLevel(logging.DEBUG)
# Format file handler
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s")
handler.setFormatter(formatter)
# Add file handler to logger
logger.addHandler(handler)
# Set bot token, get dispatcher and job queue
updater = Updater(token=config["bot_token"])
dispatcher = updater.dispatcher
job_queue = updater.job_queue
# Connect to Kraken
kraken = krakenex.API()
kraken.load_key("kraken.key")
# Cached trades history
trades = list()
# Enum for workflow handler
class WorkflowEnum(Enum):
TRADE_BUY_SELL = auto()
TRADE_CURRENCY = auto()
TRADE_SELL_ALL_CONFIRM = auto()
TRADE_PRICE = auto()
TRADE_VOL_TYPE = auto()
TRADE_VOLUME = auto()
TRADE_CONFIRM = auto()
ORDERS_CLOSE = auto()
ORDERS_CLOSE_ORDER = auto()
PRICE_CURRENCY = auto()
VALUE_CURRENCY = auto()
BOT_SUB_CMD = auto()
CHART_CURRENCY = auto()
HISTORY_NEXT = auto()
FUNDING_CURRENCY = auto()
FUNDING_CHOOSE = auto()
WITHDRAW_WALLET = auto()
WITHDRAW_VOLUME = auto()
WITHDRAW_CONFIRM = auto()
SETTINGS_CHANGE = auto()
SETTINGS_SAVE = auto()
SETTINGS_CONFIRM = auto()
# Enum for keyboard buttons
class KeyboardEnum(Enum):
BUY = auto()
SELL = auto()
VOLUME = auto()
ALL = auto()
YES = auto()
NO = auto()
CANCEL = auto()
CLOSE_ORDER = auto()
CLOSE_ALL = auto()
UPDATE_CHECK = auto()
UPDATE = auto()
RESTART = auto()
SHUTDOWN = auto()
NEXT = auto()
DEPOSIT = auto()
WITHDRAW = auto()
SETTINGS = auto()
def clean(self):
return self.name.replace("_", " ")
# Decorator to restrict access if user is not the same as in config
def restrict_access(func):
def _restrict_access(bot, update):
chat_id = get_chat_id(update)
if str(chat_id) != config["user_id"]:
if config["show_access_denied"]:
# Inform user who tried to access
bot.send_message(chat_id, text="Access denied")
# Inform owner of bot
msg = "Access denied for user %s" % chat_id
bot.send_message(config["user_id"], text=msg)
logger.info(msg)
return
else:
return func(bot, update)
return _restrict_access
# Get balance of all currencies
@restrict_access
def balance_cmd(bot, update):
update.message.reply_text("Retrieving data...")
# Send request to Kraken to get current balance of all currencies
res_balance = kraken.query_private("Balance")
# If Kraken replied with an error, show it
if res_balance["error"]:
update.message.reply_text(btfy(res_balance["error"][0]))
return
# Send request to Kraken to get open orders
res_orders = kraken.query_private("OpenOrders")
# If Kraken replied with an error, show it
if res_orders["error"]:
update.message.reply_text(btfy(res_orders["error"][0]))
return
msg = ""
# Go over all currencies in your balance
for currency_key, currency_value in res_balance["result"].items():
available_value = currency_value
if currency_key.startswith("X"):
currency_key = currency_key[1:]
if config["trade_to_currency"] in currency_key:
currency_key = config["trade_to_currency"]
else:
# Go through all open orders and check if a sell-order exists for the currency
if res_orders["result"]["open"]:
for order in res_orders["result"]["open"]:
order_desc = res_orders["result"]["open"][order]["descr"]["order"]
order_desc_list = order_desc.split(" ")
order_currency = order_desc_list[2][:-len(config["trade_to_currency"])]
order_volume = order_desc_list[1]
order_type = order_desc_list[0]
if currency_key == order_currency:
if order_type == "sell":
available_value = str(float(available_value) - float(order_volume))
if trim_zeros(currency_value) is not "0":
msg += currency_key + ": " + trim_zeros(currency_value) + "\n"
# If sell orders exist for this currency, show available volume too
if currency_value is not available_value:
msg = msg[:-len("\n")] + " (Available: " + trim_zeros(available_value) + ")\n"
update.message.reply_text(bold(msg), parse_mode=ParseMode.MARKDOWN)
# Show welcome message, update-state and keyboard for commands
def start_cmd(bot=None, update=None):
msg = "Kraken-Bot is running!\n" + get_update_state()
updater.bot.send_message(config["user_id"], msg, reply_markup=keyboard_cmds())
# Create orders to buy or sell currencies with price limit - choose 'buy' or 'sell'
@restrict_access
def trade_cmd(bot, update):
reply_msg = "Buy or sell?"
buttons = [
KeyboardButton(KeyboardEnum.BUY.clean()),
KeyboardButton(KeyboardEnum.SELL.clean())
]
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_BUY_SELL
# Save if BUY or SELL order and choose the currency to trade
def trade_buy_sell(bot, update, chat_data):
chat_data["buysell"] = update.message.text
reply_msg = "Choose currency"
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
# If SELL chosen, then include button 'ALL' to sell everything
if chat_data["buysell"].upper() == KeyboardEnum.SELL.clean():
cancel_btn.insert(0, KeyboardButton(KeyboardEnum.ALL.clean()))
reply_mrk = ReplyKeyboardMarkup(build_menu(coin_buttons(), n_cols=3, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_CURRENCY
# Show confirmation to sell all assets
def trade_sell_all(bot, update):
msg = "Sell `all` assets to current market price? All open orders will be closed!"
update.message.reply_text(msg, reply_markup=keyboard_confirm(), parse_mode=ParseMode.MARKDOWN)
return WorkflowEnum.TRADE_SELL_ALL_CONFIRM
# Sells all assets for there respective current market value
def trade_sell_all_confirm(bot, update):
if update.message.text == KeyboardEnum.NO.clean():
return cancel(bot, update)
update.message.reply_text("Preparing to sell everything...")
# Send request for open orders to Kraken
res_open_orders = kraken.query_private("OpenOrders")
# If Kraken replied with an error, show it
if res_open_orders["error"]:
update.message.reply_text(btfy(res_open_orders["error"][0]))
return
# Close all currently open orders
if res_open_orders["result"]["open"]:
for order in res_open_orders["result"]["open"]:
req_data = dict()
req_data["txid"] = order
# Send request to Kraken to cancel orders
res_open_orders = kraken.query_private("CancelOrder", req_data)
# If Kraken replied with an error, show it
if res_open_orders["error"]:
msg = "Not possible to close order\n" + order + "\n" + btfy(res_open_orders["error"][0])
update.message.reply_text(msg)
return
# Send request to Kraken to get current balance of all currencies
res_balance = kraken.query_private("Balance")
# If Kraken replied with an error, show it
if res_balance["error"]:
update.message.reply_text(btfy(res_balance["error"][0]))
return
# Go over all assets and sell them
for asset, amount in res_balance["result"].items():
# Current asset is not a crypto-currency - skip it
if asset.endswith(config["trade_to_currency"]):
continue
# Filter out currencies that have a volume of 0
if amount == "0.0000000000":
continue
req_data = dict()
req_data["type"] = "sell"
req_data["pair"] = asset + "Z" + config["trade_to_currency"]
req_data["ordertype"] = "market"
req_data["volume"] = amount
# Send request to create order to Kraken
res_add_order = kraken.query_private("AddOrder", req_data)
# If Kraken replied with an error, show it
if res_add_order["error"]:
update.message.reply_text(btfy(res_add_order["error"][0]))
continue
order_txid = res_add_order["result"]["txid"][0]
# Add Job to JobQueue to check status of created order (if setting is enabled)
if config["check_trade"]:
trade_time = config["check_trade_time"]
context = dict(order_txid=order_txid)
job_queue.run_repeating(order_state_check, trade_time, context=context)
msg = "Created orders to sell all assets"
update.message.reply_text(bold(msg), reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
return ConversationHandler.END
# Save currency to trade and enter price per unit to trade
def trade_currency(bot, update, chat_data):
chat_data["currency"] = update.message.text
reply_msg = "Enter price per unit"
reply_mrk = ReplyKeyboardRemove()
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_PRICE
# Save price per unit and choose how to enter the
# trade volume (euro, volume or all available funds)
def trade_price(bot, update, chat_data):
chat_data["price"] = update.message.text
reply_msg = "How to enter the volume?"
buttons = [
KeyboardButton(config["trade_to_currency"].upper()),
KeyboardButton(KeyboardEnum.VOLUME.clean())
]
cancel_btn = [
KeyboardButton(KeyboardEnum.ALL.clean()),
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_VOL_TYPE
# Save volume type decision and enter volume
def trade_vol_type(bot, update, chat_data):
chat_data["vol_type"] = update.message.text
reply_msg = "Enter volume"
reply_mrk = ReplyKeyboardRemove()
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_VOLUME
# Volume type 'ALL' chosen - meaning that
# all available EURO funds will be used
def trade_vol_type_all(bot, update, chat_data):
update.message.reply_text("Calculating volume...")
if chat_data["buysell"] == KeyboardEnum.BUY.clean():
# Send request to Kraken to get current balance of all currencies
res_balance = kraken.query_private("Balance")
# If Kraken replied with an error, show it
if res_balance["error"]:
update.message.reply_text(btfy(res_balance["error"][0]))
return
available_euros = float(0)
for currency_key, currency_value in res_balance["result"].items():
if config["trade_to_currency"] in currency_key:
available_euros = float(currency_value)
break
# Calculate volume depending on available euro balance and round it to 8 digits
chat_data["volume"] = "{0:.8f}".format(available_euros / float(chat_data["price"]))
if chat_data["buysell"] == KeyboardEnum.SELL.clean():
# Send request to Kraken to get euro balance to calculate volume
res_balance = kraken.query_private("Balance")
# If Kraken replied with an error, show it
if res_balance["error"]:
update.message.reply_text(btfy(res_balance["error"][0]))
return
# Send request to Kraken to get open orders
res_orders = kraken.query_private("OpenOrders")
# If Kraken replied with an error, show it
if res_orders["error"]:
update.message.reply_text(btfy(res_orders["error"][0]))
return
# Lookup volume of chosen currency
for currency, currency_volume in res_balance["result"].items():
if chat_data["currency"] in currency:
available_volume = currency_volume
break
# Go through all open orders and check if sell-orders exists for the currency
# If yes, subtract there volume from the available volume
if res_orders["result"]["open"]:
for order in res_orders["result"]["open"]:
order_desc = res_orders["result"]["open"][order]["descr"]["order"]
order_desc_list = order_desc.split(" ")
order_currency = order_desc_list[2][:-len(config["trade_to_currency"])]
order_volume = order_desc_list[1]
order_type = order_desc_list[0]
if chat_data["currency"] in order_currency:
if order_type == "sell":
available_volume = str(float(available_volume) - float(order_volume))
# Get volume from balance and round it to 8 digits
chat_data["volume"] = "{0:.8f}".format(float(available_volume))
# If available volume is 0, return without creating a trade
if chat_data["volume"] == "0.00000000":
msg = "Available " + chat_data["currency"] + " volume is 0"
update.message.reply_text(msg, reply_markup=keyboard_cmds())
return ConversationHandler.END
else:
show_trade_conf(update, chat_data)
return WorkflowEnum.TRADE_CONFIRM
# Calculate the volume depending on chosen volume type (EURO or VOLUME)
def trade_volume(bot, update, chat_data):
# Entered currency from config (EUR, USD, ...)
if chat_data["vol_type"] == config["trade_to_currency"].upper():
amount = float(update.message.text)
price_per_unit = float(chat_data["price"])
chat_data["volume"] = "{0:.8f}".format(amount / price_per_unit)
# Entered VOLUME
elif chat_data["vol_type"] == KeyboardEnum.VOLUME.clean():
chat_data["volume"] = "{0:.8f}".format(float(update.message.text))
show_trade_conf(update, chat_data)
return WorkflowEnum.TRADE_CONFIRM
# Calculate total value and show order description and confirmation for order creation
# This method is used in 'trade_volume' and in 'trade_vol_type_all'
def show_trade_conf(update, chat_data):
# Show confirmation for placing order
trade_str = (chat_data["buysell"].lower() + " " +
trim_zeros(chat_data["volume"]) + " " +
chat_data["currency"] + " @ limit " +
chat_data["price"])
# Calculate total value of order
total_value = "{0:.2f}".format(float(chat_data["volume"]) * float(chat_data["price"]))
total_value_str = "(Value: " + str(total_value) + " " + config["trade_to_currency"] + ")"
reply_msg = "Place this order?\n" + trade_str + "\n" + total_value_str
update.message.reply_text(reply_msg, reply_markup=keyboard_confirm())
# The user has to confirm placing the order
def trade_confirm(bot, update, chat_data):
if update.message.text == KeyboardEnum.NO.clean():
return cancel(bot, update)
update.message.reply_text("Placing order...")
req_data = dict()
req_data["type"] = chat_data["buysell"].lower()
req_data["price"] = chat_data["price"]
req_data["ordertype"] = "limit"
req_data["volume"] = chat_data["volume"]
# If currency is BCH then use different pair string
if chat_data["currency"] == "BCH":
req_data["pair"] = chat_data["currency"] + config["trade_to_currency"]
else:
req_data["pair"] = "X" + chat_data["currency"] + "Z" + config["trade_to_currency"]
# Send request to create order to Kraken
res_add_order = kraken.query_private("AddOrder", req_data)
# If Kraken replied with an error, show it
if res_add_order["error"]:
update.message.reply_text(btfy(res_add_order["error"][0]))
return
# If there is a transaction id then the order was placed successfully
if res_add_order["result"]["txid"]:
order_txid = res_add_order["result"]["txid"][0]
req_data = dict()
req_data["txid"] = order_txid
# Send request to get info on specific order
res_query_order = kraken.query_private("QueryOrders", req_data)
# If Kraken replied with an error, show it
if res_query_order["error"]:
update.message.reply_text(btfy(res_query_order["error"][0]))
return
if res_query_order["result"][order_txid]:
order_desc = res_query_order["result"][order_txid]["descr"]["order"]
msg = "Order placed:\n" + order_txid + "\n" + trim_zeros(order_desc)
update.message.reply_text(bold(msg), reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
# Add Job to JobQueue to check status of created order (if setting is enabled)
if config["check_trade"]:
trade_time = config["check_trade_time"]
context = dict(order_txid=order_txid)
job_queue.run_repeating(order_state_check, trade_time, context=context)
else:
update.message.reply_text("No order with TXID " + order_txid)
else:
update.message.reply_text("Undefined state: no error and no TXID")
return ConversationHandler.END
# Show and manage orders
@restrict_access
def orders_cmd(bot, update):
update.message.reply_text("Retrieving data...")
# Send request to Kraken to get open orders
res_data = kraken.query_private("OpenOrders")
# If Kraken replied with an error, show it
if res_data["error"]:
update.message.reply_text(btfy(res_data["error"][0]))
return
# Go through all open orders and show them to the user
if res_data["result"]["open"]:
for order in res_data["result"]["open"]:
order_desc = trim_zeros(res_data["result"]["open"][order]["descr"]["order"])
update.message.reply_text(bold(order + "\n" + order_desc), parse_mode=ParseMode.MARKDOWN)
else:
update.message.reply_text("No open orders")
return ConversationHandler.END
reply_msg = "What do you want to do?"
buttons = [
KeyboardButton(KeyboardEnum.CLOSE_ORDER.clean()),
KeyboardButton(KeyboardEnum.CLOSE_ALL.clean())
]
close_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=close_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.ORDERS_CLOSE
# Choose what to do with the open orders
def orders_choose_order(bot, update):
update.message.reply_text("Looking up open orders...")
# Send request for open orders to Kraken
res_data = kraken.query_private("OpenOrders")
# If Kraken replied with an error, show it
if res_data["error"]:
update.message.reply_text(btfy(res_data["error"][0]))
return
buttons = list()
# Go through all open orders and create a button
if res_data["result"]["open"]:
for order in res_data["result"]["open"]:
buttons.append(KeyboardButton(order))
else:
update.message.reply_text("No open orders")
return ConversationHandler.END
msg = "Which order to close?"
close_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=1, footer_buttons=close_btn))
update.message.reply_text(msg, reply_markup=reply_mrk)
return WorkflowEnum.ORDERS_CLOSE_ORDER
# Close all open orders
def orders_close_all(bot, update):
update.message.reply_text("Closing orders...")
# Send request for open orders to Kraken
res_data = kraken.query_private("OpenOrders")
# If Kraken replied with an error, show it
if res_data["error"]:
update.message.reply_text(btfy(res_data["error"][0]))
return
closed_orders = list()
if res_data["result"]["open"]:
for order in res_data["result"]["open"]:
req_data = dict()
req_data["txid"] = order
# Send request to Kraken to cancel orders
res_data = kraken.query_private("CancelOrder", req_data)
# If Kraken replied with an error, show it
if res_data["error"]:
msg = "Not possible to close order\n" + order + "\n" + btfy(res_data["error"][0])
update.message.reply_text(msg)
else:
closed_orders.append(order)
if closed_orders:
msg = bold("Orders closed:\n" + "\n".join(closed_orders))
update.message.reply_text(msg, reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
else:
update.message.reply_text("No orders closed")
return
else:
update.message.reply_text("No open orders", reply_markup=keyboard_cmds())
return ConversationHandler.END
# Close the specified order
def orders_close_order(bot, update):
update.message.reply_text("Closing order...")
req_data = dict()
req_data["txid"] = update.message.text
# Send request to Kraken to cancel order
res_data = kraken.query_private("CancelOrder", req_data)
# If Kraken replied with an error, show it
if res_data["error"]:
update.message.reply_text(btfy(res_data["error"][0]))
return
msg = bold("Order closed:\n" + req_data["txid"])
update.message.reply_text(msg, reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
return ConversationHandler.END
# Show the last trade price for a currency
@restrict_access
def price_cmd(bot, update):
reply_msg = "Choose currency"
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(coin_buttons(), n_cols=3, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.PRICE_CURRENCY
# Choose for which currency to show the last trade price
def price_currency(bot, update):
update.message.reply_text("Retrieving data...")
req_data = dict()
# If currency is BCH then use different pair string
if update.message.text == "BCH":
req_data["pair"] = update.message.text + config["trade_to_currency"]
else:
req_data["pair"] = "X" + update.message.text + "Z" + config["trade_to_currency"]
# Send request to Kraken to get current trading price for currency-pair
res_data = kraken.query_public("Ticker", req_data)
# If Kraken replied with an error, show it
if res_data["error"]:
update.message.reply_text(btfy(res_data["error"][0]))
return
currency = update.message.text
last_trade_price = trim_zeros(res_data["result"][req_data["pair"]]["c"][0])
msg = bold(currency + ": " + last_trade_price + " " + config["trade_to_currency"])
update.message.reply_text(msg, reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
return ConversationHandler.END
# Show the current real money value for a certain asset or for all assets combined
@restrict_access
def value_cmd(bot, update):
reply_msg = "Choose currency"
footer_btns = [
KeyboardButton(KeyboardEnum.ALL.clean()),
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(coin_buttons(), n_cols=3, footer_buttons=footer_btns))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.VALUE_CURRENCY
# Choose for which currency you want to know the current value
def value_currency(bot, update):
update.message.reply_text("Retrieving current value...")
# Get balance of all currencies
if update.message.text == KeyboardEnum.ALL.clean():
req_asset = dict()
req_asset["asset"] = config["trade_to_currency"]
# Send request to Kraken tp obtain the combined balance of all currencies
res_trade_balance = kraken.query_private("TradeBalance", req_asset)
# If Kraken replied with an error, show it
if res_trade_balance["error"]:
update.message.reply_text(btfy(res_trade_balance["error"][0]))
return
# Show only 2 digits after decimal place
total_value_euro = "{0:.2f}".format(float(res_trade_balance["result"]["eb"]))
# Generate message to user
msg = "Overall: " + total_value_euro + " " + config["trade_to_currency"]
update.message.reply_text(bold(msg), reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
# Get balance of a specific coin
else:
# Send request to Kraken to get current balance of all currencies
res_balance = kraken.query_private("Balance")
# If Kraken replied with an error, show it
if res_balance["error"]:
update.message.reply_text(btfy(res_balance["error"][0]))
return
req_price = dict()
if update.message.text == "BCH":
req_price["pair"] = update.message.text + config["trade_to_currency"]
else:
req_price["pair"] = "X" + update.message.text + "Z" + config["trade_to_currency"]
# Send request to Kraken to get current trading price for currency-pair
res_price = kraken.query_public("Ticker", req_price)
# If Kraken replied with an error, show it
if res_price["error"]:
update.message.reply_text(btfy(res_price["error"][0]))
return
# Get last trade price
pair = list(res_price["result"].keys())[0]
last_price = res_price["result"][pair]["c"][0]
value_euro = float(0)
for currency, currency_balance in res_balance["result"].items():
if update.message.text in currency:
# Calculate value by multiplying balance with last trade price
value_euro = float(currency_balance) * float(last_price)
# Show only 2 digits after decimal place
value_euro = "{0:.2f}".format(value_euro)
msg = update.message.text + ": " + value_euro + " " + config["trade_to_currency"]
# Add last trade price to msg
last_trade_price = "{0:.2f}".format(float(last_price))
msg += "\n(Ticker: " + last_trade_price + " " + config["trade_to_currency"] + ")"
update.message.reply_text(bold(msg), reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
return ConversationHandler.END
# Shows executed trades with volume and price
@restrict_access
def history_cmd(bot, update):
# Reset global trades dictionary
global trades
trades = list()
update.message.reply_text("Retrieving history data...")
# Send request to Kraken to get trades history
res_trades = kraken.query_private("TradesHistory")
# If Kraken replied with an error, show it
if res_trades["error"]:
update.message.reply_text(btfy(res_trades["error"][0]))
return
# Add all trades to global list
for trade_id, trade_details in res_trades["result"]["trades"].items():
trades.append(trade_details)
if trades:
# Sort global list with trades - on executed time
trades = sorted(trades, key=lambda k: k['time'], reverse=True)
buttons = [
KeyboardButton(KeyboardEnum.NEXT.clean())
]
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
# Get first item in list (latest trade)
newest_trade = next(iter(trades), None)
trade_str = (newest_trade["type"] + " " +
trim_zeros(newest_trade["vol"]) + " " +
newest_trade["pair"][1:] + " @ limit " +
trim_zeros(newest_trade["price"]) + " on " +
datetime_from_timestamp(newest_trade["time"]))
total_value = "{0:.2f}".format(float(newest_trade["price"]) * float(newest_trade["vol"]))
msg = trade_str + " (Value: " + total_value + " EUR)"
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=1, footer_buttons=cancel_btn))
update.message.reply_text(bold(msg), reply_markup=reply_mrk, parse_mode=ParseMode.MARKDOWN)
# Remove the first item in the trades list
trades.remove(newest_trade)
return WorkflowEnum.HISTORY_NEXT
else:
update.message.reply_text("No item in trade history", reply_markup=keyboard_cmds())
return ConversationHandler.END
# Save if BUY, SELL or ALL trade history and choose how many entries to list
def history_next(bot, update):
if trades:
# Get first item in list (latest trade)
newest_trade = next(iter(trades), None)
trade_str = (newest_trade["type"] + " " +
trim_zeros(newest_trade["vol"]) + " " +
newest_trade["pair"][1:] + " @ limit " +
trim_zeros(newest_trade["price"]) + " on " +
datetime_from_timestamp(newest_trade["time"]))
total_value = "{0:.2f}".format(float(newest_trade["price"]) * float(newest_trade["vol"]))
msg = trade_str + " (Value: " + total_value + " EUR)"
update.message.reply_text(bold(msg), parse_mode=ParseMode.MARKDOWN)
# Remove the first item in the trades list
trades.remove(newest_trade)
return WorkflowEnum.HISTORY_NEXT
else:
update.message.reply_text("Trade history is empty", reply_markup=keyboard_cmds())
return ConversationHandler.END
# Shows sub-commands to control the bot
@restrict_access
def bot_cmd(bot, update):
reply_msg = "What do you want to do?"
buttons = [
KeyboardButton(KeyboardEnum.UPDATE_CHECK.clean()),
KeyboardButton(KeyboardEnum.UPDATE.clean()),
KeyboardButton(KeyboardEnum.RESTART.clean()),
KeyboardButton(KeyboardEnum.SHUTDOWN.clean()),
KeyboardButton(KeyboardEnum.SETTINGS.clean()),
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.BOT_SUB_CMD
# Execute chosen sub-cmd of 'bot' cmd
def bot_sub_cmd(bot, update):
# Update check
if update.message.text == KeyboardEnum.UPDATE_CHECK.clean():
update.message.reply_text(get_update_state())
return
# Update
elif update.message.text == KeyboardEnum.UPDATE.clean():
return update_cmd(bot, update)
# Restart
elif update.message.text == KeyboardEnum.RESTART.clean():
restart_cmd(bot, update)
# Shutdown
elif update.message.text == KeyboardEnum.SHUTDOWN.clean():
shutdown_cmd(bot, update)
# Cancel
elif update.message.text == KeyboardEnum.CANCEL.clean():
return cancel(bot, update)
# Show links to Kraken currency charts
@restrict_access
def chart_cmd(bot, update):
reply_msg = "Choose currency"
buttons = list()
for coin, url in config["coin_charts"].items():
buttons.append(KeyboardButton(coin))
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=3, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.CHART_CURRENCY
# Get chart URL for every coin in config
def chart_currency(bot, update):
currency = update.message.text
for coin, url in config["coin_charts"].items():
if currency == coin:
update.message.reply_text(url, reply_markup=keyboard_cmds())
break
return ConversationHandler.END
# Choose currency to deposit or withdraw funds to / from
@restrict_access
def funding_cmd(bot, update):
reply_msg = "Choose currency"
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(coin_buttons(), n_cols=3, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.FUNDING_CURRENCY
# Choose withdraw or deposit
def funding_currency(bot, update, chat_data):
chat_data["currency"] = update.message.text.upper()
reply_msg = "What do you want to do?"
buttons = [
KeyboardButton(KeyboardEnum.DEPOSIT.clean()),
KeyboardButton(KeyboardEnum.WITHDRAW.clean())
]
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn))
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.FUNDING_CHOOSE
# Get wallet addresses to deposit to
def funding_deposit(bot, update, chat_data):
update.message.reply_text("Retrieving wallets to deposit...")
req_data = dict()
req_data["asset"] = chat_data["currency"]