From Bitcoin Wiki
Revision as of 00:19, 18 November 2011 by Clark (talk | contribs) (Websocket API: Heavy update of streaming data section to include
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.

Currency Symbols

List of the currency symbols available with the API:



This API is available in*, and provides various informations. It also supports making an order, a withdraw, a deposit, etc. There is also a Ruby gem and 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)));

Python version here:


All of the API methods below have cached results, ticker, depth . . . have a 10 seconds cache . No need to poll more often, you wont have more results, you could just be blocked by the prolexic anti ddos features.

Methods API version 0


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.
  • data is returned in standard json format like :


Get the current Market depth


Get your current balance

getfunds is now deprecated since multi currency, please use info.php


Place an order to Buy BTC

POST data: amount=#&price=#&Currency=PLN

returns a list of your open orders

you can omit the price to do a market order


Place an order to Sell BTC

POST data: &amount=#&price=#&Currency=PLN

returns a list of your open orders

you can omit the price to do a market order


Fetch a list of your open Orders

oid: Order ID

type: 1 for sell order or 2 for buy order

status: 1 for active, 2 for not enough funds


Cancel an order

POST data: oid=#&type=#

oid: Order ID

type: 1 for sell order or 2 for buy order


Used to redeem a mtgox coupon code

  • call with a post parameter "code" containing the code to redeem
  • it will return an array with amount (float amount value of code), currency (3 letters, BTC or USD), reference (the transaction id), and status


withdraw / Send BTC

POST data: group1=BTC&btca=bitcoin_address_to_send_to&amount=#

  • pass btca parameter to withdraw to a btc adress
  • pass group1 for a coupon : BTC2CODE or USD2CODE
  • pass group1=DWUSD for a dwolla withdraw
  • pass green=1 to use the new greenaddress feature ( see GreenAddress )
  • return code and status if successful
To make a withdraw in another Currency , use group1=USD2CODE and add a Currency parameter ( example Currency=EUR to get a mtgox EUR coupon )


get a bitcoin deposit adress for your account

  • pass POST data "description" to add a description that will appear in your history when this BTC address receive a deposit
  • returns a bitcoin deposit address


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


returns info about your account, funds, fees, API privileges . . .


returns the current ticker :

the time frame for high, low, vol, avg, vwap . . . is sliding 24 hours

what is vwap ?

please see

API version 0 examples

all api shell type CLI

python :

perl :


https :

module perl :

gather data


bash :

perl :


Methods API version 1

Multi Currency Ticker
returns the current ticker for the selected currency :
 "high": {"value":"5.70653","value_int":"570653","display":"$5.70653","currency":"USD"},
 "low": {"value":"5.4145","value_int":"541450","display":"$5.41450","currency":"USD"},
 "avg": {"value":"5.561119626","value_int":"556112","display":"$5.56112","currency":"USD"},
 "vwap": {"value":"5.610480461","value_int":"561048","display":"$5.61048","currency":"USD"},

note : last_local include only the last trade in the selected currency, last_orig include data of the original last trade ( currency,price in currency . . . ),last can be a conversion of the last trde in another currency

Multi Currency depth

Multi currency trades

to get only the trades since a given trade id, you can add the parameter since=<trade_id>

For multi currency,also returns the primary value,"Y" or "N", the primary currency is always the buyers currency

A trade can appear in more than one currency, to ignore duplicates, use only the trades having primary =Y

example of returned data :


Cancelled Trades

returns a list of all the cancelled trades this last month, list of trade ids in json format .

Full Depth

returns full depth

Streaming API

Real time streaming data may be obtained over the streaming API, implemented in[1]. The original WebSocket API[2] is deprecated as of 11-Nov-2011.


The following JavaScript code establishes a connection in the browser:

<script src=""></script>
    var conn = io.connect('');
    conn.on('message', function(data) {
        // Handle incoming data object.

Handling Events exposes a simple interface for handling events. Handling message events is shown above, but there are other events that may be handled:

conn.on('connect',    onConnect);
conn.on('disconnect', onDisconnect);
conn.on('error',      onError);
conn.on('message',    onMessage);

Incoming Data

Data arrives as a full object instead of as JSON text, eliminating the need to parse the data in the JavaScript handler. Messages that come across the socket to trigger the message event will contain the following minimum components:


The OPERATION_TYPE field may take a few values:

subscribe Notification that the user is subscribed to a channel
unsubscribe Messages will no longer arrive over the channel
remark A server message, usually a warning
private The operation for depth, trade, and ticker messages

op:subscribe and op:unsubscribe

The subscribe and unsubscribe message data are very simple, containing the channel and the operation.

  "op":"subscribe" OR "unsubscribe"

Some of the channels are:

Channel ID Description
dbf1dee9-4f2e-4a08-8cb7-748919a71b21 Trades
d5f06780-30a8-4a48-a2f8-7ed181b4a13f Ticker
24e67e0d-1cad-4cc0-9e7a-f8523ef460fe Depth


The remark operation contains message and success fields.



The payloads of the op:private messages contain the real time market information. Each message follows this form:


The MESSAGE_TYPE field may take the values:

MESSAGE_TYPE Description
ticker Ticker messages
trade Trades, as they occur
depth Orders placed or removed


Ticker messages contain the current inside Bid and Ask as well as daily highs, lows, and volume. The fields contained in the ticker match those defined in the version 1.0 API above. All fields contain currency, display, value, and value_int entries.




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

Possible outgoing commands

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



javascript, using hookio :

Another node.js project, using plain websockets (largely based on cronopio's work) :