-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathrobot.py
More file actions
2395 lines (1972 loc) · 113 KB
/
robot.py
File metadata and controls
2395 lines (1972 loc) · 113 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
################# Use examples #############
# > python robot.py initiate now bmex btc/usd 0.005
# > python robot.py initiate full_cycle bmex btc/usd 0.005
# > python robot.py process r bmex btc/usd 6398
# > python robot.py initiate now oanda usd_jpy 11 --core_strategy=traditional
# > python robot.py initiate now oanda nas100_usd 1500 --core_strategy=traditional
# > python robot.py initiate full_cycle oanda usd_jpy 100 --core_strategy=traditional
################# Libraries ##################
# Standard libraries
from sys import argv
import math
import urllib.request, urllib.error, urllib.parse
import decimal
from decimal import Decimal
import traceback
import argparse
from datetime import datetime
import random
# For lulz
import safygiphy
g = safygiphy.Giphy()
# Decimal precision and rounding
decimal.getcontext().prec = 25
decimal.getcontext().rounding = 'ROUND_DOWN'
## Custom libraries
import libs.sqltools as sqltools
sql = sqltools.sql()
import libs.platformlib as platform # detecting the OS and setting proper folders
import libs.aux_functions as aux_functions # various auxiliary functions
import libs.tdlib as tdlib # Price analysis library - in threads
import robo_class # class to store robot job constants and used variables
td_info = tdlib.tdlib()
aux_functions = aux_functions.aux_functions()
from libs.aux_functions import send_chat_message
################################ Config and imports - part I ############################################
import config # Import a configuration file
import backtest # Backtest import
b_test = backtest.backtesting()
import exch_api # exchanges
### Platform
platform = platform.platformlib()
platform_run, cmd_init = platform.initialise()
print("Initialising...")
# Parse custom params if there are any (on early stages)
parser = argparse.ArgumentParser()
parser.add_argument('--userid', type=int, help="User id (telegram")
parser.add_argument("--core_strategy", type=str, help="Core strategy name (blank is standard)") # strategy (standard / micro) # deprecate this
parser.add_argument('--is_restart', type=int, help="Restart indicator (1 or 0)")
args, unknown = parser.parse_known_args()
user_id = getattr(args, 'userid')
if user_id is None:
user_id = config.telegram_chat_id # my id
is_restart = getattr(args, 'is_restart')
if is_restart is not None: # restart indicator
is_restart = True
else:
is_restart = False
# Using coinigy to get prices so that there are no stringent restrictions on api request rates (frequency)
from libs.coinigylib import coinigy
'''# Telegram integration:using aux_functions now
#import telegram as telegram_python_bot # for bare wrapper to send files
#bot = telegram_python_bot.Bot(config.telegram_token)
'''
### Default values
no_input = False
trailing_stop_flag = True # default mode is to have trailing stop
###################################################################################
############################## Auxiliary functions #####################################
###################################################################################
### Send message: now using aux_functions
'''
def send_chat_message(user_to, text):
try:
if not config.backtesting_enabled:
bot.send_message(
chat_id=user_to,
text=text,
timeout=30
)
except:
err_msg = traceback.format_exc()
print("\n(i) Note: Failed to send telegram message. Reason: {}". format(err_msg))
'''
### Notify admin about issues
def issue_notify(robot_instance, error, only_admin = False):
admin_id = config.telegram_chat_id
user = robot_instance.user_id
admin_string = 'Error for the user {}. Reason: {}. Check the scripts.'.format(user, error)
comm_string = 'An error occured in the {} job. The admin was notified and is looking into it.'.format(robot.exchange)
robot_instance.logger.lprint([admin_string])
if not only_admin:
send_chat_message(robot.user_id, comm_string)
send_chat_message(admin_id, admin_string)
### Function to get original value
def original_value(robot, exchange, market, e_api):
try:
if not robot.simulation and not b_test.backtesting:
if exchange == 'bitmex':
all_positions = e_api.getpositions(exchange, market)
if all_positions != [{}]:
position = e_api.getpositions(exchange, market)[0]
# For the btc market
if robot.market in config.primary_calc_markets:
robot.value_original = position['contracts']/robot.price_entry
# For the other markets
else:
position = e_api.getpositions(exchange, market)[0]
robot.value_original = robot.price_entry*position['contracts_no']
else:
robot.value_original = None
elif exchange == 'oanda':
all_positions = e_api.getpositions(exchange, market)
if all_positions != [{}]:
position = e_api.getpositions(exchange, market)[0]
if robot.forex_pair:
robot.value_original = position['contracts'] # in usd
else:
robot.value_original = position['contracts']*position['entryprice'] # in usd
else:
robot.logger.lprint([ "Other exchanges are not supported yet"])
send_chat_message(robot.user_id, 'Exchange is not supported')
robot.terminate()
# In simulation
else:
robot.value_original = robot.simulation_balance*robot.margin_level
except:
robot.logger.lprint([ "API keys error when checking value"])
send_chat_message(robot.user_id, 'API keys error when checking value')
robot.terminate()
### Checking for positions # do this for oanda?
def buyer_check_positions(robot, e_api):
buy_terminate = False
hold_id = None
### If we are in the real mode and there are open positions on bitmex (e.g. we have set a stop manually) - postpone the execution
if (robot.wf_run_mode != 's') and config.postpone_entries:
positions = e_api.getpositions(robot.exchange, robot.market)
try: # if positions open, insert a record in holds
contracts_check = positions[0]['contracts']
retry = True
robot.logger.lprint(['Positions are open on the exchange, holding on until ready...'])
send_chat_message(robot.user_id, 'Positions are open on the exchange - waiting until they are closed')
### Inserting in the sqlite db if started fine
sql_string = "INSERT INTO buy_hold(market, abort_flag, price_fixed, price, source_position, mode, exchange, userid, core_strategy) " \
"VALUES ('{}', 0, {}, {}, {}, '{}', '{}', {}, '{}')".format(
robot.market, int(robot.fixed_price_flag), robot.fixed_price,
robot.source_position, robot.mode, robot.exchange, robot.user_id, robot.core_strategy)
hold_id, rows = sql.query_lastrow_id(sql_string)
except:
retry = False
# Retry until the positions are OK to go
while retry:
# Checking if there are contracts returned
try:
# If cancellation requested
approved_flag = sql.check_cancel_flag(robot, hold_id, 'buy_hold')
if not approved_flag:
sql_string = "DELETE FROM buy_hold WHERE job_id = {} " \
"AND userid = {} AND core_strategy = '{}' ".format(
hold_id, robot.user_id, robot.core_strategy)
sql.query(sql_string)
robot.logger.lprint(['Cancelled holding out and a buy task. Restart if needed.'])
send_chat_message(robot.user_id, 'Cancelled holding out and a buy task. Restart if needed.')
buy_terminate = True
retry = False
else:
positions = e_api.getpositions(robot.exchange, robot.market)
#print positions #TEST
contracts_check = positions[0]['contracts']
b_test.sleep(robot.sleep_buy_timer)
#print "Contracts check", contracts_check
except:
retry = False
# Resume if the cycle finished
if buy_terminate:
proceed_decision = False
else:
proceed_decision = True
robot.logger.lprint(['No positions open, ready to start'])
if hold_id is not None:
sql_string = "DELETE FROM buy_hold WHERE job_id = {} AND userid = {} " \
"AND core_strategy = '{}' ".format(
hold_id, robot.user_id, robot.core_strategy)
sql.query(sql_string)
return proceed_decision
else: # implement for other exchanges
return True
### Checking balance and changing the position size
def ensure_balance(robot, checked_price = None):
result = True # default
if robot.simulation or config.backtesting_enabled:
return True
else:
# On bitmex, BTC only is used as collateral
if robot.exchange == 'bitmex':
check_token = 'BTC'
else:
check_token = robot.trade
balance = e_api.getbalance(robot.exchange, check_token)
#robot.logger.lprint(['Checking balance response:', balance])
if balance is not None:
balance_avail = balance['Available']
robot.logger.lprint(['Available balance:', balance_avail])
# Changing the available balance and changing the value if there is no enough funds
if robot.exchange == 'bitmex':
balance_avail = Decimal(balance_avail).quantize(Decimal('.0001'), rounding='ROUND_DOWN')
balance_check = balance_avail * Decimal(0.99) * robot.margin_level
if (balance_check < robot.source_position) and (balance_check > 0.001): # changing position if there is more than 0.001 on the balance
robot.source_position = balance_avail * robot.margin_level * Decimal(0.99)
robot.logger.lprint(['Corrected the position in ensure balance:', balance_avail ])
result = True
if (balance_check < robot.source_position) and (balance_check <= 0.001): # do not proceed it not enough balance (less than 0.001)
result = False
if balance_check >= robot.source_position:
result = True
# Need to ensure that requested amount is fine to proceed with the buy (specifics for alts)
if (checked_price is not None) and robot.market not in config.primary_calc_markets: # (robot.market <> 'btc/usd'):
ratio = float(robot.source_position * robot.margin_level)/float(checked_price)
if ratio < 1.0:
amount_required = (float(checked_price) / float(robot.margin_level))*1.01 # allowing for a slight deviation
status_msg = 'You cannot open one contract on this market for this amount. Minimum amount needed: {}'.format(amount_required)
robot.logger.lprint([status_msg])
send_chat_message(robot.user_id, status_msg)
result = False
else:
result = True
return result
elif robot.exchange == 'oanda': # For the other exchanges (potentially to reconsider)
if Decimal(str(balance_avail * robot.margin_level)) < Decimal(str(robot.source_position)):
robot.source_position = Decimal(str(balance_avail * robot.margin_level))
robot.logger.lprint(['Corrected the position in ensure balance:', robot.source_position ])
return True
else:
return True
# If there is an api key issue
else:
robot.logger.lprint(['API keys issue'])
return None
###################################################################################
############################## MAIN WORKFLOW FUNCTIONS #########################
###################################################################################
### Re-buy (buy back) wrapper
def buy_back_wrapper(robot, b_test):
bb_price = robot.stopped_price # from the exit
# Starting buyback except for the cases when the task was aborted through telegram #Commented now - reconsidered that I still need this
# if stopped_mode != 'telegram':
robot.logger.lprint(["Buyback monitoring started:", robot.stopped_mode])
if robot.exchange == 'bitmex':
buy_trade_price = robot.value_original * (
1 + float(robot.earned_ratio * robot.margin_level) / 100) / robot.margin_level
robot.logger.lprint(
[">>> Sale outcomes: buy trade price (to use in buyback)", buy_trade_price, "main_curr_from_sale",
robot.main_curr_from_sell,
"margin", robot.margin_level, "earned ratio", robot.earned_ratio, "value original", robot.value_original])
elif robot.exchange == 'oanda':
if not robot.forex_pair:
buy_trade_price = (robot.value_original / robot.margin_level) * (
1 + float(robot.earned_ratio * robot.margin_level) / 100)
else:
buy_trade_price = (robot.value_original) * (
1 + float(robot.earned_ratio * robot.margin_level) / 100)
buy_trade_price = buy_trade_price / robot.margin_level
usd_x_rate = usd_rate_value(robot, e_api)
#print "USD RATE {} Buy trade price {}".format(usd_x_rate, buy_trade_price) #DEBUG
buy_trade_price = float(buy_trade_price)/float(usd_x_rate)
robot.logger.lprint(
[">>> OANDA sale outcomes: buy trade price (to use in buyback)", buy_trade_price, "main_curr_from_sale",
robot.main_curr_from_sell,
"margin", robot.margin_level, "earned ratio", robot.earned_ratio, "value original", robot.value_original])
else:
# commission depending on the exchange. If we do not have TD data
buy_trade_price = float(robot.balance_start) * bb_price * (1 - robot.comission_rate)
# Workaround if no orders
if (robot.no_sell_orders) and robot.exchange in ['bitmex']:
robot.terminate()
else:
# try:
# Inserting into buyback information table
sql_string = "INSERT INTO bback(market, bb_price, curr_price, trade_price, exchange, userid, core_strategy, bb_price_margin) " \
"VALUES ('{}', {}, {}, {}, '{}', {}, '{}', {})".format(
robot.market, bb_price, bb_price, buy_trade_price,
robot.exchange, robot.user_id, robot.core_strategy,
buy_trade_price * robot.margin_level)
robot.bb_id, rows = sql.query_lastrow_id(sql_string)
time_bb_trigger = b_test.time() # getting a snapshot of time for buyback so that we wait for at least an hour before starting buyback
bb_flag, direction = buy_back(robot, bb_price, time_bb_trigger,
b_test=b_test) # runs until a result is returned with a confirmation and a direction which defines the next step
'''
except:
bb_flag = False # if there were issued with inserting / finding
err_msg = traceback.format_exc()
comm_string = '{} {}: Error when performing buyback: {}. Please notify the admin'.format(robot.market, robot.exchange, err_msg)
robot.logger.lprint([comm_string])
chat.send(comm_string)
'''
# If we have reached the target to initiate a buyback and there was no cancellation through Telegram
if bb_flag:
notification_text = 'Re-entry initiated for {} on {}. Direction: {}. Confidence: {:.0%}'.format(
robot.market, robot.exchange, aux_functions.direction_name(direction), float(robot.prediction_probability))
send_chat_message(robot.user_id, notification_text)
robot.logger.lprint(["Re-entry in the direction:", aux_functions.direction_name(direction)])
# Storing entry direction
robot.entry_direction = direction
# print "bb_price {}, tp {}, buy_delta {}, tp_price {}, sl_price {}".format(bb_price, tp, buy_delta, tp_price, sl_price) # DEBUG
sql_string = "INSERT INTO workflow(run_mode, price_entry, exchange, userid, core_strategy) " \
"VALUES ('{}', {}, '{}', {}, '{}')".format(
robot.simulation_param, float(bb_price),
robot.exchange_abbr, robot.user_id, robot.core_strategy)
robot.wf_id, rows = sql.query_lastrow_id(sql_string)
if robot.wf_id is not None:
reentry_market = robot.trade
sql_string = "UPDATE workflow SET market = '{}', trade = '{}', currency = '{}', " \
"exchange = '{}' WHERE wf_id = {} AND userid = {} AND core_strategy = '{}' ".format(
robot.market, robot.trade, robot.currency, robot.exchange_abbr, robot.wf_id, robot.user_id,
robot.core_strategy)
robot.job_id, rows = sql.query_lastrow_id(sql_string)
mode_buy = 'now'
sql_string = "DELETE FROM bback WHERE id = {} AND userid = {} " \
"AND core_strategy = '{}' ".format(
robot.bb_id, robot.user_id, robot.core_strategy) # deleting buyback from the table
sql.query(sql_string)
# Rewritten - call the function rather than launch: change the input, run the robot
# Direction stored in entry direction now
robot.input('_', 'initiate', mode_buy, robot.exchange_abbr, reentry_market, str(buy_trade_price))
robot.logger.lprint([
"Buy called parameters: initiate", mode_buy, robot.exchange_abbr, reentry_market, str(buy_trade_price)
])
robot.run_program_mode = 'initiate'
# If a buyback cancellation was requested
else:
send_chat_message(robot.user_id, 'Buy back cancelled for {} on {}'.format(robot.market, robot.exchange))
# Delete buyback from the DB
sql_string = "DELETE FROM bback WHERE id = {} " \
"AND userid = {} AND core_strategy = '{}' ".format(
robot.bb_id, robot.user_id, robot.core_strategy)
sql.query(sql_string)
robot.terminate()
### Cycle to wait for the price feed. Ensure that we never get Nones in the current price
def get_price_feed(robot, b_test):
price_update = None
while price_update is None:
price_update = coinigy.price(robot.exchange_abbr, robot.market, robot.logger, b_test)
if price_update is None:
robot.logger.lprint(["---- cannot get prices from the feed. sleeping..."])
b_test.sleep(30)
return price_update
### Main workflow: buy back aux function
def buy_back_comment(td_result, td_direction, comment = ''):
if td_result:
if td_direction == 'red':
robot.logger.lprint(["---- TD buyback: short {}".format(comment)])
if td_direction == 'green':
robot.logger.lprint(["---- TD buyback: long {}".format(comment)])
### Main workflow: Looking for rebuy points (buyback)
def buy_back(robot, price_base, time_bb_initiated, b_test = b_test):
### Greetings (for logs readability)
robot.logger.lprint(["###################### CYCLE: BUY_BACK ###########################"])
if config.run_testmode: #<TEST>
td_result, td_direction, over_threshold = robot.predicted_action_direction()
return True, td_direction # testmode to <TEST>
td_direction = None # to return information on the direction of the new detected trend
td_result = False
## Checking the conditions
while not (td_result and over_threshold):
# Updating the candles
stop_reconfigure(robot, 'buy_back', b_test = b_test)
# Check if we are within market hours for traditional markets
is_market_open = is_trading_hours(b_test, robot)
if not is_market_open:
robot.prediction = 0
robot.prediction_probability = 1
robot.logger.lprint(["--- market is closed or almost closed - setting flag to no positions"])
curr_timing = b_test.strftime("%d-%m-%Y %H:%M")
robot.logger.lprint([curr_timing, robot.user_name, '|', robot.exchange, robot.market, "|",
"prediction: {}, confidence {:.0%}".format(
robot.predicted_name(robot.prediction), float(robot.prediction_probability))]) # prediction
# Check if we need to cancel
if not b_test.backtesting:
stop_bback = sql.check_bb_flag(robot)
if stop_bback:
break
# Checking time elapsed from the start of buyback
time_elapsed = (math.ceil(b_test.time() - time_bb_initiated ))/60
robot.exit_h_elapsed = round(time_elapsed/60, 1)
# Getting the current price and showing info on potential longs or potential shorts
robot.price = get_price_feed(robot, b_test)
# Updating DB
if robot.bb_id is not None and not b_test.backtesting:
sql_string = "UPDATE bback SET curr_price = {}, last_update={} WHERE id = {} AND userid = {} AND core_strategy = '{}'".format(
robot.price, b_test.time(), robot.bb_id, robot.user_id, robot.core_strategy)
sql.query(sql_string)
# Predictions check ML
td_result, td_direction, over_threshold = robot.predicted_action_direction()
robot.logger.lprint(['--- validating (re-entry): td_result {}, td_direction {}, over_threshold {}'.format(
td_result, td_direction, over_threshold)])
if td_result and over_threshold:
buy_back_comment(td_result, td_direction, 'prediction')
# No need to sleep if the buyback is confirmed
if not (td_result and over_threshold):
b_test.sleep(int(robot.sleep_timer_buyback/robot.speedrun))
# Finishing up
return td_result, td_direction
### Update information on performed orders, p1
def sell_orders_info(robot, b_test = None):
# Earned ratio for further recalculation
if not robot.short_flag:
robot.earned_ratio = round((float(robot.price_exit) / float(robot.price_entry) - 1) * 100, 2)
robot.earned_ratio_multiple = ((float(robot.price_exit) / float(robot.price_entry) - 1)*robot.margin_level) + 1
else:
robot.earned_ratio = round((float(robot.price_entry) / float(robot.price_exit) - 1) * 100, 2)
robot.earned_ratio_multiple = ((float(robot.price_entry) / float(robot.price_exit) -1)*robot.margin_level) + 1
try: # to handle errors
if not robot.simulation and not config.backtesting_enabled:
# Reset values if we are not simulating
robot.main_curr_from_sell = 0
robot.commission_total = 0
# Wait to collect orders info
b_test.sleep(10)
# Getting information on _sell_ orders executed
orders_opening_upd = e_api.getorderhistory(robot.exchange, robot.market, lastid=robot.oanda_last_trans_id)
for elem in orders_opening_upd:
robot.orders_new.add(elem['OrderUuid'])
orders_executed = robot.orders_new.symmetric_difference(robot.orders_start)
# DEBUG block
'''
print ("START", robot.orders_start, "\n\n")
print ("ORD_UPD", orders_opening_upd, "\n\n")
print ("orders_executed", orders_executed, "\n\n")
'''
# Info on executions
if orders_executed == set([]):
robot.logger.lprint(["No sell orders executed"])
robot.no_sell_orders = True
else: # iterating through orders
robot.logger.lprint(["New executed orders"]) # oanda can give no info on cancelled orders which is ok
for elem in orders_executed:
order_info = e_api.getorder(robot.exchange, robot.market, elem)
''' # The response from bitmex could be empty sometimes
if order_info is None:
notify_string = "Issue when getting order info for order {} and user {}".format(elem, robot.user_id) # troubleshooting
robot.logger.lprint([notify_string])
chat.send(notify_string, to_overwrite = config.telegram_chat_id)
'''
if order_info is not None:
if robot.exchange != 'bitmex':
robot.main_curr_from_sell += order_info['Price']
robot.commission_total += order_info['CommissionPaid']
qty_sold = order_info['Quantity'] - order_info['QuantityRemaining']
#robot.alt_sold_total += qty_sold #deprecated
robot.logger.lprint([">>", elem, "price", order_info['Price'], "quantity sold", qty_sold ]) #DEBUG
else:
#robot.price_exit = robot.bitmex_sell_avg
if robot.price_exit != 0:
if robot.market in config.primary_calc_markets: #robot.market == 'btc/usd': #
robot.main_curr_from_sell = robot.contracts_start/robot.price_exit
else:
robot.main_curr_from_sell = robot.contracts_start*robot.price_exit
#print "DEBUG: contracts_start {}, price_exit {}, main_curr_from_sell {}".format(
# robot.contracts_start, robot.price_exit, robot.main_curr_from_sell)
else:
robot.logger.lprint(["No orders to process"])
# Deprecate
robot.logger.lprint(["Total price", robot.main_curr_from_sell]) #DEBUG
# Deprecated
#else:
# If the simulation is True - main_curr_from_sell will have simulated value and the commission would be zero. Updating quantity.
#robot.alt_sold_total = robot.limit_sell_amount
#robot.logger.lprint(['Robot contracts start', robot.contracts_start]) #DEBUG
# For bitmex in simulation we are accounting for loss/profit. In real mode it is done when calculating contracts anyway
if robot.exchange == 'bitmex' and robot.simulation:
# Accounting for the loss or the profit
robot.main_curr_from_sell = float(robot.value_original) * float(robot.earned_ratio_multiple) * robot.margin_level
# In the real mode, accounting for:
if robot.exchange == 'bitmex' and not robot.simulation:
robot.main_curr_from_sell = float(robot.earned_ratio_multiple) * robot.main_curr_from_sell
except:
err_msg = traceback.format_exc()
issue_notify(robot, err_msg)
### Update information on performed orders and outcomes, p2
def sell_results_process(e_api, robot, timestamp_from, timestamp_to, use_start_value = False):
orders_result = e_api.results_over_time(
robot.exchange, robot.market, timestamp_from, timestamp_to + 60, lastid=robot.oanda_last_trans_id) # +60 sec for contingency
robot.logger.lprint(['Entry / exit results', orders_result, "| original value", robot.value_original])
trade_commissions = orders_result['commission']
trade_funding = orders_result['funding']
if use_start_value:
if robot.short_flag:
start_value = -abs(robot.value_original)
else:
start_value = abs(robot.value_original) # signs related to output, see results_over_time ()
trade_outcome_preliminary = orders_result['total_outcome']
trade_outcome = float(start_value) + float(trade_outcome_preliminary)
else:
trade_outcome = orders_result['total_outcome']
percent_gained = round(100*float(trade_outcome)/float(abs(robot.value_original/robot.margin_level)), 2) # in %
return trade_outcome, trade_commissions, trade_funding, percent_gained
def sell_orders_outcome(robot, b_test = None):
emoji_text = ''
if not robot.no_sell_orders:
if robot.exchange not in ['bitmex', 'oanda']:
robot.logger.lprint(['Exchange currently not supported'])
else: # calculation for bitmex based on timestamps
if not b_test.backtesting:
if robot.exchange == 'bitmex':
# If we have both start and end timestamps
if robot.timestamp_start_initiate is not None and robot.timestamp_finish is not None:
trade_outcome, trade_commissions, trade_funding, percent_gained = sell_results_process(e_api, robot, robot.timestamp_start_initiate, robot.timestamp_finish)
# If start timestamp comes from process - need to consider original value to calc difference
if (robot.timestamp_start_initiate is None) and (robot.timestamp_start_process is not None) and (robot.timestamp_finish is not None):
trade_outcome, trade_commissions, trade_funding, percent_gained = sell_results_process(e_api, robot, robot.timestamp_start_process,
robot.timestamp_finish, use_start_value = True)
elif robot.exchange == 'oanda': # OANDA just uses the last trade and return the actual result so no need to pass start value
# Check which timestamp to use as a start
if robot.timestamp_start_initiate is not None:
timestamp_from = robot.timestamp_start_initiate
else:
timestamp_from = robot.timestamp_start_process
trade_outcome, trade_commissions, trade_funding, percent_gained = sell_results_process(e_api, robot, timestamp_from, robot.timestamp_finish)
#print("!!!!", trade_outcome, trade_commissions, trade_funding, percent_gained )
# For consistency
robot.earned_ratio = percent_gained/robot.margin_level
else: # in backtesting mode
if not robot.short_flag:
robot.earned_ratio = round((float(robot.price_exit)/float(robot.price_entry) - 1)*100, 2) # in %
else:
robot.earned_ratio = round((float(robot.price_entry)/float(robot.price_exit) - 1)*100, 2) # in %
percent_gained = robot.earned_ratio * robot.margin_level # percent gained and earned ratio > 0 mean profit
# Processing and writing the results / communicating
# Flag for losing / winning trade
if robot.earned_ratio >= 0:
robot.losing_trade_flag = False
else:
robot.losing_trade_flag = True
robot.trade_time = b_test.strftime("%d-%m-%Y %H:%M")
#robot.logger.lprint(['Total from all sales', robot.main_curr_from_sell, 'total commission', robot.commission_total]) #not using
robot.logger.lprint(['Price entry', robot.price_entry, ', price exit', robot.price_exit])
robot.logger.lprint(['Earned % (no margin)', robot.earned_ratio, '| Original value:', robot.value_original])
# Backtesting results storage
if config.backtesting_enabled:
robot.backtest_results.append([robot.entry_time, robot.trade_time, robot.earned_ratio])
robot.logger.lprint(['> Backtesting results so far (%)'])
tmp_sum = 0
tmp_str = '\n'
for elem in robot.backtest_results:
tmp_str = str(elem[2]) + '\n'
tmp_sum += elem[2]
robot.logger.lprint([tmp_str])
robot.logger.lprint(["Total", tmp_sum, '\n'])
# Also updating a summary log
# check and fix here. multiplier is still ok to look at though
##balance_summary = robot.value_original * (1 + float(robot.earned_ratio)/100)/robot.margin_level
robot.logger.write_summary(robot.backtest_results, robot.value_original_snapshot ,
robot.start_date, robot.trade_time, robot.margin_level,
codename = robot.codename, params_info = robot.attr_string)
# Emoji to use and descriptions
if not b_test.backtesting:
# GIFs and emoji
if robot.earned_ratio < 0:
emoji_text = '👻' # whoopsie
r = g.random(tag="poor")
else:
emoji_text = '💵' # dollar
r = g.random(tag="rich")
# Getting the pic
gifdata = r['data']
if gifdata != {}:
try: # in case of api issues
gifurl = r['data']['images']['downsized']['url']
except:
gifurl = None
else:
gifurl = None
if not robot.short_flag:
trade_description = '(long)'
else:
trade_description = '(short)'
price_exit_msg = round(float(robot.price_exit), robot.round_num)
msg_result = '{} {}: Entry price: {}, exit price: {} {}. \nOutcome: {}% ({}% on margin).'.format(
emoji_text, robot.market, robot.price_entry, price_exit_msg,
trade_description, round(robot.earned_ratio, 2),
round(robot.earned_ratio * robot.margin_level, 2))
send_chat_message(robot.user_id, msg_result)
if gifurl is not None:
try:
if not config.backtesting_enabled:
bot.sendDocument(robot.user_id, gifurl)
except:
robot.logger.lprint(["Cannot send gif"])
# Updating twitter if enabled
if (robot.lambobot is not None) and not robot.simulation:
comm_string_twitter = '{} {}: closed a position. Entry price: {}, ' \
'exit price: {} {}. {}% made (multiplied by margin) ' \
'{} #{} #{} #algotrading'.format(emoji_text, robot.market.upper(),
robot.price_entry, price_exit_msg,
trade_description, round(robot.earned_ratio, 2),
robot.twitter_comment, robot.trade, robot.currency)
if gifurl is not None:
try: # just in case if this returns an error
robot.lambobot.post_image(gifurl, comm_string_twitter)
except:
try:
robot.lambobot.post(comm_string_twitter)
except:
robot.logger.lprint(["Cannot tweet the status"])
else:
try:
robot.lambobot.post(comm_string_twitter)
except:
robot.logger.lprint(["Cannot tweet the status"])
# Update the DB with trade logs
if robot.timestamp_start_initiate is None:
active_start_timestamp = robot.timestamp_start_process
else:
active_start_timestamp = robot.timestamp_start_initiate
sql_string = "INSERT INTO trade_log(userid, start_timestamp," \
" end_timestamp, trade_outcome, trade_commissions, " \
"trade_funding, earned_ratio, percent_gained, core_strategy) VALUES " \
"({}, {}, {}, {}, {}, {}, {}, {}, '{}')".format(robot.user_id, active_start_timestamp, robot.timestamp_finish,
trade_outcome, trade_commissions, trade_funding, robot.earned_ratio, percent_gained, robot.core_strategy)
sql.query(sql_string)
### Just update db with the current price info
## NOPE! This messes up the prices
'''
def stop_reconfigure_update_db(robot, b_test):
if not b_test.backtesting:
sql_string = "SELECT id FROM market_info WHERE market = '{}'".format(robot.market)
rows = sql.query(sql_string)
if rows != []:
# Existing - updating
key_row_id = rows[0][0]
sql_string = "UPDATE market_info SET price = {} WHERE id = {}".format(robot.price, key_row_id)
sql.query(sql_string)
else:
# New - inserting
sql_string = "INSERT INTO market_info(market, price) VALUES ('{}', {})".format(
robot.market, robot.price
)
sql.query(sql_string)
'''
### Stop reconfigure status updates
def stop_reconfigure_status_update(robot, mode):
# Status updates every 4H
if (
(mode == 'now') or
((mode == 'process') and (abs(int(robot.time_hour_update) - int(robot.time_hour_comms)) >= 4))
):
robot.time_hour_comms = robot.time_hour_update
# Percent of entry
if mode != 'now':
re_percent_of = robot.percent_of_entry
if re_percent_of >= 100:
re_percent_of -= 100
price_descr_text = 'Price: (^) up {0:.2f}% from entry'.format(re_percent_of)
else:
re_percent_of = 100 - re_percent_of
price_descr_text = 'Price: (v) down {0:.2f}% from entry'.format(re_percent_of)
else:
price_descr_text = ''
status_update = "Status update ({} {}) {} \n\nPrediction: {}, confidence {:.0%}".format(
robot.market, robot.exchange_abbr, price_descr_text, robot.predicted_name(robot.prediction),
float(robot.prediction_probability))
send_chat_message(robot.user_id, status_update)
# Updating twitter
if robot.lambobot is not None:
comm_string_twitter = "You should have {} on {} (confidence {:.0%})".format(
robot.predicted_name(robot.prediction), robot.market.upper(), float(robot.prediction_probability))
try: # just in case if this returns an error - this should not kill the whole script
robot.lambobot.post(comm_string_twitter)
except:
pass
### Setting stop loss based on price data
# Returns whether price flipped to opposite TD action, and new stop targets based on larger td period
def stop_reconfigure(robot, mode = None, b_test = None):
# Check if this is a time to exit in backtesting mode
if b_test.finished:
robot.logger.lprint(["Finished backtesting as per config"])
robot.terminate()
# Timers update
robot.time_hour_update = b_test.strftime("%H")
timer_minute = int(b_test.strftime("%M"))
'''
# NOPE! Prices are centralised now
# Rewritten: only update current price info and read predictions provided from the db
stop_reconfigure_update_db(robot, b_test)
'''
# Get predictions from the DB if not backtesting
if not b_test.backtesting:
sql_string = "SELECT prediction, probability FROM market_info WHERE market = '{}'".format(robot.market)
rows = sql.query(sql_string)
if rows != []:
robot.prediction = robot.predicted_num_from_name(rows[0][0])
robot.prediction_probability = float(rows[0][1])
# If backtesting
else:
# Updating control bars if due for ML
if (timer_minute in robot.control_bars_minutes) or mode == 'now':
timer_control_bars_check = '{}-{}'.format(robot.time_hour_update, timer_minute)
if robot.timer_control_bars_update is None:
robot.timer_control_bars_update = timer_control_bars_check
if (robot.timer_control_bars_update != timer_control_bars_check) or mode == 'now':
robot.timer_control_bars_update = timer_control_bars_check
robot.logger.lprint(["(i) updating prediction"])
# Predictions update (requires processed data in workflow db now
try:
if config.backtesting_use_db_labels:
label_to_predict = td_info.get_features(b_test.strftime("%Y-%m-%d %H:%M:00"),
robot) # use this to get pre-computed DB results
else:
label_to_predict = td_info.get_features_realtime(robot, b_test) # realtime features calculation
robot.prediction, robot.prediction_probability = td_info.predict_label(label_to_predict, robot)
except TypeError:
robot.logger.lprint(["error: cannot calculate features. check the prices file."])
robot.prediction, robot.prediction_probability = 0, 1
# Show the results
robot.logger.lprint(["---- (i) prediction update: {}, confidence {:.0%}".format(
robot.predicted_name(robot.prediction), robot.prediction_probability)])
# Changing the result if we are out of market hours for traditional markets
if not is_trading_hours(b_test, robot):
robot.prediction, robot.prediction_probability = 0, 1
robot.logger.lprint(["---- (i) out of market hours or close: changing the flag to 'no position'"])
# Status updates every 4H
if not robot.is_restart:
stop_reconfigure_status_update(robot, mode=mode)
robot.is_restart = False
### Main sell function to sell at current prices
# Will be performed until the balance available for sale is zero or slightly more
def sell_now(at_price, b_test = None): # change for oanda: oanda closure is as simple as calling closeposition
robot.price_exit = at_price
# First run flag now to sleep on the first call
proceed_w_sleep = False
# Timer
timer_sell_now_start = b_test.time()
if robot.limit_sell_amount is not None:
robot.limit_sell_amount = float(robot.limit_sell_amount) # using str, we will not have more decimal numbers than needed
if robot.sell_portion is not None:
robot.sell_portion = float(robot.sell_portion)
if robot.simulation:
robot.balance_start = float(robot.simulation_balance)
robot.balance_available = float(robot.simulation_balance) # balance_available as of balance to close
robot.remaining_sell_balance = float(robot.simulation_balance)
# For bitmex / oanda, we will be trading contracts, no adjustments are available. Getting the balances and setting the original value
if robot.exchange in ['bitmex', 'oanda']:
if not robot.simulation and not b_test.backtesting:
# There were issues with testnet returning blanks so changed this
contracts_check = {}
positions = e_api.getpositions(robot.exchange, robot.market) # first not empty result
for position in positions:
if position != {}:
contracts_check = position
break # exit the for loop
# print 'contracts_check', contracts_check #TEST
# If nothing was found
if contracts_check == {}:
sell_run_flag = False
contracts = 0
else:
if robot.market in config.primary_calc_markets: #robot.market == 'btc/usd': #
contracts = contracts_check['contracts']
else:
contracts = contracts_check['contracts_no']
robot.contracts_start = contracts
robot.balance_available = contracts
balance_adjust = 0
else: # if we are in the simulation mode
if robot.market in config.primary_calc_markets:
contracts = robot.price_entry * robot.simulation_balance
else:
contracts = robot.simulation_balance / robot.price_entry
robot.contracts_start = contracts
#debug_str = "Backtesting - contracts check: {}, price entry {}, value original {}".format(robot.contracts_start, robot.price_entry, robot.value_original)
#robot.logger.lprint([debug_str]) #DEBUG
# Working with sell_portion = contracts and with robot.contracts_start / robot.balance_available
# Main sell loop
sell_run_flag = True
stopmessage = 'stop' # default stop message meaning successful sale
#if (robot.exchange in ['bitmex']) or (config.backtesting_enabled and robot.exchange in ['oanda']):
if (robot.exchange in ['bitmex', 'oanda']):
while sell_run_flag:
# Wait until existing orders are cancelled - that is why we need sleep here and not in the end
# Checking Telegram requests and cancelling if needed
if proceed_w_sleep:
b_test.sleep(robot.sleep_sale)
# Update the db
process_db_updates(robot, sql, b_test, type='update')
# 0. Check open orders, cancel if unfilled
if not robot.simulation:
orders_retry = True
orders_retry_count = 0
while orders_retry and orders_retry_count < 10:
my_orders = e_api.getopenorders(robot.exchange, robot.market)
if my_orders != '':
for val in my_orders:
# Checking if some are open not filling
if val['Quantity'] == 0:
unfilled_prop = 0
else:
unfilled_prop = float(val['QuantityRemaining'])/float(val['Quantity'])
if unfilled_prop >= 0.05: # if more than 5% still left in the order
robot.logger.lprint(["-- cancelling unfilled order:", val['OrderUuid'], "quantity", val['Quantity'],
"quantity remaining", val['QuantityRemaining'], "price", val['Price']
])
e_api.cancel(robot.exchange, robot.market, val['OrderUuid'])
b_test.sleep(5) # Wait for cancellations to be processed just in case
orders_retry = False
# 1. Sell portion
if robot.simulation:
# If we are in the simulation mode - use the value from the previous run
robot.balance_available = robot.remaining_sell_balance
sell_portion = robot.balance_available
# For bitmex, we will be trading contracts, no adjustments are available
if robot.exchange in ['bitmex', 'oanda'] and not robot.simulation:
# There were issues with testnet returning blanks so changed this
contracts_check = {}
positions = e_api.getpositions(robot.exchange, robot.market) # first not empty result as there could be just 1 position open
for position in positions:
if position != {}:
contracts_check = position
break # exit the for loop
# If nothing was found
if contracts_check == {}:
sell_run_flag = False
else:
if robot.market in config.primary_calc_markets: #robot.market == 'btc/usd': #
contracts = contracts_check['contracts']
else:
contracts = contracts_check['contracts_no']
robot.balance_available = contracts
balance_adjust = 0
sell_portion = robot.balance_available
# Check if we have sold everything
if robot.balance_available <= robot.contracts_start * 0.01:
sell_run_flag = False
#print(sell_run_flag, robot.balance_available, sell_portion, robot.contracts_start)
# 2. If something is still required to be sold
if sell_run_flag: