-
Notifications
You must be signed in to change notification settings - Fork 47
/
goxapi.py
2695 lines (2311 loc) · 107 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,W0105
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 bisect
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 pubnub_light
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_DEPTH = False
FORCE_NO_LAG = 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"
# available channels as per https://mtgox.com/api/2/stream/list_public?pretty
# queried on 2013-12-14 - this must be updated when they add new currencies,
# I'm too lazy now to do that dynamically, it doesn't change often (if ever)
CHANNELS = {
"ticker.LTCGBP": "0102a446-e4d4-4082-8e83-cc02822f9172",
"ticker.LTCCNY": "0290378c-e3d7-4836-8cb1-2bfae20cc492",
"depth.BTCHKD": "049f65dc-3af3-4ffd-85a5-aac102b2a579",
"depth.BTCEUR": "057bdc6b-9f9c-44e4-bc1a-363e4443ce87",
"ticker.NMCAUD": "08c65460-cbd9-492e-8473-8507dfa66ae6",
"ticker.BTCEUR": "0bb6da8b-f6c6-4ecf-8f0d-a544ad948c15",
"depth.BTCKRW": "0c84bda7-e613-4b19-ae2a-6d26412c9f70",
"depth.BTCCNY": "0d1ecad8-e20f-459e-8bed-0bdcf927820f",
"ticker.BTCCAD": "10720792-084d-45ba-92e3-cf44d9477775",
"depth.BTCCHF": "113fec5f-294d-4929-86eb-8ca4c3fd1bed",
"ticker.LTCNOK": "13616ae8-9268-4a43-bdf7-6b8d1ac814a2",
"ticker.LTCUSD": "1366a9f3-92eb-4c6c-9ccc-492a959eca94",
"ticker.BTCBTC": "13edff67-cfa0-4d99-aa76-52bd15d6a058",
"ticker.LTCCAD": "18b55737-3f5c-4583-af63-6eb3951ead72",
"ticker.NMCCNY": "249fdefd-c6eb-4802-9f54-064bc83908aa",
"depth.BTCUSD": "24e67e0d-1cad-4cc0-9e7a-f8523ef460fe",
"ticker.BTCCHF": "2644c164-3db7-4475-8b45-c7042efe3413",
"depth.BTCAUD": "296ee352-dd5d-46f3-9bea-5e39dede2005",
"ticker.BTCCZK": "2a968b7f-6638-40ba-95e7-7284b3196d52",
"ticker.BTCSGD": "2cb73ed1-07f4-45e0-8918-bcbfda658912",
"ticker.NMCJPY": "314e2b7a-a9fa-4249-bc46-b7f662ecbc3a",
"ticker.BTCNMC": "36189b8c-cffa-40d2-b205-fb71420387ae",
"depth.BTCINR": "414fdb18-8f70-471c-a9df-b3c2740727ea",
"depth.BTCSGD": "41e5c243-3d44-4fad-b690-f39e1dbb86a8",
"ticker.BTCLTC": "48b6886f-49c0-4614-b647-ba5369b449a9",
"ticker.LTCEUR": "491bc9bb-7cd8-4719-a9e8-16dad802ffac",
"ticker.BTCINR": "55e5feb8-fea5-416b-88fa-40211541deca",
"ticker.LTCJPY": "5ad8e40f-6df3-489f-9cf1-af28426a50cf",
"depth.BTCCAD": "5b234cc3-a7c1-47ce-854f-27aee4cdbda5",
"ticker.BTCNZD": "5ddd27ca-2466-4d1a-8961-615dedb68bf1",
"depth.BTCGBP": "60c3af1b-5d40-4d0e-b9fc-ccab433d2e9c",
"depth.BTCNOK": "66da7fb4-6b0c-4a10-9cb7-e2944e046eb5",
"depth.BTCTHB": "67879668-532f-41f9-8eb0-55e7593a5ab8",
"ticker.BTCSEK": "6caf1244-655b-460f-beaf-5c56d1f4bea7",
"ticker.BTCNOK": "7532e866-3a03-4514-a4b1-6f86e3a8dc11",
"ticker.BTCGBP": "7b842b7d-d1f9-46fa-a49c-c12f1ad5a533",
"trade.lag": "85174711-be64-4de1-b783-0628995d7914",
"depth.BTCSEK": "8f1fefaa-7c55-4420-ada0-4de15c1c38f3",
"depth.BTCDKK": "9219abb0-b50c-4007-b4d2-51d1711ab19c",
"depth.BTCJPY": "94483e07-d797-4dd4-bc72-dc98f1fd39e3",
"ticker.NMCUSD": "9aaefd15-d101-49f3-a2fd-6b63b85b6bed",
"ticker.LTCAUD": "a046600a-a06c-4ebf-9ffb-bdc8157227e8",
"ticker.BTCJPY": "a39ae532-6a3c-4835-af8c-dda54cb4874e",
"depth.BTCCZK": "a7a970cf-4f6c-4d85-a74e-ac0979049b87",
"ticker.LTCDKK": "b10a706e-e8c7-4ea8-9148-669f86930b36",
"ticker.BTCPLN": "b4a02cb3-2e2d-4a88-aeea-3c66cb604d01",
"ticker.BTCRUB": "bd04f720-3c70-4dce-ae71-2422ab862c65",
"ticker.NMCGBP": "bf5126ba-5187-456f-8ae6-963678d0607f",
"ticker.BTCKRW": "bf85048d-4db9-4dbe-9ca3-5b83a1a4186e",
"ticker.BTCCNY": "c251ec35-56f9-40ab-a4f6-13325c349de4",
"depth.BTCNZD": "cedf8730-bce6-4278-b6fe-9bee42930e95",
"ticker.BTCHKD": "d3ae78dd-01dd-4074-88a7-b8aa03cd28dd",
"ticker.BTCTHB": "d58e3b69-9560-4b9e-8c58-b5c0f3fda5e1",
"ticker.BTCUSD": "d5f06780-30a8-4a48-a2f8-7ed181b4a13f",
"depth.BTCRUB": "d6412ca0-b686-464c-891a-d1ba3943f3c6",
"ticker.NMCEUR": "d8512d04-f262-4a14-82f2-8e5c96c15e68",
"trade.BTC": "dbf1dee9-4f2e-4a08-8cb7-748919a71b21",
"ticker.NMCCAD": "dc28033e-7506-484c-905d-1c811a613323",
"depth.BTCPLN": "e4ff055a-f8bf-407e-af76-676cad319a21",
"ticker.BTCDKK": "e5ce0604-574a-4059-9493-80af46c776b3",
"ticker.BTCAUD": "eb6aaa11-99d0-4f64-9e8c-1140872a423d"
}
# 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 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 MtGox will
send 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)
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)
# 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", "True"]
,["gox", "load_fulldepth", "True"]
,["gox", "load_history", "True"]
,["gox", "history_timeframe", "15"]
,["gox", "secret_key", ""]
,["gox", "secret_secret", ""]
,["pubnub", "stream_sorter_time_window", "0.5"]
]
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)
except: # pylint: disable=W0702
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: # pylint: disable=W0702
errors.append(traceback.format_exc())
for instance, functions in self._methods.items():
for func in functions:
try:
func(instance, sender, data)
sent = True
except: # pylint: disable=W0702
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, 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 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_fullhistory_processed = Signal()
self.signal_changed = Signal()
self.gox = gox
self.candles = []
self.timeframe = timeframe
self.ready_history = False
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.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 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.signal_connected = Signal()
self.signal_disconnected = Signal()
self._timer = Timer(60)
self._timer.connect(self.slot_timer)
self._info_timer = None # used when delayed requesting private/info
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, "socket receive thread")
self._http_thread = start_thread(self._http_thread_func, "http thread")
def stop(self):
"""stop the client"""
self._terminating = True
self._timer.cancel()
if self.socket:
self.debug("### closing socket")
self.socket.sock.close()
def force_reconnect(self):
"""force client to reconnect"""
self.socket.close()
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, "http request full depth")
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, "http request trade history")
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)
if not FORCE_NO_DEPTH:
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"}))
if not FORCE_NO_LAG:
self.send(json.dumps({"op":"mtgox.subscribe", "type":"lag"}))
self.request_idkey()
self.request_orders()
self.request_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 _slot_timer_info_later(self, _sender, _data):
"""the slot for the request_info_later() timer signal"""
self.request_info()
self._info_timer = None
def request_info_later(self, delay):
"""request the private/info in delay seconds from now"""
if self._info_timer:
self._info_timer.cancel()
self._info_timer = Timer(delay, True)
self._info_timer.connect(self._slot_timer_info_later)
def request_info(self):
"""request the private/info object"""
if self.use_http():
self.enqueue_http_request("money/info", {}, "info")
else:
self.send_signed_call("private/info", {}, "info")
def request_idkey(self):
"""request the private/idkey object"""
if self.use_http():
self.enqueue_http_request("money/idkey", {}, "idkey")
else:
self.send_signed_call("private/idkey", {}, "idkey")
def request_orders(self):
"""request the private/orders object"""
if self.use_http():
self.enqueue_http_request("money/orders", {}, "orders")
else:
self.send_signed_call("private/orders", {}, "orders")
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:
if answer["token"] == "unknown_error":
# enqueue it again, it will eventually succeed.
self.enqueue_http_request(api_endpoint, params, reqid)
else:
# 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.
#
# After some time of testing during times of heavy
# volatility it appears that this happens mostly when
# there is heavy load on their servers. Resubmitting
# the API call will then eventally succeed.
self.debug("### exception in _http_thread_func:",
exc, api_endpoint, params, reqid)
# enqueue it again, it will eventually succeed.
self.enqueue_http_request(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()):