NAV
javascript go ruby

Introduction

The Bitfinex API’s are designed to allow access to all of the features of the Bitfinex platform. The end goal is to allow people to potentially recreate the entire platform on their own.

If you would like to suggest changes to the documentation, please see the github at https://github.com/bitfinexcom/api_docs

Open Source Libraries

The following open source projects are works in progress. We will be continually improving them, but we want to release them early so that the community can take a look, make use of them, and offer pull requests. Nothing in the Bitcoin world exists in isolation.

GO

Node.js

Ruby

API Access

In order to access the parts of the API which require authentication, you must generate an API key and an API secret using this page

You can generate as many API keys as you would like, and each of those keys can be customized in a few ways.

Permissions

Account Info

Account History

Orders

Margin Trading

Margin Funding

Wallets

Withdraw

REST

General

URL

var url = "https://api.bitfinex.com/v1"
var url = "https://api.bitfinex.com/v1/"

https://api.bitfinex.com/v1

Authentication

var payload = {
  "request": "/v1/account_infos",
  "nonce": Date.now().toString()
};
payload := map[string]interface{}{
    "request": "/v1/account_infos",
    "nonce":   fmt.Sprintf("%v", time.Now().Unix()*10000),
}
# add in your Gemfile
gem 'bitfinex-rb'
Bitfinex::Client.configure do |conf|
  conf.secret = ENV["BFX_API_SECRET"]
  conf.api_key = ENV["BFX_API_KEY"]
end
client = Bitfinex::Client.new
import "github.com/bitfinexcom/bitfinex-api-go"

client := bitfinex.NewClient().Auth(API_KEY, API_SECRET)

Authentication is done using an API key and a secret. To generate this pair, go to the API Access page. As an example of how to authenticate, we can look at the “account_infos” endpoint. Take the example payload to the right.

//Using the "request" library, available via npm.
//From the console, run npm install request
var
  request = require('request'),
  api_key = "<Your API key here>",
  api_secret = "<Your API secret here>";
payload = new Buffer(JSON.stringify(payload))
  .toString('base64');
var
  signature = crypto
  .createHmac("sha384", api_secret)
  .update(payload)
  .digest('hex'),
  headers = {
    'X-BFX-APIKEY': api_key,
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  options = {
    url: url + '/account_infos',
    headers: headers,
    body: payload
  };
request.post(options,
  function(error, response, body) {
    console.log(body);
});
// Full example of authenticated request
package main

import (
    "crypto/hmac"
    "crypto/sha512"
    "encoding/base64"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "time"
)

func main() {
    API_KEY := "..."
    API_SECRET := "..."

    url := "https://api.bitfinex.com/v1/"
    req, err := http.NewRequest("POST", url+"/account_infos", nil)
    if err != nil {
        log.Fatal(err)
    }

    payload := map[string]interface{}{
        "request": "/v1/account_infos",
        "nonce":   fmt.Sprintf("%v", time.Now().Unix()*10000),
    }

    payload_json, _ := json.Marshal(payload)
    payload_enc := base64.StdEncoding.EncodeToString(payload_json)

    sig := hmac.New(sha512.New384, []byte(API_SECRET))
    sig.Write([]byte(payload_enc))

    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Accept", "application/json")
    req.Header.Add("X-BFX-APIKEY", API_KEY)
    req.Header.Add("X-BFX-PAYLOAD", payload_enc)
    req.Header.Add("X-BFX-SIGNATURE", hex.EncodeToString(sig.Sum(nil)))

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(body))
}

The authentications procedures is as follows:

payload = parameters-object -> JSON encode -> base64

signature = HMAC-SHA384(payload, api-secret).digest('hex')

send (api-key, payload, signature)

These are encoded as HTTP headers named:

Parameters

Requests parameters for POST requests (authenticated) (presented below in the “Request” sections) are part of the PAYLOAD, not GET parameters.

Requests parameters for GET requests (non-authenticated) are GET parameters, appended to the URL being called as follows:

/v1/call/?parameter=value

Public Endpoints

// All examples assume the following:
// 1. You already have the request object available
// 2. You have the url variable
// 3. Will use BTCUSD as the default symbol
var request = require('request')
var url = "https://api.bitfinex.com/v1"

Ticker

// request
request.get(url + "/pubticker/:symbol",
  function(error, response, body) {
    console.log(body);
});
tick = client.ticker
// response
{
  "mid":"244.755",
  "bid":"244.75",
  "ask":"244.76",
  "last_price":"244.82",
  "low":"244.2",
  "high":"248.19",
  "volume":"7842.11542563",
  "timestamp":"1444253422.348340958"
}

Endpoint

/pubticker/:symbol

Description

Gives innermost bid and asks and information on the most recent trade, as well as high, low and volume of the last 24 hours.

Response Details

Key Type Description
mid [price] (bid + ask) / 2
bid [price] Innermost bid.
ask [price] Innermost ask.
last_price [price] The price at which the last order executed.
low [price] Lowest trade price of the last 24 hours
high [price] Highest trade price of the last 24 hours
volume [price] Trading volume of the last 24 hours
timestamp [time] The timestamp at which this information was valid.

Stats

// request
request.get(url + "/stats/BTCUSD",
  function(error, response, body) {
    console.log(body);
});
stats = client.stats
// response
[{
  "period":1,
  "volume":"7967.96766158"
},{
  "period":7,
  "volume":"55938.67260266"
},{
  "period":30,
  "volume":"275148.09653645"
}]

Endpoint

/stats/:symbol

Description

Various statistics about the requested pair.

Response Details An array of the following:

Key Type Description
period [integer] period covered in days
volume [price] volume

Fundingbook

// request
var payload = {
  "limit_bids": 1,
  "limit_asks": 1
};
var options = {
  url: url + '/lendbook/USD',
  qs: payload
};
request.get(options, function(error, response, body) {
  console.log(body);
});
 funding_book = client.funding_book
// response
{
  "bids":[{
    "rate":"9.1287",
    "amount":"5000.0",
    "period":30,
    "timestamp":"1444257541.0",
    "frr":"No"
  }],
  "asks":[{
    "rate":"8.3695",
    "amount":"407.5",
    "period":2,
    "timestamp":"1444260343.0",
    "frr":"No"
  }]
}

Endpoint

/lendbook/:currency

Description

Get the full margin funding book

Request Details

Key Required Type Default Description
limit_bids false [int] 50 Limit the number of funding bids returned. May be 0 in which case the array of bids is empty.
limit_asks false [int] 50 Limit the number of funding offers returned. May be 0 in which case the array of asks is empty.

Response Details

Key Type Description
bids [array of funding bids]
rate [rate in % per 365 days]
amount [decimal]
period [days] minimum period for the margin funding contract
timestamp [time]
frr [yes/no] “Yes” if the offer is at Flash Return Rate, “No” if the offer is at fixed rate
asks [array of funding offers]
rate [rate in % per 365 days]
amount [decimal]
period [days] maximum period for the funding contract
timestamp [time]
frr [yes/no] “Yes” if the offer is at Flash Return Rate, “No” if the offer is at fixed rate

Orderbook

// request
var payload = {
  "limit_bids": 1,
  "limit_asks": 1,
  "group": 0
};
var options = {
  url: url + '/book/BTCUSD',
  qs: payload
};
request.get(options, function(error, response, body) {
  console.log(body);
});
orderbook = client.orderbook
// response
{
  "bids":[{
    "price":"574.61",
    "amount":"0.1439327",
    "timestamp":"1472506127.0"
  }],
  "asks":[{
    "price":"574.62",
    "amount":"19.1334",
    "timestamp":"1472506126.0"
  }]
}

Endpoint

/book/:symbol

Description

Get the full order book.

Request Details

Key Required Type Default Description
limit_bids false [int] 50 Limit the number of bids returned. May be 0 in which case the array of bids is empty.
limit_asks false [int] 50 Limit the number of asks returned. May be 0 in which case the array of asks is empty.
group false [0/1] 1 If 1, orders are grouped by price in the orderbook. If 0, orders are not grouped and sorted individually

Response Details

