-
Notifications
You must be signed in to change notification settings - Fork 40
/
api.py
1772 lines (1511 loc) · 68.3 KB
/
api.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
# -*- coding: utf-8 -*-
"""API handler"""
# Copyright (c) 2013 Bernd Kreuss <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
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 base64
import contextlib
from Crypto.Cipher import AES
import getpass
import gzip
import hashlib
import inspect
import io
import json
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_API = False
FORCE_NO_HTTP_API = False
USER_AGENT = "PyTrader"
def http_request(url, post=None, headers=None):
"""request data from the HTTP API, returns the response a string. If a
http error occurs it will *not* raise an exception, instead it will
return the content of the error document. This is because we get
sent 5xx http status codes even if application level errors occur
(such as canceling the same order twice or things like that) and the
real error message will be in the json that is returned, so the return
document is always much more interesting than the http status code."""
def read_gzipped(response):
"""read data from the response object,
unzip if necessary, return text string"""
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
def start_thread(thread_func, name=None):
"""start a new thread to execute the supplied function"""
thread = threading.Thread(None, thread_func)
thread.daemon = True
thread.start()
if name:
thread.name = name
return thread
def pretty_format(something):
"""pretty-format a nested dict or list for debugging purposes.
If it happens to be a valid json string then it will be parsed first"""
try:
return pretty_format(json.loads(something))
except Exception:
try:
return json.dumps(something, indent=5)
except Exception:
return str(something)
class ApiConfig(SafeConfigParser):
"""return a config parser object with default values. If you need to run
more Api() objects at the same time you will also need to give each of them
them a separate ApiConfig() object. For this reason it takes a filename
in its constructor for the ini file, you can have separate configurations
for separate Api() instances"""
_DEFAULTS = [["api", "base_currency", "XETH"],
["api", "quote_currency", "XXBT"],
["api", "use_ssl", "True"],
["api", "use_plain_old_websocket", "False"],
["api", "use_http_api", "True"],
["api", "use_tonce", "True"],
["api", "load_fulldepth", "True"],
["api", "load_history", "True"],
["api", "history_timeframe", "15"],
["api", "secret_key", ""],
["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("api", "currency"):
self.set("api", "quote_currency", self.get_string("api", "currency"))
self.remove_option("api", "currency")
self.save()
def init_defaults(self, defaults):
"""add the missing default values, default is a list of defaults"""
for (sect, opt, default) in defaults:
self._default(sect, opt, default)
def save(self):
"""save the config to the .ini file"""
with open(self.filename, 'wb') as configfile:
self.write(configfile)
def load(self):
"""(re)load the onfig from the .ini file"""
self.read(self.filename)
def get_safe(self, sect, opt):
"""get value without throwing exception."""
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):
"""get boolean value from config"""
return self.get_safe(sect, opt) == "True"
def get_string(self, sect, opt):
"""get string value from config"""
return self.get_safe(sect, opt)
def get_int(self, sect, opt):
"""get int value from config"""
vstr = self.get_safe(sect, opt)
try:
return int(vstr)
except ValueError:
return 0
def get_float(self, sect, opt):
"""get int value from config"""
vstr = self.get_safe(sect, opt)
try:
return float(vstr)
except ValueError:
return 0.0
def _default(self, section, option, default):
"""create a default option if it does not yet exist"""
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():
"""callback functions (so called slots) can be connected to a signal and
will be called when the signal is called (Signal implements __call__).
The slots receive two arguments: the sender of the signal and a custom
data object. Two different threads won't be allowed to send signals at the
same time application-wide, concurrent threads will have to wait until
the lock is releaesed again. The lock allows recursive reentry of the same
thread to avoid deadlocks when a slot wants to send a signal itself."""
_lock = threading.RLock()
signal_error = None
def __init__(self):
self._functions = weakref.WeakSet()
self._methods = weakref.WeakKeyDictionary()
# the Signal class itself has a static member signal_error where it
# will send tracebacks of exceptions that might happen. Here we
# initialize it if it does not exist already
if not Signal.signal_error:
Signal.signal_error = 1
Signal.signal_error = Signal()
def connect(self, slot):
"""connect a slot to this signal. The parameter slot can be a funtion
that takes exactly 2 arguments or a method that takes self plus 2 more
arguments, or it can even be even another signal. the first argument
is a reference to the sender of the signal and the second argument is
the payload. The payload can be anything, it totally depends on the
sender and type of the signal."""
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):
"""dispatch signal to all connected slots. This is a synchronuos
operation, It will not return before all slots have been called.
Also only exactly one thread is allowed to emit signals at any time,
all other threads that try to emit *any* signal anywhere in the
application at the same time will be blocked until the lock is released
again. The lock will allow recursive reentry of the seme thread, this
means a slot can itself emit other signals before it returns (or
signals can be directly connected to other signals) without problems.
If a slot raises an exception a traceback will be sent to the static
Signal.signal_error() or to logging.critical()"""
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():
"""This base class only exists because of the debug() method that is used
in many of the PyTrader objects to send debug output to the signal_debug."""
def __init__(self):
self.signal_debug = Signal()
def debug(self, *args):
"""send a string composed of all *args to all slots that
are connected to signal_debug or send it to the logger if
none are connected"""
msg = " ".join([unicode(x) for x in args])
if not self.signal_debug(self, (msg)):
logging.debug(msg)
class Timer(Signal):
"""a simple timer (used for stuff like keepalive)."""
def __init__(self, interval, one_shot=False):
"""create a new timer, interval is in seconds"""
Signal.__init__(self)
self._one_shot = one_shot
self._canceled = False
self._interval = interval
self._timer = None
self._start()
def _fire(self):
"""fire the signal and restart it"""
if not self._canceled:
self.__call__(self, None)
if not (self._canceled or self._one_shot):
self._start()
def _start(self):
"""start the timer"""
self._timer = threading.Timer(self._interval, self._fire)
self._timer.daemon = True
self._timer.start()
def cancel(self):
"""cancel the timer"""
self._canceled = True
self._timer.cancel()
self._timer = None
class Secret:
"""Manage the API secret. This class has methods to decrypt the
entries in the ini file and it also provides a method to create these
entries. The methods encrypt() and decrypt() will block and ask
questions on the command line, they are called outside the curses
environment (yes, its a quick and dirty hack but it works for now)."""
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):
"""decrypt "secret_secret" from the ini file with the given password.
This will return false if decryption did not seem to be successful.
After this menthod succeeded the application can access the secret"""
key = self.config.get_string("api", "secret_key")
sec = self.config.get_string("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
# now test if we now have something plausible
try:
print("testing secret...")
# is it plain ascii? (if not this will raise exception)
# dummy = self.secret.decode("ascii")
# can it be decoded? correct size afterwards?
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...")
# key must be only hex digits and have the right size
# hex_key = self.key.replace("-", "").encode("ascii")
# if len(binascii.unhexlify(hex_key)) != 16:
# raise Exception("key has wrong size")
if not self.key:
raise Exception("Unable to decrypt key")
print("OK")
return self.S_OK
except Exception as exc:
# this key and secret do not work
self.secret = ""
self.key = ""
print("### Error occurred while testing the decrypted secret:")
print(" '%s'" % exc)
print(" This does not seem to be a valid API secret")
return self.S_FAIL
def prompt_decrypt(self):
"""ask the user for password on the command line
and then try to decrypt the secret."""
if self.know_secret():
return self.S_OK
key = self.config.get_string("api", "secret_key")
sec = self.config.get_string("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):
"""ask for key, secret and password on the command line,
then encrypt the secret and store it in the ini file."""
print("Please copy/paste key and secret from exchange and")
print("then provide a password to encrypt them.")
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)
# since the secret is a base64 string we can just just pad it with
# spaces which can easily be stripped again after decryping
print(len(secret))
secret += " " * (16 - len(secret) % 16)
print(len(secret))
secret = base64.b64encode(aes.encrypt(secret)).decode("ascii")
self.config.set("api", "secret_key", key)
self.config.set("api", "secret_secret", secret)
self.config.save()
print("encrypted secret has been saved in %s" % self.config.filename)
def know_secret(self):
"""do we know the secret key? The application must be able to work
without secret and then just don't do any account related stuff"""
return(self.secret != "") and (self.key != "")
class OHLCV():
"""represents a chart candle. tim is POSIX timestamp of open time,
prices and volume are integers like in the other parts of the API"""
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):
"""update high, low and close values and add to volume"""
if price > self.hig:
self.hig = price
if price < self.low:
self.low = price
self.cls = price
self.vol += volume
class History(BaseObject):
"""represents the trading history"""
def __init__(self, api, timeframe):
BaseObject.__init__(self)
self.signal_fullhistory_processed = Signal()
self.signal_changed = Signal()
self.api = api
self.candles = []
self.timeframe = timeframe
self.ready_history = False
api.signal_trade.connect(self.slot_trade)
api.signal_fullhistory.connect(self.slot_fullhistory)
def add_candle(self, candle):
"""add a new candle to the history"""
self._add_candle(candle)
self.signal_changed(self, (self.length()))
def slot_trade(self, dummy_sender, data):
"""slot for api.signal_trade"""
(date, price, volume, dummy_typ, own) = data
if not own:
time_round = int(date / self.timeframe) * self.timeframe
candle = self.last_candle()
if candle:
if candle.tim == time_round:
candle.update(price, volume)
self.signal_changed(self, (1))
else:
self.debug("### opening new candle")
self.add_candle(OHLCV(
time_round, price, price, price, price, volume))
else:
self.add_candle(OHLCV(
time_round, price, price, price, price, volume))
def _add_candle(self, candle):
"""add a new candle to the history but don't fire signal_changed"""
self.candles.insert(0, candle)
def slot_fullhistory(self, dummy_sender, data):
"""process the result of the fullhistory request"""
(history) = data
if not len(history):
self.debug("### history download was empty")
return
def get_time_round(date):
"""round timestamp to current candle timeframe"""
return int(date / self.timeframe) * self.timeframe
# remove existing recent candle(s) if any, we will create them fresh
date_begin = get_time_round(history[0]["date"])
while len(self.candles) and self.candles[0].tim >= date_begin:
self.candles.pop(0)
new_candle = OHLCV(0, 0, 0, 0, 0, 0) # this is a dummy, not actually inserted
count_added = 0
for trade in history:
date = trade["date"]
price = trade["price"]
volume = trade["amount"]
time_round = get_time_round(date)
if time_round > new_candle.tim:
if new_candle.tim > 0:
self._add_candle(new_candle)
count_added += 1
new_candle = OHLCV(time_round, price, price, price, price, volume)
new_candle.update(price, volume)
# insert current (incomplete) candle
self._add_candle(new_candle)
count_added += 1
# self.debug("### got %d updated candle(s)" % count_added)
self.ready_history = True
self.signal_fullhistory_processed(self, None)
self.signal_changed(self, (self.length()))
def last_candle(self):
"""return the last (current) candle or None if empty"""
if self.length() > 0:
return self.candles[0]
else:
return None
def length(self):
"""return the number of candles in the history"""
return len(self.candles)
class Api(BaseObject):
"""represents the API of the exchange. An Instance of this
class will connect to the streaming socket.io API, receive live
events, it will emit signals you can hook into for all events,
it has methods to buy and sell"""
def __init__(self, secret, config):
"""initialize the API but do not yet connect to it."""
BaseObject.__init__(self)
self.signal_depth = Signal()
self.signal_trade = Signal()
self.signal_ticker = Signal()
self.signal_fulldepth = Signal()
self.signal_fullhistory = Signal()
self.signal_wallet = Signal()
self.signal_userorder = Signal()
self.signal_orderlag = Signal()
self.signal_disconnected = Signal() # socket connection lost
self.signal_ready = Signal() # connected and fully initialized
self.signal_order_too_fast = Signal() # don't use that
self.strategies = weakref.WeakValueDictionary()
# the following are not fired by the api itself but by the
# application controlling it to pass some of its events
self.signal_keypress = Signal()
self.signal_strategy_unload = Signal()
# self._idkey = ""
self.wallet = {}
self.trade_fee = 0 # percent (float, for example 0.6 means 0.6%)
self.monthly_volume = 0 # variable currency per exchange
self.order_lag = 0 # microseconds
self.socket_lag = 0 # microseconds
self.last_tid = 0
self.count_submitted = 0 # number of submitted orders not yet acked
self.msg = {} # the incoming message that is currently processed
# the following will be set to true once the information
# has been received after connect, once all thes flags are
# true it will emit the signal_connected.
# self.ready_idkey = False
self.ready_info = False
self._was_disconnected = True
self.config = config
self.curr_base = config.get_string("api", "base_currency")
self.curr_quote = config.get_string("api", "quote_currency")
self.currency = self.curr_quote # used for monthly_volume currency
self.exchange = config.get_string("pytrader", "exchange")
# these are needed for conversion from/to intereger, float, string
self.mult_quote = 1e5
self.format_quote = "%12.5f"
self.mult_base = 1e8
self.format_base = "%16.8f"
Signal.signal_error.connect(self.signal_debug)
timeframe = 60 * config.get_int("api", "history_timeframe")
if not timeframe:
timeframe = 60 * 15
self.history = History(self, timeframe)
self.history.signal_debug.connect(self.signal_debug)
self.orderbook = OrderBook(self)
self.orderbook.signal_debug.connect(self.signal_debug)
use_websocket = self.config.get_bool("api", "use_plain_old_websocket")
if "socketio" in FORCE_PROTOCOL:
use_websocket = False
if "websocket" in FORCE_PROTOCOL:
use_websocket = True
if self.exchange == "gox": # So obsolete...
if use_websocket:
from exchanges.gox import WebsocketClient
self.client = WebsocketClient(self.curr_base, self.curr_quote, secret, config)
else:
from exchanges.gox import SocketIOClient
self.client = SocketIOClient(self.curr_base, self.curr_quote, secret, config)
elif self.exchange == "kraken":
from exchanges.kraken import PollClient
self.client = PollClient(self.curr_base, self.curr_quote, secret, config)
elif self.exchange == "poloniex":
from exchanges.poloniex import WebsocketClient
self.client = WebsocketClient(self.curr_base, self.curr_quote, secret, config)
else:
raise Exception("Unsupported exchange")
self.client.signal_debug.connect(self.signal_debug)
self.client.signal_disconnected.connect(self.slot_disconnected)
self.client.signal_connected.connect(self.slot_client_connected)
self.client.signal_recv.connect(self.slot_recv)
self.client.signal_fulldepth.connect(self.signal_fulldepth)
self.client.signal_fullhistory.connect(self.signal_fullhistory)
self.client.signal_ticker.connect(self.signal_ticker)
self.timer_poll = Timer(120)
self.timer_poll.connect(self.slot_poll)
self.history.signal_changed.connect(self.slot_history_changed)
self.history.signal_fullhistory_processed.connect(self.slot_fullhistory_processed)
self.orderbook.signal_fulldepth_processed.connect(self.slot_fulldepth_processed)
self.orderbook.signal_owns_initialized.connect(self.slot_owns_initialized)
def start(self):
"""connect to API and start receiving events."""
self.debug("### Starting API, trading %s%s" % (self.curr_base, self.curr_quote))
self.client.start()
def stop(self):
"""shutdown the client"""
self.debug("### shutdown...")
self.client.stop()
def order(self, typ, price, volume):
"""place pending order. If price=0 then it will be filled at market"""
self.count_submitted += 1
self.client.send_order_add(typ, price, volume)
def buy(self, price, volume):
"""new buy order, if price=0 then buy at market"""
self.order("bid", price, volume)
def sell(self, price, volume):
"""new sell order, if price=0 then sell at market"""
self.order("ask", price, volume)
def cancel(self, oid):
"""cancel order"""
self.client.send_order_cancel(oid)
def cancel_by_price(self, price):
"""cancel all orders at price"""
for i in reversed(range(len(self.orderbook.owns))):
order = self.orderbook.owns[i]
if order.price == price:
if order.oid != "":
self.cancel(order.oid)
def cancel_by_type(self, typ=None):
"""cancel all orders of type (or all orders if typ=None)"""
for i in reversed(range(len(self.orderbook.owns))):
order = self.orderbook.owns[i]
if typ is None or typ == order.typ:
if order.oid != "":
self.cancel(order.oid)
def base2float(self, int_number):
"""convert base currency values from integer to float. Base
currency are the coins you are trading (BTC, LTC, etc). Use this method
to convert order volumes (amount of coins) from int to float."""
return float(int_number) / self.mult_base
def base2str(self, int_number):
"""convert base currency values from integer to formatted string"""
return self.format_base % (float(int_number) / self.mult_base)
def base2int(self, float_number):
"""convert base currency values from float to integer"""
return int(round(float_number * self.mult_base))
def quote2float(self, int_number):
"""convert quote currency values from integer to float. Quote
currency is the currency used to quote prices (USD, EUR, etc), use this
method to convert the prices of orders, bid or ask from int to float."""
return float(int_number) / self.mult_quote
def quote2str(self, int_number):
"""convert quote currency values from integer to formatted string"""
return self.format_quote % (float(int_number) / self.mult_quote)
def quote2int(self, float_number):
"""convert quote currency values from float to integer"""
return int(round(float_number * self.mult_quote))
def check_connect_ready(self):
"""check if everything that is needed has been downloaded
and emit the connect signal if everything is ready"""
need_no_account = not self.client.secret.know_secret()
need_no_depth = not self.config.get_bool("api", "load_fulldepth")
need_no_history = not self.config.get_bool("api", "load_history")
need_no_depth = need_no_depth or FORCE_NO_FULLDEPTH
need_no_history = need_no_history or FORCE_NO_HISTORY
ready_account = self.ready_info and self.orderbook.ready_owns # and self.ready_idkey...
if ready_account or need_no_account:
if self.orderbook.ready_depth or need_no_depth:
if self.history.ready_history or need_no_history:
if self._was_disconnected:
self.signal_ready(self, None)
self._was_disconnected = False
def slot_client_connected(self, _sender, _data):
"""connected to the client"""
self.check_connect_ready()
def slot_fulldepth_processed(self, _sender, _data):
"""connected to the orderbook"""
self.check_connect_ready()
def slot_fullhistory_processed(self, _sender, _data):
"""connected to the history"""
self.check_connect_ready()
def slot_owns_initialized(self, _sender, _data):
"""connected to the orderbook"""
self.check_connect_ready()
def slot_disconnected(self, _sender, _data):
"""this slot is connected to the client object, all it currently
does is to emit a disconnected signal itself"""
# self.ready_idkey = False
self.ready_info = False
self.orderbook.ready_owns = False
self.orderbook.ready_depth = False
self.history.ready_history = False
self._was_disconnected = True
self.signal_disconnected(self, None)
def slot_recv(self, dummy_sender, data):
"""Slot for signal_recv, handle new incoming JSON message. Decode the
JSON string into a Python object and dispatch it to the method that
can handle it."""
(str_json) = data
handler = None
if type(str_json) == dict:
msg = str_json # was already a dict
else:
msg = json.loads(str_json)
self.msg = msg
if "stamp" in msg:
delay = time.time() * 1e6 - int(msg["stamp"])
self.socket_lag = (self.socket_lag * 29 + delay) / 30
if "op" in msg:
try:
msg_op = msg["op"]
handler = getattr(self, "_on_op_" + msg_op)
except AttributeError:
self.debug("slot_recv() ignoring: op=%s" % msg_op)
else:
self.debug("slot_recv() ignoring:", msg)
if handler:
handler(msg)
def slot_poll(self, _sender, _data):
"""poll stuff from http in regular intervals, not yet implemented"""
if self.client.secret and self.client.secret.know_secret():
# poll recent own trades
# fixme: how do i do this, whats the api for this?
pass
def slot_history_changed(self, _sender, _data):
"""this is a small optimzation, if we tell the client the time
of the last known candle then it won't fetch full history next time"""
last_candle = self.history.last_candle()
if last_candle:
self.client.history_last_candle = last_candle.tim
def _on_op_error(self, msg):
"""handle error mesages (op:error)"""
self.debug("### _on_op_error()", msg)
def _on_op_subscribe(self, msg):
"""handle subscribe messages (op:subscribe)"""
self.debug("### subscribed channel", msg["channel"])
def _on_op_ticker(self, msg):
"""handle incoming ticker message"""
msg = msg["ticker"]
bid = msg["bid"]
ask = msg["ask"]
# self.debug(" tick: %s %s" % (bid, ask))
self.signal_ticker(self, (bid, ask))
def _on_op_depth(self, msg):
"""handle incoming depth message"""
msg = msg["depth"]
# if msg["currency"] != self.curr_quote:
# return
# if msg["base"] != self.curr_base:
# return
typ = msg["type"]
price = msg["price"]
volume = msg["volume"]
# timestamp = msg["timestamp"]
# total_volume = msg["total_volume"]
# delay = time.time() - timestamp
# self.debug("depth: %s: %.8f @ %.8f total: %.8f (age: %0.4f s)" % (
# typ,
# volume,
# price,
# price * volume,
# delay / 1e6
# ))
self.signal_depth(self, (typ, price, volume)) # , total_volume))
def _on_op_trade(self, msg):
"""handle incoming trade message"""
# if msg["trade"]["price_currency"] != self.curr_quote:
# return
# if msg["trade"]["base"] != self.curr_base:
# return
# else:
# own = True
trade = msg['trade']
typ = trade["type"]
price = trade["price"]
volume = trade["amount"]
timestamp = int(trade["timestamp"])
# if own:
# self.debug("trade: %s: %s @ %s (own order filled)" % (
# typ,
# volume,
# price
# ))
# # send another private/info request because the fee might have
# # changed. We request it a minute later because the server
# # seems to need some time until the new values are available.
# # self.client.request_info_later(60)
# else:
self.debug("trade: %s: %s @ %s" % (
typ,
volume,
price
))
self.signal_trade(self, (timestamp, price, volume, typ, False)) # own))
def _on_op_chat(self, msg):
"""trollbox messages"""
msg = msg['msg']
self.debug("[c]%s %s[%s]: %s" % (
msg['type'] if msg['type'] != 'trollboxMessage' else ' >',
msg['user'],
msg['rep'],
msg['msg']
))
def _on_op_result(self, msg):
"""handle result of authenticated API call (op:result, id:xxxxxx)"""
result = msg["result"]
reqid = msg["id"]
# if reqid == "idkey":
# self.debug("### got key, subscribing to account messages")
# self._idkey = result
# self.client.on_idkey_received(result)
# self.ready_idkey = True
# self.check_connect_ready()
if reqid == "orders":
# self.debug("### got own order list")
# self.count_submitted = 0
self.orderbook.init_own(result)
# self.debug("### have %d own orders for %s/%s" % (len(self.orderbook.owns), self.curr_base, self.curr_quote))
elif reqid == "info":
# self.debug("### got account info")
self.wallet = {}
for currency in result:
self.wallet[currency] = float(result[currency])
# ## Old Gox shit
# wallet = result["Wallets"]
# self.monthly_volume = int(result["Monthly_Volume"]["value_int"])
# self.trade_fee = float(result["Trade_Fee"])
# for currency in wallet:
# self.wallet[currency] = int(
# wallet[currency]["Balance"]["value_int"])
self.signal_wallet(self, None)
self.ready_info = True
if self.client._wait_for_next_info:
self.client._wait_for_next_info = False
self.check_connect_ready()
elif reqid == "volume":
self.monthly_volume = result['volume']
self.currency = result['currency']
self.trade_fee = result['fee']
elif reqid == "order_lag":
lag_usec = result["lag"]
lag_text = result["lag_text"]
# self.debug("### got order lag: %s" % lag_text)
self.order_lag = lag_usec