From Bitcoin Wiki
Revision as of 09:11, 26 July 2011 by Ken (talk | contribs) (fixed ticker channel number, fixed ticker specification)
Jump to: navigation, search

The MtGox API provides various methods to access different informations from the market, place orders, and more.

Two APIs are available at this point: the HTTP api (available by posting to*) and the websocket API.

Number Formats

In the "old API", currency- and amount-values (price, volume,...) were given as float. These values are likely being deprecated and replaced by fields of the same name with "_int" as suffix. These are fixed-decimal, so you have to move the decimal point yourself (divide). The exponent differs based on the kind of the value.

In order to convert the int to a decimal you can...

kind of field ...divide by ...multiply by
BTC (volume, amount) 1E8 (10,000,000) 0.00000001
USD (price) 1E5 (100,000) 0.00001
JPY (price) 1E3 (1,000) 0.001

Implementation advice: it's probably best to use int or Decimal (if your language/db offers such a type) in your clients. Using float will likely lead to nasty rounding problems.


This API is available in*, and provides various informations. It also supports making an order, a withdraw, a deposit, etc. There is also a Perl module for interacting with the HTTP API.


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:


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, ''.$path);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	// 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

// old api (get funds)

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



This allows retrieving all trades which happened in the last 24 hours. The returned data is cached and may not reflect latest activity.


  • since: Passing a tid in "since" allows retrieving all trades since that trade. The passed id is may not exist. Ie. to get all trades from the very beginning one would just call . since returns only 100 trades, and you can call the method again by passing the latest trade you have imported in since.


Allows downloading the activity history for a given currency (BTC or USD for now).

Websocket API

ported on 7/10/2011 from


You can connect via: ws://

The WebSocket protocol version used is that described in draft-ietf-hybi-thewebsocketprotocol-00 (aka draft-00).


The websocket will subscribe you to some channels automatically:

Channel ID Description
dbf1dee9-4f2e-4a08-8cb7-748919a71b21 trades (each time a trade happens, you get something here)
d5f06780-30a8-4a48-a2f8-7ed181b4a13f the mtgox ticker (lots of updates, with often the same data)
24e67e0d-1cad-4cc0-9e7a-f8523ef460fe depth information in realtime (price + amount + type... type=1=Ask, type=2=Bid)

Additionally each user has a "own" channel which streams informations about orders (new order, deleted order, etc) and trades only the user's trades).

Each message is a JSON-encoded object, with at least "op" element. The "op" element contains the operation to be done (for outgoing messages), or the type of message (for incoming messages).

Possible outgoing commands

unsubscribe Stop receiving messages from a channel (parameter "channel")

Incoming Data



ticker contains the following:

Name Value
buy highest bid as float
sell lowest ask as float
high maximum rate since last close as float
low minimum rate since last close as float
vol traded volume since last close



trade contains the following:

Name Value
amount the traded amount in item (BTC), float, deprecated
amount_int the traded amount * 1E8
date unix timestamp of trade
item What was this trade about
price price per unit, float, deprecated
price_int price in smallest unit as integer (5 decimals of USD, 3 in case of JPY)
price_currency currency in which trade was completed
tid Trade id (big integer, which is in fact trade timestamp in microseconds)
trade_type Did this trade result from the execution of a bid or a ask?


Changes to the market depth data are broadcast so an up-to-date market depth can be kept by clients.


depth contains the following:

Name Value
currency the currency affected
item the item (BTC)
price price as a float, deprecated
price_int the price at which volume change happened (5 decimal for USD, 3 for JPY)
type 1=ask, 2=bid. deprecated, use type_str
type_str type of order at this depth, either "ask" or "bid"
volume the volume change as float, deprecated
volume_int volume change * 1E8

Order update (private)

  "channel":"(partial key)",

order_upd cointains the following:

Name Value
amount change in volume of the order
oid ID of the affected order