Bitcoin Forum
May 13, 2024, 10:12:41 PM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: Trying to access mtgox API through with python-code  (Read 2133 times)
trasp (OP)
Newbie
*
Offline Offline

Activity: 23
Merit: 0


View Profile
September 27, 2011, 03:19:41 AM
Last edit: September 28, 2011, 04:24:04 AM by trasp
 #1

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
1715638361
Hero Member
*
Offline Offline

Posts: 1715638361

View Profile Personal Message (Offline)

Ignore
1715638361
Reply with quote  #2

1715638361
Report to moderator
1715638361
Hero Member
*
Offline Offline

Posts: 1715638361

View Profile Personal Message (Offline)

Ignore
1715638361
Reply with quote  #2

1715638361
Report to moderator
Transactions must be included in a block to be properly completed. When you send a transaction, it is broadcast to miners. Miners can then optionally include it in their next blocks. Miners will be more inclined to include your transaction if it has a higher transaction fee.
Advertised sites are not endorsed by the Bitcoin Forum. They may be unsafe, untrustworthy, or illegal in your jurisdiction.
Chris Acheson
Sr. Member
****
Offline Offline

Activity: 266
Merit: 251


View Profile
September 27, 2011, 10:33:57 AM
 #2

Try this: https://github.com/ezl/mtgox
kokjo
Legendary
*
Offline Offline

Activity: 1050
Merit: 1000

You are WRONG!


View Profile
September 27, 2011, 10:43:08 AM
 #3

https://github.com/kokjo/MtGoxAPI

"The whole problem with the world is that fools and fanatics are always so certain of themselves and wiser people so full of doubts." -Bertrand Russell
trasp (OP)
Newbie
*
Offline Offline

Activity: 23
Merit: 0


View Profile
September 27, 2011, 04:14:47 PM
 #4