Key Type
bids [array]
price [price]
amount [decimal]
timestamp [time]
asks [array]
price [price]
amount [decimal]
timestamp [time]

Trades

// request
var payload = {
  "timestamp": false,
  "limit_trades": 1
};
var options = {
  url: url + '/trades/BTCUSD',
  qs: payload
};
request.get(options, function(error, response, body) {
  console.log(body);
});
trades = client.trades
// response
[{
  "timestamp":1444266681,
  "tid":11988919,
  "price":"244.8",
  "amount":"0.03297384",
  "exchange":"bitfinex",
  "type":"sell"
}]

Endpoint

/trades/:symbol

Description

Get a list of the most recent trades for the given symbol.

Request Details

Key Required Type Default Description
timestamp false [time] Only show trades at or after this timestamp.
limit_trades false [int] 50 Limit the number of trades returned. Must be >= 1.

Response Details

Key Type Description
tid [integer]
timestamp [time]
price [price]
amount [decimal]
exchange [string]
type [string] “sell” or “buy” (can be “” if undetermined)

Lends

// request
var payload = {
  "timestamp": false,
  "limit_lends": 1
},
options = {
  url: url + '/lends/USD',
  qs: payload
};
request.get(options, function(error, response, body) {
  console.log(body);
});
lends = client.lends
// response
[{
  "rate":"9.8998",
  "amount_lent":"22528933.77950878",
  "amount_used":"0.0",
  "timestamp":1444264307
}]

Endpoint

/lends/:currency

Description

Get a list of the most recent funding data for the given currency: total amount provided and Flash Return Rate (in % by 365 days) over time.

Request Details

Key Required Type Default Description
timestamp false [time] Only show data at or after this timestamp.
limit_lends false [int] 50 Limit the amount of funding data returned. Must be >= 1

*Response Details

Key Type Description
rate [decimal, % by 365 days] Average rate of total funding received at fixed rates, ie past Flash Return Rate annualized
amount_lent [decimal] Total amount of open margin funding in the given currency
amount_used [decimal] Total amount of open margin funding used in a margin position in the given currency
timestamp [time]

Symbols

// request
var options = {
  url: url + '/symbols',
  qs: {}
};
request.get(options, function(error, response, body) {
  console.log(body);
});
symbols = client.symbols
// response
["btcusd","ltcusd","ltcbtc","ethusd", "ethbtc"]

Endpoint

/symbols

Description

Get a list of valid symbol IDs.

Response Details

A list of symbol names. Currently “btcusd”, “ltcusd”, “ltcbtc”, “ethusd”, “ethbtc”

Symbol Details

// request
var options = {
  url: url + '/symbols_details',
  qs: {}
};
request.get(options, function(error, response, body) {
  console.log(body);
});
symbols_details = client.symbols_details
// reponse
[{
  "pair":"btcusd",
  "price_precision":5,
  "initial_margin":"30.0",
  "minimum_margin":"15.0",
  "maximum_order_size":"2000.0",
  "minimum_order_size":"0.01",
  "expiration":"NA"
},{
  "pair":"ltcusd",
  "price_precision":5,
  "initial_margin":"30.0",
  "minimum_margin":"15.0",
  "maximum_order_size":"5000.0",
  "minimum_order_size":"0.1",
  "expiration":"NA"
},{
  "pair":"ltcbtc",
  "price_precision":5,
  "initial_margin":"30.0",
  "minimum_margin":"15.0",
  "maximum_order_size":"5000.0",
  "minimum_order_size":"0.1",
  "expiration":"NA"
},
...
...
]

Endpoint

/symbols_details

Description

Get a list of valid symbol IDs and the pair details.

Response Details

Key Type Description
pair [string] the pair code
price_precision [integer] Maximum number of significant digits for price in this pair
initial_margin [decimal] Initial margin required to open a position in this pair
minimum_margin [decimal] Minimal margin to maintain (in %)
maximum_order_size [decimal] Maximum order size of the pair
expiration [string] Expiration date for limited contracts/pairs

Authenticated Endpoints

// All examples assume the following:
// 1. You are using the provided example request object
// 2. You use your API key and secret
// 3. BTCUSD is the default symbol
var
  request = require('request'),
  api_key = "<Your API key>",
  api_secret = "<Your API secret>",
  baseRequest = request.defaults({
    headers: {
        'X-BFX-APIKEY': api_key,
    },
    baseUrl: "https://api.bitfinex.com/v1"
  });

Account Info

