-
Notifications
You must be signed in to change notification settings - Fork 76
/
telegram_kraken_bot.py
2281 lines (1722 loc) · 79.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
# coding: utf-8
import re
import os
import sys
import json
import time
import inspect
import logging
import datetime
import threading
from enum import Enum, auto
import requests
import krakenex
from bs4 import BeautifulSoup
from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, ParseMode
from telegram.ext import Updater, CommandHandler, ConversationHandler, RegexHandler, MessageHandler
from telegram.ext.filters import Filters
# Emojis for messages
e_err = "‼ " # Error
e_wit = "⏳ " # Wait
e_fns = "🏁 " # Finished
e_ntf = "🔔 " # Notify
e_bgn = "✨ " # Beginning
e_cnc = "❌ " # Cancel
e_top = "👍 " # Top
e_dne = "✔ " # Done
e_fld = "✖ " # Failed
e_gby = "👋 " # Goodbye
e_qst = "❓ " # Question
# 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
# Formatter string for logging
formatter_str = "%(asctime)s - %(levelname)s - %(name)s - %(message)s"
date_format = "%y%m%d"
# Folder name for logfiles
log_dir = "log"
# Do not use the logger directly. Use function 'log(msg, severity)'
logging.basicConfig(level=config["log_level"], format=formatter_str)
logger = logging.getLogger()
# Current date for logging
date = datetime.datetime.now().strftime(date_format)
# Add a file handler to the logger if enabled
if config["log_to_file"]:
# If log directory doesn't exist, create it
if not os.path.exists(log_dir):
os.makedirs(log_dir)
# Create a file handler for logging
logfile_path = os.path.join(log_dir, date + ".log")
handler = logging.FileHandler(logfile_path, encoding="utf-8")
handler.setLevel(config["log_level"])
# Format file handler
formatter = logging.Formatter(formatter_str)
handler.setFormatter(formatter)
# Add file handler to logger
logger.addHandler(handler)
# Redirect all uncaught exceptions to logfile
sys.stderr = open(logfile_path, "w")
# 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 objects
# All successfully executed trades
trades = list()
# All open orders
orders = list()
# All assets with internal long name & external short name
assets = dict()
# All assets from config with their trading pair
pairs = dict()
# Minimum order limits for assets
limits = dict()
# 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_VOLUME_ASSET = auto()
TRADE_CONFIRM = auto()
ORDERS_CLOSE = auto()
ORDERS_CLOSE_ORDER = auto()
PRICE_CURRENCY = auto()
VALUE_CURRENCY = auto()
BOT_SUB_CMD = auto()
CHART_CURRENCY = auto()
TRADES_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()
API_STATE = auto()
MARKET_PRICE = auto()
def clean(self):
return self.name.replace("_", " ")
# Log an event and save it in a file with current date as name if enabled
def log(severity, msg):
# Check if logging is enabled
if config["log_level"] is 0:
return
# Add file handler to logger if enabled
if config["log_to_file"]:
now = datetime.datetime.now().strftime(date_format)
# If current date not the same as initial one, create new FileHandler
if str(now) != str(date):
# Remove old handlers
for hdlr in logger.handlers[:]:
logger.removeHandler(hdlr)
new_hdlr = logging.FileHandler(logfile_path, encoding="utf-8")
new_hdlr.setLevel(config["log_level"])
# Format file handler
new_hdlr.setFormatter(formatter)
# Add file handler to logger
logger.addHandler(new_hdlr)
# The actual logging
logger.log(severity, msg)
# Issue Kraken API requests
def kraken_api(method, data=None, private=False, retries=None):
# Get arguments of this function
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
# Get name of caller function
caller = inspect.currentframe().f_back.f_code.co_name
# Log caller of this function and all arguments
log(logging.DEBUG, caller + " - args: " + str([(i, values[i]) for i in args]))
try:
if private:
return kraken.query_private(method, data)
else:
return kraken.query_public(method, data)
except Exception as ex:
log(logging.ERROR, str(ex))
ex_name = type(ex).__name__
# Handle the following exceptions immediately without retrying
# Mostly this means that the API keys are not correct
if "Incorrect padding" in str(ex):
msg = "Incorrect padding: please verify that your Kraken API keys are valid"
return {"error": [msg]}
# No need to retry if the API service is not available right now
elif "Service:Unavailable" in str(ex):
msg = "Service: Unavailable"
return {"error": [msg]}
# Is retrying on error enabled?
if config["retries"] > 0:
# It's the first call, start retrying
if retries is None:
retries = config["retries"]
return kraken_api(method, data, private, retries)
# If 'retries' is bigger then 0, decrement it and retry again
elif retries > 0:
retries -= 1
return kraken_api(method, data, private, retries)
# Return error from last Kraken request
else:
return {"error": [ex_name + ":" + str(ex)]}
# Retrying on error not enabled, return error from last Kraken request
else:
return {"error": [ex_name + ":" + str(ex)]}
# 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)
log(logging.WARNING, 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(e_wit + "Retrieving balance...")
# Send request to Kraken to get current balance of all currencies
res_balance = kraken_api("Balance", private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_balance, update):
return
# Send request to Kraken to get open orders
res_orders = kraken_api("OpenOrders", private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_orders, update):
return
msg = str()
# Go over all currencies in your balance
for currency_key, currency_value in res_balance["result"].items():
available_value = currency_value
# Go through all open orders and check if an 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_type = order_desc_list[0]
order_volume = order_desc_list[1]
price_per_coin = order_desc_list[5]
# Check if asset is fiat-currency (EUR, USD, ...) and BUY order
if currency_key.startswith("Z") and order_type == "buy":
available_value = float(available_value) - (float(order_volume) * float(price_per_coin))
# Current asset is a coin and not a fiat currency
else:
for asset, data in assets.items():
if order_desc_list[2].endswith(data["altname"]):
order_currency = order_desc_list[2][:-len(data["altname"])]
break
# Reduce current volume for coin if open sell-order exists
if assets[currency_key]["altname"] == order_currency and order_type == "sell":
available_value = float(available_value) - float(order_volume)
# Only show assets with volume > 0
if trim_zeros(currency_value) is not "0":
msg += bold(assets[currency_key]["altname"] + ": " + trim_zeros(currency_value) + "\n")
available_value = trim_zeros(float(available_value))
currency_value = trim_zeros(float(currency_value))
# If orders exist for this asset, show available volume too
if currency_value == available_value:
msg += "(Available: all)\n"
else:
msg += "(Available: " + available_value + ")\n"
update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN)
# 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())]
menu = build_menu(buttons, n_cols=2, footer_buttons=cancel_btn)
reply_mrk = ReplyKeyboardMarkup(menu, resize_keyboard=True)
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):
# Clear data in case command is executed again without properly exiting first
clear_chat_data(chat_data)
chat_data["buysell"] = update.message.text.lower()
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()))
menu = build_menu(coin_buttons(), n_cols=3, footer_buttons=cancel_btn)
reply_mrk = ReplyKeyboardMarkup(menu, resize_keyboard=True)
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 = e_qst + "Sell " + bold("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.upper() == KeyboardEnum.NO.clean():
return cancel(bot, update)
update.message.reply_text(e_wit + "Preparing to sell everything...")
# Send request for open orders to Kraken
res_open_orders = kraken_api("OpenOrders", private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_open_orders, update):
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_api("CancelOrder", data=req_data, private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_open_orders, update, "Not possible to close order\n" + order + "\n"):
return
# Send request to Kraken to get current balance of all assets
res_balance = kraken_api("Balance", private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_balance, update):
return
# Go over all assets and sell them
for balance_asset, amount in res_balance["result"].items():
# Asset is fiat-currency and not crypto-currency - skip it
if balance_asset.startswith("Z"):
continue
# Filter out 0 volume currencies
if amount == "0.0000000000":
continue
# Get clean asset name
balance_asset = assets[balance_asset]["altname"]
# Make sure that the order size is at least the minimum order limit
if balance_asset in limits:
if float(amount) < float(limits[balance_asset]):
msg_error = e_err + "Volume to low. Must be > " + limits[balance_asset]
msg_next = "Selling next asset..."
update.message.reply_text(msg_error + "\n" + msg_next)
log(logging.WARNING, msg_error)
continue
else:
log(logging.WARNING, "No minimum order limit in config for coin " + balance_asset)
continue
req_data = dict()
req_data["type"] = "sell"
req_data["trading_agreement"] = "agree"
req_data["pair"] = pairs[balance_asset]
req_data["ordertype"] = "market"
req_data["volume"] = amount
# Send request to create order to Kraken
res_add_order = kraken_api("AddOrder", data=req_data, private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_add_order, update):
continue
msg = e_fns + "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.upper()
asset_one, asset_two = assets_in_pair(pairs[chat_data["currency"]])
chat_data["one"] = asset_one
chat_data["two"] = asset_two
button = [KeyboardButton(KeyboardEnum.MARKET_PRICE.clean())]
cancel_btn = [KeyboardButton(KeyboardEnum.CANCEL.clean())]
reply_mrk = ReplyKeyboardMarkup(build_menu(button, footer_buttons=cancel_btn), resize_keyboard=True)
reply_msg = "Enter price per coin in " + bold(assets[chat_data["two"]]["altname"])
update.message.reply_text(reply_msg, reply_markup=reply_mrk, parse_mode=ParseMode.MARKDOWN)
return WorkflowEnum.TRADE_PRICE
# Save price per unit and choose how to enter the
# trade volume (fiat currency, volume or all available funds)
def trade_price(bot, update, chat_data):
# Check if key 'market_price' already exists. Yes means that we
# already saved the values and we only need to enter the volume again
if "market_price" not in chat_data:
if update.message.text.upper() == KeyboardEnum.MARKET_PRICE.clean():
chat_data["market_price"] = True
else:
chat_data["market_price"] = False
chat_data["price"] = update.message.text.upper().replace(",", ".")
reply_msg = "How to enter the volume?"
# If price is 'MARKET PRICE' and it's a buy-order, don't show options
# how to enter volume since there is only one way to do it
if chat_data["market_price"] and chat_data["buysell"] == "buy":
cancel_btn = build_menu([KeyboardButton(KeyboardEnum.CANCEL.clean())])
reply_mrk = ReplyKeyboardMarkup(cancel_btn, resize_keyboard=True)
update.message.reply_text("Enter volume", reply_markup=reply_mrk)
chat_data["vol_type"] = KeyboardEnum.VOLUME.clean()
return WorkflowEnum.TRADE_VOLUME
elif chat_data["market_price"] and chat_data["buysell"] == "sell":
buttons = [
KeyboardButton(KeyboardEnum.ALL.clean()),
KeyboardButton(KeyboardEnum.VOLUME.clean())
]
cancel_btn = [KeyboardButton(KeyboardEnum.CANCEL.clean())]
cancel_btn = build_menu(buttons, n_cols=2, footer_buttons=cancel_btn)
reply_mrk = ReplyKeyboardMarkup(cancel_btn, resize_keyboard=True)
else:
buttons = [
KeyboardButton(assets[chat_data["two"]]["altname"]),
KeyboardButton(KeyboardEnum.VOLUME.clean()),
KeyboardButton(KeyboardEnum.ALL.clean())
]
cancel_btn = [KeyboardButton(KeyboardEnum.CANCEL.clean())]
cancel_btn = build_menu(buttons, n_cols=3, footer_buttons=cancel_btn)
reply_mrk = ReplyKeyboardMarkup(cancel_btn, resize_keyboard=True)
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_asset(bot, update, chat_data):
# Check if correct currency entered
if chat_data["two"].endswith(update.message.text.upper()):
chat_data["vol_type"] = update.message.text.upper()
else:
update.message.reply_text(e_err + "Entered volume type not valid")
return WorkflowEnum.TRADE_VOL_TYPE
reply_msg = "Enter volume in " + bold(chat_data["vol_type"])
cancel_btn = build_menu([KeyboardButton(KeyboardEnum.CANCEL.clean())])
reply_mrk = ReplyKeyboardMarkup(cancel_btn, resize_keyboard=True)
update.message.reply_text(reply_msg, reply_markup=reply_mrk, parse_mode=ParseMode.MARKDOWN)
return WorkflowEnum.TRADE_VOLUME_ASSET
# Volume type 'VOLUME' chosen - meaning that
# you can enter the volume directly
def trade_vol_volume(bot, update, chat_data):
chat_data["vol_type"] = update.message.text.upper()
reply_msg = "Enter volume"
cancel_btn = build_menu([KeyboardButton(KeyboardEnum.CANCEL.clean())])
reply_mrk = ReplyKeyboardMarkup(cancel_btn, resize_keyboard=True)
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_VOLUME
# Volume type 'ALL' chosen - meaning that
# all available funds will be used
def trade_vol_all(bot, update, chat_data):
update.message.reply_text(e_wit + "Calculating volume...")
# Send request to Kraken to get current balance of all currencies
res_balance = kraken_api("Balance", private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_balance, update):
return
# Send request to Kraken to get open orders
res_orders = kraken_api("OpenOrders", private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_orders, update):
return
# BUY -----------------
if chat_data["buysell"].upper() == KeyboardEnum.BUY.clean():
# Get amount of available currency to buy from
avail_buy_from_cur = float(res_balance["result"][chat_data["two"]])
# Go through all open orders and check if buy-orders exist
# If yes, subtract their value from the total of currency to buy from
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(" ")
coin_price = trim_zeros(order_desc_list[5])
order_volume = order_desc_list[1]
order_type = order_desc_list[0]
if order_type == "buy":
avail_buy_from_cur = float(avail_buy_from_cur) - (float(order_volume) * float(coin_price))
# Calculate volume depending on available trade-to balance and round it to 8 digits
chat_data["volume"] = trim_zeros(avail_buy_from_cur / float(chat_data["price"]))
# If available volume is 0, return without creating an order
if chat_data["volume"] == "0.00000000":
msg = e_err + "Available " + assets[chat_data["two"]]["altname"] + " volume is 0"
update.message.reply_text(msg, reply_markup=keyboard_cmds())
return ConversationHandler.END
else:
trade_show_conf(update, chat_data)
# SELL -----------------
if chat_data["buysell"].upper() == KeyboardEnum.SELL.clean():
available_volume = res_balance["result"][chat_data["one"]]
# Go through all open orders and check if sell-orders exists for the currency
# If yes, subtract their 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(" ")
# Get the currency of the order
for asset, data in assets.items():
if order_desc_list[2].endswith(data["altname"]):
order_currency = order_desc_list[2][:-len(data["altname"])]
break
order_volume = order_desc_list[1]
order_type = order_desc_list[0]
# Check if currency from oder is the same as currency to sell
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"] = trim_zeros(float(available_volume))
# If available volume is 0, return without creating an order
if chat_data["volume"] == "0.00000000":
msg = e_err + "Available " + chat_data["currency"] + " volume is 0"
update.message.reply_text(msg, reply_markup=keyboard_cmds())
return ConversationHandler.END
else:
trade_show_conf(update, chat_data)
return WorkflowEnum.TRADE_CONFIRM
# Calculate the volume depending on entered volume type currency
def trade_volume_asset(bot, update, chat_data):
amount = float(update.message.text.replace(",", "."))
price_per_unit = float(chat_data["price"])
chat_data["volume"] = trim_zeros(amount / price_per_unit)
# Make sure that the order size is at least the minimum order limit
if chat_data["currency"] in limits:
if float(chat_data["volume"]) < float(limits[chat_data["currency"]]):
msg_error = e_err + "Volume to low. Must be > " + limits[chat_data["currency"]]
update.message.reply_text(msg_error)
log(logging.WARNING, msg_error)
reply_msg = "Enter new volume"
cancel_btn = build_menu([KeyboardButton(KeyboardEnum.CANCEL.clean())])
reply_mrk = ReplyKeyboardMarkup(cancel_btn, resize_keyboard=True)
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_VOLUME
else:
log(logging.WARNING, "No minimum order limit in config for coin " + chat_data["currency"])
trade_show_conf(update, chat_data)
return WorkflowEnum.TRADE_CONFIRM
# Calculate the volume depending on entered volume type 'VOLUME'
def trade_volume(bot, update, chat_data):
chat_data["volume"] = trim_zeros(float(update.message.text.replace(",", ".")))
# Make sure that the order size is at least the minimum order limit
if chat_data["currency"] in limits:
if float(chat_data["volume"]) < float(limits[chat_data["currency"]]):
msg_error = e_err + "Volume to low. Must be > " + limits[chat_data["currency"]]
update.message.reply_text(msg_error)
log(logging.WARNING, msg_error)
reply_msg = "Enter new volume"
cancel_btn = build_menu([KeyboardButton(KeyboardEnum.CANCEL.clean())])
reply_mrk = ReplyKeyboardMarkup(cancel_btn, resize_keyboard=True)
update.message.reply_text(reply_msg, reply_markup=reply_mrk)
return WorkflowEnum.TRADE_VOLUME
else:
log(logging.WARNING, "No minimum order limit in config for coin " + chat_data["currency"])
trade_show_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 trade_show_conf(update, chat_data):
asset_two = assets[chat_data["two"]]["altname"]
# Generate trade string to show at confirmation
if chat_data["market_price"]:
update.message.reply_text(e_wit + "Retrieving estimated price...")
# Send request to Kraken to get current trading price for pair
res_data = kraken_api("Ticker", data={"pair": pairs[chat_data["currency"]]}, private=False)
# If Kraken replied with an error, show it
if handle_api_error(res_data, update):
return
chat_data["price"] = res_data["result"][pairs[chat_data["currency"]]]["c"][0]
chat_data["trade_str"] = (chat_data["buysell"].lower() + " " +
trim_zeros(chat_data["volume"]) + " " +
chat_data["currency"] + " @ market price ≈" +
trim_zeros(chat_data["price"]) + " " +
asset_two)
else:
chat_data["trade_str"] = (chat_data["buysell"].lower() + " " +
trim_zeros(chat_data["volume"]) + " " +
chat_data["currency"] + " @ limit " +
trim_zeros(chat_data["price"]) + " " +
asset_two)
# If fiat currency, then show 2 digits after decimal place
if chat_data["two"].startswith("Z"):
# Calculate total value of order
total_value = trim_zeros(float(chat_data["volume"]) * float(chat_data["price"]), 2)
# Else, show 8 digits after decimal place
else:
# Calculate total value of order
total_value = trim_zeros(float(chat_data["volume"]) * float(chat_data["price"]))
if chat_data["market_price"]:
total_value_str = "(Value: ≈" + str(trim_zeros(total_value)) + " " + asset_two + ")"
else:
total_value_str = "(Value: " + str(trim_zeros(total_value)) + " " + asset_two + ")"
msg = e_qst + "Place this order?\n" + chat_data["trade_str"] + "\n" + total_value_str
update.message.reply_text(msg, reply_markup=keyboard_confirm())
# The user has to confirm placing the order
def trade_confirm(bot, update, chat_data):
if update.message.text.upper() == KeyboardEnum.NO.clean():
return cancel(bot, update, chat_data=chat_data)
update.message.reply_text(e_wit + "Placing order...")
req_data = dict()
req_data["type"] = chat_data["buysell"].lower()
req_data["volume"] = chat_data["volume"]
req_data["pair"] = pairs[chat_data["currency"]]
# Order type MARKET
if chat_data["market_price"]:
req_data["ordertype"] = "market"
req_data["trading_agreement"] = "agree"
# Order type LIMIT
else:
req_data["ordertype"] = "limit"
req_data["price"] = chat_data["price"]
# Send request to create order to Kraken
res_add_order = kraken_api("AddOrder", req_data, private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_add_order, update):
return
# If there is a transaction ID then the order was placed successfully
if res_add_order["result"]["txid"]:
msg = e_fns + "Order placed:\n" + res_add_order["result"]["txid"][0] + "\n" + chat_data["trade_str"]
update.message.reply_text(bold(msg), reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
else:
update.message.reply_text("Undefined state: no error and no TXID")
clear_chat_data(chat_data)
return ConversationHandler.END
# Show and manage orders
@restrict_access
def orders_cmd(bot, update):
update.message.reply_text(e_wit + "Retrieving orders...")
# Send request to Kraken to get open orders
res_data = kraken_api("OpenOrders", private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_data, update):
return
# Reset global orders list
global orders
orders = list()
# Go through all open orders and show them to the user
if res_data["result"]["open"]:
for order_id, order_details in res_data["result"]["open"].items():
# Add order to global order list so that it can be used later
# without requesting data from Kraken again
orders.append({order_id: order_details})
order = "Order: " + order_id
order_desc = trim_zeros(order_details["descr"]["order"])
update.message.reply_text(bold(order + "\n" + order_desc), parse_mode=ParseMode.MARKDOWN)
else:
update.message.reply_text(e_fns + bold("No open orders"), parse_mode=ParseMode.MARKDOWN)
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())
]
menu = build_menu(buttons, n_cols=2, footer_buttons=close_btn)
reply_mrk = ReplyKeyboardMarkup(menu, resize_keyboard=True)
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):
buttons = list()
# Go through all open orders and create a button
if orders:
for order in orders:
order_id = next(iter(order), None)
buttons.append(KeyboardButton(order_id))
else:
update.message.reply_text("No open orders")
return ConversationHandler.END
msg = "Which order to close?"
close_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
menu = build_menu(buttons, n_cols=1, footer_buttons=close_btn)
reply_mrk = ReplyKeyboardMarkup(menu, resize_keyboard=True)
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(e_wit + "Closing orders...")
closed_orders = list()
if orders:
for x in range(0, len(orders)):
order_id = next(iter(orders[x]), None)
# Send request to Kraken to cancel orders
res_data = kraken_api("CancelOrder", data={"txid": order_id}, private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_data, update, "Order not closed:\n" + order_id + "\n"):
# If we are currently not closing the last order,
# show message that we a continuing with the next one
if x+1 != len(orders):
update.message.reply_text(e_wit + "Closing next order...")
else:
closed_orders.append(order_id)
if closed_orders:
msg = e_fns + bold("Orders closed:\n" + "\n".join(closed_orders))
update.message.reply_text(msg, reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
else:
msg = e_fns + bold("No orders closed")
update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN)
return
else:
msg = e_fns + bold("No open orders")
update.message.reply_text(msg, reply_markup=keyboard_cmds(), parse_mode=ParseMode.MARKDOWN)
return ConversationHandler.END
# Close the specified order
def orders_close_order(bot, update):
update.message.reply_text(e_wit + "Closing order...")
req_data = dict()
req_data["txid"] = update.message.text
# Send request to Kraken to cancel order
res_data = kraken_api("CancelOrder", data=req_data, private=True)
# If Kraken replied with an error, show it
if handle_api_error(res_data, update):
return
msg = e_fns + 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):
# If single-price option is active, get prices for all coins
if config["single_price"]:
update.message.reply_text(e_wit + "Retrieving prices...")
req_data = dict()
req_data["pair"] = str()
# Add all configured asset pairs to the request
for asset, trade_pair in pairs.items():
req_data["pair"] += trade_pair + ","
# Get rid of last comma
req_data["pair"] = req_data["pair"][:-1]
# Send request to Kraken to get current trading price for currency-pair
res_data = kraken_api("Ticker", data=req_data, private=False)
# If Kraken replied with an error, show it
if handle_api_error(res_data, update):
return
msg = str()
for pair, data in res_data["result"].items():
last_trade_price = trim_zeros(data["c"][0])
coin = list(pairs.keys())[list(pairs.values()).index(pair)]
msg += coin + ": " + last_trade_price + " " + config["used_pairs"][coin] + "\n"
update.message.reply_text(bold(msg), parse_mode=ParseMode.MARKDOWN)
return ConversationHandler.END
# Let user choose for which coin to get the price
else:
reply_msg = "Choose currency"
cancel_btn = [
KeyboardButton(KeyboardEnum.CANCEL.clean())
]
menu = build_menu(coin_buttons(), n_cols=3, footer_buttons=cancel_btn)
reply_mrk = ReplyKeyboardMarkup(menu, resize_keyboard=True)
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(e_wit + "Retrieving price...")
currency = update.message.text.upper()
req_data = {"pair": pairs[currency]}
# Send request to Kraken to get current trading price for currency-pair
res_data = kraken_api("Ticker", data=req_data, private=False)
# If Kraken replied with an error, show it
if handle_api_error(res_data, update):
return
last_trade_price = trim_zeros(res_data["result"][req_data["pair"]]["c"][0])
msg = bold(currency + ": " + last_trade_price + " " + config["used_pairs"][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())
]
menu = build_menu(coin_buttons(), n_cols=3, footer_buttons=footer_btns)
reply_mrk = ReplyKeyboardMarkup(menu, resize_keyboard=True)
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(e_wit + "Retrieving current value...")
# ALL COINS (balance of all coins)
if update.message.text.upper() == KeyboardEnum.ALL.clean():
req_asset = dict()
req_asset["asset"] = config["base_currency"]