-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbalancer.py
executable file
·1918 lines (1671 loc) · 77 KB
/
balancer.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 calendar
import configparser
import datetime
import inspect
import logging
import os
import pickle
import random
import smtplib
import socket
import sys
import time
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
from time import sleep
import ccxt
import requests
MIN_ORDER_SIZE = 0.001
MIN_FIAT_ORDER_SIZE = 100
INIT = False
ORDER = None
LAST_ORDER = None
BAL = {'cryptoBalance': 0, 'totalBalanceInCrypto': 0, 'price': 0}
EMAIL_SENT = False
EMAIL_ONLY = False
KEEP_ORDERS = False
NO_LOG = False
SIMULATE = False
DATA_DIR = ''
STARTED = datetime.datetime.utcnow().replace(microsecond=0)
STOP_ERRORS = ['order_size', 'smaller', 'MIN_NOTIONAL', 'nsufficient', 'too low', 'too small', 'not_enough', 'below',
'exceeds account', 'price', 'nvalid arg', 'nvalid orderQty']
ACCOUNT_ERRORS = ['account has been disabled', 'key is disabled', 'authentication failed', 'permission denied',
'invalid api key', 'access denied']
RETRY_MESSAGE = 'Got an error %s %s, retrying in about 5 seconds...'
NOT_IMPLEMENTED_MESSAGE = '%s is not implemented for %s'
NA = 'n/a'
class ExchangeConfig:
def __init__(self):
self.mm_quotes = ['OFF', 'MM', 'MMRange']
self.report_cadences = ['T', 'D', 'M', 'A']
self.mayer_file = f'{DATA_DIR}mayer.avg'
self.api_password = ''
config = configparser.ConfigParser(interpolation=None)
config.read(f'{DATA_DIR}{INSTANCE}.txt')
try:
props = config['config']
self.bot_version = '1.4.7'
self.exchange = str(props['exchange']).strip('"').lower()
self.api_key = str(props['api_key']).strip('"')
self.api_secret = str(props['api_secret']).strip('"')
if config.has_option('config', 'api_password'):
self.api_password = str(props['api_password']).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.start_crypto_price = abs(int(props['start_crypto_price']))
self.start_margin_balance = abs(float(props['start_margin_balance']))
self.start_mayer_multiple = abs(float(props['start_mayer_multiple']))
self.start_date = str(props['start_date']).strip('"').strip()
self.reference_net_deposits = abs(float(props['reference_net_deposits']))
self.crypto_quote_in_percent = abs(float(props['crypto_quote_in_percent']))
self.auto_quote = str(props['auto_quote']).strip('"')
self.mm_quote_0 = abs(float(props['mm_quote_0']))
self.mm_quote_100 = abs(float(props['mm_quote_100']))
self.tolerance_in_percent = abs(float(props['tolerance_in_percent']))
self.period_in_minutes = abs(float(props['period_in_minutes']))
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'])
self.stop_buy = bool(str(props['stop_buy']).strip('"').lower() == 'true')
self.stop_sell = bool(str(props['stop_sell']).strip('"').lower() == 'true')
self.max_crypto_quote_in_percent = abs(float(props['max_crypto_quote_in_percent']))
self.max_leverage_in_percent = abs(float(props['max_leverage_in_percent']))
self.backtrade_only_on_profit = bool(str(props['backtrade_only_on_profit']).strip('"').lower() == 'true')
self.report = str(props['report']).strip('"')
self.base, self.quote = self.pair.split("/")
if self.auto_quote not in self.mm_quotes:
raise SystemExit(f"Invalid value for auto_quote: '{self.auto_quote}' possible values are: {self.mm_quotes}")
if self.report not in self.report_cadences:
raise SystemExit(f"Invalid value for report: '{self.report}' possible values are: {self.report_cadences}")
self.period_in_seconds = round(self.period_in_minutes * 60)
self.satoshi_factor = 0.00000001
if config.has_option('config', 'mayer_file'):
self.mayer_file = str(props['mayer_file']).strip('"')
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(f'Invalid configuration for {INSTANCE}')
class Order:
"""
Holds the relevant data of an order
"""
__slots__ = 'id', 'price', 'amount', 'side', 'datetime'
def __init__(self, ccxt_order, amount_fiat: float = None, amount_crypto: float = None, price: float = None):
if 'id' in ccxt_order:
self.id = ccxt_order['id']
elif 'uuid' in ccxt_order:
self.id = ccxt_order['uuid']
if 'price' in ccxt_order:
self.price = set_price(ccxt_order['price'], price)
elif 'info' in ccxt_order:
self.price = set_price(ccxt_order['info']['price'], price)
if 'amount' in ccxt_order:
self.amount = compute_amount(ccxt_order['amount'], ccxt_order['price'] if 'price' in ccxt_order else None, amount_fiat, amount_crypto)
elif 'info' in ccxt_order:
self.amount = compute_amount(ccxt_order['info']['amount'], ccxt_order['info']['price'], amount_fiat, amount_crypto)
if 'side' in ccxt_order:
self.side = ccxt_order['side']
elif 'direction' in ccxt_order:
self.side = ccxt_order['direction']
elif 'info' in ccxt_order:
self.side = ccxt_order['info']['direction']
if 'datetime' in ccxt_order:
self.datetime = ccxt_order['datetime']
elif 'created_at' in ccxt_order:
self.datetime = ccxt_order['created_at']
elif 'info' in ccxt_order:
self.datetime = ccxt_order['info']['created_at']
def __str__(self):
return f"{self.side}, price: {self.price}, amount: {self.amount}, order id: {self.id}, created: {self.datetime}"
class Stats:
"""
Holds the daily statistics in a ring memory (today plus the previous two)
"""
def __init__(self, day_of_year: int = None, data: dict = None):
self.days = []
if day_of_year and data:
self.add_day(day_of_year, data)
def add_day(self, day_of_year: int, data: dict):
if self.get_day(day_of_year) 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:
for day in matched:
return day
return None
def function_logger(console_level: int, log_file: str = None, 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 log_file and file_level:
fh = RotatingFileHandler(f"{log_file}.log", 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 compute_amount(ccxt_amount: float = None, price: float = None, amount_fiat: float = None, amount_crypto: float = None):
if CONF.exchange == 'bitmex':
return amount_fiat if amount_fiat is not None else ccxt_amount if \
(not ccxt_amount or ccxt_amount >= MIN_FIAT_ORDER_SIZE or not price) else round(price * ccxt_amount)
return ccxt_amount if ccxt_amount is not None else amount_crypto
def set_price(ccxt_price: float = None, price: float = None):
return round(ccxt_price) if ccxt_price is not None else round(price) if price is not None else None
def fetch_mayer(tries: int = 0):
try:
req = requests.get('https://bitcoinition.com/current.json', timeout=10)
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)
part['labels'].append("MM")
if mayer is None:
part['mail'].append("Mayer multiple: {:>19} (n/a)".format(advice))
part['csv'].append(NA)
return
if advice == 'HOLD':
part['mail'].append("Mayer multiple: {:>19.2f} (< {:.2f} = {})".format(mayer['current'], 2.4, advice))
elif advice == 'BUY':
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("{:.2f}".format(mayer['current']))
def get_mayer():
btc_usd = get_btc_usd_pair()
mayer = calculate_mayer(get_current_price(btc_usd, 0, 3))
if mayer is None:
mayer = fetch_mayer()
return mayer
def calculate_mayer(price: float):
average = read_daily_average()
if average:
return {'current': price / average}
return None
def read_daily_average():
if CONF.mayer_file and os.path.isfile(CONF.mayer_file):
with open(CONF.mayer_file, "rt") as file:
return float(file.read())
return None
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
now = datetime.datetime.utcnow()
if immediately or datetime.datetime(2012, 1, 17, 12, 25).time() > now.time() \
> datetime.datetime(2012, 1, 17, 12, 1).time() and EMAIL_SENT != now.day:
content = create_mail_content(True)
filename_csv = f'{DATA_DIR}{INSTANCE}.csv'
update_csv(content, filename_csv)
if immediately or is_due_date(datetime.date.today()):
cadence = "Daily" if CONF.report in ['T', 'D'] else "Monthly" if CONF.report == 'M' else 'Annual'
subject = f"{cadence} BalanceR report {INSTANCE}"
send_mail(subject, content['text'], filename_csv)
EMAIL_SENT = now.day
def is_due_date(today: datetime.date):
if CONF.report in ['T', 'D']:
return True
if today.day == calendar.monthrange(today.year, today.month)[1]:
if CONF.report == 'M':
return True
if today.month == 12:
return True
return False
def trade_report():
"""
Creates a trade report email
"""
if CONF.report == 'T':
subject = f"RB Trade report {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 = ORDER if ORDER else get_closed_order()
trade = ["Trade", "-----", '\n'.join(create_report_part_trade(order)), '\n\n']
text = '\n'.join(trade)
else:
text = ''
performance_part = create_report_part_performance(daily)
base_values_part = create_report_part_base_values()
advice_part = create_report_part_advice()
settings_part = create_report_part_settings()
general_part = create_mail_part_general()
performance = ["Performance", "-----------", '\n'.join(performance_part['mail']) +
'\n* (change since yesterday noon)', '\n\n']
if CONF.exchange == 'bitmex':
start = ["Base information", "----------------", '\n'.join(base_values_part['mail']), '\n\n']
else:
start = []
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']
if not CONF.info:
text += '\n'.join(performance) + '\n'.join(start) + '\n'.join(advice) + '\n'.join(settings) + '\n'.join(
general) + CONF.url + '\n'
else:
text += '\n'.join(performance) + '\n'.join(start) + '\n'.join(advice) + '\n'.join(settings) + '\n'.join(
general) + CONF.info + '\n\n' + CONF.url + '\n'
csv = None if not daily else "{};{} UTC;{};{};{};{};{}\n".format(INSTANCE,
datetime.datetime.utcnow().replace(microsecond=0),
';'.join(performance_part['csv']),
';'.join(base_values_part['csv']),
';'.join(advice_part['csv']),
';'.join(settings_part['csv']),
CONF.info)
labels = None if not daily else "Bot;Datetime;{};{};{};{};\n".format(';'.join(performance_part['labels']),
';'.join(base_values_part['labels']),
';'.join(advice_part['labels']),
';'.join(settings_part['labels']))
return {'text': text, 'csv': csv, 'labels': labels}
def create_report_part_base_values():
part = {'mail': [], 'csv': [], 'labels': []}
part['labels'].append("Price")
part['labels'].append("Margin")
part['labels'].append("MM")
part['labels'].append("Start Date")
if CONF.exchange == 'bitmex':
part['mail'].append("Price {}: {:>24}".format(CONF.quote, CONF.start_crypto_price))
part['mail'].append("Margin balance {}: {:>15}".format(CONF.base, round(CONF.start_margin_balance, 4)))
part['mail'].append("MM: {:>31}".format(round(CONF.start_mayer_multiple, 4)))
part['mail'].append("Start date: {:>27}".format(CONF.start_date))
part['csv'].append("{}".format(CONF.start_crypto_price))
part['csv'].append("{}".format(CONF.start_margin_balance))
part['csv'].append("{}".format(round(CONF.start_mayer_multiple, 1)))
part['csv'].append("{}".format(CONF.start_date))
else:
part['csv'].append(NA)
part['csv'].append(NA)
part['csv'].append(NA)
part['csv'].append(NA)
return part
def create_report_part_settings():
part = {'mail': [], 'csv': [], 'labels': []}
part['labels'].append("Quote {}".format(CONF.base))
base_len = len(CONF.base)
if CONF.auto_quote == 'MMRange':
part['csv'].append(NA)
else:
part['mail'].append("Quote {} in %: {:>{}}".format(CONF.base, CONF.crypto_quote_in_percent, 22-base_len))
part['csv'].append("{}".format(CONF.crypto_quote_in_percent))
part['labels'].append("Auto-Quote")
part['mail'].append("Auto-quote: {:>23}".format(CONF.auto_quote))
part['csv'].append("{}".format(CONF.auto_quote))
part['labels'].append("MM Q0")
part['mail'].append("MM quote 0: {:>23}".format(CONF.mm_quote_0))
part['csv'].append("{}".format(CONF.mm_quote_0))
part['labels'].append("MM Q100")
part['mail'].append("MM quote 100: {:>21}".format(CONF.mm_quote_100))
part['csv'].append("{}".format(CONF.mm_quote_100))
part['labels'].append("Max Quote")
part['mail'].append("Max quote {} in %: {:>{}}".format(CONF.base, CONF.max_crypto_quote_in_percent, 18-base_len))
part['csv'].append("{}".format(CONF.max_crypto_quote_in_percent))
part['labels'].append("Max Leverage")
part['mail'].append("Max leverage in %: {:>16}".format(CONF.max_leverage_in_percent))
part['csv'].append("{}".format(CONF.max_leverage_in_percent))
part['labels'].append("Tol. %")
part['mail'].append("Tolerance in %: {:>19}".format(CONF.tolerance_in_percent))
part['csv'].append("{}".format(CONF.tolerance_in_percent))
part['labels'].append("Period Min.")
part['mail'].append("Period in minutes: {:>16}".format(CONF.period_in_minutes))
part['csv'].append("{}".format(CONF.period_in_minutes))
part['labels'].append("Trade Trials")
part['mail'].append("Trade trials: {:>21}".format(CONF.trade_trials))
part['csv'].append("{}".format(CONF.trade_trials))
part['labels'].append("Order Adj. Sec.")
part['mail'].append("Order adjust seconds: {:>13}".format(CONF.order_adjust_seconds))
part['csv'].append("{}".format(CONF.order_adjust_seconds))
part['labels'].append("Trade Adv. %")
part['mail'].append("Trade advantage in %: {:>13}".format(CONF.trade_advantage_in_percent))
part['csv'].append("{}".format(CONF.trade_advantage_in_percent))
part['labels'].append("Stop Buy")
part['mail'].append("Stop buy: {:>25}".format(str('Y' if CONF.stop_buy is True else 'N')))
part['csv'].append("{}".format(str('Y' if CONF.stop_buy is True else 'N')))
part['labels'].append("Stop Sell")
part['mail'].append("Stop sell: {:>24}".format(str('Y' if CONF.stop_sell is True else 'N')))
part['csv'].append("{}".format(str('Y' if CONF.stop_sell is True else 'N')))
part['labels'].append("Backtrade Only Profit")
part['mail'].append("Backtrade only on profit: {:>9}".format(str('Y' if CONF.backtrade_only_on_profit is True else 'N')))
part['csv'].append("{}".format(str('Y' if CONF.backtrade_only_on_profit is True else 'N')))
part['labels'].append("Report")
part['mail'].append("Report: {:>27}".format(CONF.report))
part['csv'].append("{}".format(CONF.report))
part['labels'].append("Info")
return part
def create_mail_part_general():
return ["Generated: {:>28}".format(str(datetime.datetime.utcnow().replace(microsecond=0)) + " UTC"),
"Bot: {:>30}".format(INSTANCE + '@' + socket.gethostname()),
"Version: {:>26}".format(CONF.bot_version),
"Running since: {:>20} UTC".format(str(STARTED))]
def create_report_part_advice():
part = {'mail': [], 'csv': [], 'labels': []}
append_mayer(part)
return part
def create_report_part_performance(daily: bool):
part = {'mail': [], 'csv': [], 'labels': []}
margin_balance = get_margin_balance()
net_deposits = get_net_deposits()
sleep_for(0, 1)
append_performance(part, margin_balance, net_deposits)
sleep_for(0, 1)
append_balances(part, margin_balance, daily)
return part
def create_report_part_trade(last_order: Order):
return ["{:>17}".format(str(last_order))]
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):
"""
Calculates and appends the absolute and relative overall performance
"""
part['labels'].append("Deposit {}".format(CONF.base))
part['labels'].append("Overall Perf. {}".format(CONF.base))
part['labels'].append("Performance %")
base_len = len(CONF.base)
if net_deposits is None:
part['mail'].append("Net deposits {}: {:>{}}".format(CONF.base, NA, 20-base_len))
part['mail'].append("Overall performance in {}: {:>{}} (% n/a)".format(CONF.base, NA, 10-base_len))
part['csv'].append(NA)
part['csv'].append(NA)
part['csv'].append(NA)
else:
part['mail'].append("Net deposits {}: {:>{}.4f}".format(CONF.base, net_deposits, 20-base_len))
part['csv'].append("{:.4f}".format(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 {}: {:>+{}.4f} ({:+.2f}%)".format(CONF.base,
absolute_performance,
10-base_len,
relative_performance))
part['csv'].append("{:.4f};{:+.2f}".format(absolute_performance, relative_performance))
else:
part['mail'].append("Overall performance in {}: {:>+{}.4f} (% n/a)".format(CONF.base,
absolute_performance,
10-base_len))
part['csv'].append("{:.4f};n/a".format(absolute_performance))
def append_balances(part: dict, margin_balance: float, daily: bool):
"""
Appends wallet balance, margin balance (including stats), used margin and leverage information, liquidation price
"""
price = get_current_price()
append_wallet_balance(part, price)
stats = load_statistics()
if CONF.exchange == 'bitmex':
margin_balance_of_fiat = get_margin_balance_of_fiat()
today = calculate_daily_statistics(margin_balance, margin_balance_of_fiat['total'], price, stats, daily)
append_margin_change(part, today)
append_position_change(part, today)
else:
c_bal = get_crypto_balance()
crypto_total = c_bal['total'] if c_bal else 0
f_bal = get_fiat_balance()
fiat_total = f_bal['total'] if f_bal else 0
today = calculate_daily_statistics(crypto_total, fiat_total, price, stats, daily)
append_balance_change(part, today)
yesterday = None if stats is None else stats.get_day(int(datetime.date.today().strftime("%Y%j")) - 1)
append_value_change(part, today, yesterday, price)
append_trading_result(part, today, yesterday, price)
append_price_change(part, today, price)
append_actual_quote(part, price)
append_margin_leverage(part)
part['labels'].append("Target Position {}".format(CONF.quote))
target_position = NA
if CONF.exchange == 'bitmex':
target_position = round(calculate_target_position(calculate_target_quote(), price))
part['mail'].append("Target position {}: {:>{}}".format(CONF.quote, target_position, 17-len(CONF.quote)))
part['csv'].append("{}".format(target_position))
append_liquidation_price(part)
def append_wallet_balance(part: dict, price: float):
wallet_balance = get_wallet_balance(price)
part['labels'].append("Wallet {}".format(CONF.base))
base_len = len(CONF.base)
if wallet_balance is None:
part['mail'].append("Wallet balance {}: {:>{}}".format(CONF.base, NA, 15-base_len))
part['csv'].append(NA)
else:
part['mail'].append("Wallet balance {}: {:>{}.4f}".format(CONF.base, wallet_balance, 18-base_len))
part['csv'].append("{:.4f}".format(wallet_balance))
def append_liquidation_price(part: dict):
poi = None
part['labels'].append("Liq. Price {}".format(CONF.quote))
if CONF.exchange == 'bitmex':
sleep_for(1, 2)
poi = get_position_info()
padding = 15-len(CONF.quote)
if poi is not None and 'liquidationPrice' in poi and poi['liquidationPrice'] is not None:
part['mail'].append("Liquidation price {}: {:>{}}".format(CONF.quote, round(float(poi['liquidationPrice'])), padding))
part['csv'].append("{}".format(round(float(poi['liquidationPrice']))))
else:
part['mail'].append("Liquidation price {}: {:>{}}".format(CONF.quote, 'n/a', padding))
part['csv'].append(NA)
def append_margin_change(part: dict, today: dict):
"""
Appends crypto margin and its change (bitmex only)
"""
part['labels'].append("Margin {}".format(CONF.base))
part['labels'].append("Change %")
part['labels'].append("Position {}".format(CONF.quote))
part['labels'].append("Change %")
m_bal = "Margin balance {}: {:>{}.4f}".format(CONF.base, today['mBal'], 18-len(CONF.base))
change = NA
if 'mBalChan24' in today:
change = "{:+.2f}%".format(today['mBalChan24'])
m_bal += " (" + change + ")*"
change = "{:+.2f}".format(today['mBalChan24'])
part['mail'].append(m_bal)
part['csv'].append("{:.4f};{}".format(today['mBal'], change))
def append_position_change(part: dict, today: dict):
"""
Appends fiat position and its change (bitmex only)
"""
fm_bal = "Position {}: {:>{}}".format(CONF.quote, round(today['fmBal']), 24-len(CONF.quote))
change = NA
if 'fmBalChan24' in today:
change = "{:+.2f}%".format(today['fmBalChan24'])
fm_bal += " (" + change + ")*"
change = "{:+.2f}".format(today['fmBalChan24'])
part['mail'].append(fm_bal)
part['csv'].append("{};{}".format(round(today['fmBal']), change))
def append_balance_change(part: dict, today: dict):
"""
Appends balance changes
"""
part['labels'].append("Balance {}".format(CONF.base))
part['labels'].append("Change %")
part['labels'].append("Balance {}".format(CONF.quote))
part['labels'].append("Change %")
m_bal = "Balance {}: {:>{}.4f}".format(CONF.base, today['mBal'], 25-len(CONF.base))
change = NA
if 'mBalChan24' in today:
change = "{:+.2f}%".format(today['mBalChan24'])
m_bal += " (" + change + ")*"
change = "{:+.2f}".format(today['mBalChan24'])
part['mail'].append(m_bal)
part['csv'].append("{:.4f};{}".format(today['mBal'], change))
fm_bal = "Balance {}: {:>{}}".format(CONF.quote, round(today['fmBal']), 25-len(CONF.quote))
change = NA
if 'fmBalChan24' in today:
change = "{:+.2f}%".format(today['fmBalChan24'])
fm_bal += " (" + change + ")*"
change = "{:+.2f}".format(today['fmBalChan24'])
part['mail'].append(fm_bal)
part['csv'].append("{};{}".format(round(today['fmBal']), change))
def append_value_change(part: dict, today: dict, yesterday: dict, price: float):
part['labels'].append("Value Change %")
change = NA
if CONF.exchange == 'bitmex':
if 'mBalChan24' in today and 'priceChan24' in today:
margin_change = today['mBalChan24']
price_change = today['priceChan24']
margin_leverage = get_margin_leverage()
if margin_leverage:
margin_leverage = round(margin_leverage * 100)
change = "{:+.4f}".format(margin_change - price_change * margin_leverage / 100)
elif yesterday and 'mBal' in today and 'fmBal' in today:
yesterday_total_in_fiat = yesterday['mBal'] * yesterday['price'] + yesterday['fmBal']
today_total_in_fiat = today['mBal'] * price + today['fmBal']
change = "{:+.2f}".format(
(today_total_in_fiat / yesterday_total_in_fiat - 1) * 100) if yesterday_total_in_fiat > 0 else NA
if change != NA:
part['mail'].append("Value change: {:>21}%*".format(change))
else:
part['mail'].append("Value change: {:>21}*".format(change))
part['csv'].append("{}".format(change))
def append_trading_result(part: dict, today: dict, yesterday: dict, price: float):
part['labels'].append("Trading Result {}".format(CONF.quote))
trading_result = NA
if yesterday and 'mBal' in today and 'fmBal' in today:
trading_result = (today['mBal'] - yesterday['mBal']) * price + today['fmBal'] - yesterday['fmBal']
trading_result = "{:+}".format(round(trading_result))
part['mail'].append("Trading result in {}: {:>{}}*".format(CONF.quote, trading_result, 15-len(CONF.quote)))
part['csv'].append("{}".format(trading_result))
def append_price_change(part: dict, today: dict, price: float):
"""
Appends price changes
"""
part['labels'].append("{} Price {}".format(CONF.base, CONF.quote))
part['labels'].append("Change %")
padding = 26-len(CONF.base)-len(CONF.quote)
rate = "{} price {}: {:>{}}".format(CONF.base, CONF.quote, round(price), padding)
change = NA
if 'priceChan24' in today:
change = "{:+.2f}%".format(today['priceChan24'])
rate += " (" + change + ")*"
change = "{:+.2f}".format(today['priceChan24'])
part['mail'].append(rate)
part['csv'].append("{};{}".format(round(price), change))
def append_actual_quote(part: dict, price: float = None):
"""
:param part: dict { 'labels': [], 'mail': [], 'csv': [] }
:param price: optional, but required for bitmex
"""
part['labels'].append("Actual Quote %")
actual_quote = calculate_actual_quote(price)
if actual_quote >= CONF.max_crypto_quote_in_percent * 0.98:
part['mail'].append("Actual quote: {:>21n}% (Max.)".format(round(actual_quote)))
else:
part['mail'].append("Actual quote: {:>21n}%".format(round(actual_quote)))
part['csv'].append("{:n}".format(round(actual_quote)))
def append_margin_leverage(part: dict):
part['labels'].append("Leverage %")
margin_leverage = get_margin_leverage()
if margin_leverage:
margin_leverage = round(margin_leverage * 100)
if margin_leverage >= CONF.max_leverage_in_percent * 0.98:
part['mail'].append("Margin leverage: {:>18n}% (Max.)".format(margin_leverage))
else:
part['mail'].append("Margin leverage: {:>18n}%".format(margin_leverage))
part['csv'].append("{:n}".format(margin_leverage))
else:
part['mail'].append("Margin leverage: {:>18}".format("% n/a"))
part['csv'].append(NA)
def calculate_daily_statistics(m_bal: float, fm_bal: float, price: float, stats: Stats, update_stats: bool):
"""
Calculates, updates and persists the change in the margin balance compared with yesterday
:param m_bal: today's margin balance
:param fm_bal: today's fiat margin balance
:param price: the current rate
:param stats: the loaded stats
:param update_stats: update and persists the statistic values
:return: today's statistics including price and margin balance changes compared with 24 hours ago
"""
today = {'mBal': m_bal, 'fmBal': fm_bal, 'price': price}
if stats is None:
stats = Stats()
if update_stats and datetime.datetime.utcnow().time() > datetime.datetime(2012, 1, 17, 12, 1).time() and not \
stats.get_day(int(datetime.date.today().strftime("%Y%j"))):
stats.add_day(int(datetime.date.today().strftime("%Y%j")), today)
persist_statistics(stats)
before_24h = stats.get_day(int(datetime.date.today().strftime("%Y%j")) - 1)
if before_24h:
if 'mBal' in before_24h and before_24h['mBal'] and before_24h['mBal'] > 0:
today['mBalChan24'] = round((today['mBal'] / before_24h['mBal'] - 1) * 100, 2)
if 'fmBal' in before_24h and before_24h['fmBal'] and before_24h['fmBal'] > 0:
today['fmBalChan24'] = round((today['fmBal'] / before_24h['fmBal'] - 1) * 100, 2)
if 'price' in before_24h:
today['priceChan24'] = round((today['price'] / before_24h['price'] - 1) * 100, 2)
return today
def load_statistics():
stats_file = f'{DATA_DIR}{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: Stats):
stats_file = f'{DATA_DIR}{INSTANCE}.pkl'
with open(stats_file, "wb") as file:
pickle.dump(stats, file)
def update_csv(content: dict, filename_csv: str):
if not os.path.isfile(filename_csv) or (
int(datetime.date.today().strftime("%j")) == 1 and not is_already_written(filename_csv)):
write_csv_header(content['labels'], filename_csv)
write_csv(content['csv'], filename_csv)
def write_csv_header(content: str, filename_csv: str):
with open(filename_csv, 'w') as file:
file.write(content)
def write_csv(content: str, filename_csv: str):
if not is_already_written(filename_csv):
with open(filename_csv, 'a') 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 set_start_values(values: dict):
config = configparser.ConfigParser(interpolation=None, allow_no_value=True, comment_prefixes="£", strict=False)
config.read(f'{DATA_DIR}{INSTANCE}.txt')
config.set('config', 'start_crypto_price', str(values['crypto_price']))
config.set('config', 'start_margin_balance', str(values['margin_balance']))
config.set('config', 'start_mayer_multiple', str(values['mayer_multiple']))
config.set('config', 'reference_net_deposits', str(values['net_deposits']))
sv_type = 'Initial'
if 'date' in values and values['date']:
config.set('config', 'start_date', str(values['date']))
sv_type = 'Final'
LOG.info('%s start position: price: %s, margin: %s, mayer: %s, deposits: %s', sv_type, values['crypto_price'],
values['margin_balance'], values['mayer_multiple'], values['net_deposits'])
with open(f'{DATA_DIR}{INSTANCE}.txt', 'w') as config_file:
config.write(config_file)
def update_deposits(reference_deposits: float, diff: float = 0):
new_margin_balance = CONF.start_margin_balance + diff
config = configparser.ConfigParser(interpolation=None, allow_no_value=True, comment_prefixes="£", strict=False)
config.read(f'{DATA_DIR}{INSTANCE}.txt')
if diff and CONF.net_deposits_in_base_currency:
new_net_deposits_in_base_currency = CONF.net_deposits_in_base_currency + diff
config.set('config', 'net_deposits_in_base_currency', str(new_net_deposits_in_base_currency))
config.set('config', 'start_margin_balance', str(new_margin_balance))
config.set('config', 'reference_net_deposits', str(reference_deposits))
with open(f'{DATA_DIR}{INSTANCE}.txt', 'w') as config_file:
config.write(config_file)
if diff:
if CONF.net_deposits_in_base_currency:
LOG.info('Updated start margin, reference and net deposits: %s %s %s (%s)', str(new_margin_balance),
str(reference_deposits), str(new_net_deposits_in_base_currency), str(diff))
else:
LOG.info('Updated start margin and reference deposits: %s %s (%s)', str(new_margin_balance),
str(reference_deposits), str(diff))
else:
LOG.info('Initialized reference deposits: %s', str(reference_deposits))
def get_margin_balance():
"""
Fetches the margin balance (of crypto) in fiat
return: balance of crypto in fiat
"""
try:
if CONF.exchange == 'kraken':
bal = EXCHANGE.private_post_tradebalance({'asset': CONF.base})['result']
# bal['free'] = float(bal['mf'])
return float(bal['e'])
# bal['used'] = float(bal['m'])
if CONF.exchange in ['bitpanda', 'coinbase', 'coinbasepro']:
return get_crypto_balance()['total'] + get_fiat_balance()['total'] / get_current_price()
return get_crypto_balance()['total']
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)
return get_margin_balance()
def get_margin_balance_of_fiat():
"""
Fetches the margin balance (of fiat) in fiat
return: balance of fiat in fiat
"""
try:
if CONF.exchange == 'bitmex':
pos = get_position_info()
if not pos or 'markPrice' not in pos or not pos['markPrice']:
return {'total': 0}
return {'total': float(pos['homeNotional']) * float(pos['markPrice'])}
LOG.warning(NOT_IMPLEMENTED_MESSAGE, 'get_margin_balance_of_fiat()', 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)
return get_margin_balance_of_fiat()
def get_margin_leverage():
"""
Fetch the leverage
"""
try:
if CONF.exchange == 'bitmex':
return float(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
if CONF.exchange in ['bitpanda', 'coinbase']:
return 0 # Margin trading unavailable
LOG.warning(NOT_IMPLEMENTED_MESSAGE, 'get_margin_leverage()', 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)
return get_margin_leverage()
def get_net_deposits(from_exchange: bool = False):
"""
Get deposits and withdraws to calculate the net deposits in crypto.
return: net deposits
"""
if not from_exchange and 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 (int(result['deposited']) + int(result['transferIn']) - int(result['withdrawn']) - int(result['transferOut'])) * 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
if CONF.exchange in ['bitpanda', 'coinbase', 'coinbasepro']:
net_deposits = 0
net_withdrawals = 0
deposits = EXCHANGE.fetch_deposits(CONF.base)
for deposit in deposits:
net_deposits += deposit['amount']
withdrawals = EXCHANGE.fetch_withdrawals(CONF.base)
for withdrawal in withdrawals:
net_withdrawals += withdrawal['amount']
if net_deposits > net_withdrawals:
return net_deposits - net_withdrawals
return 0
LOG.warning(NOT_IMPLEMENTED_MESSAGE, 'get_net_deposit()', 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)
return get_net_deposits(from_exchange)
def get_wallet_balance(price: float):
"""
Fetch the wallet balance in crypto
"""
try:
if CONF.exchange == 'bitmex':
return float(EXCHANGE.fetch_balance()['info'][0]['walletBalance']) * CONF.satoshi_factor
if CONF.exchange == 'kraken':
asset = CONF.base if CONF.base != 'BTC' else 'XBt'
return float(EXCHANGE.private_post_tradebalance({'asset': asset})['result']['tb'])
if CONF.exchange in ['bitpanda', 'coinbase']:
balance = 0
balances = EXCHANGE.fetch_balance()
if balances:
if CONF.base in balances and 'total' in balances[CONF.base]:
balance += balances[CONF.base]['total']
if CONF.quote in balances and 'total' in balances[CONF.quote]:
fiat = balances[CONF.quote]['total']
if fiat and fiat > 0:
balance += fiat / price
return balance
LOG.warning('get_net_deposit() could not retrieve bitpanda/coinbase wallet balance')
return 0
LOG.warning(NOT_IMPLEMENTED_MESSAGE, 'get_wallet_balance()', 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)
return get_wallet_balance(price)
def get_balances():
"""
Fetch the margin and wallet balance in satoshi
"""
try:
if CONF.exchange == 'bitmex':
return EXCHANGE.fetch_balance()['info'][0]
LOG.warning(NOT_IMPLEMENTED_MESSAGE, 'get_balances()', 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)
return get_balances()
def get_open_orders():
"""
Gets open orders
:return: [Order]
"""
try:
if CONF.exchange == 'paymium':
orders = EXCHANGE.private_get_user_orders({'active': True})