// request
var payload = {
  "request": "/v1/account_infos",
  "nonce": Date.now().toString()
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/account_infos",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
client.account_info
// response
[{
  "maker_fees":"0.1",
  "taker_fees":"0.2",
  "fees":[{
    "pairs":"BTC",
    "maker_fees":"0.1",
    "taker_fees":"0.2"
   },{
    "pairs":"LTC",
    "maker_fees":"0.1",
    "taker_fees":"0.2"
   },
   {
    "pairs":"DRK",
    "maker_fees":"0.1",
    "taker_fees":"0.2"
  }]
}]

Endpoint

/account_infos

Description

Return information about your account (trading fees).

Response Details

Key Type Description
pairs [string] The currency included in the pairs with this fee schedule
maker_fees [decimal] Your current fees for maker orders (limit orders not marketable, in percent)
taker_fees [decimal] Your current fees for taker orders (marketable order, in percent)

Summary

// request
var payload = {
  "request": "/v1/summary",
  "nonce": Date.now().toString(),
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/summary",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  }
  body: payload
}
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
client.summary
//response
{
  "trade_vol_30d":[
    {"curr":"BTC","vol":11.88696022},
    {"curr":"LTC","vol":0.0},
    {"curr":"ETH","vol":0.1},
    {"curr":"Total (USD)","vol":5027.63}
  ],
  "funding_profit_30d":[
    {"curr":"USD","amount":0.0},
    {"curr":"BTC","amount":0.0},
    {"curr":"LTC","amount":0.0},
    {"curr":"ETH","amount":0.0}
  ],
  "maker_fee":0.001,
  "taker_fee":0.002
}

Endpoint

/summary

Description

Returns a 30-day summary of your trading volume and return on margin funding

Response Details

Key Type Description
trade_vol_30d [string] Trading volumes for any currency for the last 30 days
funding_profit_30d [string] Funding profits for any currency for the last 30 days
maker_fees [decimal] Your current fees for maker orders (limit orders not marketable, in percent)
taker_fees [decimal] Your current fees for taker orders (marketable order, in percent)

Deposit

// request
var payload = {
  "request": "/v1/deposit/new",
  "nonce": Date.now().toString(),
  "method": "bitcoin",
  "wallet_name": "exchange",
  "renew": 0
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/deposit/new",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
new_address = client.deposit("bitcoin", "exchange")
// response
{
  "result":"success",
  "method":"bitcoin",
  "currency":"BTC",
  "address":"1A2wyHKJ4KWEoahDHVxwQy3kdd6g1qiSYV"
}

Endpoint

/deposit/new

Description

Return your deposit address to make a new deposit.

Request Details

Key Type Description
method [string] Method of deposit (methods accepted: “bitcoin”, “litecoin”, “ethereum”, “mastercoin” (tethers)).
wallet_name [string] Wallet to deposit in (accepted: “trading”, “exchange”, “deposit”). Your wallet needs to already exist
renew [integer] (optional) Default is 0. If set to 1, will return a new unused deposit address

Response Details

Key Type Description
result [string] “success” or “error”
method [string]
currency [string]
address [string] The deposit address (or error message if result = “error”)

Orders

New Order

// request
var payload = {
  "request": "/v1/order/new",
  "nonce": Date.now().toString(),
  "symbol": "BTCUSD",
  "amount":"0.01",
  "price": "0.01",
  "exchange": "bitfinex",
  "side": "buy",
  "type": "exchange limit"
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/order/new",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
client.new_order("usdbtc", 100, "market", "sell", 0)
// response
{
  "id":448364249,
  "symbol":"btcusd",
  "exchange":"bitfinex",
  "price":"0.01",
  "avg_execution_price":"0.0",
  "side":"buy",
  "type":"exchange limit",
  "timestamp":"1444272165.252370982",
  "is_live":true,
  "is_cancelled":false,
  "is_hidden":false,
  "was_forced":false,
  "original_amount":"0.01",
  "remaining_amount":"0.01",
  "executed_amount":"0.0",
  "order_id":448364249
}

Endpoint

/order/new

Description

Submit a new order.

Request Details

Key Type Description
symbol [string] The name of the symbol (see `/symbols`).
amount [decimal] Order size: how much to buy or sell.
price [price] Price to buy or sell at. Must be positive. Use random number for market orders.
exchange [string] “bitfinex”
side [string] Either “buy” or “sell”.
type [string] Either “market” / “limit” / “stop” / “trailing-stop” / “fill-or-kill” / “exchange market” / “exchange limit” / “exchange stop” / “exchange trailing-stop” / “exchange fill-or-kill”. (type starting by “exchange ” are exchange orders, others are margin trading orders)
is_hidden [bool] true if the order should be hidden. Default is false.
is_postonly [bool] true if the order should be post only. Default is false. Only relevant for limit orders.
use_all_available [int] Optional. default is 0. 1 will post an order that will use all of your available balance.
ocoorder [bool] Set an additional STOP OCO order that will be linked with the current order.
buy_price_oco [price] If ocoorder is true, this field represent the price of the OCO stop order to place

Response Details

Key Type Description
order_id [int] An order object containing the order’s ID as well as all the information provided by /order/status

Order Types

Margin trading type Exchange type
LIMIT EXCHANGE LIMIT
MARKET EXCHANGE MARKET
STOP EXCHANGE STOP
TRAILING STOP EXCHANGE TRAILING STOP
FILL-OR-KILL EXCHANGE FILL-OR-KILL

Multiple new orders

// request
var payload = {
  "request": "/v1/order/new/multi",
  "nonce": Date.now().toString(),
  "orders": [{
    "symbol": "BTCUSD",
    "amount": "0.01",
    "price": "0.01",
    "exchange": "bitfinex",
    "side": "buy",
    "type": "exchange limit"
  },{
    "symbol": "BTCUSD",
    "amount": "0.02",
    "price": "0.03",
    "exchange": "bitfinex",
    "side": "buy",
    "type": "exchange limit"
  }]
};

payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
    url: "/order/new/multi",
    headers: {
        'X-BFX-PAYLOAD': payload,
        'X-BFX-SIGNATURE': signature
    },
    body: payload
};
baseRequest.post(options, function (error, response, body) {
    console.log(body);
});
response = client.multiple_orders([{symbol: "btcusd", amount: 10, price: 0, exchange: "bitfinex", side: "buy", type: "market"}])
// response
{
  "order_ids":[{
    "id":448383727,
    "symbol":"btcusd",
    "exchange":"bitfinex",
    "price":"0.01",
    "avg_execution_price":"0.0",
    "side":"buy",
    "type":"exchange limit",
    "timestamp":"1444274013.621701916",
    "is_live":true,
    "is_cancelled":false,
    "is_hidden":false,
    "was_forced":false,
    "original_amount":"0.01",
    "remaining_amount":"0.01",
    "executed_amount":"0.0"
  },{
    "id":448383729,
    "symbol":"btcusd",
    "exchange":"bitfinex",
    "price":"0.03",
    "avg_execution_price":"0.0",
    "side":"buy",
    "type":"exchange limit",
    "timestamp":"1444274013.661297306",
    "is_live":true,
    "is_cancelled":false,
    "is_hidden":false,
    "was_forced":false,
    "original_amount":"0.02",
    "remaining_amount":"0.02",
    "executed_amount":"0.0"
  }],
  "status":"success"
}

Endpoint

/order/new/multi

Description

Submit several new orders at once.

Request Details

Key Type Description
symbol [string] The name of the symbol (see `/symbols`).
amount [decimal] Order size: how much to buy or sell.
price [price] Price to buy or sell at. May omit if a market order.
exchange [string] “bitfinex”, “bitstamp”, “all” (for no routing).
side [string] Either “buy” or “sell”.
type [string] Either “market” / “limit” / “stop” / “trailing-stop” / “fill-or-kill”.

Response Details

Key Type Description
order_ids [array] An array of order objects each having their own unique ID, as well as the information given by /order/status for each of the orders opened.

Cancel order

// request
var payload = {
  "request": "/v1/order/cancel",
  "nonce": Date.now().toString(),
  "order_id": 448364249
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/order/cancel",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function (error, response, body) {
  console.log(body);
});
response = client.cancel_orders(448364249)
// response
{
  "id":446915287,
  "symbol":"btcusd",
  "exchange":null,
  "price":"239.0",
  "avg_execution_price":"0.0",
  "side":"sell",
  "type":"trailing stop",
  "timestamp":"1444141982.0",
  "is_live":true,
  "is_cancelled":false,
  "is_hidden":false,
  "was_forced":false,
  "original_amount":"1.0",
  "remaining_amount":"1.0",
  "executed_amount":"0.0"
}

Endpoint

/order/cancel

Description

Cancel an order.

Request Details

Key Type Description
order_id [int] The order ID given by `/order/new`.

Response Details

Result of /order/status for the cancelled order.

Cancel multiple orders

// request
var payload = {
  "request": "/v1/order/cancel/multi",
  "nonce": Date.now().toString(),
  "order_ids": [448402101, 448402099]
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/order/cancel/multi",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function (error, response, body) {
  console.log(body);
});
response = client.cancel_orders([448402101, 448402099])
// response
{"result":"Orders cancelled"}

Endpoint

/order/cancel/multi

Description

Cancel multiples orders at once.

Request Details

Key Type Description
order_ids [array] An array of the order IDs given by `/order/new` or `/order/new/multi`

Response Details

Confirmation of cancellation of the orders.

Cancel all orders

// request
var payload = {
  "request": "/v1/order/cancel/all",
  "nonce": Date.now().toString()
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/order/cancel/all",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function (error, response, body) {
  console.log(body);
});
response = client.cancel_orders
// response
{"result":"All orders cancelled"}

Endpoint

/order/cancel/all

Description

Cancel all active orders at once.

Request Details

No arguments required

Response Details

Confirmation of cancellation of the orders.

Replace order

// request
var payload = {
  "order_id": 448411153,
  "request": "/v1/order/cancel/replace",
  "nonce": Date.now().toString(),
  "symbol": "BTCUSD",
  "amount":"0.02",
  "price": "0.02",
  "exchange": "bitfinex",
  "side": "buy",
  "type": "exchange limit",
  "use_remaining": false
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/order/cancel/replace",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
})
response = client.replace_order(100,"usdbtc", 10, "market", "buy", 0)
// response
{
  "id":448411365,
  "symbol":"btcusd",
  "exchange":"bitfinex",
  "price":"0.02",
  "avg_execution_price":"0.0",
  "side":"buy",
  "type":"exchange limit",
  "timestamp":"1444276597.691580782",
  "is_live":true,
  "is_cancelled":false,
  "is_hidden":false,
  "was_forced":false,
  "original_amount":"0.02",
  "remaining_amount":"0.02",
  "executed_amount":"0.0",
  "order_id":448411365
}

Endpoint

/order/cancel/replace

Description

Replace an orders with a new one.

Request Details

Key Type Description
order_id [int] The order ID (to be replaced) given by `/order/new`.
symbol [string] The name of the symbol (see `/symbols`).
amount [decimal] Order size: how much to buy or sell.
price [price] Price to buy or sell at. May omit if a market order.
exchange [string] “bitfinex”, “bitstamp”, “all” (for no routing).
side [string] Either “buy” or “sell”.
type [string] Either “market” / “limit” / “stop” / “trailing-stop” / “fill-or-kill” / “exchange market” / “exchange limit” / “exchange stop” / “exchange trailing-stop” / “exchange fill-or-kill”. (type starting by “exchange ” are exchange orders, others are margin trading orders)
is_hidden [bool] true if the order should be hidden. Default is false.
use_remaining [bool] True if the new order should use the remaining amount of the original order. Default is false