Both these examples is using the old mtgox API =(
semyazza
Sr. Member
****
Offline Offline

Activity: 339
Merit: 250


View Profile
September 28, 2011, 02:00:50 AM
 #5

Both these examples is using the old mtgox API =(

Here's another one using the old API.  Should be easy to change/get ideas from.

Code:
#!/usr/bin/env python

import simplejson
import urllib
import urllib2
import urlparse

market_depth_url = "http://mtgox.com/code/data/getDepth.php"
ticker_data_url = "http://mtgox.com/code/data/ticker.php"
recent_trades_url = "http://mtgox.com/code/data/getTrades.php"
current_balance_url = "https://mtgox.com/code/getFunds.php?name=blah&pass=blah"
buy_order_url = "https://mtgox.com/code/buyBTC.php?name=blah&pass=blah&amount=number&price=number"
sell_order_url = "https://mtgox.com/code/sellBTC.php?name=blah&pass=blah&amount=number&price=number"
open_order_url = "https://mtgox.com/code/getOrders.php?name=blah&pass=blah"
cancel_order_url = "https://mtgox.com/code/cancelOrder.php?name=blah&pass=blah&oid=number&type=number"
send_btc_url = "https://mtgox.com/code/withdraw.php?name=blah&pass=blah&group1=BTC&btca=bitcoin_address_to_send_to&amount=number"
checkout_url = "https://mtgox.com/merch/checkout"
verify_transaction_url = "https://mtgox.com/code/gateway/checkTxn.php"

def getBitcoinSellValue(quantity):
    data = simplejson.load(urllib2.urlopen(market_depth_url))
    data['bids'].sort(reverse=True)
   
    market_USD_value = 0
    total_bitcoins = 0
   
    for i in data['bids']:
        market_USD_value = market_USD_value + ((i[0]) * (i[1]))
        total_bitcoins = total_bitcoins + (i[1])
       
        if total_bitcoins >= quantity:
            bitcoin_value = market_USD_value / total_bitcoins
            return bitcoin_value


def getBitcoinBuyValue(quantity):
    data = simplejson.load(urllib2.urlopen(market_depth_url))
    data['asks'].sort()
   
    market_USD_value = 0
    total_bitcoins = 0
   
    for i in data['asks']:
        market_USD_value = market_USD_value + ((i[0]) * (i[1]))
        total_bitcoins = total_bitcoins + (i[1])
        if total_bitcoins >= quantity:
            bitcoin_value = market_USD_value / total_bitcoins
            return bitcoin_value

       
def createSellOrder(username, password, amount, price):
    format_url = urlparse.urlparse(sell_order_url)
    new_url = format_url.scheme + ":" + "//" + format_url.netloc + format_url.path
    query = urlparse.parse_qs(format_url.query)
   
    query['price'] = price
    query['amount'] = amount
    query['name'] = username
    query['pass'] = password
   
    f = urllib.urlopen(new_url, urllib.urlencode(query))
   
    return f.read()
   
   
def createBuyOrder(username, password, amount, price):
    format_url = urlparse.urlparse(buy_order_url)
    new_url = format_url.scheme + ":" + "//" + format_url.netloc + format_url.path
    query = urlparse.parse_qs(format_url.query)
   
    query['price'] = price
    query['amount'] = amount
    query['name'] = username
    query['pass'] = password
   
    f = urllib.urlopen(new_url, urllib.urlencode(query))
   
    return f.read()
   
   
def getBalance(username, password):
    format_url = urlparse.urlparse(current_balance_url)
    new_url = format_url.scheme + ":" + "//" + format_url.netloc + format_url.path
    query = urlparse.parse_qs(format_url.query)
   
    query['name'] = username
    query['pass'] = password
   
    f = urllib.urlopen(new_url, urllib.urlencode(query))
   
    return f.read()
   
   
def getOpenOrders(username, password):
    format_url = urlparse.urlparse(open_order_url)
    new_url = format_url.scheme + ":" + "//" + format_url.netloc + format_url.path
    query = urlparse.parse_qs(format_url.query)
   
    query['name'] = username
    query['pass'] = password
   
    f = urllib.urlopen(new_url, urllib.urlencode(query))
   
    return f.read()
   
   
def cancelOrder(username, password, orderid, type):
    format_url = urlparse.urlparse(cancel_order_url)
    new_url = format_url.scheme + ":" + "//" + format_url.netloc + format_url.path
    query = urlparse.parse_qs(format_url.query)
   
    query['oid'] = orderid
    query['type'] = type
    query['name'] = username
    query['pass'] = password
   
    f = urllib.urlopen(new_url, urllib.urlencode(query))
   
    return f.read()
   
   
def sendBTC(username, password, destination, amount):
    format_url = urlparse.urlparse(send_btc_url)
    new_url = format_url.scheme + ":" + "//" + format_url.netloc + format_url.path
    query = urlparse.parse_qs(format_url.query)
   
    query['btca'] = destination
    query['amount'] = amount
    query['name'] = username
    query['pass'] = password
    query['group1'] = 'BTC'
   
    f = urllib.urlopen(new_url, urllib.urlencode(query))
   
    return f.read()
   
def verifyTransaction(txn_id, merchID, amount):
    format_url = urlparse.urlparse(verify_transaction_url)
    new_url = format_url.scheme + ":" + "//" + format_url.netloc + format_url.path
    query = urlparse.parse_qs(format_url.query)
   
    query['txn_id'] = txn_id
    query['amount'] = amount
    query['merchID'] = merchID
   
    f = urllib.urlopen(new_url, urllib.urlencode(query))
   
    return f.read()

trasp (OP)
Newbie
*
Offline Offline

Activity: 23
Merit: 0


View Profile
September 28, 2011, 04:22:38 AM
 #6

Actually, I had it mostly right, I had managed to get the URL wrong and missed one parameter for urllib, which I'm now unsure if I really need or not. Big up to ahihi/Optonic (goxsh), your code helped me understanding this authentication-thing! (didn't fully understand that code currently on the wiki)

And thanks for the links and code Smiley
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!