Post
Topic
Board Marketplace
Topic OP
Trying to access mtgox API through with python-code
by
trasp
on 27/09/2011, 03:19:41 UTC
Well, I've been fooling around some with the mtgix APi but can't get it to work, looked through goxsh, the wiki and some thread here with some C#-code and as far as I can tell this code really should work, but obviously it doesn't Sad... some help would be very much appriciated...


Edit:

I managed to fix it and replaced the code, this should work for anyone else struggling with mtgox API:

Code:
# API
import urllib, urllib2, json
# API-Auth
import base64
import hmac
import hashlib
import time

## [...]

        self.counter = 0
        self.apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        self.secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        self.useragent = "TraspAPInfo"

## [...]

    def _url_mtgox(self, url, postdict=None, timeout=8):
        if postdict:
            postdata = urllib.urlencode(postdict)                                                                                                  # nonce=##########
            sign = base64.b64encode(str(hmac.new(base64.b64decode(self.secret), postdata, hashlib.sha512).digest())) # Decode the secret from mtgox -> Use that as key to hash the postdata -> Encode that string
            headers = {
                "User-Agent":self.useragent,
                "Rest-Key":self.apikey,
                "Rest-Sign":sign
                }
            request = urllib2.Request(url, postdata, headers)
        else:
            request = urllib2.Request(url)
        response = urllib2.urlopen(request, postdata, timeout=timeout)
        return json.loads(response.read())

## [...]

    @pyqtSlot()
    def info(self,cry="USD"):
        api = "https://mtgox.com/api/0/info.php"
        postdict = {
            "nonce":int(time.time())*1000+self.counter
            }
        self.counter += 1
        jsondata = self._url_mtgox(api,postdict=postdict)
        self.ui.statusEdit.append(jsondata["Wallets"][cry]["Balance"]["display"])                                                             # Print Balance