-
Notifications
You must be signed in to change notification settings - Fork 2
/
maverage.py
executable file
·1606 lines (1370 loc) · 61 KB
/
maverage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
import configparser
import datetime
import inspect
import logging
import os
import pickle
import random
import smtplib
import socket
import sqlite3
import sys
import time
from math import floor
from time import sleep
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from logging.handlers import RotatingFileHandler
import ccxt
import requests
MIN_ORDER_SIZE = 0.001
STATE = {'last_action': None, 'order': None, 'stop_loss_order': None, 'stop_loss_price': None}
STATS = None
EMAIL_SENT = False
EMAIL_ONLY = False
RESET = False
STOP_ERRORS = ['nsufficient', 'too low', 'not_enough', 'margin_below', 'liquidation price', 'closed_already', 'zero margin']
ACCOUNT_ERRORS = ['account has been disabled', 'key is disabled', 'authentication failed', 'permission denied']
RETRY_MESSAGE = 'Got an error %s %s, retrying in about 5 seconds...'
class ExchangeConfig:
def __init__(self):
config = configparser.ConfigParser()
config.read(INSTANCE + ".txt")
try:
props = config['config']
self.bot_version = '0.8.5'
self.exchange = str(props['exchange']).strip('"').lower()
self.api_key = str(props['api_key']).strip('"')
self.api_secret = str(props['api_secret']).strip('"')
self.test = bool(str(props['test']).strip('"').lower() == 'true')
self.pair = str(props['pair']).strip('"')
self.symbol = str(props['symbol']).strip('"')
self.net_deposits_in_base_currency = abs(float(props['net_deposits_in_base_currency']))
self.leverage_default = abs(float(props['leverage_default']))
self.apply_leverage = bool(str(props['apply_leverage']).strip('"').lower() == 'true')
self.daily_report = bool(str(props['daily_report']).strip('"').lower() == 'true')
self.trade_report = bool(str(props['trade_report']).strip('"').lower() == 'true')
self.short_in_percent = abs(int(props['short_in_percent']))
self.ma_minutes_short = abs(int(props['ma_minutes_short']))
self.ma_minutes_long = abs(int(props['ma_minutes_long']))
self.stop_loss = bool(str(props['stop_loss']).strip('"').lower() == 'true')
self.stop_loss_in_percent = abs(float(props['stop_loss_in_percent']))
self.no_action_at_loss = bool(str(props['no_action_at_loss']).strip('"').lower() == 'true')
self.trade_trials = abs(int(props['trade_trials']))
self.order_adjust_seconds = abs(int(props['order_adjust_seconds']))
self.trade_advantage_in_percent = float(props['trade_advantage_in_percent'])
currency = self.pair.split("/")
self.base = currency[0]
self.quote = currency[1]
self.database = 'mamaster.db'
self.interval = 10
self.satoshi_factor = 0.00000001
self.recipient_addresses = str(props['recipient_addresses']).strip('"').replace(' ', '').split(",")
self.sender_address = str(props['sender_address']).strip('"')
self.sender_password = str(props['sender_password']).strip('"')
self.mail_server = str(props['mail_server']).strip('"')
self.info = str(props['info']).strip('"')
self.url = 'https://bitcoin-schweiz.ch/bot/'
except (configparser.NoSectionError, KeyError):
raise SystemExit('Invalid configuration for ' + INSTANCE)
class Order:
"""
Holds the relevant data of an order
"""
__slots__ = 'id', 'price', 'amount', 'side', 'type', 'datetime'
undefined = 'undefined'
def __init__(self, ccxt_order=None):
if ccxt_order:
self.id = ccxt_order['id']
self.amount = ccxt_order['amount']
self.side = ccxt_order['side'].lower()
if ccxt_order['type'] in ['stop-loss', 'trailing_stop']:
self.type = 'stop'
else:
self.type = ccxt_order['type']
if self.type == 'stop':
if 'info' in ccxt_order and 'stopPx' in ccxt_order['info']:
self.price = ccxt_order['info']['stopPx']
else:
self.price = ccxt_order['price']
else:
self.price = ccxt_order['price']
self.datetime = ccxt_order['datetime']
def __str__(self):
return "{} {} order id: {}, price: {}, amount: {}, created: {}".format(self.type, self.side,
self.id if hasattr(self, 'id') and self.id else self.undefined,
self.price if hasattr(self, 'price') and self.price else self.undefined,
self.amount if hasattr(self, 'amount') and self.amount else self.undefined,
self.datetime if hasattr(self, 'datetime') and self.datetime else self.undefined)
class Stats:
"""
Holds the daily statistics in a ring memory (today plus the previous two)
"""
def __init__(self, day_of_year: int, data: dict):
self.days = []
self.add_day(day_of_year, data)
def add_day(self, day_of_year: int, data: dict):
existing = self.get_day(day_of_year)
if existing is None:
data['day'] = day_of_year
if len(self.days) > 2:
self.days = sorted(self.days, key=lambda item: item['day'], reverse=True) # desc
self.days.pop()
self.days.append(data)
def get_day(self, day_of_year: int):
matched = filter(lambda element: element['day'] == day_of_year, self.days)
if matched is not None:
for day in matched:
return day
return None
def function_logger(console_level: int, log_file: str, file_level: int = None):
function_name = inspect.stack()[1][3]
logger = logging.getLogger(function_name)
# By default log all messages
logger.setLevel(logging.DEBUG)
# StreamHandler logs to console
ch = logging.StreamHandler()
ch.setLevel(console_level)
ch.setFormatter(logging.Formatter('%(asctime)s: %(message)s', '%Y-%m-%d %H:%M:%S'))
logger.addHandler(ch)
if file_level is not None:
fh = RotatingFileHandler("{}.log".format(log_file), mode='a', maxBytes=5 * 1024 * 1024, backupCount=4,
encoding=None, delay=False)
fh.setLevel(file_level)
fh.setFormatter(logging.Formatter('%(asctime)s - %(lineno)4d - %(levelname)-8s - %(message)s'))
logger.addHandler(fh)
return logger
def fetch_mayer(tries: int = 0):
try:
req = requests.get('https://mayermultiple.info/current.json')
if req.text:
mayer = req.json()['data']
return {'current': float(mayer['current_mayer_multiple']), 'average': float(mayer['average_mayer_multiple'])}
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.ReadTimeout,
ValueError) as error:
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
if tries < 4:
sleep_for(4, 6)
return fetch_mayer(tries + 1)
LOG.warning('Failed to fetch Mayer multiple, giving up after 4 attempts')
return None
def evaluate_mayer(mayer: dict = None):
if mayer is None:
return 'n/a'
if mayer['current'] < mayer['average']:
return 'BUY'
if mayer['current'] > 2.4:
return 'SELL'
return 'HOLD'
def append_mayer(part: dict):
mayer = fetch_mayer()
advice = evaluate_mayer(mayer)
if mayer is None:
part['mail'].append("Mayer multiple: {:>19} (n/a)".format(advice))
part['csv'].append("Mayer multiple:;n/a")
return
if advice != 'HOLD':
part['mail'].append("Mayer multiple: {:>19.2f} (< {:.2f} = {})".format(mayer['current'], mayer['average'], advice))
else:
part['mail'].append("Mayer multiple: {:>19.2f} (< {:.2f} = {})".format(mayer['current'], 2.4, advice))
part['csv'].append("Mayer multiple:;{:.2f}".format(mayer['current']))
def daily_report(immediately: bool = False):
"""
Creates a daily report email around 12:02 UTC or immediately if told to do so
"""
global EMAIL_SENT
if CONF.daily_report:
now = datetime.datetime.utcnow().replace(microsecond=0)
if immediately or EMAIL_SENT != now.day and datetime.time(12, 22, 0) > now.time() > datetime.time(12, 1, 0):
subject = "Daily MAverage report {}".format(INSTANCE)
content = create_mail_content(True)
filename_csv = INSTANCE + '.csv'
write_csv(content['csv'], filename_csv)
send_mail(subject, content['text'], filename_csv)
EMAIL_SENT = now.day
def trade_report(prefix: str):
"""
Creates a trade report email
"""
if CONF.trade_report:
subject = "{} Trade report {}".format(prefix, INSTANCE)
content = create_mail_content()
send_mail(subject, content['text'])
def create_mail_content(daily: bool = False):
"""
Fetches and formats the data required for the daily report email
:return dict: text: str
"""
if not daily:
order = STATE['order'] if STATE['order'] else STATE['stop_loss_order']
trade_part = create_report_part_trade(order)
performance_part = create_report_part_performance(daily)
advice_part = create_report_part_advice()
settings_part = create_report_part_settings()
general_part = create_mail_part_general()
trade = ["Last trade", "----------", '\n'.join(trade_part['mail']), '\n\n'] if not daily else ''
performance = ["Performance", "-----------",
'\n'.join(performance_part['mail']) + '\n* (change within 24 hours)', '\n\n']
advice = ["Assessment / advice", "-------------------", '\n'.join(advice_part['mail']), '\n\n']
settings = ["Your settings", "-------------", '\n'.join(settings_part['mail']), '\n\n']
general = ["General", "-------", '\n'.join(general_part), '\n\n']
text = '\n'.join(trade) + '\n'.join(performance) + '\n'.join(advice) + '\n'.join(settings) + '\n'.join(general)
if CONF.info:
text += CONF.info + '\n\n'
text += CONF.url + '\n'
csv = None if not daily else "{};{} UTC;{};{};{};{}\n".format(INSTANCE,
datetime.datetime.utcnow().replace(microsecond=0),
';'.join(performance_part['csv']),
';'.join(advice_part['csv']),
';'.join(settings_part['csv']),
CONF.info)
return {'text': text, 'csv': csv}
def create_report_part_settings():
return {'mail': ["Daily report: {:>21}".format(str('Y' if CONF.daily_report is True else 'N')),
"Trade report: {:>21}".format(str('Y' if CONF.trade_report is True else 'N')),
"Short in %: {:>23}".format(CONF.short_in_percent),
"MA minutes short: {:>17}".format(str(CONF.ma_minutes_short)),
"MA minutes long: {:>18}".format(str(CONF.ma_minutes_long)),
"Stop loss: {:>24}".format(str('Y' if CONF.stop_loss is True else 'N')),
"Stop loss in %: {:>19}".format(str(CONF.stop_loss_in_percent)),
"No action at loss: {:>16}".format(str('Y' if CONF.no_action_at_loss is True else 'N')),
"Trade trials: {:>21}".format(CONF.trade_trials),
"Order adjust seconds: {:>13}".format(CONF.order_adjust_seconds),
"Trade advantage in %: {:>13}".format(CONF.trade_advantage_in_percent),
"Leverage default: {:>17}x".format(str(CONF.leverage_default)),
"Apply leverage: {:>19}".format(str('Y' if CONF.apply_leverage is True else 'N'))],
'csv': ["Daily report:;{}".format(str('Y' if CONF.daily_report is True else 'N')),
"Trade report:;{}".format(str('Y' if CONF.trade_report is True else 'N')),
"Short in %:;{}".format(str(CONF.short_in_percent)),
"MA minutes short:;{}".format(str(CONF.ma_minutes_short)),
"MA minutes long:;{}".format(str(CONF.ma_minutes_long)),
"Stop loss:;{}".format(str('Y' if CONF.stop_loss is True else 'N')),
"Stop loss in %:;{}".format(CONF.stop_loss_in_percent),
"No action at loss:;{}".format(str('Y' if CONF.no_action_at_loss is True else 'N')),
"Trade trials:;{}".format(CONF.trade_trials),
"Order adjust seconds:;{}".format(CONF.order_adjust_seconds),
"Trade advantage in %:;{}".format(CONF.trade_advantage_in_percent),
"Leverage default:;{}".format(str(CONF.leverage_default)),
"Apply leverage:;{}".format(str('Y' if CONF.apply_leverage is True else 'N'))]}
def create_mail_part_general():
general = ["Generated: {:>28}".format(str(datetime.datetime.utcnow().replace(microsecond=0)) + " UTC"),
"Bot: {:>30}".format(INSTANCE + '@' + socket.gethostname()),
"Version: {:>26}".format(CONF.bot_version)]
return general
def create_report_part_advice():
relevant_rates = get_last_rates(calculate_fetch_size(CONF.ma_minutes_long))
ma_short = calculate_ma(relevant_rates, calculate_fetch_size(CONF.ma_minutes_short))
ma_long = calculate_ma(relevant_rates, calculate_fetch_size(CONF.ma_minutes_long))
moving_average = str(round(ma_long)) + '/' + str(round(ma_short)) + ' = ' + read_action()
padding = 13 - len(str(CONF.ma_minutes_long)) - len(str(CONF.ma_minutes_short)) + len(moving_average)
part = {'mail': [
"Moving average {}/{}: {:>{}}".format(CONF.ma_minutes_long, CONF.ma_minutes_short, moving_average, padding)],
'csv': []}
append_mayer(part)
return part
def create_report_part_performance(daily: bool):
part = {'mail': [], 'csv': []}
margin_balance = get_margin_balance()
net_deposits = get_net_deposits()
sleep_for(0, 1)
price = get_current_price()
append_performance(part, margin_balance['total'], net_deposits, price)
wallet_balance = get_wallet_balance()
sleep_for(0, 1)
append_balances(part, margin_balance, wallet_balance, price, daily)
return part
def create_report_part_trade(last_order: Order):
part = {'mail': ["Executed: {:>17}".format(str(last_order))],
'csv': ["Executed:;{}".format(str(last_order))]}
return part
def send_mail(subject: str, text: str, attachment: str = None):
recipients = ", ".join(CONF.recipient_addresses)
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = CONF.sender_address
msg['To'] = recipients
readable_part = MIMEMultipart('alternative')
readable_part.attach(MIMEText(text, 'plain', 'utf-8'))
html = '<html><body><pre style="font:monospace">' + text + '</pre></body></html>'
readable_part.attach(MIMEText(html, 'html', 'utf-8'))
msg.attach(readable_part)
if attachment and os.path.isfile(attachment):
part = MIMEBase('application', 'octet-stream')
with open(attachment, "rb") as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename={}".format(attachment))
msg.attach(part)
server = smtplib.SMTP_SSL(CONF.mail_server, 465)
# server.starttls()
server.set_debuglevel(0)
server.login(CONF.sender_address, CONF.sender_password)
server.send_message(msg, None, None, mail_options=(), rcpt_options=())
server.quit()
LOG.info("Sent email to %s", recipients)
def append_performance(part: dict, margin_balance: float, net_deposits: float, price: float):
"""
Calculates and appends the absolute and relative overall performance
"""
if net_deposits is None:
part['mail'].append("Net deposits {}: {:>17}".format(CONF.base, 'n/a'))
part['mail'].append("Overall performance in {}: {:>7}".format(CONF.base, 'n/a'))
part['csv'].append("Net deposits {}:;{}".format(CONF.base, 'n/a'))
part['csv'].append("Overall performance in {}:;{}".format(CONF.base, 'n/a'))
else:
part['mail'].append("Net deposits {}: {:>20.4f}".format(CONF.base, net_deposits))
part['csv'].append("Net deposits {}:;{:.4f}".format(CONF.base, net_deposits))
absolute_performance = margin_balance - net_deposits
if net_deposits > 0 and absolute_performance != 0:
relative_performance = round(100 / (net_deposits / absolute_performance), 2)
part['mail'].append("Overall performance in {}: {:>+10.4f} ({:+.2f}%)".format(CONF.base,
absolute_performance,
relative_performance))
part['csv'].append("Overall performance in {}:;{:.4f};{:+.2f}%".format(CONF.base,
absolute_performance,
relative_performance))
else:
part['mail'].append("Overall performance in {}: {:>+10.4f} (% n/a)".format(CONF.base, absolute_performance))
part['csv'].append("Overall performance in {}:;{:.4f};% n/a".format(CONF.base, absolute_performance))
def append_balances(part: dict, margin_balance: dict, wallet_balance: dict, price: float, daily: bool):
"""
Appends price, wallet balance, margin balance (including stats), used margin and leverage information
"""
if wallet_balance['crypto'] == 0 and wallet_balance['fiat'] > 0:
wallet_balance['crypto'] = wallet_balance['fiat'] / price
part['mail'].append("Wallet balance {}: {:>18.4f}".format(CONF.base, wallet_balance['crypto']))
part['csv'].append("Wallet balance {}:;{:.4f}".format(CONF.base, wallet_balance['crypto']))
today = calculate_daily_statistics(margin_balance['total'], price, daily)
append_margin_change(part, today, CONF.base)
append_price_change(part, today, price)
used_margin = calculate_used_margin_percentage(margin_balance)
part['mail'].append("Used margin: {:>23.2f}%".format(used_margin))
part['csv'].append("Used margin:;{:.2f}%".format(used_margin))
if CONF.exchange == 'kraken':
actual_leverage = get_margin_leverage()
part['mail'].append("Actual leverage: {:>19.2f}%".format(actual_leverage))
part['csv'].append("Actual leverage:;{:.2f}%".format(used_margin))
else:
actual_leverage = get_margin_leverage()
part['mail'].append("Actual leverage: {:>19.2f}x".format(actual_leverage))
part['csv'].append("Actual leverage:;{:.2f}".format(actual_leverage))
used_balance = get_used_balance()
if used_balance is None:
used_balance = 'n/a'
part['mail'].append("Position {}: {:>22}".format(CONF.quote, used_balance))
part['csv'].append("Position {}:;{}".format(CONF.quote, used_balance))
else:
part['mail'].append("Position {}: {:>22.2f}".format(CONF.quote, used_balance))
part['csv'].append("Position {}:;{:.2f}".format(CONF.quote, used_balance))
def append_margin_change(part: dict, today: dict, currency: str):
"""
Appends margin changes
"""
formatter_mail = 18.4 if currency == CONF.base else 16.2
m_bal = "Margin balance {}: {:>{}f}".format(currency, today['mBal'], formatter_mail)
if 'mBalChan24' in today:
change = "{:+.2f}%".format(today['mBalChan24'])
m_bal += " (" if currency == CONF.base else " ("
m_bal += change
m_bal += ")*"
else:
change = "% n/a"
part['mail'].append(m_bal)
formatter_csv = .4 if currency == CONF.base else .2
part['csv'].append("Margin balance {}:;{:{}f};{}".format(currency, today['mBal'], formatter_csv, change))
def append_price_change(part: dict, today: dict, price: float):
"""
Appends price changes
"""
rate = "{} price {}: {:>21.2f}".format(CONF.base, CONF.quote, float(price))
if 'priceChan24' in today:
change = "{:+.2f}%".format(today['priceChan24'])
rate += " ("
rate += change
rate += ")*"
else:
change = "% n/a"
part['mail'].append(rate)
part['csv'].append("{} price {}:;{:.2f};{}".format(CONF.base, CONF.quote, float(price), change))
def calculate_daily_statistics(m_bal: float, price: float, update_stats: bool):
"""
Calculates, updates and persists the change in the margin balance compared with yesterday
:param m_bal: todays margin balance
:param price: the current rate
:param update_stats: update and persists the statistic values
:return todays statistics including price and margin balance changes compared with 24 hours ago
"""
global STATS
today = {'mBal': m_bal, 'price': price}
if STATS is None:
if update_stats and datetime.datetime.utcnow().time() > datetime.datetime(2012, 1, 17, 12, 1).time():
STATS = Stats(int(datetime.date.today().strftime("%Y%j")), today)
persist_statistics()
return today
if update_stats and datetime.datetime.utcnow().time() > datetime.datetime(2012, 1, 17, 12, 1).time():
STATS.add_day(int(datetime.date.today().strftime("%Y%j")), today)
persist_statistics()
before_24h = STATS.get_day(int(datetime.date.today().strftime("%Y%j")) - 1)
if before_24h is not None:
today['mBalChan24'] = round((today['mBal'] / before_24h['mBal'] - 1) * 100, 2) if before_24h['mBal'] != 0 else 0
if 'price' in before_24h:
today['priceChan24'] = round((today['price'] / before_24h['price'] - 1) * 100, 2) if before_24h['price'] != 0 else 0
return today
def load_statistics():
stats_file = INSTANCE + '.pkl'
if os.path.isfile(stats_file):
with open(stats_file, "rb") as file:
return pickle.load(file)
return None
def persist_statistics():
stats_file = INSTANCE + '.pkl'
with open(stats_file, "wb") as file:
pickle.dump(STATS, file)
def calculate_used_margin_percentage(bal=None):
"""
Calculates the used margin percentage
"""
if bal is None:
bal = get_margin_balance()
if bal['total'] <= 0:
return 0
return float(100 - (bal['free'] / bal['total']) * 100)
def write_csv(content: str, filename_csv: str):
if not is_already_written(filename_csv):
write_mode = 'a' if int(datetime.date.today().strftime("%j")) != 1 else 'w'
with open(filename_csv, write_mode) as file:
file.write(content)
def is_already_written(filename_csv: str):
if os.path.isfile(filename_csv):
with open(filename_csv, 'r') as file:
return str(datetime.date.today().isoformat()) in list(file)[-1]
return False
def get_margin_balance():
"""
Fetches the margin balance in fiat (free and total)
return: balance in fiat
"""
try:
if CONF.exchange == 'bitmex':
bal = EXCHANGE.fetch_balance()[CONF.base]
elif CONF.exchange == 'kraken':
bal = EXCHANGE.private_post_tradebalance({'asset': CONF.base})['result']
bal['free'] = float(bal['mf'])
bal['total'] = float(bal['e'])
bal['used'] = float(bal['m'])
return bal
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
handle_account_errors(str(error.args))
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
get_margin_balance()
def get_margin_leverage():
"""
Fetch the leverage
"""
try:
if CONF.exchange == 'bitmex':
return EXCHANGE.fetch_balance()['info'][0]['marginLeverage']
if CONF.exchange == 'kraken':
result = EXCHANGE.private_post_tradebalance()['result']
if hasattr(result, 'ml'):
return float(result['ml'])
return 0
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
handle_account_errors(str(error.args))
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
get_margin_leverage()
def get_net_deposits():
"""
Get deposits and withdraws to calculate the net deposits in crypto.
return: net deposits
"""
if CONF.net_deposits_in_base_currency:
return CONF.net_deposits_in_base_currency
try:
currency = CONF.base if CONF.base != 'BTC' else 'XBt'
if CONF.exchange == 'bitmex':
result = EXCHANGE.private_get_user_wallet({'currency': currency})
return (result['deposited'] - result['withdrawn']) * CONF.satoshi_factor
if CONF.exchange == 'kraken':
net_deposits = 0
deposits = EXCHANGE.fetch_deposits(CONF.base)
for deposit in deposits:
net_deposits += deposit['amount']
ledgers = EXCHANGE.private_post_ledgers({'asset': currency, 'type': 'withdrawal'})['result']['ledger']
for withdrawal_id in ledgers:
net_deposits += float(ledgers[withdrawal_id]['amount'])
return net_deposits
LOG.error("get_net_deposit() not yet implemented for %s", CONF.exchange)
return None
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
handle_account_errors(str(error.args))
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
get_net_deposits()
def get_position_info():
"""
Fetch position information
"""
try:
if CONF.exchange == 'bitmex':
response = EXCHANGE.private_get_position()
if response and response[0] and response[0]['avgEntryPrice']:
return response[0]
return None
if CONF.exchange == 'kraken':
# in crypto
response = EXCHANGE.private_post_tradebalance({'asset': CONF.base})
return response['result']
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
handle_account_errors(str(error.args))
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
get_position_info()
def get_wallet_balance():
"""
Fetch the wallet balance in crypto
"""
try:
if CONF.exchange == 'bitmex':
return {'crypto': EXCHANGE.fetch_balance()['info'][0]['walletBalance'] * CONF.satoshi_factor}
if CONF.exchange == 'kraken':
asset = CONF.base if CONF.base != 'BTC' else 'XBt'
return {'crypto': float(EXCHANGE.private_post_tradebalance({'asset': asset})['result']['tb'])}
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
handle_account_errors(str(error.args))
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
get_wallet_balance()
def get_open_trades():
try:
return EXCHANGE.private_get_trades({'status': 'open'})['models']
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
get_open_trades()
def get_open_trade(currency_pair: str):
trades = get_open_trades()
if trades is not None:
for trade in trades:
if trade['currency_pair_code'] == currency_pair:
return trade
return None
def update_stop_loss_trade(trade_id: str, stop_loss_price: float):
try:
EXCHANGE.private_put_trades_id({'id': trade_id, 'stop_loss': stop_loss_price})
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
if any(e in str(error.args) for e in STOP_ERRORS):
LOG.error('Unable to update trade {} with price {:.2f}'.format(trade_id, stop_loss_price), str(error.args))
return False
handle_account_errors(str(error.args))
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
update_stop_loss_trade(trade_id, stop_loss_price)
return True
def get_open_order():
"""
Gets current open order
:return Order
"""
try:
result = EXCHANGE.fetch_open_orders(CONF.pair, since=None, limit=3, params={'reverse': True})
if result is not None and len(result) > 0:
return Order(result[-1])
return None
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
handle_account_errors(str(error.args))
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
get_open_order()
def get_closed_order():
"""
Gets the last closed order
:return Order
"""
try:
result = EXCHANGE.fetch_closed_orders(CONF.pair, since=None, limit=3, params={'reverse': True})
if result is not None and len(result) > 0:
orders = sorted(result, key=lambda order: order['datetime'])
last_order = Order(orders[-1])
LOG.info('Last %s', str(last_order))
return last_order
return None
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
handle_account_errors(str(error.args))
LOG.error(RETRY_MESSAGE, type(error).__name__, str(error.args))
sleep_for(4, 6)
get_closed_order()
def get_current_price(limit: int = None, attempts: int = 0):
"""
Fetches the current BTC/USD exchange rate
In case of failure, the function calls itself again until success
:return int current market price
"""
try:
price = EXCHANGE.fetch_ticker(CONF.pair)['bid']
if not price:
LOG.warning('Price was None')
sleep_for(1, 2)
get_current_price(limit, attempts)
else:
return int(price)
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
handle_account_errors(str(error.args))
LOG.debug('Got an error %s %s, retrying in 5 seconds...', type(error).__name__, str(error.args))
attempts += 1
if not limit or attempts < limit:
sleep_for(4, 6)
get_current_price(limit, attempts)
else:
return 0
def get_last_rates(limit: int):
"""
Fetches the last x rates from the database
:param limit: Number of rates to be fetched
:return The fetched results
"""
conn = sqlite3.connect(CONF.database, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
curs = conn.cursor()
try:
return curs.execute("SELECT price FROM rates ORDER BY date_time DESC LIMIT {}".format(limit)).fetchall()
finally:
curs.close()
conn.close()
def get_all_entries():
"""
Fetches all entries from the database
:return The fetched results
"""
conn = sqlite3.connect(CONF.database, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
curs = conn.cursor()
try:
return curs.execute("SELECT date_time, price FROM rates ORDER BY date_time DESC").fetchall()
finally:
curs.close()
conn.close()
def calculate_ma(rates: [[]], size: int, current: int = 0):
"""
Calculates the moving average based on the input list and the requested size
:param rates: List of rate tuples fetched from the database
:param size: relevant period of rates for calculation (first x)
:param current: current market price, optional
:return float: calculated moving average
"""
total = current
stop = size if current == 0 else size - 1
i = 0
while i < stop:
total += rates[i][0]
i += 1
return total / size
def dump_to_csv(entries: [[]]):
buffer = []
for entry in entries:
buffer.append("{};{}".format(entry[0], entry[1]))
content = '\n'.join(buffer)
with open(CONF.database + '.csv', 'w') as file:
file.write(content)
def connect_to_exchange():
exchanges = {'bitmex': ccxt.bitmex,
'kraken': ccxt.kraken}
exchange = exchanges[CONF.exchange]({
'enableRateLimit': True,
'apiKey': CONF.api_key,
'secret': CONF.api_secret,
# 'verbose': True,
})
if hasattr(CONF, 'test') & CONF.test:
if 'test' in exchange.urls:
exchange.urls['api'] = exchange.urls['test']
else:
raise SystemExit('Test not supported by %s', CONF.exchange)
return exchange
def write_control_file():
with open(INSTANCE + '.pid', 'w') as file:
file.write(str(os.getpid()) + ' ' + INSTANCE)
def read_action():
action_file = INSTANCE + '.act'
if os.path.isfile(action_file):
with open(action_file, 'rt') as file:
return file.read().strip()
return None
def write_action(act: str):
act = act[:5].rstrip()
now = str(datetime.datetime.utcnow().replace(microsecond=0))
with open(INSTANCE + '.act', 'wt') as file:
file.write('{} (since {} UTC)'.format(act, now))
def do_buy():
"""
Buys at market price lowered by configured percentage or at market price if not successful
within the configured trade attempts
:return Order
"""
i = 1
while i <= CONF.trade_trials:
buy_price = calculate_buy_price(get_current_price())
order_size = calculate_buy_order_size(buy_price)
if order_size is None:
return None
order = create_buy_order(buy_price, order_size)
if order is None:
LOG.error("Could not create buy order over %s", order_size)
return None
write_action('-BUY')
order_status = poll_order_status(order.id, 10)
if order_status in ['open', 'live']:
cancel_order(order)
i += 1
if buy_or_sell() == 'SELL':
return do_sell()
daily_report()
else:
return order
order_size = calculate_buy_order_size(get_current_price())
if order_size is None:
return None
write_action('-BUY')
return create_market_buy_order(order_size)
def calculate_buy_price(price: float):
"""
Calculates the buy price based on the market price lowered by configured percentage
:param price: market price
:return buy price
"""
return round(price / (1 + CONF.trade_advantage_in_percent / 100), 1)
def poll_order_status(order_id: str, interval: int):
order_status = 'open'
attempts = round(CONF.order_adjust_seconds / interval) if CONF.order_adjust_seconds > interval else 1
i = 0
while i < attempts and order_status == 'open':
daily_report()
sleep(interval-1)
order_status = fetch_order_status(order_id)
i += 1
return order_status
def do_sell():
"""
Sells at market price raised by configured percentage or at market price if not successful
within the configured trade attempts
:return Order
"""
order_size = calculate_sell_order_size()
if order_size is None:
return None
i = 1
while i <= CONF.trade_trials:
sell_price = calculate_sell_price(get_current_price())
order = create_sell_order(sell_price, order_size)
if order is None:
LOG.error("Could not create sell order over %s", order_size)
return None
write_action('-SELL')
order_status = poll_order_status(order.id, 10)
if order_status in ['open', 'live']:
cancel_order(order)
i += 1
if buy_or_sell() == 'BUY':
return do_buy()
daily_report()
else:
return order
write_action('-SELL')
return create_market_sell_order(order_size)
def calculate_sell_price(price: float):
"""
Calculates the sell price based on the market price raised by configured percentage
:param price: market price
:return sell price
"""
return round(price * (1 + CONF.trade_advantage_in_percent / 100), 1)
def calculate_buy_order_size(buy_price: float):
"""
Calculates the buy order size. For BitMex the short position amount needs to be taken into account.
Minus 1% for fees.
:param buy_price:
:return the calculated buy_order_size in crypto or None
"""
if CONF.exchange == 'bitmex':
poi = get_position_info()
total = get_crypto_balance()['total']
if CONF.apply_leverage:
total *= CONF.leverage_default
if poi is not None:
pnl = poi['unrealisedGrossPnl'] * CONF.satoshi_factor # negative if loss
if poi['homeNotional'] < 0:
size = (total + pnl + abs(poi['homeNotional']) / 0.99) / 1.01
else:
size = (total + pnl - (poi['homeNotional']) / 0.99) / 1.01
else:
size = total / 1.01
elif CONF.exchange == 'kraken':
if CONF.apply_leverage:
total = get_fiat_balance()['total'] * CONF.leverage_default
else:
total = get_fiat_balance()['total']
size = to_crypto_amount(total / 1.01, buy_price)
# no position and no fiat - so we will buy crypto with crypto
if size < 0.000001:
if CONF.apply_leverage:
free = get_fiat_balance()['free'] * CONF.leverage_default
else:
free = get_fiat_balance()['free']
size = free / 1.01
# size = get_crypto_balance()['total'] / 1.01
# kraken fees are a bit higher
size /= 1.04
return size if size > MIN_ORDER_SIZE else None
def calculate_sell_order_size():
"""
Calculates the sell order size. Depending on the configured short_in_percent value, the long position amount or the
percentage already used.
Minus 1% for fees.
:return the calculated sell_order_size or None
"""
total = get_crypto_balance()['total']
used = calculate_percentage_used()
if CONF.exchange == 'kraken':
if CONF.apply_leverage and CONF.leverage_default > 1:
total *= (CONF.leverage_default + 1)
else:
total *= 2
elif CONF.apply_leverage:
total *= CONF.leverage_default
if CONF.exchange == 'bitmex':
poi = get_position_info()
if poi is not None:
if poi['homeNotional'] > 0:
pnl = poi['unrealisedGrossPnl'] * CONF.satoshi_factor # negative if loss
diff = (total - (poi['homeNotional'] * 1.01)) / (100 / CONF.short_in_percent)
factor = (100 + CONF.short_in_percent) / 100
size = ((poi['homeNotional'] * factor) + diff) + pnl
return size if size > MIN_ORDER_SIZE else None
if used > CONF.short_in_percent:
return None
diff = CONF.short_in_percent - used
if diff <= 0:
return None
size = total / (100 / diff)
size /= 1.01
# kraken fees are a bit higher
if CONF.exchange == 'kraken':
size /= 1.04
return size if size > MIN_ORDER_SIZE else None
def calculate_fetch_size(minutes: int):
"""
Calculates the fetch size for the requested minutes. The stored rate data has 10 or 2 minute intervals.
:param minutes: