-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdaemon.py
More file actions
1646 lines (1340 loc) · 62.3 KB
/
daemon.py
File metadata and controls
1646 lines (1340 loc) · 62.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
### Daemon script for commands processing
# add --userid=NNNNNN when starting, otherwise the admin account from config will be used
################################ Libraries ############################################
## Standard libraries
import os
import time
from sys import exit
import argparse
import re
from datetime import datetime
# Data manipulation
import pandas as pd
import numpy as np
import sqlite3 # for sqlite connection in pandas df_sql
## Custom libraries
from libs.telegramlib import telegram
import libs.sqltools as sqltools
sql = sqltools.sql()
import libs.platformlib as platform # detecting the OS and setting proper folders
from libs.coinigylib import coinigy # library to work with coinigy
import config
# Python telegram bot
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
import telegram as telegram_python_bot # for bare wrapper to send files
# Threading for v3
import _thread
import logging
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Create the EventHandler and pass it your bot's token.
updater = Updater(config.telegram_token)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Parse custom params if there are any
parser = argparse.ArgumentParser()
parser.add_argument('--userid', type=int, help="User id (telegram")
# One to ignore admin (so that admin can debug on testnet locally) and for admin only
parser.add_argument('--ignore_admin', type=int, help="Ignore admin (0/1)")
parser.add_argument('--only_admin', type=int, help="Only admin (0/1)")
args, unknown = parser.parse_known_args()
user_id = getattr(args, 'userid')
if user_id is None:
user_id = config.telegram_chat_id # my id
ignore_admin = bool(getattr(args, 'ignore_admin')) # 1 to ignore
only_admin = bool(getattr(args, 'only_admin')) # 1 to enable admin only mode
coinigy = coinigy(user_id) # replace with a proper user
# Universal functions for all exchanges, custom built
import exch_api
# Auxiliary function to check which strategy is active for chat
# different keys may be used depending on the strategy
def which_strategy(user_to):
sql_string = "SELECT active_strategy FROM user_info WHERE userid = '{}'".format(user_to)
rows = sql.query(sql_string)
try:
strategy_name = rows[0][0] # first result
return strategy_name
except:
return 'standard'
strategy_name = which_strategy(user_id)
e_api_to = exch_api.api(user_id, strategy = strategy_name)
# Platform
platform = platform.platformlib()
platform_run, cmd_init = platform.initialise()
#################### For Telegram integration ###############################################################
chat = telegram(user_id, start_override = True)
comm_method = 'chat' # 'mail' or 'chat', chat is preferable for the smooth experience
send_messages = True
# Dataframes for responses type, response 1, response 2 (when needed)
responses_df = pd.DataFrame(data=np.array([['none']]),
index=['none'],
columns=['type'])
responses_df_1 = pd.DataFrame(data=np.array([['none']]),
index=['none'],
columns=['type'])
responses_df_2 = pd.DataFrame(data=np.array([['none']]),
index=['none'],
columns=['type'])
responses_param_wf = pd.DataFrame(data=np.array([['none']]),
index=['none'],
columns=['type'])
responses_param_auto = pd.DataFrame(data=np.array([['none']]),
index=['none'],
columns=['type'])
# Streaming responses
responses_stream = pd.DataFrame(data=np.array([['none']]),
index=['none'],
columns=['type'])
strategy_exchange_stream = {}
######################################################################################
############################## MONITORING BOT ######################################
#####################################################################################
# Response sanitisation
def sanitise(line):
line = re.sub('[!@#$]', '', line)
for word in ['drop', 'insert', 'select', 'update']:
line = re.sub(word, '', line)
return line
########## Sending in a thread
def send_chat_message(user_to, text):
bot.send_message(
chat_id = user_to,
text = text
)
########## Close position
def telegram_close_position(user_to):
reply_string = 'Close options (specify id):\n'
sql_string = "SELECT * FROM jobs WHERE userid = {}".format(user_to)
rows = sql.query(sql_string)
if rows == []:
send_chat_message('No active tasks')
#send_chat_message(user_to, 'No active tasks')
else:
for row in rows:
if bool(row[4]):
simulation_str = '(simulation)'
else:
simulation_str = ''
reply_string += '{}: {}, EP {} {}, strategy "{}"\n'.format(row[0], row[1], row[3], simulation_str, row[18])
reply_string += 'all\n\nReply anything else to cancel the request'
send_chat_message(user_to, reply_string)
responses_df.loc[user_to] = 'close_position'
def telegram_close_position_execute(user_to, value):
msg_text = sanitise(value)
# If not all were requested
if msg_text.find('all') < 0:
try:
sql_string = "UPDATE jobs SET selling = 1 " \
"WHERE job_id = {} AND userid = {}".format(msg_text,
user_to) # flagging for cancellation
sql.query(sql_string)
send_chat_message(user_to, 'Job ' + msg_text.upper() + ' flagged for closing')
except:
send_chat_message(user_to, 'Incorrect task name')
# Terminating all if requested
else:
send_chat_message(user_to, 'Marked everything for closing')
sql_string = "UPDATE jobs SET selling = 1 WHERE userid = {}".format(user_to)
sql.query(sql_string)
responses_df.loc[user_to] = None
########## Balances info
def telegram_balance(user_to, exchange = None, strategy = None):
balance_available = None
if exchange is not None and strategy is not None:
e_api_to = exch_api.api(user_to, strategy = strategy)
balance = e_api_to.getbalance(exchange)
print("Balance for the user {} on the strategy {}: {}".format(user_to, strategy, balance))
if balance is not None:
balance_available = round(balance['Available'], 4)
balance_str = 'Available for opening new positions on {} ({} strategy): {}'.format(exchange, strategy, balance_available)
send_chat_message(user_to, balance_str)
else:
balance_available = None
send_chat_message(user_to, 'Cannot get the balance. API keys are inactive or incorrect')
else:
sql_string = "SELECT strategy, exchange FROM keys WHERE user = '{}'".format(user_to)
rows = sql.query(sql_string)
if rows != []:
for row in rows:
retry_continue = True
retry_count = 0
strategy = row[0]
exchange = row[1]
#print 'Checking', strategy, exchange
while retry_count < 10 and retry_continue:
try:
e_api_to = exch_api.api(user_to, strategy = strategy)
balance = e_api_to.getbalance(exchange)
balance_available = round(balance['Available'], 4)
balance_str = 'Available for opening new positions on {} strategy: {}'.format(strategy, balance_available)
retry_continue = False
except:
retry_count += 1
print("Seems like too many requests now, retrying")
time.sleep(0.2)
# Return the result
if retry_count == 10:
send_chat_message(user_to, 'Cannot get the balance for {} ({}): API keys are inactive or incorrect'.format(exchange, strategy))
else:
send_chat_message(user_to, balance_str)
return balance_available
### 'New'
def telegram_new_sell(user_to):
# New instances for threading
msg = """
This will launch a trading task when you already (!) have an open position on the market. If you do not know what you are doing, please reply something random and then use the /auto option.
To start, answer with a message with the following parameters:
> mode market entry_price
Modes: 's' (simulation), 'r' (real mode)
Example: r btc/usd 6000
^ this will launch a job (long) on btc/usd in regular mode where you entered at 6000
Note that your stops will be automatically reconfigured by the bot. The direction will be detected automatically based on your position.
"""
send_chat_message(user_to, msg)
send_chat_message(user_to, available_markets_generator())
responses_df.loc[user_to] = 'new_sell'
def telegram_new_sell_execute(user_to, value):
global platform_run, cmd_init
exchange, strategy_name = strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1]
exchange = exchange_name_convert(exchange) # abbreviation
msg_text = sanitise(value)
# Starting a new process with a new task
msg_text_split = msg_text.split()
# Processing params - should all be entered
try:
run_simulation_param = msg_text_split[0].lower()
run_exchange = exchange #msg_text_split[1].lower()
run_market = msg_text_split[1].upper()
try:
run_trade, run_currency = run_market.split('-')
except:
run_trade = run_market # if only one market vs BTC is provided - e.g. XRPH18 on bitmex
run_currency = 'BTC'
run_price_curr = msg_text_split[2]
# Deprecated
'''
run_tp = msg_text_split[3]
run_sl = msg_text_split[4]
try:
run_limit_sell_amount = msg_text_split[5]
except:
run_limit_sell_amount = ''
try:
run_sell_portion = msg_text_split[6]
except:
run_sell_portion = ''
'''
# Run depending on the platform
user_id_str = '--userid={}'.format(user_to)
strategy_str = '--core_strategy={}'.format(strategy_name)
try:
entry_price_str = '--entry_cutoff_price={}'.format(run_price_curr)
except:
entry_price_str = ''
if platform_run == 'Windows':
cmd_str = cmd_init + ' '.join(['process', run_simulation_param, run_exchange, run_market,
run_price_curr, user_id_str, entry_price_str, strategy_str])
else:
# Nix
cmd_str = cmd_init + ' '.join(['process', run_simulation_param, run_exchange, run_market,
run_price_curr, user_id_str, entry_price_str, strategy_str]) + '"'
os.system(cmd_str)
# Check if launched
send_chat_message(user_to, 'Launching under the strategy {}, hold on...'.format(strategy_name))
time.sleep(30)
sql_string = "SELECT job_id FROM jobs WHERE market = '{}' " \
"AND userid = {} AND core_strategy='{}'".format(run_market.upper(), user_to, strategy_name)
rows = sql.query(sql_string)
try:
launched_confirmation = rows[0][0] # first result if existing
print('>>> Started a new job on the market {}. Simulation mode: {}'.format(run_market.upper(),
run_simulation_param))
send_chat_message(user_to, 'Launched a new bot with these parameters')
except:
send_chat_message(user_to, 'The job was not launched')
except:
send_chat_message(user_to, 'Incorrect response format, please select a new command or start again')
responses_df.loc[user_to] = None
def exchange_name_convert(name):
if name == 'bitmex':
name = 'bmex'
elif name == 'oanda':
name = 'oanda'
return name
### Auto
def telegram_auto(user_to):
# Real mode on bitmex with fullta: r bmex
wf_run_mode = 'r'
wf_exchange = 'bmex'
exchange, strategy = strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1]
wf_exchange = exchange_name_convert(exchange) # abbreviation
# Insert a record in the db, using just dummy values for tp and sl
# Market, trade, currency will be updated with proper values in telegram buy
sql_string = "INSERT INTO workflow(run_mode, exchange, userid, core_strategy) " \
"VALUES ('{}', '{}', '{}', '{}')".format(wf_run_mode, wf_exchange, user_to, strategy)
wf_id, rows = sql.query_lastrow_id(sql_string)
# Start the buy job
telegram_initiate_position(user_to, wf_id, True)
### For workflows
def telegram_workflow(user_to):
send_chat_message(user_to, 'Specify mode "r" (real mode) or "s" (simulation) for further reference.')
responses_df.loc[user_to] = 'workflow'
def telegram_workflow_launch(user_to, value):
exchange, strategy = strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1]
wf_exchange = exchange_name_convert(exchange) # abbreviation
msg_text = sanitise(value)
responses_df.loc[user_to] = None # will be starting a new one anyway
# Getting parameters
msg_text_split = msg_text.split()
# Processing params - should all be entered
try:
wf_run_mode = msg_text_split[0]
if wf_run_mode not in ['s', 'r']:
send_chat_message(user_to, 'Incorrect run mode specified')
responses_df.loc[user_to] = None
else:
if wf_exchange not in config.exch_supported:
send_chat_message(user_to, 'Incorrect exchange specified')
else:
# Insert a record in the db
sql_string = "INSERT INTO workflow(run_mode, exchange, userid, core_strategy) " \
"VALUES ('{}', '{}', {}, '{}')".format(
wf_run_mode, wf_exchange, user_to, strategy_name)
wf_id, rows = sql.query_lastrow_id(sql_string)
# Start the buy job
telegram_initiate_position(user_to, wf_id)
except:
send_chat_message(user_to, 'Incorrect response format, please select a new command or start again')
### My positions
def telegram_mypositions(user_to):
exchange, strategy_name = strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1]
e_api_to = exch_api.api(user_to, strategy = strategy_name)
reply_str = 'Positions opened on the exchange:\n'
send_chat_message(user_to, 'Checking your positions, hold on...')
user_positions = e_api_to.getpositions(exchange, None)
if user_positions != []:
for position in user_positions:
reply_str += '{}\n'.format(position)
send_chat_message(user_to, reply_str)
else:
send_chat_message(user_to, 'No positions')
### 'Initiate_position'
def telegram_initiate_position(user_to, wf_id = None, exch_fullta_mode = False):
if exch_fullta_mode:
msg = """
This will launch a fully automated process of searching entries and profitable exits, and your position sizes will be adjusted automatically. To launch, reply with the contract name and the position size in BTC. Here are some examples:
btc/usd 0.3
^ Bitcoin perpetual contract, entry amounted in 0.3 bitcoin
If you just want to use your whole balance and you roughly know the amount, you could specify a larger number and the maximum available balance will be used automatically.
"""
send_chat_message(user_to, msg)
send_chat_message(user_to, available_markets_generator())
responses_df.loc[user_to] = 'initiate'
responses_param_wf[user_to] = wf_id
responses_param_auto[user_to] = True
else:
msg = """
Specify the parameters:
mode source_currency-buy_currency [total_in_source currency] [price] [time limit for the price in minutes]
Modes: now/fullta. Add -s (now-s) for simulation.
After opening a position, the task will be finished (!). If you want to launch fully automated trading, use /auto instead. Some examples:
fullta btc/usd 0.05
^ initiate (open) a long position automatically for the amount of 0.05 btc.
now btc/usd -0.1
^ initiate a short on Ripple immediately for the amount of 0.1 btc.
"""
send_chat_message(user_to, msg)
send_chat_message(user_to, available_markets_generator())
responses_df.loc[user_to] = 'initiate'
responses_param_wf[user_to] = wf_id
responses_param_auto[user_to] = False
def telegram_initiate_execute(user_to, value):
global platform_run
if user_to in list(strategy_exchange_stream.keys()):
exchange, strategy_name = strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1]
exchange = exchange_name_convert(exchange) # abbreviation
msg_text = sanitise(value)
wf_id = responses_param_wf[user_to].values[0]
exch_fullta_mode = responses_param_auto[user_to].values[0]
try:
# Starting a new process with a new task
msg_text_split = msg_text.split()
# Checking if exch_fullta_mode is used
if exch_fullta_mode:
buy_mode = 'fullta'
buy_exchange = exchange
buy_market = msg_text_split[0].upper()
buy_total = msg_text_split[1]
buy_price = ''
buy_time_limit = ''
else:
buy_mode = msg_text_split[0].lower()
buy_exchange = exchange #msg_text_split[1].lower()
buy_market = msg_text_split[1].upper()
try:
buy_total = msg_text_split[2]
except:
buy_total = ''
try:
buy_price = msg_text_split[3]
except:
buy_price = ''
try:
buy_time_limit = msg_text_split[4]
except:
buy_time_limit = ''
# Checking the market
try:
buy_trade, buy_currency = buy_market.split('-')
except:
buy_trade = buy_market # if only one market vs BTC is provided - e.g. XRPH18 on bitmex
buy_currency = 'BTC'
# Check if the buy for the same user and market is running
sql_string = "SELECT * FROM buys WHERE market = '{}' AND userid = {} " \
"AND core_strategy = '{}'".format(buy_market, user_to, strategy_name)
rows = sql.query(sql_string)
try:
exists = rows[0][0] # first result
send_chat_message(user_to,
'Warning: another buy on the same market is running. One of them may be redundant, please check after launch.')
except:
pass
# Updating the db
if wf_id is not None:
sql_string = "UPDATE workflow SET market = '{}', trade = '{}', currency = '{}', " \
"exchange = '{}' WHERE wf_id = {} AND userid = {} AND core_strategy='{}'".format(
buy_market, buy_trade, buy_currency,
buy_exchange, wf_id, user_to, strategy_name)
job_id, rows = sql.query_lastrow_id(sql_string)
# Run depending on the platform
user_id_str = '--userid={}'.format(user_to)
strategy_str = '--core_strategy={}'.format(strategy_name)
if platform_run == 'Windows':
cmd_str = cmd_init + ' '.join(
['initiate', buy_mode, buy_exchange, buy_market, buy_total, buy_price, buy_time_limit, user_id_str, strategy_str])
else:
# Nix
cmd_str = cmd_init + ' '.join(
['initiate', buy_mode, buy_exchange, buy_market, buy_total, buy_price, buy_time_limit,
user_id_str, strategy_str]) + '"'
os.system(cmd_str)
send_chat_message(user_to, 'New task requested successfully (strategy: {}). Please allow for a few minutes for this task to launch.'.format(strategy_name))
print("Started a new buy job: ", cmd_str)
except:
send_chat_message(user_to, 'Incorrect response format, please select a new command or start again')
responses_df.loc[user_to] = None
responses_param_wf.loc[user_to] = None
responses_param_auto.loc[user_to] = None
########## Clean DB
def telegram_clean_my_db(user_to):
global responses_df
msg_resp = "❗\n\nThis will: \n- stop all your tasks \n- clean all your jobs and workflow database records " \
"\n\nRespond 'yes' to confirm or anything else to cancel."
send_chat_message(user_to, msg_resp)
responses_df.loc[user_to] = 'db_clean'
def telegram_db_clean_execute(user_to, value):
global responses_df
if value.lower().find('yes') >= 0:
send_chat_message(user_to, "Aborting all tasks, hold on for a few minutes...")
for tbl_name in ['buys', 'jobs', 'bback', 'buy_hold']:
sql_string = "UPDATE {} SET abort_flag=1 WHERE userid = {}".format(tbl_name, user_to)
sql.query(sql_string)
time.sleep(90)
send_chat_message(user_to, "Cleaning the database...")
for tbl_name in ['jobs', 'workflow', 'buys', 'bback', 'buy_hold']:
sql_string = "DELETE from {} WHERE userid = {}".format(tbl_name, user_to)
sql.query(sql_string)
send_chat_message(user_to, "Database cleaned")
else:
send_chat_message(user_to, "Does not look like yes. Cancelled the request.")
responses_df.loc[user_to] = None
########## Margin change, needs a df update for monitoring
def telegram_margin_change_r(user_to):
exchange, strategy_name = strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1]
# Getting the current margin value
sql_string = "SELECT param_val FROM user_params WHERE userid = {} " \
"AND param_name = 'margin' AND core_strategy='{}'".format(user_to, strategy_name)
rows = sql.query(sql_string)
if rows != []:
margin_level = rows[0][0]
reply_string = 'Your current margin level on strategy "{}": {}.\n\n'.format(strategy_name, margin_level)
else:
sql_string = "INSERT INTO user_params(userid, param_name, param_val, core_strategy) " \
"VALUES ({}, '{}', {}, '{}')".format(user_to, 'margin', 5, strategy_name)
rows = sql.query(sql_string)
reply_string = 'Your current margin level on strategy "{}": 5\n'.format(strategy_name)
reply_string += 'Choose one of the options below to change your margin level ' \
'(10 is extreme and recommended for traditional markets only). ' \
'\n\nIf you are not sure what this means, please go to bitmex and read about margin trading. '
keyboard = [[
InlineKeyboardButton("1", callback_data='margin:1'),
InlineKeyboardButton("2", callback_data='margin:2'),
InlineKeyboardButton("3", callback_data='margin:3'),
InlineKeyboardButton("5", callback_data='margin:5'),
InlineKeyboardButton("10", callback_data='margin:10')
]]
reply_markup = InlineKeyboardMarkup(keyboard)
bot.send_message(
chat_id=user_to,
text = reply_string,
reply_markup=reply_markup
)
############################################################################################################
### Using the whole balance always
def telegram_use_all_balance(user_to):
global responses_df
# Getting the current param value
sql_string = "SELECT param_val FROM user_params WHERE userid = {} " \
"AND param_name = 'use_all_balance'".format(user_to)
rows = sql.query(sql_string)
if rows != []:
use_all_balance = bool(int(rows[0][0]))
reply_string = 'Current value: {}'.format(use_all_balance)
else:
sql_string = "INSERT INTO user_params(userid, param_name, param_val) " \
"VALUES ({}, '{}', {})".format(user_to, 'use_all_balance', 0)
rows = sql.query(sql_string)
reply_string = 'Current value: False'
# Monitoring further
responses_df.loc[user_to] = 'use_all_balance'
send_chat_message(user_to, reply_string)
reply_string = 'Reply T (True) or F (False) to enable or disable the option. Reply anything random to cancel the request'
send_chat_message(user_to, reply_string)
### Updating the value
def telegram_use_all_balance_execute(user_to, value):
msg_text = sanitise(value).lower()
value_upd = None
if msg_text == 't' or msg_text == 'true':
value_upd = 1
if msg_text == 'f' or msg_text == 'false':
value_upd = 0
if value_upd is not None:
sql_string = "UPDATE user_params SET param_val = {} WHERE param_name = 'use_all_balance' " \
"AND userid = {} ".format(value_upd, user_to)
sql.query(sql_string)
send_chat_message(user_to, 'Parameter updated and will be applied when opening new positions')
responses_df.loc[user_to] = None
responses_df.loc[user_to] = None
################################################################################
### Traditional market signals subscription
def telegram_traditional_markets_overview(user_to):
global responses_df
# Getting the current param value
sql_string = "SELECT param_val FROM user_params WHERE userid = {} " \
"AND param_name = 'traditional_markets_overview'".format(user_to)
rows = sql.query(sql_string)
if rows != []:
use_all_balance = bool(int(rows[0][0]))
reply_string = 'Current value: {}'.format(use_all_balance)
else:
sql_string = "INSERT INTO user_params(userid, param_name, param_val) " \
"VALUES ({}, '{}', {})".format(user_to, 'traditional_markets_overview', 0)
rows = sql.query(sql_string)
reply_string = 'Current value: False'
# Monitoring further
responses_df.loc[user_to] = 'traditional_markets_overview'
send_chat_message(user_to, reply_string)
reply_string = 'Reply T (True) or F (False) to enable or disable the option. Reply anything random to cancel the request'
send_chat_message(user_to, reply_string)
### Updating the value
def telegram_traditional_markets_overview_execute(user_to, value):
msg_text = sanitise(value).lower()
value_upd = None
if (msg_text == 't' or msg_text == 'true'):
value_upd = 1
if (msg_text == 'f' or msg_text == 'false'):
value_upd = 0
if value_upd is not None:
sql_string = "UPDATE user_params SET param_val = {} WHERE param_name = 'traditional_markets_overview' " \
"AND userid = {} ".format(value_upd, user_to)
sql.query(sql_string)
if value_upd == 1:
send_chat_message(user_to, 'You will start receiving daily reports with traditional market signals from now on. You can always unsubscribe using the same command.')
else:
send_chat_message(user_to, 'You were successfully unsubscribed.')
responses_df.loc[user_to] = None
responses_df.loc[user_to] = None
#############################################################################################################
### Strategy status
def telegram_strategy_status(user_to):
response = 'Available strategies:'
sql_string = "SELECT name, description FROM strategies"
rows = sql.query(sql_string)
for row in rows:
add_str = '\n- {}: {}'.format(row[0], row[1])
response += add_str
send_chat_message(user_to, response)
## Trades hist
def telegram_trades(user_to):
global responses_df
sql_string = "SELECT start_timestamp, end_timestamp, trade_outcome, trade_commissions, " \
"trade_funding, earned_ratio, percent_gained, core_strategy " \
"FROM trade_log WHERE userid = {} ORDER BY end_timestamp DESC LIMIT 3".format(user_id)
rows = sql.query(sql_string)
reply_string = 'Your last 3 trades:\n\n'
if rows != []:
for row in rows:
time_utc = datetime.utcfromtimestamp(row[0]).strftime('%m/%d/%Y %H:%M')
reply_string += 'Timestamp (UTC): {} \nOutcome (BTC): {} \nCommissions: {} \nFunding: {} ' \
'\nResult (no margin): {}% \nResult (on margin): {}% \nStrategy: {}\n\n'.format(
time_utc, row[2], row[3], row[4], row[5], row[6], row[7]
)
else:
reply_string = 'No trade history available'
send_chat_message(user_to, reply_string)
# Also collecting and sending the full history
filename = 'temp/trades_{}.csv'.format(user_to)
conn = sqlite3.connect("workflow.db")
df = pd.read_sql('select * from trade_log where userid={}'.format(user_to), conn)
df.drop('id', axis=1, inplace=True)
df.to_csv(filename)
conn.commit()
conn.close()
bot.send_document(
chat_id=user_to,
caption= 'Full history of trades performed by bot on your account',
document=open(filename, 'rb')
)
## Select the strategy
def telegram_e_strategy_select(user_to, stream_name = None):
keyboard_arr = config.strategies
keyboard_arr_transformed = []
keyboard = []
for elem, value in keyboard_arr.items():
keyboard_arr_transformed.append(
InlineKeyboardButton(str(elem), callback_data='input_platform:{}'.format(elem))
)
# An option to repeat the last one
if user_to in list(strategy_exchange_stream.keys()):
keyboard_arr_transformed.append(
InlineKeyboardButton('Last selected', callback_data='input_platform:LASTVAL')
)
keyboard.append(keyboard_arr_transformed)
reply_markup = InlineKeyboardMarkup(keyboard)
bot.send_message(
chat_id=user_to,
text = 'Select your platform',
reply_markup=reply_markup
)
responses_stream.loc[user_to] = stream_name
def telegram_e_strategy_select_f(user_to, platform):
items_pre = config.strategies
keyboard_arr_transformed = []
keyboard = []
if platform == 'LASTVAL':
stream_process(user_to, None, None)
else:
keyboard_arr = dict((key,value) for key, value in items_pre.items() if key == platform)
for elem, value in keyboard_arr.items():
for strategy_name in value:
keyboard_arr_transformed.append(
InlineKeyboardButton(str(strategy_name), callback_data='input_strategy:{}_{}'.format(platform, strategy_name))
)
keyboard.append(keyboard_arr_transformed)
reply_markup = InlineKeyboardMarkup(keyboard)
bot.send_message(
chat_id=user_to,
text = 'Available strategies',
reply_markup=reply_markup
)
### Handling callbacks ######
def callback_handle(bot, update):
sql.query_data = update.callback_query
callback_response = sql.query_data.data
user_to = sql.query_data.message.chat_id
message_id=sql.query_data.message.message_id
if user_to in list(strategy_exchange_stream.keys()):
exchange, strategy = strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1]
# Check what
if 'margin:' in callback_response:
margin_level = int(callback_response.replace("margin:", ""))
sql_string = "UPDATE user_params SET param_val = {} WHERE param_name = 'margin' " \
"AND userid = {} AND core_strategy='{}'".format(
margin_level, user_to, strategy)
sql.query(sql_string)
bot.edit_message_text(
text="Margin level updated and will be applied when opening new positions",
chat_id=user_to,
message_id=message_id)
elif 'keys:' in callback_response:
exchange_to_use = callback_response.replace('keys:', '')
bot.edit_message_text(
text="Updating keys for {}".format(exchange_to_use),
chat_id=user_to,
message_id=message_id)
# Strategy selection
if exchange_to_use == 'oanda':
reply_string = 'Please choose the platform to change keys for'
keyboard = [[
InlineKeyboardButton("bitmex", callback_data='keys:bitmex'),
InlineKeyboardButton("oanda", callback_data='keys:oanda')
]]
reply_markup = InlineKeyboardMarkup(keyboard)
bot.send_message(
chat_id=user_to,
text = reply_string,
reply_markup=reply_markup
)
elif 'abort:' in callback_response:
option = int(callback_response.replace("abort:", ""))
telegram_abort_execute(user_to, option)
bot.edit_message_text(
text="Abort requested",
chat_id=user_to,
message_id=message_id)
elif 'input_platform:' in callback_response:
selected_platform = callback_response.replace("input_platform:", "")
if selected_platform != 'LASTVAL':
text_upd = "Select strategy for the platform {}".format(selected_platform)
else:
text_upd = "Using last values: {} {}".format(strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1])
bot.edit_message_text(
text=text_upd,
chat_id=user_to,
message_id=message_id)
telegram_e_strategy_select_f(user_to, selected_platform)
elif 'input_strategy:' in callback_response:
selected_all = callback_response.replace("input_strategy:", "")
selected_arr = selected_all.split('_')
selected_exchange, selected_strategy = selected_arr[0], selected_arr[1]
bot.edit_message_text(
text="Selected platform: {}, strategy: {}".format(selected_exchange, selected_strategy),
chat_id=user_to,
message_id=message_id)
# End of selection for the stream
stream_process(user_to, selected_exchange, selected_strategy)
### Process stream: important milestone
def stream_process(user_to, exchange, strategy):
if exchange is not None and strategy is not None:
strategy_exchange_stream[user_to] = [exchange, strategy]
if (responses_stream.loc[user_to] == 'keys_update').bool():
telegram_keys_set(user_to)
elif (responses_stream.loc[user_to] == 'margin_change').bool():
telegram_margin_change_r(user_to)
elif (responses_stream.loc[user_to] == 'auto_job').bool():
telegram_auto(user_to)
elif (responses_stream.loc[user_to] == 'initiate_position').bool():
telegram_initiate_position(user_to)
elif (responses_stream.loc[user_to] == 'new_sell').bool():
telegram_new_sell(user_to)
elif (responses_stream.loc[user_to] == 'telegram_workflow').bool():
telegram_workflow(user_to)
elif (responses_stream.loc[user_to] == 'telegram_mypositions').bool():
telegram_mypositions(user_to)
responses_stream.loc[user_to] = None
########## Admin add user
def telegram_add_user(user_to):
global responses_df
send_chat_message(user_to, "User name:")
# Monitoring further
responses_df.loc[user_to] = 'add_user_step_1'
def telegram_add_user_1(user_to, value):
global responses_df
global responses_df_1
responses_df_1.loc[user_to] = value
send_chat_message(user_to, "User id:")
# Monitoring further
responses_df.loc[user_to] = 'add_user_step_2'
def telegram_add_user_2(user_to, value):
global responses_df
global responses_df_1
global responses_df_2
responses_df_2.loc[user_to] = value
# Add the user
add_name = str(responses_df_1.loc[user_to].values[0])
add_id = int(responses_df_2.loc[user_to])
sql_string = "INSERT INTO user_info(userid, name) VALUES ({}, '{}')".format(add_id, add_name)
sql.query(sql_string)
sql_string = "INSERT INTO user_params(userid, param_name, param_val) VALUES ({}, '{}', {})".format(add_id,
'margin', 5) # default recommended margin
sql.query(sql_string)
send_chat_message(user_to, 'User added')
# Cleanup
responses_df.loc[user_to], responses_df_1.loc[user_to], responses_df_2.loc[user_to] = None, None, None
########## Keys update
def telegram_keys_set(user_to):
global responses_df
reply_string = "What is your key id (not secret key)? Reply 'cancel' if you would like to cancel the request."
send_chat_message(user_to, reply_string)
responses_df.loc[user_to] = 'keys_step_1'
def telegram_keys_set_1(user_to, value):
global responses_df, responses_df_1
responses_df_1.loc[user_to] = value
if value.lower().find('cancel') < 0:
reply_string = "What is your secret key?"
send_chat_message(user_to, reply_string)
responses_df.loc[user_to] = 'keys_step_2'
else:
responses_df.loc[user_to], responses_df_1.loc[user_to] = None, None
send_chat_message(user_to, 'Request cancelled')
def telegram_keys_set_2(user_to, value):
global responses_df, responses_df_1, responses_df_2
responses_df_2.loc[user_to] = value
# Getting info on what strategy and exchange to use
exchange, strategy = strategy_exchange_stream[user_to][0], strategy_exchange_stream[user_to][1]
# Keys check
key_id = sanitise(str(responses_df_1.loc[user_to].values[0]))
key_secret = sanitise(str(responses_df_2.loc[user_to].values[0]))
# Check if the key exists
user_id = user_to
sql_string = "SELECT id FROM keys WHERE user = {} AND strategy='{}' AND exchange = '{}' ".format(user_id, strategy, exchange)
rows = sql.query(sql_string)
if rows != []:
# Existing - updating
key_row_id = rows[0][0]
sql_string = "UPDATE keys SET key_id = '{}', key_secret = '{}' WHERE id = {} and exchange = '{}' ".format(
key_id, key_secret, key_row_id, exchange)
sql.query(sql_string)
else:
# New - inserting
sql_string = "INSERT INTO keys(user, key_id, key_secret, strategy, exchange) VALUES ({}, '{}', '{}', '{}', '{}')".format(
user_id, key_id, key_secret, strategy, exchange)
sql.query(sql_string)
# Checking balance to ensure that the keys are correct #finish
send_chat_message(user_to, 'Validating the keys...')
api_validate = telegram_balance(user_id, exchange = exchange, strategy = strategy)
if api_validate is not None:
send_chat_message(user_to, 'Keys checked for correctness and saved')
else:
send_chat_message(user_to, 'Keys do not seem to work')