MtGox/API/HTTP

From Bitcoin Wiki
Revision as of 09:04, 16 April 2012 by Neofutur (talk | contribs) (→‎Java)
Jump to navigation Jump to search

Two versions of the HTTP API are currently available, see the following pages for details on the methods available for each:

Summary

All HTTP API requests are sent to URLs beginning with https://mtgox.com/api/*. It allows placing orders, performing withdrawls, deposits, and other things. All responses are in JSON format.

There is a Ruby gem, guten-mtgox and a Perl module available for interacting with the HTTP API.

Cache

All API methods are cached for 10 seconds. Do not request results more often than that, you might be blocked by the anti-DDoS filters.

Authentication

Authentication is performed by signing each request using HMAC-SHA512. The request must contain an extra value "nonce" which must be an always incrementing numeric value. A reference implementation is provided here:

Warning : the API is no more accepting authentication by login/pass ( since 2012 march 1 ) , you _need_ to use an API key.

PHP

<?php

function mtgox_query($path, array $req = array()) {
	// API settings
	$key = '';
	$secret = '';

	// generate a nonce as microtime, with as-string handling to avoid problems with 32bits systems
	$mt = explode(' ', microtime());
	$req['nonce'] = $mt[1].substr($mt[0], 2, 6);

	// generate the POST data string
	$post_data = http_build_query($req, '', '&');

	// generate the extra headers
	$headers = array(
		'Rest-Key: '.$key,
		'Rest-Sign: '.base64_encode(hash_hmac('sha512', $post_data, base64_decode($secret), true)),
	);

	// our curl handle (initialize if required)
	static $ch = null;
	if (is_null($ch)) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MtGox PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
	}
	curl_setopt($ch, CURLOPT_URL, 'https://mtgox.com/api/'.$path);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

	// run the query
	$res = curl_exec($ch);
	if ($res === false) throw new Exception('Could not get reply: '.curl_error($ch));
	$dec = json_decode($res, true);
	if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');
	return $dec;
}

// example 1: get infos about the account, plus the list of rights we have access to
var_dump(mtgox_query('0/info.php'));

// old api (get funds)
var_dump(mtgox_query('0/getFunds.php'));

// trade example
// var_dump(mtgox_query('0/buyBTC.php', array('amount' => 1, 'price' => 15)));

Python

Python version here: https://bitcointalk.org/index.php?topic=49789.msg592388#msg592388

Node.js

Generic trading library (supports MtGox and Bitfloor): https://github.com/bitfloor/trader.nodejs

var querystring = require('querystring'),
        https = require('https'),
        crypto = require('crypto');

function MtGoxClient(key, secret) {
        this.key = key;
        this.secret = secret;
}

MtGoxClient.prototype.query = function(path, args, callback) {
        var client = this;

        // if no args or invalid args provided, just reset the arg object
        if (typeof args != "object") args = {};

        // generate a nonce
        args['nonce'] = (new Date()).getTime() * 1000;
        // compute the post data
        var post = querystring.stringify(args);
        // compute the sha512 signature of the post data
        var hmac = crypto.createHmac('sha512', new Buffer(client.secret, 'base64'));
        hmac.update(post);

        // this is our query
        var options = {
                host: 'mtgox.com',
                port: 443,
                path: '/api/' + path,
                method: 'POST',
                agent: false,
                headers: {
                        'Rest-Key': client.key,
                        'Rest-Sign': hmac.digest('base64'),
                        'User-Agent': 'Mozilla/4.0 (compatible; MtGox node.js client)',
                        'Content-type': 'application/x-www-form-urlencoded'
                }
        };

        // run the query, buffer the data and call the callback
        var req = https.request(options, function(res) {
                res.setEncoding('utf8');
                var buffer = '';
                res.on('data', function(data) { buffer += data; });
                res.on('end', function() { if (typeof callback == "function") { callback(JSON.parse(buffer)); } });
        });

        // basic error management
        req.on('error', function(e) {
                console.log('warning: problem with request: ' + e.message);
        });

        // post the data
        req.write(post);
        req.end();
};

var client = new MtGoxClient('mykey', 'mysecret');
client.query('1/BTCUSD/public/ticker', {}, function(json) {
        // do something
        console.log(json);
});

Java

basic Java Example on https://gist.github.com/2396722 hoping for many java forks and pull requests on github