Response Details

Key Type Description
order_id [int] A randomly generated ID for the order and the information given by /order/status.

Order status

// request
var payload = {
  "order_id": 448411153,
  "request": "/v1/order/status",
  "nonce": Date.now().toString()
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/order/status",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.order_status(448411153)
// response
{
  "id":448411153,
  "symbol":"btcusd",
  "exchange":null,
  "price":"0.01",
  "avg_execution_price":"0.0",
  "side":"buy",
  "type":"exchange limit",
  "timestamp":"1444276570.0",
  "is_live":false,
  "is_cancelled":true,
  "is_hidden":false,
  "oco_order":null,
  "was_forced":false,
  "original_amount":"0.01",
  "remaining_amount":"0.01",
  "executed_amount":"0.0"
}

Endpoint

/order/status

Description

Get the status of an order. Is it active? Was it cancelled? To what extent has it been executed? etc.

Request Details

Key Type Description
order_id [int] The order ID given by `/order/new`

Response Details

Key Type Description
symbol [string] The symbol name the order belongs to.
exchange [string] “bitfinex”, “bitstamp”.
price [decimal] The price the order was issued at (can be null for market orders).
avg_execution_price [decimal] The average price at which this order as been executed so far. 0 if the order has not been executed at all.
side [string] Either “buy” or “sell”.
type [string] Either “market” / “limit” / “stop” / “trailing-stop”.
timestamp [time] The timestamp the order was submitted.
is_live [bool] Could the order still be filled?
is_cancelled [bool] Has the order been cancelled?
is_hidden [bool] Is the order hidden?
oco_order [integer] If the order is an OCO order, the ID of the linked order. Otherwise, null
was_forced [bool] For margin only true if it was forced by the system.
executed_amount [decimal] How much of the order has been executed so far in its history?
remaining_amount [decimal] How much is still remaining to be submitted?
original_amount [decimal] What was the order originally submitted for?

Active orders

// request
var payload = {
  "request": "/v1/orders",
  "nonce": Date.now().toString()
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/orders",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.orders
// response
[{
  "id":448411365,
  "symbol":"btcusd",
  "exchange":"bitfinex",
  "price":"0.02",
  "avg_execution_price":"0.0",
  "side":"buy",
  "type":"exchange limit",
  "timestamp":"1444276597.0",
  "is_live":true,
  "is_cancelled":false,
  "is_hidden":false,
  "was_forced":false,
  "original_amount":"0.02",
  "remaining_amount":"0.02",
  "executed_amount":"0.0"
}]

Endpoint

/orders

Description

View your active orders.

Response Details

An array of the results of /order/status for all your live orders.

Positions

Active Positions

// request
var payload = {
  "request": "/v1/positions",
  "nonce": Date.now().toString()
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/positions",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.positions
// response
[{
  "id":943715,
  "symbol":"btcusd",
  "status":"ACTIVE",
  "base":"246.94",
  "amount":"1.0",
  "timestamp":"1444141857.0",
  "swap":"0.0",
  "pl":"-2.22042"
}]

Endpoint

/positions

Description

View your active positions.

Response Details

An array of your active positions.

Claim position

// request
var payload = {
  "request": "/v1/position/claim",
  "nonce": Date.now().toString(),
  "position_id": 943715
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/position/claim",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
client.claim_position(100,10)
// response
{
  "id":943715,
  "symbol":"btcusd",
  "status":"ACTIVE",
  "base":"246.94",
  "amount":"1.0",
  "timestamp":"1444141857.0",
  "swap":"0.0",
  "pl":"-2.2304"
}

Endpoint

/position/claim

Description

A position can be claimed if:

It is a long position: The amount in the last unit of the position pair that you have in your trading wallet AND/OR the realized profit of the position is greater or equal to the purchase amount of the position (base price * position amount) and the funds which need to be returned. For example, for a long BTCUSD position, you can claim the position if the amount of USD you have in the trading wallet is greater than the base price * the position amount and the funds used.

It is a short position: The amount in the first unit of the position pair that you have in your trading wallet is greater or equal to the amount of the position and the margin funding used.

Request Details

Key Type Description
position_id [int] The position ID given by `/positions`.
amount [decimal] The partial amount you wish to claim

Response Details

Status of the position for the claimed position, if the position could be claimed.

Historical Data

Balance History

// request
var payload = {
  "request": "/v1/history",
  "nonce": Date.now().toString(),
  "currency": "USD",
  "limit": 1
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/history",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.history
// response
[{
  "currency":"USD",
  "amount":"-246.94",
  "balance":"515.4476526",
  "description":"Position claimed @ 245.2 on wallet trading",
  "timestamp":"1444277602.0"
}]

Endpoint

/history

Description

View all of your balance ledger entries.

Request Details

Key Type Description
currency [string] The currency to look for.
since [time] Optional. Return only the history after this timestamp.
until [time] Optional. Return only the history before this timestamp.
limit [int] Optional. Limit the number of entries to return. Default is 500.
wallet [string] Optional. Return only entries that took place in this wallet. Accepted inputs are: “trading”, “exchange”, “deposit”.

Response Details

Key Type Description
currency [string] Currency
amount [decimal] Positive (credit) or negative (debit)
balance [decimal] Wallet balance after the current entry
description [string] Description of the entry. Includes the wallet in which the operation took place
timestamp [time] Timestamp of the entry

Deposit-Withdrawal History

// request
var payload = {
  "request": "/v1/history/movements",
  "nonce": Date.now().toString(),
  "currency": "BTC",
  "limit": 1
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/history/movements",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
reponse = client.movements
// response
[{
  "id":581183,
  "currency":"BTC",
  "method":"BITCOIN",
  "type":"WITHDRAWAL",
  "amount":".01",
  "description":"3QXYWgRGX2BPYBpUDBssGbeWEa5zq6snBZ, offchain transfer ",
  "address":"3QXYWgRGX2BPYBpUDBssGbeWEa5zq6snBZ",
  "status":"COMPLETED",
  "timestamp":"1443833327.0"
}]

Endpoint

/history/movements

Description

View your past deposits/withdrawals.

Request Details

Key Type Description
currency [string] The currency to look for.
method [string] Optional. The method of the deposit/withdrawal (can be “bitcoin”, “litecoin”, “darkcoin”, “wire”).
since [time] Optional. Return only the history after this timestamp.
until [time] Optional. Return only the history before this timestamp.
limit [int] Optional. Limit the number of entries to return. Default is 500.

Response Details

An array of histories

Key Type Description
currency [string]
method [string]
type [string]
amount [decimal] Absolute value of the movement
description [string] Description of the movement (txid, destination address,,,,)
address [string] Deposit address used or withdrawal destination address
status [string] Status of the movement
timestamp [time] Timestamp of the movement

Past Trades

// request
var payload = {
  "request": "/v1/mytrades",
  "nonce": Date.now().toString(),
  "symbol": "BTCUSD",
  "limit_trades": 1
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/mytrades",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.mytrades

Response

// response
[{
  "price":"246.94",
  "amount":"1.0",
  "timestamp":"1444141857.0",
  "exchange":"",
  "type":"Buy",
  "fee_currency":"USD",
  "fee_amount":"-0.49388",
  "tid":11970839,
  "order_id":446913929
}]

Endpoint

/mytrades

Description

View your past trades.

Request Details

Key Type Description
symbol [string] The pair traded (BTCUSD, …).
timestamp [time] Trades made before this timestamp won’t be returned.
until [time] Optional. Trades made after this timestamp won’t be returned.
limit_trades [int] Optional. Limit the number of trades returned. Default is 50.
reverse [int] Optional. Return trades in reverse order (the oldest comes first). Default is returning newest trades first.

Response Details

An array of trades

Key Type Description
price [price]
amount [decimal]
exchange [string]
type [string] Sell or Buy
fee_currency [string] Currency you paid this trade’s fee in
fee_amount [decimal] Amount of fees you paid for this trade
tid [integer] unique identification number of the trade
order_id [integer] unique identification number of the parent order of the trade

Margin Funding

New Offer

// request
var payload = {
  "request": "/v1/offer/new",
  "nonce": Date.now().toString(),
  "currency": "USD",
  "amount": "50.00",
  "rate": "20",
  "period": 2,
  "direction": "lend"
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/offer/new",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.new_offer("btc", 10.0, 20, 365, "lend")
// response
{
  "id":13800585,
  "currency":"USD",
  "rate":"20.0",
  "period":2,
  "direction":"lend",
  "timestamp":"1444279698.21175971",
  "is_live":true,
  "is_cancelled":false,
  "original_amount":"50.0",
  "remaining_amount":"50.0",
  "executed_amount":"0.0",
  "offer_id":13800585
}

Endpoint

/offer/new

Description

Submit a new offer.

Request Details

Key Type Description
currency [string] The name of the currency.
amount [decimal] Offer size: how much to lend or borrow.
rate [decimal] Rate to lend or borrow at. In percentage per 365 days. (Set to 0 for FRR).
period [integer] Number of days of the funding contract (in days)
direction [string] Either “lend” or “loan”.

Response Details

Key Type Description
id [int] A randomly generated ID for the offer and the information given by /offer/status
currency [string] The name of the currency.
rate [decimal] Rate to lend or borrow at. In percentage per 365 days. (Set to 0 for FRR).
period [integer] Number of days of the funding contract (in days)
direction [string] Either “lend” or “loan”.
is_live [bool] Could the offer still be filled?
is_cancelled [bool] Has the offer been cancelled?
executed_amount [decimal] How much of the offer has been executed so far in its history?
remaining_amount [decimal] How much is still remaining to be submitted?
original_amount [decimal] What was the offer originally submitted for?

Cancel Offer

// request
var payload = {
  "request": "/v1/offer/cancel",
  "nonce": Date.now().toString(),
  "offer_id": 13800585
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/offer/cancel",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
    console.log(body);
});
response = client.cancel_offer(1000)
// response
{
  "id":13800585,
  "currency":"USD",
  "rate":"20.0",
  "period":2,
  "direction":"lend",
  "timestamp":"1444279698.0",
  "is_live":true,
  "is_cancelled":false,
  "original_amount":"50.0",
  "remaining_amount":"50.0",
  "executed_amount":"0.0"
}

Endpoint

/offer/cancel

Description

Cancel an offer.

Request Details

Key Type Description
offer_id [int] The offer ID given by `/offer/new`.

Response Details

Result of /offer/status for the cancelled offer.

Offer Status

// request
var payload = {
  "request": "/v1/offer/status",
  "nonce": Date.now().toString(),
  "offer_id": 13800585
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/offer/status",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.offer_status(1000)
// response
{
  "id":13800585,
  "currency":"USD",
  "rate":"20.0",
  "period":2,
  "direction":"lend",
  "timestamp":"1444279698.0",
  "is_live":false,
  "is_cancelled":true,
  "original_amount":"50.0",
  "remaining_amount":"50.0",
  "executed_amount":"0.0"
}

Endpoint

/offer/status

Description

Get the status of an offer. Is it active? Was it cancelled? To what extent has it been executed? etc.

Request Details

Key Type Description
offer_id [int] The offer ID given by `/offer/new`.

Response Details

Key Type Description
currency [string] The currency name of the offer.
rate [decimal] The rate the offer was issued at (in % per 365 days).
period [integer] The number of days of the offer.
direction [string] Either “lend” or “loan”.
type [string] Either “market” / “limit” / “stop” / “trailing-stop”.
timestamp [time] The timestamp the offer was submitted.
is_live [bool] Could the offer still be filled?
is_cancelled [bool] Has the offer been cancelled?
executed_amount [decimal] How much of the offer has been executed so far in its history?
remaining_amount [decimal] How much is still remaining to be submitted?
original_amount [decimal] What was the offer originally submitted for?

Active Credits

// request
var payload = {
  "request": "/v1/credits",
  "nonce": Date.now().toString(),
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/credits",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.credits
// response
[{
  "id":13800719,
  "currency":"USD",
  "rate":"31.39",
  "period":2,
  "direction":"lend",
  "timestamp":"1444280237.0",
  "is_live":true,
  "is_cancelled":false,
  "original_amount":"50.0",
  "remaining_amount":"50.0",
  "executed_amount":"0.0"
}]

Endpoint

/credits

Description

View your funds currently taken (active credits).

Response Details

An array of your active credits

Offers

// request
var payload = {
  "request": "/v1/offers",
  "nonce": Date.now().toString(),
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/offers",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.offers
// response
[{
  "id":13800719,
  "currency":"USD",
  "rate":"31.39",
  "period":2,
  "direction":"lend",
  "timestamp":"1444280237.0",
  "is_live":true,
  "is_cancelled":false,
  "original_amount":"50.0",
  "remaining_amount":"50.0",
  "executed_amount":"0.0"
}]

Endpoint

/offers

Description

View your active offers.

Response Details

An array of the results of /offer/status for all your live offers (lending or borrowing).

Active funding used in a margin position

// request
var payload = {
  "request": "/v1/taken_funds",
  "nonce": Date.now().toString(),
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/taken_funds",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.taken_funds
// response
[{
  "id":11576737,
  "position_id":944309,
  "currency":"USD",
  "rate":"9.8874",
  "period":2,
  "amount":"34.24603414",
  "timestamp":"1444280948.0",
  "auto_close":false
}]

Endpoint

/taken_funds

Description

View your funding currently borrowed and used in a margin position.

Response Details

An array of your active margin funds.

Active funding not used in a margin position

// request
var payload = {
  "request": "/v1/unused_taken_funds",
  "nonce": Date.now().toString(),
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/taken_funds",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.unused_taken_funds
// response
[{
  "id":11576737,
  "position_id":944309,
  "currency":"USD",
  "rate":"9.8874",
  "period":2,
  "amount":"34.24603414",
  "timestamp":"1444280948.0",
  "auto_close":false
}]

Endpoint

/unused_taken_funds

Description

View your funding currently borrowed and not used (available for a new margin position).

Response Details

An array of your active unused margin funds.

Total taken funds

// request
var payload = {
  "request": "/v1/total_taken_funds",
  "nonce": Date.now().toString(),
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/total_taken_funds",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.total_taken_funds
// response
[{
  "position_pair":"BTCUSD",
  "total_swaps":"34.24603414"
}]

Endpoint

/total_taken_funds

Description

View the total of your active funding used in your position(s).

Response Details

Key Type Description
position_pair [string] Pair of the position
total_swaps [decimal] Sum of the active funding backing this position

Close margin funding

// request
var payload = {
  "request": "/v1/funding/close",
  "nonce": Date.now().toString(),
  "swap_id": 11576737
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/funding/close",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.close_funding(1000)
// response
{
  "id":11576737,
  "position_id":944309,
  "currency":"USD",
  "rate":"9.8874",
  "period":2,
  "amount":"34.24603414",
  "timestamp":"1444280948.0",
  "auto_close":false
}

Endpoint

/funding/close

Description

Allow you to close an unused or used taken fund

Request Details

Key Type Description
swap_id [int] The ID given by `/taken_funds` or `/unused_taken_funds`.

Response Details

Status of the margin funding contract. Closed if it could be closed.

Wallet Balances

// request
var payload = {
  "request": "/v1/balances",
  "nonce": Date.now().toString()
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/balances",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.balances
// response
[{
  "type":"deposit",
  "currency":"btc",
  "amount":"0.0",
  "available":"0.0"
},{
  "type":"deposit",
  "currency":"usd",
  "amount":"1.0",
  "available":"1.0"
},{
  "type":"exchange",
  "currency":"btc",
  "amount":"1",
  "available":"1"
},{
  "type":"exchange",
  "currency":"usd",
  "amount":"1",
  "available":"1"
},{
  "type":"trading",
  "currency":"btc",
  "amount":"1",
  "available":"1"
},{
  "type":"trading",
  "currency":"usd",
  "amount":"1",
  "available":"1"
}]

Endpoint

/balances

Description

See your balances.

Response Details

An array of wallet balances

Key Type Description
type [string] “trading”, “deposit” or “exchange”.
currency [string] Currency
amount [decimal] How much balance of this currency in this wallet
available [decimal] How much X there is in this wallet that is available to trade.

Margin Information

// request
var payload = {
  "request": "/v1/margin_infos",
  "nonce": Date.now().toString()
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/margin_infos",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.margin_infos
// response
[{
  "margin_balance":"14.80039951",
  "tradable_balance":"-12.50620089",
  "unrealized_pl":"-0.18392",
  "unrealized_swap":"-0.00038653",
  "net_value":"14.61609298",
  "required_margin":"7.3569",
  "leverage":"2.5",
  "margin_requirement":"13.0",
  "margin_limits":[{
    "on_pair":"BTCUSD",
    "initial_margin":"30.0",
    "margin_requirement":"15.0",
    "tradable_balance":"-0.329243259666666667"
  }],
  "message": "Margin requirement, leverage and tradable balance are now per pair. You will find them under margin_limits, for each pair. Please update your code as soon as possible."
}]

Endpoint

/margin_infos

Description

See your trading wallet information for margin trading.

Response Details

Key Type Description
margin_balance [decimal] the USD value of all your trading assets (based on last prices)
unrealized_pl [decimal] The unrealized profit/loss of all your open positions
unrealized_swap [decimal] The margin funding used by all your open positions
net_value [decimal] Your net value (the USD value of your trading wallet, including your margin balance, your unrealized P/L and margin funding)
required_margin [decimal] The minimum net value to maintain in your trading wallet, under which all of your positions are fully liquidated
margin_limits [array] The list of margin limits for each pair. The array gives you the following information, for each pair:
on_pair [string] The pair for which these limits are valid
initial_margin [decimal] The minimum margin (in %) to maintain to open or increase a position
tradable_balance [decimal] Your tradable balance in USD (the maximum size you can open on leverage for this pair)
margin_requirements [decimal] The maintenance margin (% of the USD value of all of your open positions in the current pair to maintain)

Transfer Between Wallets

// request
var payload = {
  "request": "/v1/transfer",
  "nonce": Date.now().toString(),
  "amount": "1.0",
  "currency": "USD",
  "walletfrom": "exchange",
  "walletto": "deposit"
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/transfer",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.transfer(10, 'btc', "exchange", "deposit")
// response
[{
  "status":"success",
  "message":"1.0 USD transfered from Exchange to Deposit"
}]

Endpoint

/transfer

Description

Allow you to move available balances between your wallets.

Request Details

Key Type Description
amount [decimal] Amount to transfer.
currency [string] Currency of funds to transfer.
walletfrom [string] Wallet to transfer from.
walletto [string] Wallet to transfer to.

Response Details

Key Type Description
status [string] “success” or “error”.
message [string] Success or error message

Withdrawal

// request
var payload = {
  "request": "/v1/withdraw",
  "nonce": Date.now().toString(),
  "amount": "0.01",
  "withdraw_type": "bitcoin",
  "walletselected": "exchange",
  "address": "1DKwqRhDmVyHJDL4FUYpDmQMYA3Rsxtvur"
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/withdraw",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  },
  body: payload
};
baseRequest.post(options, function(error, response, body) {
  console.log(body);
});
response = client.withdraw("bitcoin","deposit",1000, address: "1DKwqRhDmVyHJDL4FUYpDmQMYA3Rsxtvur")
// response
[{
  "status":"success",
  "message":"Your withdrawal request has been successfully submitted.",
  "withdrawal_id":586829
}]

Endpoint

/withdraw

Description

Allow you to request a withdrawal from one of your wallet.

Request Details

Key Type Description
withdraw_type [string] can be “bitcoin”, “litecoin” or “ethereum” or “tether” or “wire”.
walletselected [string] The wallet to withdraw from, can be “trading”, “exchange”, or “deposit”.
amount [string] Amount to withdraw.
For cryptocurrencies withdrawals (including “tether”)
address [string] Destination address for withdrawal.
For wire withdrawals
expressWire [int] Optional. “1” to submit an express wire withdrawal, “0” or omit for a normal withdrawal
account_name [string] Account name
account_number [string] Account number
bank_name [string] Bank name
bank_address [string] Bank address
bank_city [string] Bank city
bank_country [string] Bank country
detail_payment [string] Optional. Message to beneficiary
intermediary_bank_name [string] Optional. Intermediary bank name
intermediary_bank_address [string] Optional. Intermediary bank address
intermediary_bank_city [string] Optional. Intermediary bank city
intermediary_bank_country [string] Optional. Intermediary bank country
intermediary_bank_account [string] Optional. Intermediary bank account
intermediary_bank_swift [string] Optional. Intermediary bank SWIFT

Request Details

Key Type Description
status [string] “success” or “error”.
message [string] Success or error message
withdrawal_id [int] ID of the withdrawal (0 if unsuccessful)

Key Permissions

Request

var payload = {
  "request": "/v1/key_info",
  "nonce": Date.now().toString()
};
payload = new Buffer(JSON.stringify(payload)).toString('base64');
var signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
var options = {
  url: "/key_info",
  headers: {
    'X-BFX-PAYLOAD': payload,
    'X-BFX-SIGNATURE': signature
  }
};
baseRequest.get(options, function(error, response, body) {
  console.log(body);
});
response = client.key_info

Response

{
"account":{
"read":true,
"write":false
},
"history":{
"read":true,
"write":false
},
"orders":{
"read":true,
"write":true
},
"positions":{
"read":true,
"write":true
},
"funding":{
"read":true,
"write":true
},
"wallets":{
"read":true,
"write":true
},
"withdraw":{
"read":null,
"write":null
}
}

Endpoint

/key_info

Description

Check the permissions of the key being used to generate this request

Request Details

No additional params

Response Details

A JSON object with a key for each of the possible permissions whose value is another JSON object with both a read and write key which has a value of true or false

Websocket

General

Current Version

Bitfinex Websocket API current version is 1.1

Changelog

v1.2 (dev)

v1.1

v1.0 Initial Release

SSL Websocket Connection

URI: wss://api2.bitfinex.com:3000/ws

Message encoding

Each message sent and received via the Bitfinex’s websocket channel is encoded in JSON format

Supported Pairs

BTCUSD, LTCUSD, LTCBTC, ETHUSD, ETHBTC

Public Channels

Authenticated Channels

How to Connect

Open up a websocket connection to the websocket URI.

//using the ws library
var WebSocket = require('ws');
var w = new WebSocket("wss://api2.bitfinex.com:3000/ws");
w.onmessage = function(msg) {
    console.log(msg.data);
};
import (
    "code.google.com/p/go.net/websocket"
)

ws, err := websocket.Dial("wss://api2.bitfinex.com:3000/ws", "", "http://localhost/")
if err != nil {
    return err
}

Error Codes

In case of error, you receive a message containing the proper error code (code JSON field).

Info Messages

{
   "event":"info",
   "version": 1
}

Info messages are sent from the websocket server to notify the state of your connection. Right after connecting you receive an info message that contains the actual version of the websocket stream.

{
   "event":"info",
   "code": "<CODE>",
   "msg": "<MSG>"
}

Websocket server sends other info messages to inform regarding relevant events.

Ping/Pong

// request
{
   "event":"ping"
}

// response
{
   "event":"pong"
}

Use ping message to test your connection to the websocket server.

Subscribe to Channels

// request
{
   "event":"subscribe",
   "channel":"CHANNEL_NAME"
}

// response
{
   "event":"subscribed",
   "channel":"CHANNEL_NAME",
   "chanId":"<CHANNEL_ID>"
}

// response-failure
{
   "event":"error",
   "msg":"<ERROR_MSG>",
   "code":"<ERROR_CODE>"
}

To receive data from a channel you have to send a “subscribe” message first.

Heartbeating

["<Chan Id>", "hb"]

If there is no new message in the channel for 1 second, Websocket server will send you an heartbeat message in this format.

Snapshot

["<Chan Id>",
  ["<Group of Update Messages>",
    ["<Update Message>"]
  ]
]

Upon subscribing to a channel an initial snapshot is sent. Typically, the snapshot will have as its first item, the chanId, its second item will be an array of update messages (each of which is itself an array). So The array would have 3 levels.

Update

After receiving the snapshot, you will receive updates upon any change.

Unsubscribe to Channels

// request
{
   "event":"unsubscribe",
   "chanId":"<CHANNEL_ID>"
}

// response
{
   "event":"unsubscribed",
   "status":"OK",
   "chanId":"<CHANNEL_ID>"
}

// response-failure
{
   "event":"error",
   "msg":"<ERROR_MSG>",
   "code":"<ERROR_CODE>"
}

To stop receiving data from a channel you have to send a “unsubscribe” message.

Public Channels

Order Books

w.send(JSON.stringify({
    "event": "subscribe",
    "channel": "book",
    "pair": "BTCUSD",
    "prec": "P0",
    "len":"<LENGTH>"
}))
// request
{
   "event":"subscribe",
   "channel":"book",
   "pair":"<PAIR>",
   "prec":"<PRECISION>",
   "freq":"<FREQUENCY>"
}

// response
{
   "event":"subscribed",
   "channel":"book",
   "chanId":"<CHANNEL_ID>",
   "pair":"<PAIR>",
   "prec":"<PRECISION>",
   "freq":"<FREQUENCY>",
   "len":"<LENGTH>"
}

The Order Books channel allow you to keep track of the state of the Bitfinex order book. It is provided on a price aggregated basis, with customizable precision. After receiving the response, you will receive a snapshot of the book, followed by updates upon any changes to the book.

// snapshot
[
   "<CHANNEL_ID>",
   [
      [
         "<PRICE>",
         "<COUNT>",
         "<AMOUNT>"
      ],
      [
         "..."
      ]
   ]
]

// updates
[
   "<CHANNEL_ID>",
   "<PRICE>",
   "<COUNT>",
   "<AMOUNT>"
]

Fields

Fields Type Description
PRECISION string Level of price aggregation (P0, P1, P2, P3).
The default is P0.
FREQUENCY string Frequency of updates (F0, F1, F2, F3).
F0=realtime / F1=2sec / F2=5sec / F3=10sec.
PRICE float Price level.
COUNT int Number of orders at that price level.
±AMOUNT float Total amount available at that price level.
Positive values mean bid, negative values mean ask.
LENGTH string Number of price points (“25”, “100”) [default=“25”]

Precision Levels per Pair

Pair Precision Level Number of decimal places Example
BTCUSD P0 2 $0.01
P1 1 $0.10
P2 0 $1
P3 -1 $10
LTCUSD P0 4 $0.0001
P1 3 $0.001
P2 2 $0.01
P3 1 $0.1
LTCBTC P0 6 ฿0.000001
P1 5 ฿0.00001
P2 4 ฿0.0001
P3 3 ฿0.001
ETHUSD P0 4 $0.0001
P1 3 $0.001
P2 2 $0.01
P3 1 $0.1
ETHBTC P0 6 ฿0.000001
P1 5 ฿0.00001
P2 4 ฿0.0001
P3 3 ฿0.001

Raw Order Books

These are the most granular books.

w.send(JSON.stringify({
    "event": "subscribe",
    "channel": "book",
    "pair": "BTCUSD",
    "prec": "R0",
    "len":"<LENGTH>"
}))
// request
{
   "event":"subscribe",
   "channel":"book",
   "pair":"<PAIR>",
   "prec":"R0"
}

// response
{
   "event":"subscribed",
   "channel":"book",
   "chanId":"<CHANNEL_ID>",
   "pair":"<PAIR>",
   "prec":"R0",
   "len":"<LENGTH>"
}

// snapshot
[
   "<CHANNEL_ID>",
   [
      [
         "<ORD_ID>",
         "<PRICE>",
         "<AMOUNT>"
      ],
      [
         "..."
      ]
   ]
]

// updates
[
   "<CHANNEL_ID>",
   "<ORD_ID>",
   "<ORD_PRICE>",
   "<AMOUNT>"
]

Fields

Fields Type Description
PRECISION string Aggregation level (R0).
ORD_ID int Order id.
ORD_PRICE float Order price.
±AMOUNT float Total amount available at that price level.
Positive values mean bid, negative values mean ask.
LENGTH string Number of price points (“25”

Trades

This channel sends a trade message whenever a trade occurs at Bitfinex. It includes all the pertinent details of the trade, such as price, size and time.

w.send(JSON.stringify({
    "event": "subscribe",
    "channel": "trades",
    "pair": "BTCUSD"
}))
// request
{
  "event": "subscribe",
  "channel": "trades",
  "pair": "BTCUSD"
}

// response
{
  "event": "subscribed",
  "channel": "trades",
  "chanId": "<CHANNEL_ID>",
  "pair":"<PAIR>"
}

// snapshot
[  
   "<CHANNEL_ID>",
   [  
      [  
         "<SEQ> OR <ID>",
         "<TIMESTAMP>",
         "<PRICE>",
         "<AMOUNT>"
      ],
      [  
         "..."
      ]
   ]
]

// updates
[
   "<CHANNEL_ID>",
   "te",
   "<SEQ>",
   "<TIMESTAMP>",
   "<PRICE>",
   "<AMOUNT>"
]

[
   "<CHANNEL_ID>",
   "tu",
   "<SEQ>",
   "<ID>",
   "<TIMESTAMP>",
   "<PRICE>",
   "<AMOUNT>"
]

here is an example of a real trade

[ 5, 'te', '1234-BTCUSD', 1443659698, 236.42, 0.49064538 ]

[ 5, 'tu', '1234-BTCUSD', 15254529, 1443659698, 236.42, 0.49064538 ]

Fields

Fields Type Description
SEQ string Trade sequence id
ID int Trade database id
TIMESTAMP int Unix timestamp of the trade.
PRICE float Price at which the trade was executed
±AMOUNT float How much was bought (positive) or sold (negative).
The order that causes the trade determines if it is a buy or a sell.

Ticker

The ticker is a high level overview of the state of the market. It shows you the current best bid and ask, as well as the last trade price. It also includes information such as daily volume and how much the price has moved over the last day.

w.send(JSON.stringify({
    "event": "subscribe",
    "channel": "ticker",
    "pair": "BTCUSD"
}))
// request
{
   "event":"subscribe",
   "channel":"ticker",
   "pair":"BTCUSD"
}

// response
{
   "event":"subscribed",
   "channel":"ticker",
   "chanId":"<CHANNEL_ID>"
}

// snapshot
[
   "<CHANNEL_ID>",
   "<BID>",
   "<BID_SIZE>",
   "<ASK>",
   "<ASK_SIZE>",
   "<DAILY_CHANGE>",
   "<DAILY_CHANGE_PERC>",
   "<LAST_PRICE>",
   "<VOLUME>",
   "<HIGH>",
   "<LOW>"
]

// updates
[
   "<CHANNEL_ID>",
   "<BID>",
   "<BID_SIZE>",
   "<ASK>",
   "<ASK_SIZE>",
   "<DAILY_CHANGE>",
   "<DAILY_CHANGE_PERC>",
   "<LAST_PRICE>",
   "<VOLUME>",
   "<HIGH>",
   "<LOW>"
]

Here is an example of a real ticker

[ 2, 236.62, 9.0029, 236.88, 7.1138, -1.02, 0, 236.52, 5191.36754297, 250.01, 220.05 ]

Fields

Fields Type Description
BID float Price of last highest bid
BID_SIZE float Size of the last highest bid
ASK float Price of last lowest ask
ASK_SIZE float Size of the last lowest ask
DAILY_CHANGE float Amount that the last price
has changed since yesterday
DAILY_CHANGE_PERC float Amount that the price
has changed expressed in percentage terms
LAST_PRICE float Price of the last trade.
VOLUME float Daily volume
HIGH float Daily high
LOW float Daily low

Authenticated Channels

Account Information

var
    crypto = require('crypto'),
    api_key = 'API_KEY',
    api_secret = 'API_SECRET',
    payload = 'AUTH' + (new Date().getTime()),
    signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex');
w.send(JSON.stringify({
    event: "auth",
    apiKey: api_key,
    authSig: signature,
    authPayload: payload
}));
ws, err := websocket.Dial("wss://api2.bitfinex.com:3000/ws", "", "http://localhost/")
if err != nil {
    return err
}

payload := "AUTH" + fmt.Sprintf("%v", time.Now().Unix())

sig := hmac.New(sha512.New384, []byte("API_KEY"))
sig.Write([]byte(payload))
payload_sign := hex.EncodeToString(sig.Sum(nil))

connectMsg, _ := json.Marshal(map[string]interface{}{
    "event":       "auth",
    "apiKey":      "API_KEY",
    "authSig":     payload_sign,
    "authPayload": payload,
})

// Send auth message
_, err = ws.Write(connectMsg)
    log.Fatal(err)
    return
}

// Read all incoming messages
var msg string
for {
    if err = websocket.Message.Receive(ws, &msg); err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(msg)
    }
// request
{  
   "event":"auth",
   "status":"OK",
   "chanId":0,
   "userId":"<USER_ID>"
}

// response
{  
   "event":"auth",
   "status":"OK",
   "chanId":0,
   "userId":"<USER_ID>"
}

// response-failure
{  
   "event":"auth",
   "status":"FAIL",
   "chanId":0,
   "code":"<ERROR_CODE>"
}

This channel allows you to keep up to date with the status of your account. You can receive updates on your positions, your balances, your orders and your trades.

Account info always uses chanId 0.

Position Snapshot

Fields

[  
   0,
   "ps",
   [  
      [  
         "<POS_PAIR>",
         "<POS_STATUS>",
         "<POS_AMOUNT>",
         "<POS_BASE_PRICE>",
         "<POS_MARGIN_FUNDING>",
         "<POS_MARGIN_FUNDING_TYPE>"
      ],
      [  
         "..."
      ]
   ]
]
Term Type Description
POS_PAIR string Pair (BTCUSD, …).
POS_STATUS string Status (ACTIVE, CLOSED).
±POS_AMOUNT float Size of the position.
Positive values means a long position,
negative values means a short position.
POS_BASE_PRICE float The price at which you entered your position.
POS_MARGIN_FUNDING float The amount of funding being used for this position.
POS_MARGIN_FUNDING_TYPE int 0 for daily, 1 for term.

Wallet Snapshot

[
   0,
   "ws",
   [
      [
         "<WLT_NAME>",
         "<WLT_CURRENCY>",
         "<WLT_BALANCE>",
         "<WLT_INTEREST_UNSETTLED>"
      ]
   ]
]

Fields

Term Type Description
WLT_NAME string Wallet name (exchange, trading, deposit)
WLT_BALANCE float Wallet balance
WLT_INTEREST_UNSETTLED float Unsettled interest

Order Snapshots

os and hos indentify respectively active and inactive orders snapshots

[
   0,
   "os",
   [
      [
         "<ORD_ID>",
         "<ORD_PAIR>",
         "<ORD_AMOUNT>",
         "<ORD_AMOUNT_ORIG>",
         "<ORD_TYPE>",
         "<ORD_STATUS>",
         "<ORD_PRICE>",
         "<ORD_PRICE_AVG>",
         "<ORD_CREATED_AT>",
         "<ORD_NOTIFY>",
         "<ORD_HIDDEN>",
         "<ORD_OCO>"
      ],
      [
         "..."
      ]
   ]
]

Fields

Term Type Description
ORD_ID int order id
ORD_PAIR string Pair (BTCUSD, …)
±ORD_AMOUNT float Positive means buy, negative means sell.
±ORD_AMOUNT_ORIG float Original amount
ORD_TYPE string The type of the order
[“LIMIT”, “MARKET”, “STOP”, “TRAILING STOP”, “EXCHANGE MARKET”, “EXCHANGE LIMIT”, “EXCHANGE STOP”, “EXCHANGE TRAILING STOP”, “FOK”, “EXCHANGE FOK”].
ORD_STATUS string Status [ACTIVE, EXECUTED, PARTIALLY FILLED, CANCELED]
ORD_PRICE float Price
ORD_PRICE_AVG float Average price
ORD_CREATED_AT string Creation date/time
ORD_NOTIFY int 1 if Notify flag is active, 0 if not
ORD_HIDDEN int 1 if Hidden, 0 if not hidden
ORD_OCO int ID of the linked order, 0 otherwise

Trade Snapshot

[
   0,
   "ts",
   [
      [
         "<TRD_ID>",
         "<TRD_PAIR>",
         "<TRD_TIMESTAMP>",
         "<TRD_ORD_ID>",
         "<TRD_AMOUNT_EXECUTED>",
         "<TRD_PRICE_EXECUTED>",
         "<ORD_TYPE>",
         "<ORD_PRICE>",
         "<FEE>",
         "<FEE_CURRENCY>"
      ],
      [
         "..."
      ]
   ]
]

Fields

Term Type Description
TRD_ID int Trade database id
TRD_PAIR string Pair (BTCUSD, …)
TRD_TIMESTAMP int Execution timestamp
TRD_ORD_ID int Order id
±TRD_AMOUNT_EXECUTED float Positive means buy, negative means sell
TRD_PRICE_EXECUTED float Execution price
ORD_TYPE string Order type
ORD_PRICE float Order price
FEE float Fee
FE_CURRENCY string Fee currency

Order Updates

[
   0,
   "<on|ou|oc>",
   [
      "<ORD_ID>",
      "<ORD_PAIR>",
      "<ORD_AMOUNT>",
      "<ORD_AMOUNT_ORIG>",
      "<ORD_TYPE>",
      "<ORD_STATUS>",
      "<ORD_PRICE>",
      "<ORD_PRICE_AVG>",
      "<ORD_CREATED_AT>",
      "<ORD_NOTIFY>",
      "<ORD_HIDDEN>",
      "<ORD_OCO>"
   ]
]

Position Updates

[  
   0,
   "<pn|pu|pc>",
   [  
      "<POS_PAIR>",
      "<POS_STATUS>",
      "<POS_AMOUNT>",
      "<POS_BASE_PRICE>",
      "<POS_MARGIN_FUNDING>",
      "<POS_MARGIN_FUNDING_TYPE>"
   ]
]

Wallet Updates

[
   0,
   "wu",
   [
      "<WLT_NAME>",
      "<WLT_CURRENCY>",
      "<WLT_BALANCE>",
      "<WLT_INTEREST_UNSETTLED>"
   ]
]

Executed Trades

[
   0,
   "te",
   [
      "<TRD_SEQ>",
      "<TRD_PAIR>",
      "<TRD_TIMESTAMP>",
      "<TRD_ORD_ID>",
      "<TRD_AMOUNT_EXECUTED>",
      "<TRD_PRICE_EXECUTED>",
      "<ORD_TYPE>",
      "<ORD_PRICE>"
   ]
]

After a te message you receive shortly a tu message that contains the real trade id (TRD_ID) and additional/updated fields.

[
   0,
   "tu",
   [
      "<TRD_SEQ>",
      "<TRD_ID>",
      "<TRD_PAIR>",
      "<TRD_TIMESTAMP>",
      "<TRD_ORD_ID>",
      "<TRD_AMOUNT_EXECUTED>",
      "<TRD_PRICE_EXECUTED>",
      "<ORD_TYPE>",
      "<ORD_PRICE>",
      "<FEE>",
      "<FEE_CURRENCY>"
   ]
]

Abbreviated Terms Glossary

Term Definition
ps position snapshot
pn new position
pu position update
pc position close
ws wallet snapshot
wu wallet update
os order snapshot
on new order
ou order update
oc order cancel
te trade executed
tu trade execution update

Unauthentication

// request
{  
   "event":"unauth"
}

// response
{  
   "event":"unauth",
   "status":"OK",
   "chanId":0
}

// response-failure
{
   "event":"error",
   "status":"FAILED",
   "chanId":0,
   "code":"<CODE>"
}