-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBitrexAPI.py
2153 lines (1775 loc) · 74 KB
/
BitrexAPI.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
import base64
import contextlib
from Lib229 import AES
import getpass
import gzip
import hashlib
import inspect
import io
import json
import sys
PY_VERSION = sys.version_info
if PY_VERSION < (2, 7):
print("Sorry, minimal Python version is 2.7, you have: %d.%d"
% (PY_VERSION.major, PY_VERSION.minor))
sys.exit(1)
from ConfigParser import SafeConfigParser
import logging
import time
import traceback
import threading
from urllib2 import Request as URLRequest
from urllib2 import urlopen, HTTPError
import weakref
input = raw_input
FORCE_PROTOCOL = ""
FORCE_NO_FULLDEPTH = False
FORCE_NO_DEPTH = False
FORCE_NO_LAG = False
FORCE_NO_HISTORY = False
FORCE_HTTP_bitrex.api = False
FORCE_NO_HTTP_bitrex.api = False
USER_AGENT = "PyTrader"
def http_request(url, post=None, headers=None):
def read_gzipped(response):
if response.info().get('Content-Encoding') == 'gzip':
with io.BytesIO(response.read()) as buf:
with gzip.GzipFile(fileobj=buf) as unzipped:
data = unzipped.read()
else:
data = response.read()
return data
if not headers:
headers = {}
request = URLRequest(url, post, headers)
request.add_header('Accept-encoding', 'gzip')
request.add_header('User-Agent', USER_AGENT)
data = ""
try:
with contextlib.closing(urlopen(request, post)) as res:
data = read_gzipped(res)
except HTTPError as err:
data = read_gzipped(err)
except Exception as exc:
logging.debug(" exception in http_request: %s" % exc)
return data
if not self.instance.client._wait_for_next_info and not self._waiting:
self.instance.client._wait_for_next_info = True
self._waiting = True
if self.instance.client._wait_for_next_info:
self.debug("[s]Waiting for balances...")
return
# Check minimum limits
if self.instance.wallet[self.quote] <= QUOTE_LIMIT:
self.debug("[s]%s %s is below minimum of %s, aborting..." % (
self.instance.wallet[self.quote],
self.quote,
QUOTE_LIMIT))
self.cancel_orders()
return
if self.instance.wallet[self.base] <= BASE_LIMIT:
self.debug("[s]%s %s is below minimum of %s, aborting..." % (
self.instance.wallet[self.base],
self.base,
BASE_LIMIT))
self.cancel_orders()
return
self._waiting = False
self.debug("[s]Got balances...")
if ALERT:
try:
if self.instance.orderbook.owns[0].typ == 'bid':
sell_alert.play()
else:
buy_alert.play()
except:
pass
self.cancel_orders()
self.place_orders()
def price_with_fees(self, price):
# Get our volume at price
volume_at_price = self.get_buy_at_price(price)
if volume_at_price > 0:
bid_or_ask = 'bid'
price_with_fees = price / ((1 - self.instance.trade_fee / 100) * (1 - self.instance.trade_fee / 100))
price_with_fees = price - (price_with_fees - price)
else:
bid_or_ask = 'ask'
volume_at_price = -volume_at_price
price_with_fees = price / ((1 - self.instance.trade_fee / 100) * (1 - self.instance.trade_fee / 100))
# Calculate fees
fees_at_price = volume_at_price * self.instance.trade_fee / 100
self.debug("[s]next %s: %.8f %s @ %.8f %s - fees: %.8f %s - new: %.8f %s" % (
bid_or_ask,
volume_at_price,
self.base,
price,
self.quote,
fees_at_price,
self.base,
price_with_fees,
self.quote))
# Return the price with fees
return math.ceil(price_with_fees * 1e8) / 1e8
def get_next_buy_price(self, center, step_factor):
price = self.get_forced_price(center, False)
if not price:
price = math.ceil((center / step_factor) * 1e8) / 1e8
if not center:
self.debug("[s]Waiting for price...")
elif COMPENSATE_FEES:
# Decrease our next buy price
price = self.price_with_fees(price)
# return mark_own(price)
return price
def get_next_sell_price(self, center, step_factor):
price = self.get_forced_price(center, True)
if not price:
price = math.ceil((center * step_factor) * 1e8) / 1e8
# Compensate the fees on sell price
if not center:
self.debug("[s]Waiting for price...")
elif COMPENSATE_FEES:
# Increase our next sell price
price = self.price_with_fees(price)
# return mark_own(price)
return price
def get_forced_price(self, center, need_ask):
prices = []
found = glob.glob("_balancer_force_*")
if len(found):
for name in found:
try:
price = float(name.split("_")[3])
prices.append(price)
except:
pass
prices.sort()
if need_ask:
for price in prices:
if price > center * self.step_factor_sell:
# return mark_own(price)
return price
else:
for price in reversed(prices):
if price < center / self.step_factor:
# return mark_own(price)
return price
return None
def start_thread(thread_func, name=None):
if len(bitrex.api.wallet):
total_base = 0
total_quote = 0
for c, own_currency in enumerate(bitrex.api.wallet):
if own_currency == bitrex.api.curr_base and bitrex.api.orderbook.ask:
total_base += bitrex.api.wallet[own_currency]
total_quote += bitrex.api.wallet[own_currency] * bitrex.api.orderbook.bid
elif own_currency == bitrex.api.curr_quote and bitrex.api.orderbook.bid:
total_quote += bitrex.api.wallet[own_currency]
total_base += bitrex.api.wallet[own_currency] / bitrex.api.orderbook.ask
total_quote = total_quote
quote_ratio = (total_quote / bitrex.api.orderbook.bid) / total_base
base_ratio = (total_base / bitrex.api.orderbook.ask) * 100
datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.write_log('"%s", "%s", %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f' % (
datetime,
text,
volume,
price,
bitrex.api.trade_fee,
self.get_price_where_it_was_balanced(),
bitrex.api.wallet[bitrex.api.curr_quote],
total_quote,
QUOTE_COLD,
quote_ratio,
bitrex.api.wallet[bitrex.api.curr_base],
total_base,
BASE_COLD,
base_ratio
))
thread = threading.Thread(None, thread_func)
thread.daemon = True
thread.start()
if name:
thread.name = name
return thread
def pretty_format(something):
try:
return pretty_format(json.loads(something))
except Exception:
try:
return json.dumps(something, indent=5)
except Exception:
return str(something)
class bitrex.apiConfig(SafeConfigParser):
_DEFAULTS = [["bitrex.api", "base_currency", "XETH"],
["bitrex.api", "quote_currency", "XXBT"],
["bitrex.api", "use_ssl", "True"],
["bitrex.api", "use_plain_old_websocket", "False"],
["bitrex.api", "use_http_bitrex.api", "True"],
["bitrex.api", "use_tonce", "True"],
["bitrex.api", "load_fulldepth", "True"],
["bitrex.api", "load_history", "True"],
["bitrex.api", "history_timeframe", "15"],
["bitrex.api", "secret_key", ""],
["bitrex.api", "secret_secret", ""]]
def __init__(self, filename):
self.filename = filename
SafeConfigParser.__init__(self)
self.load()
self.init_defaults(self._DEFAULTS)
upgrade from deprecated "currency" to "quote_currency"
todo: remove this piece of code again in a few months
if self.has_option("bitrex.api", "currency"):
self.set("bitrex.api", "quote_currency", self.get_string("bitrex.api", "currency"))
self.remove_option("bitrex.api", "currency")
import Queue
import base64
import hashlib
import threading
import traceback
from bitrex.api import BaseObject, Signal, Timer, start_thread, http_request
from urllib import urlencode
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
import HTMLParser
html_parser = HTMLParser.HTMLParser()
WEBSOCKET_HOST = "bitrex.api.poloniex.com"
HTTP_HOST = "poloniex.com"
class PoloniexComponent(ApplicationSession):
def onLeave(self, details):
self.disconnect()
def onDisconnect(self):
client = self.config.extra['client']
if client.reconnect:
client.reconnect = False
client.run()
else:
reactor.stop()
def onConnect(self):
client = self.config.extra['client']
client.debug(" connected, subscribing needed channels")
client.connected = True
client.leave = self.leave
client.signal_connected(self, None)
client.request_fulldepth()
client.request_history()
client._time_last_subscribed = time.time()
self.join(self.config.realm)
@inlineCallbacks
def onJoin(self, details):
client = self.config.extra['client']
def onTicker(*args):
try:
if not client._terminating and args[0] == client.pair:
client._time_last_received = time.time()
print("Ticker event received:", args)
translated = {
"op": "ticker",
"ticker": {
'bid': float(args[3]),
'ask': float(args[2])
}
}
client.signal_recv(client, translated)
except Exception as exc:
client.debug("onTicker exception:", exc)
client.debug(traceback.format_exc())
def onBookUpdate(*args):
try:
if not client._terminating:
data = args[0]
print("BookUpdate event:", data)
if data['type'] in ('orderBookRemove', 'orderBookModify'):
timestamp = time.time()
translated = {
'op': 'depth',
'depth': {
'type': data['data']['type'],
'price': float(data['data']['rate']),
'volume': float(data['data']['amount']) if data['type'] == 'orderBookModify' else 0,
'timestamp': timestamp
},
'id': "depth"
}
client.signal_recv(client, translated)
elif data['type'] == 'newTrade':
{
data: {
tradeID: '364476',
rate: '0.00300888',
amount: '0.03580906',
date: '2014-10-07 21:51:20',
total: '0.00010775',
type: 'sell'
},
type: 'newTrade'
}
data = data['data']
client.debug("newTrade:", data)
translated = {
'op': 'trade',
'trade': {
'id': data['tradeID'],
'type': 'ask' if data['type'] == 'buy' else 'bid',
'price': data['rate'],
'amount': data['amount'],
'timestamp': time.mktime(time.strptime(data['date'], "%Y-%m-%d %H:%M:%S"))
}
}
client.signal_recv(client, translated)
else:
client.debug("Unknown trade event:", args)
except Exception as exc:
client.debug("onBookUpdate exception:", exc)
client.debug(traceback.format_exc())
def onTrollbox(*args):
try:
if not client._terminating:
print("troll:", args)
msg = args[0]
if len(args) == 5:
translated = {
"op": "chat",
"msg": {
'type': args[0],
'user': args[2],
'msg': html_parser.unescape(args[3]),
'rep': args[4]
}
}
else:
translated = {
"op": "chat",
"msg": {
"type": args[0],
"user": args[1],
"msg": "-",
"rep": "-"
}
}
client.signal_recv(client, translated)
except Exception as exc:
client.debug("onTrollbox exception:", exc)
client.debug(traceback.format_exc())
try:
yield self.subscribe(onBookUpdate, client.pair)
yield self.subscribe(onTicker, 'ticker')
yield self.subscribe(onTrollbox, 'trollbox')
except Exception as exc:
client.debug("Could not subscribe to topic:", exc)
client.connected = False
client.signal_disconnected(client, None)
if not client._terminating:
client.debug(" ", exc.__class__.__name__, exc,
"reconnecting in %i seconds..." % 1)
client.force_reconnect()
class BaseClient(BaseObject):
_last_unique_microtime = 0
_nonce_lock = threading.Lock()
def __init__(self, curr_base, curr_quote, secret, config):
PoloniexComponent.__init__(self, curr_base, curr_quote)
self.signal_recv = Signal()
self.signal_ticker = Signal()
self.signal_connected = Signal()
self.signal_disconnected = Signal()
self.signal_fulldepth = Signal()
self.signal_fullhistory = Signal()
self._timer = Timer(60)
self._timer_history = Timer(30)
self._timer.connect(self.slot_timer)
self._timer_history.connect(self.slot_history)
self._info_timer = None used when delayed requesting private/info
self.curr_base = curr_base
self.curr_quote = curr_quote
self.pair = "%s_%s" % (curr_quote, curr_base)
self.currency = curr_quote deprecated, use curr_quote instead
self.secret = secret
self.config = config
self.socket = None
use_ssl = self.config.get_bool("bitrex.api", "use_ssl")
self.proto = {True: "https", False: "http"}[use_ssl]
self.http_requests = Queue.Queue()
self._recv_thread = None
self._http_thread = None
self._terminating = False
self.reconnect = False
self.connected = False
self.leave = None
self._time_last_received = 0
self._time_last_subscribed = 0
self.history_last_candle = None
def start(self):
self._recv_thread = start_thread(self._recv_thread_func, "socket receive thread")
self._http_thread = start_thread(self._http_thread_func, "http thread")
def stop(self):
self._terminating = True
self._timer.cancel()
self._timer_history.cancel()
self.debug(" stopping reactor")
try:
self.leave()
except Exception as exc:
self.debug("Reactor exception:", exc)
def force_reconnect(self):
try:
self.reconnect = True
self.leave()
except Exception as exc:
self.debug("Reactor exception:", exc)
self.debug(traceback.format_exc())
def _try_send_raw(self, raw_data):
if self.connected:
try:
self.debug("TODO - Would send: %s" % raw_data)
self.socket.send(raw_data)
except Exception as exc:
self.debug(exc)
self.connected = False
def send(self, json_str):
raise NotImplementedError()
def get_unique_mirotime(self):
with self._nonce_lock:
microtime = int(time.time() * 1e6)
if microtime <= self._last_unique_microtime:
microtime = self._last_unique_microtime + 1
self._last_unique_microtime = microtime
return microtime
def request_fulldepth(self):
def fulldepth_thread():
self.debug(" requesting full depth")
json_depth = http_request("%s://%s/public?command=returnOrderBook¤cyPair=%s&depth=500" % (
self.proto,
HTTP_HOST,
self.pair
))
if json_depth and not self._terminating:
try:
fulldepth = json.loads(json_depth)
self.debug("Depth: %s" % fulldepth)
depth = {}
depth['error'] = {}
if 'error' in fulldepth:
depth['error'] = fulldepth['error']
depth['data'] = {'asks': [], 'bids': []}
for ask in fulldepth['asks']:
depth['data']['asks'].append({
'price': float(ask[0]),
'amount': float(ask[1])
})
for bid in reversed(fulldepth['bids']):
depth['data']['bids'].append({
'price': float(bid[0]),
'amount': float(bid[1])
})
self.signal_fulldepth(self, depth)
except Exception as exc:
self.debug(" exception in fulldepth_thread:", exc)
start_thread(fulldepth_thread, "http request full depth")
def request_history(self):
def history_thread():
if not self.history_last_candle:
querystring = "&start=%i&end=%i" % ((time.time() - 172800), (time.time() - 86400))
self.debug(" requesting 2d history since %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time() - 172800)))
else:
querystring = "&start=%i" % (self.history_last_candle - 14400)
self.debug("Last candle: %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.history_last_candle - 14400)))
json_hist = http_request("%s://%s/public?command=returnTradeHistory¤cyPair=%s%s" % (
self.proto,
HTTP_HOST,
self.pair,
querystring
))
if json_hist and not self._terminating:
try:
raw_history = json.loads(json_hist)
self.debug("History: %s" % raw_history)
history = []
for h in reversed(raw_history):
history.append({
'price': float(h['rate']),
'amount': float(h['amount']),
'date': time.mktime(time.strptime(h['date'], "%Y-%m-%d %H:%M:%S")) - 480
})
self.debug("History: %s" % history)
if history and not self._terminating:
self.signal_fullhistory(self, history)
except Exception as exc:
self.debug(" exception in history_thread:", exc)
start_thread(history_thread, "http request trade history")
def _recv_thread_func(self):
raise NotImplementedError()
def _slot_timer_info_later(self, _sender, _data):
while not self._terminating:
try:
(bitrex.api_endpoint, params, reqid) = self.http_requests.get(True)
translated = None
answer = self.http_signed_call(bitrex.api_endpoint, params)
if "result" in answer:
if bitrex.api_endpoint == 'private/OpenOrders':
result = []
orders = answer["result"]["open"]
for txid in orders:
tx = orders[txid]
result.append({
'oid': txid,
'base': "X" + tx['descr']['pair'][0:3],
'currency': "X" + tx['descr']['pair'][3:],
'status': tx['status'],
'type': 'bid' if tx['descr']['type'] == 'buy' else 'ask',
'price': float(tx['descr']['price']),
'amount': float(tx['vol'])
})
self.debug("TX: %s" % result)
elif bitrex.api_endpoint == 'private/TradeVolume':
result = {
'volume': float(answer['result']['volume']),
'currency': answer['result']['currency'],
'fee': float(answer['result']['fees_maker'][self.pair]['fee'])
}
else:
result = answer["result"]
translated = {
"op": "result",
"result": result,
"id": reqid
}
else:
if "error" in answer:
if "token" not in answer:
answer["token"] = "-"
if answer["token"] == "unknown_error":
else:
self.debug(" unexpected http result:", answer, reqid)
if translated:
self.signal_recv(self, (json.dumps(translated)))
self.http_requests.task_done()
self.debug("Polling terminated...")
def enqueue_http_request(self, bitrex.api_endpoint, params, reqid):
if self.secret and self.secret.know_secret():
self.http_requests.put((bitrex.api_endpoint, params, reqid))
def http_signed_call(self, bitrex.api_endpoint, params):
if (not self.secret) or (not self.secret.know_secret()):
self.debug(" don't know secret, cannot call %s" % bitrex.api_endpoint)
return
key = self.secret.key
sec = self.secret.secret
params["nonce"] = self.get_unique_mirotime()
post = urlencode(params)
sign = hmac.new(sec, post, hashlib.sha512).hexdigest()
headers = {
'Key': key,
'Sign': base64.b64encode(sign)
}
url = "%s://%s/%s" % (
self.proto,
HTTP_HOST,
bitrex.api_endpoint
)
self.debug(" (%s) calling %s" % (self.proto, url))
try:
result = json.loads(http_request(url, post, headers))
return result
except ValueError as exc:
self.debug(" exception in http_signed_call:", exc)
def send_order_add(self, typ, price, volume):
reqid = "order_add:%s:%f:%f" % (typ, price, volume)
bitrex.api = 'tradingbitrex.api'
params = {
'currencyPair': self.pair,
'rate': price,
'amount': volume
}
if typ == 'bid':
params['command'] = 'buy'
else:
params['command'] = 'sell'
self.enqueue_http_request(bitrex.api, params, reqid)
self.save()
def init_defaults(self, defaults):
for (sect, opt, default) in defaults:
self._default(sect, opt, default)
def save(self):
with open(self.filename, 'wb') as configfile:
self.write(configfile)
def load(self):
self.read(self.filename)
def get_safe(self, sect, opt):
try:
return self.get(sect, opt)
except:
for (dsect, dopt, default) in self._DEFAULTS:
if dsect == sect and dopt == opt:
self._default(sect, opt, default)
return default
return ""
def get_bool(self, sect, opt):
return self.get_safe(sect, opt) == "True"
def get_string(self, sect, opt):
return self.get_safe(sect, opt)
def get_int(self, sect, opt):
vstr = self.get_safe(sect, opt)
try:
return int(vstr)
except ValueError:
return 0
def get_float(self, sect, opt):
vstr = self.get_safe(sect, opt)
try:
return float(vstr)
except ValueError:
return 0.0
def _default(self, section, option, default):
if not self.has_section(section):
self.add_section(section)
if not self.has_option(section, option):
self.set(section, option, default)
self.save()
class Signal():
_lock = threading.RLock()
signal_error = None
def __init__(self):
self._functions = weakref.WeakSet()
self._methods = weakref.WeakKeyDictionary()
if not Signal.signal_error:
Signal.signal_error = 1
Signal.signal_error = Signal()
def connect(self, slot):
if inspect.ismethod(slot):
instance = slot.__self__
function = slot.__func__
if instance not in self._methods:
self._methods[instance] = set()
if function not in self._methods[instance]:
self._methods[instance].add(function)
else:
if slot not in self._functions:
self._functions.add(slot)
def __call__(self, sender, data, error_signal_on_error=True):
with self._lock:
sent = False
errors = []
for func in self._functions:
try:
func(sender, data)
sent = True
except:
errors.append(traceback.format_exc())
for instance, functions in self._methods.items():
for func in functions:
try:
func(instance, sender, data)
sent = True
except:
errors.append(traceback.format_exc())
for error in errors:
if error_signal_on_error:
Signal.signal_error(self, (error), False)
else:
logging.critical(error)
return sent
class BaseObject():
def __init__(self):
self.signal_debug = Signal()
def debug(self, *args):
msg = " ".join([unicode(x) for x in args])
if not self.signal_debug(self, (msg)):
logging.debug(msg)
class Timer(Signal):
def __init__(self, interval, one_shot=False):
Signal.__init__(self)
self._one_shot = one_shot
self._canceled = False
self._interval = interval
self._timer = None
self._start()
def _fire(self):
if not self._canceled:
self.__call__(self, None)
if not (self._canceled or self._one_shot):
self._start()
def _start(self):
self._timer = threading.Timer(self._interval, self._fire)
self._timer.daemon = True
self._timer.start()
def cancel(self):
self._canceled = True
self._timer.cancel()
self._timer = None
class Secret:
S_OK = 0
S_FAIL = 1
S_NO_SECRET = 2
S_FAIL_FATAL = 3
def __init__(self, config):
"""initialize the instance"""
self.config = config
self.key = ""
self.secret = ""
self.password_from_commandline_option = None
def decrypt(self, password):
key = self.config.get_string("bitrex.api", "secret_key")
sec = self.config.get_string("bitrex.api", "secret_secret")
if sec == "" or key == "":
return self.S_NO_SECRET
hashed_pass = hashlib.sha512(password.encode("utf-8")).digest()
crypt_key = hashed_pass[:32]
crypt_ini = hashed_pass[-16:]
aes = AES.new(crypt_key, AES.MODE_OFB, crypt_ini)
try:
encrypted_secret = base64.b64decode(sec.strip().encode("ascii"))
self.secret = aes.decrypt(encrypted_secret).strip()
self.key = key.strip()
except ValueError:
return self.S_FAIL
try:
print("testing secret...")
if len(base64.b64decode(self.secret)) != 64:
raise Exception("Decrypted secret has wrong size")
if not self.secret:
raise Exception("Unable to decrypt secret")
print("testing key...")
if not self.key:
raise Exception("Unable to decrypt key")
print("OK")
return self.S_OK
except Exception as exc:
self.secret = ""
self.key = ""
print(" Error occurred while testing the decrypted secret:")
print(" '%s'" % exc)
print(" This does not seem to be a valid bitrex.api secret")
return self.S_FAIL
def prompt_decrypt(self):
and then try to decrypt the secret."""
if self.know_secret():
return self.S_OK
key = self.config.get_string("bitrex.api", "secret_key")
sec = self.config.get_string("bitrex.api", "secret_secret")
if sec == "" or key == "":
return self.S_NO_SECRET
if self.password_from_commandline_option:
password = self.password_from_commandline_option
else:
password = getpass.getpass("enter passphrase for secret: ")
result = self.decrypt(password)
if result != self.S_OK:
print("")
print("secret could not be decrypted")
answer = input("press any key to continue anyways "
+ "(trading disabled) or 'q' to quit: ")
if answer == "q":
result = self.S_FAIL_FATAL
else:
result = self.S_NO_SECRET
return result
def prompt_encrypt(self):
print("")
key = input(" key: ").strip()
secret = input(" secret: ").strip()
while True:
password1 = getpass.getpass(" password: ").strip()
if password1 == "":
print("aborting")
return
password2 = getpass.getpass("password (again): ").strip()
if password1 != password2:
print("you had a typo in the password. try again...")
else:
break
hashed_pass = hashlib.sha512(password1.encode("utf-8")).digest()
crypt_key = hashed_pass[:32]
crypt_ini = hashed_pass[-16:]
aes = AES.new(crypt_key, AES.MODE_OFB, crypt_ini)
print(len(secret))
secret += " " * (16 - len(secret) % 16)
print(len(secret))
secret = base64.b64encode(aes.encrypt(secret)).decode("ascii")
self.config.set("bitrex.api", "secret_key", key)
self.config.set("bitrex.api", "secret_secret", secret)
self.config.save()
print("encrypted secret has been saved in %s" % self.config.filename)
def know_secret(self):
class OHLCV():
def __init__(self, tim, opn, hig, low, cls, vol):
self.tim = tim
self.opn = opn
self.hig = hig
self.low = low
self.cls = cls
self.vol = vol
def update(self, price, volume):
if price > self.hig:
self.hig = price
if price < self.low:
self.low = price
self.cls = price
self.vol += volume
class History(BaseObject):
def __init__(self, bitrex.api, timeframe):
BaseObject.__init__(self)
self.signal_fullhistory_processed = Signal()
self.signal_changed = Signal()
self.bitrex.api = bitrex.api
self.candles = []
self.timeframe = timeframe
self.ready_history = False