forked from Trasp/GoxCLI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoxcli.py
3706 lines (3504 loc) · 150 KB
/
goxcli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import os,sys
from datetime import datetime
from functools import partial
from decimal import Decimal,InvalidOperation
from optparse import OptionParser,OptionGroup
# Regular expression-support
import re
# HTTP, SSL and Pipes
from ssl import SSLError
from contextlib import closing
import socket
import urllib
import urllib2
# Encoding, and encrypting
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
import binascii
import base64
import hmac
import hashlib
# Json-Support
# Slow json only needed for prettyprint, should add regexps instead.
import json, cjson
import xml.dom.minidom
import readline
import random
import uuid
import getpass
import string
import traceback
import locale
import time
class CredentialError(Exception): pass
class RightError(Exception):
def __init__(self, message, right=None, kind=None, arg=None):
self.msg = "Need %s rights to use %s %s" % (right, kind, arg)
class InputError(Exception):
def __init__(self, message, arg=None, kind=None):
if arg:
self.arg = arg
self.msg = "Invalid %s:" % (kind if kind else "argument")
else:
self.msg = message
self.arg = u""
Exception.__init__(self, message)
class MtGoxError(Exception):
pass
class DaemonError(Exception):
pass
class TokenizationError(Exception):
pass
class JsonParser:
@staticmethod
def parse(obj, force = False):
u"Parse json-strings."
# cjson is fast and good enough for our purposes
json = cjson.decode(obj)
if u"error" in json and not force:
raise MtGoxError(json[u"error"])
else:
return json
@staticmethod
def build(obj):
u"Build json-strings from object(s)."
return cjson.encode(obj)
class XmlParse(object):
def __init__(self, path):
u"Parse config-file in XML-format."
self.path = path
self.doc = None
self.cfg = None
self.colors = None
self.currencies = None
def _deviceNode(self, id, name, standard, credentials):
u"Construct deviceNodes from values."
# Create top node of device
dNode = self.doc.createElement(id)
dNode.setAttribute("name", name)
dNode.setAttribute("standard", standard)
# Unpack credentials and create credential-node
port, key, length, secret = credentials
# Key-node
kNode = self.doc.createElement("key")
kNode.setAttribute("value", str(key))
# Port-node
pNode = self.doc.createElement("port")
pNode.setAttribute("value", str(port))
# Secret-Node
sNode = self.doc.createElement("secret")
sNode.setAttribute("length", str(length))
sNode.appendChild(self.doc.createTextNode(secret))
# Append key and secret to credential-node
cNode = self.doc.createElement("credentials")
cNode.appendChild(kNode)
cNode.appendChild(pNode)
cNode.appendChild(sNode)
# Base64-encode credential-node
cNode = self.doc.createTextNode( base64.b64encode(cNode.toxml()) )
# Add as credentials as textNode to device's top node
dNode.appendChild(cNode)
return dNode
def addDevice(self, device):
u"Add device to config"
if not isinstance(device, DeviceItem):
raise ValueError()
oNode = self.getDevice(device.id)
if oNode:
oNode.node.parentNode.replaceChild(device.node, oNode.node)
else:
try:
element = self.cfg.getElementsByTagName("devices")[0]
except IndexError:
pNode = self.doc.createElement("devices")
pNode.appendChild(device.node)
self.cfg.insertBefore(pNode, self.cfg.firstChild)
else:
element.appendChild(device.node)
self.write()
@property
def devices(self):
u"Returns devices as a list."
return [d for d in self.iterDevices()]
@devices.setter
def devices(self, iter):
devices = self.doc.createElement("devices")
for device in iter:
devices.appendChild(device.node)
for pNode in self.cfg.getElementsByTagName("devices"):
self.cfg.removeChild(pNode)
#self.cfg.replaceChild(devices,pNode)
#break
#else:
self.cfg.insertBefore(devices, self.cfg.firstChild)
self.write()
@devices.deleter
def devices(self,device):
# Compare id with all devices in XML
for dNode in self.cfg.getElementsByTagName(device.id): # "device"
# Remove device on match
dNode.parentNode.removeChild(dNode)
def delDevice(self, id, write = True):
u"Delete device with a specified ID in loaded document."
for pNode in self.cfg.childNodes:
if pNode.tagName == "devices":
for dNode in pNode.childNodes:
if dNode.tagName == id:
pNode.removeChild(dNode)
if write: self.write()
return id
else:
return None
else:
return None
def getDevice(self, id):
u"Get device with a specified ID from loaded document."
for pNodes in self.cfg.getElementsByTagName("devices"):
dNodes = self.cfg.getElementsByTagName(id)
if dNodes:
return DeviceItem( dNodes[0] )
else:
return None
def iterDevices(self):
u"Iterate over all devices in config."
for devices in self.cfg.getElementsByTagName("devices"):
for dNode in devices.childNodes:
yield DeviceItem(dNode)
def parse(self, path):
u"Parse document from harddrive."
with open(path, "r") as f:
data = f.read()
return self.parseString(data)
def parseString(self, s):
u"Parse document from string."
# Setup pattern matching newLines and indents between tags
i = re.compile(">\n( *)<")
# Sanitize prettyprinted document from pattern
doc = xml.dom.minidom.parseString(re.sub(i,"><",s))
# Setup pattern matching newLines and indents inside textNodes
i = re.compile("\n( *)")
# Sanitize pretty textNodes that belong to device-Nodes
pNodes = (p.childNodes for p in doc.getElementsByTagName("devices"))
for pNode in pNodes:
for dNode in pNode:
nNode = doc.createTextNode(re.sub(i, "", dNode.firstChild.data))
dNode.replaceChild(nNode, dNode.firstChild)
return doc
def read(self, path=None, colors=False, currencies=False):
u"Read config and (re)set dictionaries with new settings."
if path: self.path = path
self.doc = self.parse(self.path)
cfg = self.doc.firstChild
if cfg.tagName == "GoxCLI":
self.cfg = cfg
else:
raise InputError("Error reading XML")
for sNode in self.cfg.childNodes:
if sNode.tagName == "settings":
#sNode = node
break
if currencies:
self.currencies = self._read_currencies(sNode)
if colors:
self.colors = self._read_colors(sNode)
def _read_colors(self,sNode):
u"Read colors from document and return settings in a dictionary."
ansi = sNode.getElementsByTagName("ansi")[0].childNodes
ansi = dict((c.tagName, c.attributes["value"].value) for c in ansi)
# Human readeable settings (colorNode)
cNode = sNode.getElementsByTagName("shell")[0]
# Save a dict with (keys = human readable, values = ansi).
color = lambda v: (v.tagName, ansi[v.attributes["value"].value])
return dict(color(v) for v in cNode.childNodes)
def currency(self, currency):
u"Read currencies from document and return settings in a dictionary."
currency = currency.upper()
if self.currencies:
try:
return sorted(self.currencies[currency].itervalues())
except KeyError:
raise InputError("Invalid currency: %s" % currency,
kind = "currency", arg = currency)
for sNode in self.cfg.childNodes:
if sNode.tagName == "settings":
break
else:
raise InputError("Invalid XML: No settings found",
kind = "XML", arg = "No settings found" )
for cNode in sNode.childNodes:
if cNode.tagName == "currencies":
for cNode in cNode.childNodes:
if cNode.tagName == currency:
break
else:
m = "%s: %s" % ("Currency not found", currency)
raise InputError("Invalid XML: " + m, kind = "XML", arg = m)
prefix = cNode.attributes["symbol"].value
decimals = int( cNode.attributes["decimals"].value )
break
else:
raise InputError("Invalid XML: No currency found",
kind = "XML", arg = "No currency found")
return decimals, prefix.decode("utf-8")
def _read_currencies(self,sNode):
u"Read currencies from document and return settings in a dictionary."
cNodes = sNode.getElementsByTagName("currencies")[0].childNodes
cDict = dict()
for cNode in cNodes:
currency = cNode.tagName
try:
prefix = cNode.attributes["symbol"].value
decimals = int( cNode.attributes["decimals"].value )
except IndexError:
# TODO: Was it really IndexError?
m = "%s: %s" % ("Malformed currency: ", currency.upper())
raise InputError("Invalid XML: %s" % m, kind = "XML", arg = m)
else:
cDict[currency] = dict(
decimals = decimals,
prefix = prefix
)
return cDict
def write(self, path=None, indent=4):
path = self.path if not None else path
indent = " " * indent
# Create fixed indentation for device's textNodes
si = "".join(("\n",indent * 2))
li = "".join(("\n",indent * 3))
# Clone config-element
doc = xml.dom.minidom.Document()
doc.appendChild(self.doc.firstChild.cloneNode(True))
for pNode in doc.getElementsByTagName("devices"):
for dNode in pNode.childNodes:
# Split credential-data into lines of 40 characters
nNode = dNode.firstChild.data
nNode = [nNode[x:x+40] for x in xrange(0,len(nNode),40)]
nNode = li.join(nNode)
nNode = "{0}{1}{2}".format(li, nNode, si)
nNode = self.doc.createTextNode(nNode)
dNode.replaceChild(nNode, dNode.firstChild)
trails=re.compile(' *\n')
final = doc.toprettyxml(indent) #.encode('ascii', 'replace')
final = re.sub(trails,"\n",final)
with open(path, "w") as f:
f.write(final.encode("utf-8"))
class DeviceItem(object):
def __init__(self, *args, **kwargs):
u"Container holding info about device."
if len(args) == 1:
self.__init_fromNode(*args)
elif len(args) == 3:
self.__init_fromValues(*args, **kwargs)
else:
raise TypeError("takes 2 or 4 arguments (%s given)"
% str(len(args)+1))
def __init_fromNode(self, dNode):
u"Create a item from existing Minidom-node."
if isinstance(dNode, xml.dom.minidom.Element):
self._node = dNode
self._credentials = None
else:
raise TypeError()
def __init_fromValues(self, name, key, secret, standard="USD", encrypted=0):
u"Create item from values given."
# cloneNode will require all nodes to have ownerDocument set.
doc = xml.dom.minidom.Document()
# Create a new ID
id = "d%s" % uuid.uuid4().hex
# Create top node of device
dNode = doc.createElement(id)
dNode.setAttribute("name", name)
dNode.setAttribute("standard", standard)
# Create the "encoded textNode"
# Key-node
kNode = doc.createElement("key")
kNode.setAttribute("value", str(key))
# Listening-node (if AF_UNIX 1/0, if AF_INET Port/0)
lNode = doc.createElement("port")
lNode.setAttribute("value", "0")
# Secret-Node
sNode = doc.createElement("secret")
sNode.setAttribute("length", str(encrypted))
tNode = doc.createTextNode( secret )
sNode.appendChild(tNode)
# Append key and secret to credential-node
cNode = doc.createElement("credentials")
cNode.appendChild(kNode)
cNode.appendChild(lNode)
cNode.appendChild(sNode)
# Base64-encode credential-node
tNode = doc.createTextNode( base64.b64encode(cNode.toxml()) )
# Add as credentials as a textNode to device
dNode.appendChild(tNode)
self._node = dNode
self._credentials = None
@property
def _cNode(self):
u"Read credential-node from node (Base64-encoded string)."
if not self._credentials:
cNode = base64.b64decode( self._node.firstChild.data )
cNode = xml.dom.minidom.parseString( cNode )
self._credentials = cNode.firstChild
return self._credentials
@_cNode.setter
def _cNode(self,cNode):
u"Base64-Encode credential-node's Xml-String and append to node."
text = base64.b64encode( cNode.toxml() )
tNode = xml.dom.minidom.Document().createTextNode( text )
if self._node.hasChildNodes():
self._node.replaceChild(tNode, self._node.firstChild)
else:
self._node.appendChild(tNode)
self._credentials = cNode
@property
def id(self):
u"Read device's id from node."
return self._node.tagName
@id.setter
def id(self,id):
u"Set device's id in node."
self._node.tagName = id
@property
def name(self):
u"Read device's name from node."
return self._node.attributes["name"].value
@name.setter
def name(self,name):
u"Set device's name in node."
self._node.setAttribute("name", str(name))
@property
def node(self):
u"Return Minidom-node."
return self._node
@node.setter
def node(self,n):
u"Set new Minidom-node."
if isinstance(device, xml.dom.minidom.Element):
self._node = n
self._credentials = None
else:
raise ValueError("DeviceNode must be minidom Element")
@property
def key(self):
u"Read secret from node."
key = self._cNode.getElementsByTagName("key")[0]
key = key.attributes.item(0).value
return key
@key.setter
def key(self,key):
u"Set secret in node."
kNode = xml.dom.minidom.Document().createElement("key")
kNode.setAttribute("value", str(key))
cNode = self._cNode
cNode.replaceChild(kNode, cNode.getElementsByTagName("key")[0])
self._cNode = cNode
@property
def length(self):
u"Read-only property, is set with passing pair of secret and" + \
u" length to secret-property."
sNode = self._cNode.getElementsByTagName("secret")[0]
return int(sNode.attributes["length"].value)
@property
def listening(self):
u"Read listening-status in node. 1/0 if system is" \
u" compatible with AF_UNIX, otherwise it represents the listening port"
listening = self._cNode.getElementsByTagName("port")[0]
listening = int(listening.attributes["value"].value)
return listening
@listening.setter
def listening(self,listening):
u"Set listening-status in node."
lNode = xml.dom.minidom.Document().createElement("port")
lNode.setAttribute("value", str(listening))
cNode = self._cNode
cNode.replaceChild(lNode, cNode.getElementsByTagName("port")[0])
self._cNode = cNode
@property
def secret(self):
u"Read secret from node."
sNode = self._cNode.getElementsByTagName("secret")[0]
return sNode.firstChild.data
@secret.setter
def secret(self,secret,length="0"):
u"Pass both secret and length as a pair (secret, length) to set"
u" secret and length or pass only the secret if not using encrypted" + \
u" secrets."
doc = Document()
tNode = doc.createTextNode(secret)
sNode = doc.createElement("secret")
sNode.setAttribute("length", str(length))
sNode.appendChild(tNode)
cNode = self._cNode
cNode.replaceChild(sNode, cNode.getElementsByTagName("secret")[0])
self._cNode = cNode
@property
def standard(self):
u"Read standard currency from node."
return self._node.attributes["standard"].value
@standard.setter
def standard(self,s):
u"Set standard currency in node."
self._node.setAttribute("standard", str(s))
class ServiceReader:
@staticmethod
def read(device):
u"Read credentials from service"
if socket.AF_UNIX:
# Unix inter-communication socket, supposedly more secure
host = "/tmp/{0}".format(device.id) # device.id
s = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
else:
# Create a TCP socket (Fallback/windows)
host = ("127.0.0.1", device.listening)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
try:
s.connect(host)
except socket.error, e:
raise DaemonError("Could not connect to service.")
s.send(device.id)
try:
# Receive up to 1kB
data = s.recv(1024)
except socket.timeout:
raise DaemonError("Socket timed out when connecting to service.")
try:
data = cjson.decode(data)
except cjson.DecodeError, e:
print e
raise DaemonError("Got invalid reply.")
return data["key"],data["secret"],int(data["counter"])
class LoginDaemon(object):
def __init__(self, parent):
u"Background service providing credentials after logging in."
self.parent = parent
def kill(self, device):
u"Kill old background service"
if socket.AF_UNIX:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
host = "/tmp/{0}".format(device.id)
else:
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ("127.0.0.1", device.listening)
# Set timeout in seconds
sock.settimeout(0.5)
try:
# Connect to LoginDaemon
sock.connect(host)
except socket.error:
raise DaemonError(u"Could not connect to service.")
else:
# Sending random data to kill, any data will do
sock.send("terminateAndDie")
try:
# Receive up to 1kB
data = sock.recv(1024)
except socket.timeout,e:
print "timeout",e
else:
if data != "":
raise DaemonError(u"Malformed reply.")
else:
return r'{"return": "Terminated.", "result": "success"}'
def run(self,daemon=False):
u"Start daemon threads and listen on socket"
if not all((self.parent._secret, self.parent._key, self.parent.device)):
raise DaemonError("Credentials not set")
if socket.AF_UNIX:
# Unix inter-communication socket, supposedly more secure,
# Can only listen at one ID per machine, but instead not be accessed
# by other users than the one that started the service.
sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
# TODO: Maybe I should prefix the pids for each user
host = "/tmp/{0}".format(self.parent.device.id)
if daemon:
if os.path.exists(host):
raise DaemonError(
u"Service allready listening on this ID. If you are" + \
u" sure no service is listening, confirm that no" + \
u" other file is blocking and that you have access" + \
u" to %s" % host)
try:
os.remove(host)
except OSError:
if os.path.exists(host):
try:
os.unlink(host)
except OSError:
raise DaemonError(
u"Service could not open socket for this ID." + \
u" Please confirm that no other file is blocking" +\
u" and that you have access to %s" % host
)
listening = 1
else:
# TCP socket, windows-machines...
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Pick random port above 1024
listening = random.randrange(1025,65555)
# Bind to localhost only
host = ("127.0.0.1", listening)
try:
sock.bind(host)
except socket.error,e:
if not socket.AF_UNIX:
# Bind failed using TCP, try again with other ports
# (TODO: Catch device busy-errors instead)
fail = 1
while fail < 100:
listening = random.randrange(1025,65555)
host = ("127.0.0.1", listening)
try:
sock.bind(host)
except:
fail += 1
else:
break
else:
raise DaemonError(u"Could not open listening socket.")
else:
# TODO: Catch different kinds of errorcodes (like access denied)
raise DaemonError(u"Could not open listening socket.")
# Allow only one connection at a time
sock.listen(1)
if not daemon:
self._daemonize(self._listen, sock)
return listening
def _daemonize(self, proc, *args):
# Throw as background job. This is the same as:
# if not((os.fork() == 0 and os.fork() == 0)): sys.exit(0)
if os.fork():
# Main process
return
else:
# New process
if not os.fork():
# Another fork, our background service
# NOTE: Without this last fork the process die if the user log
# out or close the running shell.
sys.stdin = open(os.devnull, 'r')
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')
self._listen(*args)
sys.exit(0)
def _listen(self, sock):
running = True
# Listen for incoming connections
while running:
# Wait for a new connection
connection, address = sock.accept()
# Recieve data from client
data = connection.recv(33)
if data == self.parent.device.id:
# Credentials requested
self.parent._counter += 1
# Return json with credentials
reply = dict(key=self.parent._key,
secret=self.parent._secret,
counter=self.parent._counter
)
connection.send(cjson.encode(reply))
else:
# Other data recieved, killing service
connection.send("")
running = False
# Job done, close connection before exiting
connection.close()
sys.exit(0)
class MtGoxAPI(object):
def __init__(self, credentials):
u"Handles requests made to Mt.Gox."
self._credentials = credentials
self._url = "https://mtgox.com/api/"
@property
def credentials(self):
if hasattr(self._credentials, "__call__"):
return self._credentials()
elif hasattr(self, "_secret"):
self._counter += 1
return self._key, self._secret, self._counter
else:
self._key, self._secret = self._credentials
self._counter = 0
@credentials.setter
def credentials(self, *args):
if len(args) == 1 and hasattr(args[0], "__call__"):
self._credentials = args[0]
elif len(args) == 2:
self._credentials = args
else:
raise ValueError("credentials expected 2 items, got %s" % len(args))
def activate(self,actkey,dName,pw=None):
u"Activate application and add device to config. You will need at" \
u" least some rights to use most of the functions in this application."
rel_path = "activate.php"
appkey = "52915cb8-4d97-4115-a43a-393c407143ae"
params = {
u"name": dName,
u"key": actkey,
u"app": appkey
}
return self._request(rel_path, api=0, params=params, auth=False)
def add_order(self, kind, amount, price, currency):
rel_path = "order/add"
params = {
"amount_int":str(amount),
"price_int":str(price),
"type":kind
}
return self._request(rel_path, params=params, currency=currency, auth=True)
def block(self,hash=None,depth=None):
u"Retrieve information about a block in bitcoin's blockchain," \
u" at least one of the arguments hash and number must be defined."
rel_path = "bitcoin/block_list_tx"
if hash:
params = dict(hash=hash)
elif depth:
params = dict(depth=depth)
else:
params = dict()
return self._request(rel_path, params=params, auth=False)
def btcaddress(self,hash):
u"Requests information about a specific BTC-address."
rel_path = "bitcoin/addr_details"
params = {"hash":hash}
return self._request(rel_path, params=params, auth=False)
def cancel(self, type, oid):
u"Cancel order identified with type and oid"
rel_path = "cancelOrder.php"
params = {
"type":{"ask":1,"bid":2}[type],
"oid":oid
}
return self._request(rel_path, api=0, params=params, auth=True)
def deposit(self):
u"Requests address for depositing BTC to your wallet at Mt.Gox."
rel_path = "bitcoin/address"
return self._request(rel_path, auth=True)
def depth(self,currency=None,full=False):
u"Request current depth-table at Mt.Gox (aka order book)."
if full:
rel_path = "fulldepth"
else:
rel_path = "depth"
return self._request(rel_path, currency = currency, auth = False)
def history(self, currency, page = 1):
u"Request wallet history. The history of your BTC-wallet will be" \
" requested if no currency is defined."
rel_path = "wallet/history"
params = {"currency":currency,"page":page}
return self._request(rel_path, params = params, auth = True)
def info(self):
u"Retrieve private info from Mt.Gox"
rel_path = "info"
return self._request(rel_path, auth = True)
def lag(self):
u"Returns the time MtGox takes to process each order." \
u" If this value is too high, trades will be delayed and depth-table" \
u" will probably not be reliable."
rel_path = "order/lag"
return self._request(rel_path, auth = False)
def orders(self):
u"Requests your open, invalid or pending orders."
rel_path = "orders"
return self._request(rel_path, auth = True)
def status(self, type, oid):
u"Returns trades that have matched the order specified, result will" \
u" be empty if order still is intact."
rel_path = "order/result"
params = dict(type = type, order = oid)
return self._request(rel_path, params=params, auth=True)
def ticker(self,currency="USD"):
u"Request latest ticker from Mt.Gox."
rel_path = "ticker"
return self._request(rel_path, currency=currency, auth=False)
def trades(self,currency="USD",since=None):
u"Requests a list of successfull trades from Mt.Gox, returns a" \
u" maximum of one hundred orders."
rel_path = "trades"
p = {"since":since} if since else {}
return self._request(rel_path, currency=currency, params=p, auth=False)
def transaction(self,hash):
u"Request information about a transaction within the BTC blockchain."
rel_path = "bitcoin/tx_details"
params = {"hash":hash}
return self._request(rel_path, params=params, auth=False)
def withdraw(self, currency, destination, amount, account, green = False):
u"Withdraw BTC or Dollars."
rel_path = "withdraw.php"
g = {False:"0",True:"1"}[green]
destination = destination.lower()
if destination == "coupon":
if currency in ("BTC","USD"):
params = {
u"group1": "".join((currency,"2CODE")),
u"amount": amount
}
else:
params = {
u"group1": u"USD2CODE",
u"amount": amount,
u"Currency": currency
}
elif (currency == "BTC") and (destination == "btc"):
params = {
u"group1": u"BTC",
u"btca": account,
u"amount": amount,
u"green": g
}
elif (currency == "USD") and (destination == "dwolla"):
params = {
u"group1": u"DWUSD",
u"dwaccount": account,
u"amount": amount,
u"green": g
}
elif (currency == "USD") and (destination == "lr"):
params = {
u"group1": u"USD",
u"account": account,
u"amount": amount,
u"green": g
}
elif (currency == "USD") and (destination == "paxum"):
params = {
u"group1": u"PAXUMUSD",
u"paxumaccount": account,
u"amount": amount,
u"green": g
}
else:
raise InputError("Impossible combination of arguments and/or currency.")
return self._request(rel_path, api = 0, params=params, auth=True)
def _request(self, rel_path, api = 1, params = {}, currency = None, auth = True):
if api and currency:
url = "".join((self._url, "1/", "".join(("BTC",currency,"/")), rel_path))
elif api:
url = "".join((self._url, "1/generic/", rel_path))
else:
url = "".join((self._url, "0/", rel_path))
timeout = 15
if auth:
# Function requires authentication
key,secret,counter = self.credentials
# Timestamp*1000+counter to make no more than 1000 requests per second possible
params["nonce"] = (int(time.time())*1000)+counter
# Format the post_data, if not null
post_data = urllib.urlencode(params) if len(params) > 0 else None
try:
# Decode secret
secret = base64.b64decode(secret)
# Hmac-sha512-hash secret and postdata
hash = hmac.new(secret, post_data, hashlib.sha512)
# Digest hash as binary and encode with base64
sign = base64.b64encode(str(hash.digest()))
except TypeError:
# Catch exception thrown due to bad key or secret
raise CredentialError(
u"Could not sign request due to bad secret or wrong" + \
u" password. Please try again or request new " + \
u" credentials by reactivating your application."
)
else:
# Apply the base64-encoded data together with api-key to header
headers = {
"User-Agent":"GoxCLI",
"Rest-Key":key,
"Rest-Sign":sign
}
req = urllib2.Request(url, post_data, headers)
else:
post_data = urllib.urlencode(params) if len(params) > 0 else None
req = urllib2.Request(url, post_data)
try:
with closing(urllib2.urlopen(req, post_data, timeout)) as response:
return response.read()
except SSLError, e:
raise MtGoxError("Could not reach Mt.Gox. Operation timed out.")
except urllib2.HTTPError, e:
if e.code == 403:
raise MtGoxError("Authorization to this API denied")
else:
raise urllib2.HTTPError(e.url, e.code, e.msg, None, None)
class DepthParser(object):
def __init__(self, currencyDecimals, args = []):
self._cPrec = Decimal(1) / 10 ** currencyDecimals
self.__sides = ("asks","bids")
try:
for arg,value in (arg.split("=") for arg in args):
arg = arg.lower()
if hasattr(self, arg):
try:
setattr(self, arg, value)
except InvalidOperation:
raise InputError( "Invalid value: %s" % value,
kind = "value", arg = value )
except ValueError:
raise InputError( "Invalid value: %s" % value,
kind = "value", arg = value )
else:
raise InputError("Invalid argument: %s" % arg, arg = arg)
except ValueError:
raise InputError("Invalid argument")
@property
def side(self):
try:
return self._side
except AttributeError:
return None
@side.setter
def side(self,value):
if value:
if value == "bids":
self._side = value
self.__sides = ("bids",)
elif value == "asks":
self._side = value
self.__sides = ("asks",)
else:
raise InputError( "Invalid value : %s" % value,
kind = "value", arg = value )
else:
self._side = None
self.__sides = ("asks","bids")
@property
def low(self):
try:
return self._minPrice
except AttributeError:
return None
@low.setter
def low(self, value):
if value:
self._minPrice = Decimal(value)
else:
self._minPrice = None
@property
def high(self):
try:
return self._maxPrice
except AttributeError:
return None
@high.setter
def high(self, value):
if value:
self._maxPrice = Decimal(value)
else:
self._maxPrice = None
@property
def amount(self):
try:
return self._maxAmount
except AttributeError:
return None
@amount.setter
def amount(self, value):
if value:
self._maxAmount = Decimal(value)
else:
self._maxAmount = None
@property
def value(self):
try:
return self._maxValue
except AttributeError: