forked from prof7bit/goxtool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
goxapi.py
2067 lines (1755 loc) · 78.2 KB
/
goxapi.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
"""Mt.Gox API"""
# 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.
# pylint: disable=C0302,C0301,R0902,R0903,R0912,R0913,R0914,R0915,W0703
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 binascii
import contextlib
from Crypto.Cipher import AES
import getpass
import gzip
import hashlib
import hmac
import inspect
import io
import json
import logging
import Queue
import time
import traceback
import threading
from urllib2 import Request as URLRequest
from urllib2 import urlopen, HTTPError
from urllib import urlencode
import weakref
import websocket
input = raw_input # pylint: disable=W0622,C0103
FORCE_PROTOCOL = ""
FORCE_NO_FULLDEPTH = False
FORCE_NO_HISTORY = False
FORCE_HTTP_API = False
FORCE_NO_HTTP_API = False
SOCKETIO_HOST = "socketio.mtgox.com"
WEBSOCKET_HOST = "websocket.mtgox.com"
HTTP_HOST = "data.mtgox.com"
USER_AGENT = "goxtool.py"
# deprecated, use gox.quote2str() and gox.base2str() instead
def int2str(value_int, currency):
"""return currency integer formatted as a string"""
if currency in "BTC LTC NMC":
return ("%16.8f" % (value_int / 100000000.0))
elif currency in "JPY SEK":
return ("%12.3f" % (value_int / 1000.0))
else:
return ("%12.5f" % (value_int / 100000.0))
# deprecated, use gox.quote2float() and gox.base2float() instead
def int2float(value_int, currency):
"""convert integer to float, determine the factor by currency name"""
if currency in "BTC LTC NMC":
return value_int / 100000000.0
elif currency in "JPY SEK":
return value_int / 1000.0
else:
return value_int / 100000.0
# deprecated, use gox.quote2int() and gox.base2int() instead
def float2int(value_float, currency):
"""convert float value to integer, determine the factor by currency name"""
if currency in "BTC LTC NMC":
return int(round(value_float * 100000000))
elif currency in "JPY SEK":
return int(round(value_float * 1000))
else:
return int(round(value_float * 100000))
def http_request(url, post=None, headers=None):
"""request data from the HTTP API, returns a string"""
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)
return data
def start_thread(thread_func):
"""start a new thread to execute the supplied function"""
thread = threading.Thread(None, thread_func)
thread.daemon = True
thread.start()
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)
# pylint: disable=R0904
class GoxConfig(SafeConfigParser):
"""return a config parser object with default values. If you need to run
more Gox() objects at the same time you will also need to give each of them
them a separate GoxConfig() object. For this reason it takes a filename
in its constructor for the ini file, you can have separate configurations
for separate Gox() instances"""
_DEFAULTS = [["gox", "base_currency", "BTC"]
,["gox", "quote_currency", "USD"]
,["gox", "use_ssl", "True"]
,["gox", "use_plain_old_websocket", "True"]
,["gox", "use_http_api", "True"]
,["gox", "use_tonce", "False"]
,["gox", "load_fulldepth", "True"]
,["gox", "load_history", "True"]
,["gox", "history_timeframe", "15"]
,["gox", "secret_key", ""]
,["gox", "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("gox", "currency"):
self.set("gox", "quote_currency", self.get_string("gox", "currency"))
self.remove_option("gox", "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)
# pylint: disable=W0702
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):
if slot.__self__ not in self._methods:
self._methods[slot.__self__] = set()
self._methods[slot.__self__].add(slot.__func__)
else:
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
# pylint: disable=W0702
except:
errors.append(traceback.format_exc())
for obj, funcs in self._methods.items():
for func in funcs:
try:
func(obj, sender, data)
sent = True
# pylint: disable=W0702
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 goxtool 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 who
are connected to signal_debug or send it to the logger if
nobody is connected"""
msg = " ".join([str(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):
"""create a new timer, interval is in seconds"""
Signal.__init__(self)
self._interval = interval
self._timer = None
self._start()
def _fire(self):
"""fire the signal and restart it"""
self.__call__(self, None)
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._timer.cancel()
class Secret:
"""Manage the MtGox 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 = ""
# pylint: disable=C0103
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("gox", "secret_key")
sec = self.config.get_string("gox", "secret_secret")
if sec == "" or key == "":
return self.S_NO_SECRET
# pylint: disable=E1101
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")
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")
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 MtGox 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("gox", "secret_key")
sec = self.config.get_string("gox", "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
# pylint: disable=R0201
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 MtGox 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
# pylint: disable=E1101
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("gox", "secret_key", key)
self.config.set("gox", "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 gox 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, gox, timeframe):
BaseObject.__init__(self)
self.signal_changed = Signal()
self.gox = gox
self.candles = []
self.timeframe = timeframe
gox.signal_trade.connect(self.slot_trade)
gox.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 gox.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(int(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 = int(trade["date"])
price = int(trade["price_int"])
volume = int(trade["amount_int"])
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.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 BaseClient(BaseObject):
"""abstract base class for SocketIOClient and WebsocketClient"""
_last_unique_microtime = 0
_nonce_lock = threading.Lock()
def __init__(self, curr_base, curr_quote, secret, config):
BaseObject.__init__(self)
self.signal_recv = Signal()
self.signal_fulldepth = Signal()
self.signal_fullhistory = Signal()
self._timer = Timer(60)
self._timer.connect(self.slot_timer)
self.curr_base = curr_base
self.curr_quote = curr_quote
self.currency = curr_quote # deprecated, use curr_quote instead
self.secret = secret
self.config = config
self.socket = None
self.http_requests = Queue.Queue()
self._recv_thread = None
self._http_thread = None
self._terminating = False
self.connected = False
self._time_last_received = 0
self._time_last_subscribed = 0
self.history_last_candle = None
def start(self):
"""start the client"""
self._recv_thread = start_thread(self._recv_thread_func)
self._http_thread = start_thread(self._http_thread_func)
def stop(self):
"""stop the client"""
self._terminating = True
self._timer.cancel()
if self.socket:
self.debug("""closing socket""")
self.socket.sock.close()
#self._recv_thread.join()
def _try_send_raw(self, raw_data):
"""send raw data to the websocket or disconnect and close"""
if self.connected:
try:
self.socket.send(raw_data)
except Exception as exc:
self.debug(exc)
self.connected = False
self.socket.close()
def send(self, json_str):
"""there exist 2 subtly different ways to send a string over a
websocket. Each client class will override this send method"""
raise NotImplementedError()
def get_unique_mirotime(self):
"""produce a unique nonce that is guaranteed to be ever increasing"""
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 use_http(self):
"""should we use http api? return true if yes"""
use_http = self.config.get_bool("gox", "use_http_api")
if FORCE_HTTP_API:
use_http = True
if FORCE_NO_HTTP_API:
use_http = False
return use_http
def use_tonce(self):
"""should we use tonce instead on nonce? tonce is current microtime
and also works when messages come out of order (which happens at
the mtgox server in certain siuations). They still have to be unique
because mtgox will remember all recently used tonce values. It will
only be accepted when the local clock is +/- 10 seconds exact."""
return self.config.get_bool("gox", "use_tonce")
def request_fulldepth(self):
"""start the fulldepth thread"""
def fulldepth_thread():
"""request the full market depth, initialize the order book
and then terminate. This is called in a separate thread after
the streaming API has been connected."""
self.debug("requesting initial full depth")
use_ssl = self.config.get_bool("gox", "use_ssl")
proto = {True: "https", False: "http"}[use_ssl]
fulldepth = http_request("%s://%s/api/2/%s%s/money/depth/full" % (
proto,
HTTP_HOST,
self.curr_base,
self.curr_quote
))
self.signal_fulldepth(self, (json.loads(fulldepth)))
start_thread(fulldepth_thread)
def request_history(self):
"""request trading history"""
# Gox() will have set this field to the timestamp of the last
# known candle, so we only request data since this time
since = self.history_last_candle
def history_thread():
"""request trading history"""
# 1308503626, 218868 <-- last small transacion ID
# 1309108565, 1309108565842636 <-- first big transaction ID
if since:
querystring = "?since=%i" % (since * 1000000)
else:
querystring = ""
self.debug("requesting history")
use_ssl = self.config.get_bool("gox", "use_ssl")
proto = {True: "https", False: "http"}[use_ssl]
json_hist = http_request("%s://%s/api/2/%s%s/money/trades%s" % (
proto,
HTTP_HOST,
self.curr_base,
self.curr_quote,
querystring
))
history = json.loads(json_hist)
if history["result"] == "success":
self.signal_fullhistory(self, history["data"])
start_thread(history_thread)
def _recv_thread_func(self):
"""this will be executed as the main receiving thread, each type of
client (websocket or socketio) will implement its own"""
raise NotImplementedError()
def channel_subscribe(self, download_market_data=True):
"""subscribe to needed channnels and download initial data (orders,
account info, depth, history, etc. Some of these might be redundant but
at the time I wrote this code the socketio server seemed to have a bug,
not being able to subscribe via the GET parameters, so I send all
needed subscription requests here again, just to be on the safe side."""
symb = "%s%s" % (self.curr_base, self.curr_quote)
self.send(json.dumps({"op":"mtgox.subscribe", "channel":"depth.%s" % symb}))
self.send(json.dumps({"op":"mtgox.subscribe", "channel":"ticker.%s" % symb}))
# trades and lag are the same channels for all currencies
self.send(json.dumps({"op":"mtgox.subscribe", "type":"trades"}))
self.send(json.dumps({"op":"mtgox.subscribe", "type":"lag"}))
if self.use_http():
self.enqueue_http_request("money/idkey", {}, "idkey")
self.enqueue_http_request("money/orders", {}, "orders")
self.enqueue_http_request("money/info", {}, "info")
else:
self.send_signed_call("private/idkey", {}, "idkey")
self.send_signed_call("private/orders", {}, "orders")
self.send_signed_call("private/info", {}, "info")
if download_market_data:
if self.config.get_bool("gox", "load_fulldepth"):
if not FORCE_NO_FULLDEPTH:
self.request_fulldepth()
if self.config.get_bool("gox", "load_history"):
if not FORCE_NO_HISTORY:
self.request_history()
self._time_last_subscribed = time.time()
def _http_thread_func(self):
"""send queued http requests to the http API (only used when
http api is forced, normally this is much slower)"""
while not self._terminating:
# pop queued request from the queue and process it
(api_endpoint, params, reqid) = self.http_requests.get(True)
translated = None
try:
answer = self.http_signed_call(api_endpoint, params)
if answer["result"] == "success":
# the following will reformat the answer in such a way
# that we can pass it directly to signal_recv()
# as if it had come directly from the websocket
translated = {
"op": "result",
"result": answer["data"],
"id": reqid
}
else:
if "error" in answer:
# these are errors like "Order amount is too low"
# or "Order not found" and the like, we send them
# to signal_recv() as if they had come from the
# streaming API beause Gox() can handle these errors.
translated = {
"op": "remark",
"success": False,
"message": answer["error"],
"token": answer["token"],
"id": reqid
}
else:
self.debug("### unexpected http result:", answer, reqid)
except Exception as exc:
# should this ever happen? HTTP 5xx wont trigger this,
# something else must have gone wrong, a totally malformed
# reply or something else. Log the error and don't retry
self.debug("### exception in _http_thread_func:",
exc, api_endpoint, params, reqid)
if translated:
self.signal_recv(self, (json.dumps(translated)))
self.http_requests.task_done()
def enqueue_http_request(self, api_endpoint, params, reqid):
"""enqueue a request for sending to the HTTP API, returns
immediately, behaves exactly like sending it over the websocket."""
if self.secret and self.secret.know_secret():
self.http_requests.put((api_endpoint, params, reqid))
def http_signed_call(self, api_endpoint, params):
"""send a signed request to the HTTP API V2"""
if (not self.secret) or (not self.secret.know_secret()):
self.debug("### don't know secret, cannot call %s" % api_endpoint)
return
key = self.secret.key
sec = self.secret.secret
if self.use_tonce():
params["tonce"] = self.get_unique_mirotime()
else:
params["nonce"] = self.get_unique_mirotime()
post = urlencode(params)
prefix = api_endpoint + chr(0)
# pylint: disable=E1101
sign = hmac.new(base64.b64decode(sec), prefix + post, hashlib.sha512).digest()
headers = {
'Rest-Key': key,
'Rest-Sign': base64.b64encode(sign)
}
use_ssl = self.config.get_bool("gox", "use_ssl")
proto = {True: "https", False: "http"}[use_ssl]
url = "%s://%s/api/2/%s" % (
proto,
HTTP_HOST,
api_endpoint
)
self.debug("### (%s) calling %s" % (proto, url))
return json.loads(http_request(url, post, headers))
def send_signed_call(self, api_endpoint, params, reqid):
"""send a signed (authenticated) API call over the socket.io.
This method will only succeed if the secret key is available,
otherwise it will just log a warning and do nothing."""
if (not self.secret) or (not self.secret.know_secret()):
self.debug("### don't know secret, cannot call %s" % api_endpoint)
return
key = self.secret.key
sec = self.secret.secret
call = {
"id" : reqid,
"call" : api_endpoint,
"params" : params,
"currency" : self.curr_quote,
"item" : self.curr_base
}
if self.use_tonce():
call["tonce"] = self.get_unique_mirotime()
else:
call["nonce"] = self.get_unique_mirotime()
call = json.dumps(call)
# pylint: disable=E1101
sign = hmac.new(base64.b64decode(sec), call, hashlib.sha512).digest()
signedcall = key.replace("-", "").decode("hex") + sign + call
self.debug("### (socket) calling %s" % api_endpoint)
self.send(json.dumps({
"op" : "call",
"call" : base64.b64encode(signedcall),
"id" : reqid,
"context" : "mtgox.com"
}))
def send_order_add(self, typ, price, volume):
"""send an order"""
reqid = "order_add:%s:%d:%d" % (typ, price, volume)
if price > 0:
params = {"type": typ, "price_int": price, "amount_int": volume}
else:
params = {"type": typ, "amount_int": volume}
if self.use_http():
api = "%s%s/money/order/add" % (self.curr_base , self.curr_quote)
self.enqueue_http_request(api, params, reqid)
else:
api = "order/add"
self.send_signed_call(api, params, reqid)
def send_order_cancel(self, oid):
"""cancel an order"""
params = {"oid": oid}
reqid = "order_cancel:%s" % oid
if self.use_http():
api = "money/order/cancel"
self.enqueue_http_request(api, params, reqid)
else:
api = "order/cancel"
self.send_signed_call(api, params, reqid)
def slot_timer(self, _sender, _data):
"""check timeout (last received, dead socket?)"""
if self.connected:
if time.time() - self._time_last_received > 60:
self.debug("did not receive anything for a long time, disconnecting.")
self.socket.close()
self.connected = False
if time.time() - self._time_last_subscribed > 3600:
# sometimes after running for a few hours it
# will lose some of the subscriptons for no
# obvious reason. I've seen it losing the trades
# and the lag channel channel already, and maybe
# even others. Simply subscribing again completely
# fixes this condition. For this reason we renew
# all channel subscriptions once every hour.
self.debug("### refreshing channel subscriptions")
self.channel_subscribe(False)
class WebsocketClient(BaseClient):
"""this implements a connection to MtGox through the older (but faster)
websocket protocol. Unfortuntely its just as unreliable as the socket.io."""
def __init__(self, curr_base, curr_quote, secret, config):
BaseClient.__init__(self, curr_base, curr_quote, secret, config)
self.hostname = WEBSOCKET_HOST
def _recv_thread_func(self):
"""connect to the websocket and start receiving in an infinite loop.
Try to reconnect whenever connection is lost. Each received json
string will be dispatched with a signal_recv signal"""
reconnect_time = 1
use_ssl = self.config.get_bool("gox", "use_ssl")
wsp = {True: "wss://", False: "ws://"}[use_ssl]
port = {True: 443, False: 80}[use_ssl]
ws_origin = "%s:%d" % (self.hostname, port)
ws_headers = ["User-Agent: %s" % USER_AGENT]
while not self._terminating: #loop 0 (connect, reconnect)
try:
# channels separated by "/", wildcards allowed. Available
# channels see here: https://mtgox.com/api/2/stream/list_public
# example: ws://websocket.mtgox.com/?Channel=depth.LTCEUR/ticker.LTCEUR
# the trades and lag channel will be subscribed after connect
sym = "%s%s" % (self.curr_base, self.curr_quote)
ws_url = "%s%s?Channel=depth.%s/ticker.%s" % \
(wsp, self.hostname, sym, sym)
self.debug("trying plain old Websocket: %s ... " % ws_url)
self.socket = websocket.WebSocket()
# The server is somewhat picky when it comes to the exact
# host:port syntax of the origin header, so I am supplying
# my own origin header instead of the auto-generated one
self.socket.connect(ws_url, origin=ws_origin, header=ws_headers)
self._time_last_received = time.time()