Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

bitfinex-api-node

bitfinexcom11kMIT7.0.0

Node reference library for Bitfinex API

bitfinex, bitcoin, BTC

readme

Bitfinex WSv2 Trading API for Node.JS - Bitcoin, Ethereum, Ripple and more

Build Status

A Node.JS reference implementation of the Bitfinex API

Features

  • Official implementation
  • REST v2 API
  • WebSockets v2 API
  • WebSockets v1 API

Installation

  npm i --save bitfinex-api-node

Quickstart

const { WSv2 } = require('bitfinex-api-node')
const ws = new WSv2({ transform: true })

// do something with ws client

Docs

Refer to the docs/ folder for JSDoc-generated HTML documentation, and the examples/ folder for executable examples covering common use cases.

Official API documentation at https://docs.bitfinex.com/v2/reference

Examples

Sending an order & tracking status:

const ws = bfx.ws()

ws.on('error', (err) => console.log(err))
ws.on('open', ws.auth.bind(ws))

ws.once('auth', () => {
  const o = new Order({
    cid: Date.now(),
    symbol: 'tETHUSD',
    amount: 0.1,
    type: Order.type.MARKET
  }, ws)

  // Enable automatic updates
  o.registerListeners()

  o.on('update', () => {
    console.log(`order updated: ${o.serialize()}`)
  })

  o.on('close', () => {
    console.log(`order closed: ${o.status}`)
    ws.close()
  })

  o.submit().then(() => {
    console.log(`submitted order ${o.id}`)
  }).catch((err) => {
    console.error(err)
    ws.close()
  })
})

ws.open()

Cancel all open orders

const ws = bfx.ws(2)

ws.on('error', (err) => console.log(err))
ws.on('open', ws.auth.bind(ws))

ws.onOrderSnapshot({}, (orders) => {
  if (orders.length === 0) {
    console.log('no open orders')
    return
  }

  console.log(`recv ${orders.length} open orders`)

  ws.cancelOrders(orders).then(() => {
    console.log('cancelled orders')
  })
})

ws.open()

Subscribe to trades by pair

const ws = bfx.ws(2)

ws.on('error', (err) => console.log(err))
ws.on('open', () => {
  ws.subscribeTrades('BTCUSD')
})

ws.onTrades({ symbol: 'tBTCUSD' }, (trades) => {
  console.log(`trades: ${JSON.stringify(trades)}`)
})
ws.onTradeEntry({ symbol: 'tBTCUSD' }, (trades) => {
  console.log(`te: ${JSON.stringify(trades)}`)
})

ws.open()

Version 2.0.0 Breaking changes

constructor takes only an options object now, including the API keys

Old:

new BFX(API_KEY, API_SECRET, { version: 2 })

since 2.0.0:

new BFX({ apiKey: '', apiSecret: '' })

trade and orderbook snapshots are emitted as nested lists

To make dealing with snapshots better predictable, snapshots are emitted as an array.

normalized orderbooks for R0

Lists of raw orderbooks (R0) are ordered in the same order as P0, P1, P2, P3

Testing

npm test

FAQ

Order Creation Limits

The base limit per-user is 1,000 orders per 5 minute interval, and is shared between all account API connections. It increases proportionally to your trade volume based on the following formula:

1000 + (TOTAL_PAIRS_PLATFORM * 60 * 5) / (250000000 / USER_VOL_LAST_30d)

Where TOTAL_PAIRS_PLATFORM is the number of pairs shared between Ethfinex/Bitfinex (currently ~101) and USER_VOL_LAST_30d is in USD.

'on' Packet Guarantees

No; if your order fills immediately, the first packet referencing the order will be an oc signaling the order has closed. If the order fills partially immediately after creation, an on packet will arrive with a status of PARTIALLY FILLED...

For example, if you submit a LIMIT buy for 0.2 BTC and it is added to the order book, an on packet will arrive via ws2. After a partial fill of 0.1 BTC, an ou packet will arrive, followed by a final oc after the remaining 0.1 BTC fills.

On the other hand, if the order fills immediately for 0.2 BTC, you will only receive an oc packet.

Nonce too small

I make multiple parallel request and I receive an error that the nonce is too small. What does it mean?

Nonces are used to guard against replay attacks. When multiple HTTP requests arrive at the API with the wrong nonce, e.g. because of an async timing issue, the API will reject the request.

If you need to go parallel, you have to use multiple API keys right now.

te vs tu Messages

A te packet is sent first to the client immediately after a trade has been matched & executed, followed by a tu message once it has completed processing. During times of high load, the tu message may be noticably delayed, and as such only the te message should be used for a realtime feed.

Sequencing

If you enable sequencing on v2 of the WS API, each incoming packet will have a public sequence number at the end, along with an auth sequence number in the case of channel 0 packets. The public seq numbers increment on each packet, and the auth seq numbers increment on each authenticated action (new orders, etc). These values allow you to verify that no packets have been missed/dropped, since they always increase monotonically.

Differences Between R* and P* Order Books

Order books with precision R0 are considered 'raw' and contain entries for each order submitted to the book, whereas P* books contain entries for each price level (which aggregate orders).

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

changelog

7.0.0

  • chore: remove pulse deps

6.0.0

  • removed unused deps: chai, request-promise, request, crc-32
  • removed bluebird Promise
  • update params of submitOrder and cancelOrders methods of WS transport to support new rest api signature
  • bumped bfx-api-node-rest version up to 5.1.1, breaks previous versions compatibility
  • bumped mocha, jsdoc-to-markdown, docdash, blessed-contrib, ws versions to fix vulnerabilities
  • moved dev deps readline-promise, blessed, blessed-contrib, cli-table3, p-iteration into corresponding section

5.0.4

  • fix: public funding trade parsing
  • styling: fix code formatting

5.0.0

  • upgrade: upgraded bfx-api-node-rest to 4.0.0, breaks previous versions compatibility
  • fix: jsdocs

4.0.17

  • added pulse examples

4.0.16

  • fix: unsubscribe fails depending on channel id type

4.0.15

  • fix 2 high vulnerabilities, switch from cli-table2 to cli-table3 dependency

4.0.14

  • fix: README docs reference

4.0.13

  • meta: mv several moduels to deps from dev-deps for bfx-cli

4.0.12

  • meta: mv readline-promise to deps from dev-deps

4.0.11

  • meta: added nyc for coverage file gen
  • meta: added husky npm test pre-commit hook
  • meta: refactored to async/await instead of Promises where possible
  • meta: refactored examples to reduce boilerplate and normalize output
  • meta: removed example script runners from package.json
  • examples: removed CLI scripts in favour of a dedicated bfx-cli module
  • examples: renamed 'orders' to 'list-open-orders'
  • examples: positions now always includes P/L
  • WSv2: support '*' filter value to match all
  • WSv2: added sequencingEnabled() method
  • WSv2: added usesAgent() method
  • WSv2: added getURL() method
  • WSv2: fix in cancelOrders() to prevent context clobber for this.cancelOrder() call
  • WSv2: default connection url now exposed on WSv2.url
  • WSv2: removed unused prec/len params from unsubscribeOrderBook()
  • WSv2: removed unused rawMsg param from _handleEventMessage()
  • WSv2: fix getDataChannelId() not filtering by channel type
  • WS2Manager: reconnect() and close() now return promises
  • WS2Manager: added getAuthArgs()
  • WS2Manager: added missing tests

4.0.10

  • fix: refactor tests so they can run alongside all other HF/API library tests

4.0.9

  • WS2Manager: respect internal auth arg settings

4.0.8

  • WSv2: fix on trade message handler by prioritising channel data symbol over pair symbol

4.0.7

  • WSv2: refactor to use async/await style where possible
  • WSv2: reconnect() now always resolves on completion

4.0.6

  • WSv2: fix internal flag persistence #521

4.0.5

  • WSv2: add auth arg management (pre-set dms and calc)
  • WSv2: add updateAthArgs()
  • WSv2: add getAuthArgs()
  • WS2Manager: fix auth args handling with new methods
  • WS2Manager: rename setAuthCredentials -> setAPICredentials

4.0.4

4.0.3

  • WS2Manager: add setAuthArgs method

4.0.2

  • WS2Manager: add reconnect method

4.0.1

  • WSv2: fix fte and ftu event routing

4.0.0

3.0.2

  • WSv2: affCode support

3.0.1

  • docs: update

3.0.0

  • Updates function rest2.withdraw to v2 functionality
  • Updates function rest2.transfer to v2 functionality
  • adds function rest2.getDepositAddress
  • adds function rest2.submitAutoFunding
  • adds function rest2.closeFunding
  • adds function rest2.cancelFundingOffer
  • adds function rest2.submitFundingOffer
  • adds function rest2.claimPosition
  • adds function rest2.cancelOrder
  • adds function rest2.updateOrder
  • adds function rest2.submitOrder

2.0.10

  • WSv2: ignore notification auth seq numbers (no longer provided by API)

2.0.9

  • WS2Manager: add managedUnsubscribe()
  • WS2Manager: add close()
  • WS2Manager: add getAuthenticatedSocket()
  • WSv2: add suppport for liquidations feed (status methods)
  • WSv2: add reconnect throttler in case of connection reset w/ many open sockets

2.0.8

  • Bump dependency versions

2.0.7

  • WSv2: increase data chan limit to 30 (732499b)

2.0.6

  • WSv2: decrease data chan limit to 25 (6816992)
  • add close-positions script (face1fc)
  • add symbol-details script (708849e)
  • add currencies script (cff1647)
  • add funding info fetch example (337f202)
  • standard --fix (5e6f786, fb5e319, b56b157)
  • fix lastMidPrice in example courtesy of MowgliB (004f904)

2.0.5

  • WSv2: improve reconnect functionality courtesy of cwolters (950105d)
  • WSv2: add funding info example (b597c4d)
  • WSv2: add order creation w/ TIF example (f25df58)
  • bump dep versions (5e4d439, d72d56f)
  • mv babel deps to dev-deps (a576c57)

2.0.4

  • add symbols back into ws2 ticker messages [models updated] (1f4a7eb)

2.0.3

  • add browser builds (e651496)
  • add errors in case of missing chan sub filters (4607154)
  • remove symbols from ws2 ticker messages (06b0e13)

2.0.2

  • improve logging (ceddd87, 404bd7a)
  • export WS2Manager class (afcdefe)

2.0.1

  • extract most logic into external libraries (13edff8)
  • add support for all currencies in funding offer/loan/credit history (e39f360)
  • add automatic re-subscribe on reconnect (e4f65ec)
  • add withAllSockets method to manager (90c7fd5)
  • split trades listeners between public and private trades (3a428a6)
  • allow multiple nonce consumers (2a51dcd)
  • REST API v2: add currencies method (122648a)
  • OrderBook: add funding support (d8572a6)
  • LedgerEntry: add wallet (e5b91c5)
  • and more!

2.0.0

  • added CLI commands (971e8bf)
  • added TradingTicker model (1099273)
  • added model class transform support to RESTv2 (1099273)
  • added ability to unserialize objects in Model.unserialize() (b23a576)
  • added ledgers & movements examples (176d5a9)
  • filled in FundingInfo model (268ecc9)
  • updated MarginInfo model indices (268ecc9)
  • increased max WSv2 listener limit to 1k (5ade818)
  • REST API v2: fix calc balances API path (5e2f834)
  • WS API v2: added notifyUI helper to generate broadcasts (22cb5bc)
  • WS API v2: added support for DMS flag in auth (11e57b1)
  • WS API v2: added socket manager for auto multiplexing (f693bb9)
  • WS API v2: fixed error notification seq # tracking (1b1c1f3)
  • WS API v2: fixed trades event name resolution w/ seq numbers (46af211)
  • REST API v2: added ability to auth via token (07f8756)
  • REST API v2: added ability to fetch order history for all symbols (57f8c7b)
  • REST API v2: added ability to fetch account trades for all symbols (14b13c1)
  • REST API v2: added user info endpoint & associated model (36c0079)
  • OrderBook: fixed unserialization for raw books (01b5ce4)
  • OrderBook: removal of unknown entries no longer raises an error (7bd5bc2)
  • OrderBook: array sort is maintained on update (520a9a0)
  • OrderBook: converts exp notation numbers to fixed for checksum (2c8487c)
  • and more!

2.0.0-beta.1

  • refactored general model handling (broke out field indexes) (c616696)
  • REST API v1: add support for close position endpoint (14db6fe)
  • REST API v2: added query param support to the candles() handler (be779c3)
  • REST API v2: added platform status endpoint (5e3fe56)
  • WS API v2: clean up channel subscriptions on open/close (7c17b96, 92ce89d)
  • WS API v2: now passes update packet & order to Order model events (c616696)
  • WS API v2: added support for new order flags (79c4a40, 3406ac3)
  • WS API v2: added support for filtering by id to order event listeners (be779c3)
  • WS API v2: added support for managed order book checksum verification (cab9635)
  • WS API v2: added support for atomic order updates (36d10c4)
  • OrderBook: added arrayOBMidPrice helper (f0e3074)
  • OrderBook: added checksum helpers (cab9635)
  • refactored general model handling (broke out field indexes) (c616696)
  • and many small fixes & tweaks

2.0.0-beta

  • WS API v2: added optional auto-reconnect
  • WS API v2: added optional packet watchdog
  • WS API v2: added optional order packet buffering via multi-op endpoint
  • WS API v2: added optional order book & candle managment/persistence
  • WS API v2: added optional seq number verification/audit
  • WS API v2: added many extra callback/listener funcs (i.e. onMaintenanceStart)
  • WS API v2: added ability to mass-unsubscribe listeners by group ID
  • WS API v2: most callback methods now support message filtering
  • WS API v2: replaced transform logic w/ model classes (i.e. Order)
  • WS API v2: many methods now return promises, such as submitOrder()
  • REST API v2: transform method updated to match WSv2 class
  • REST API v1: minor refactor, methods unchanged
  • REST API v2: minor refactor, methods unchanged
  • WS API v1: minor refactor, methods unchanged
  • BFX constructor exposes & caches clients on .rest() and .ws() methods
  • Updated ws2 examples
  • Added model classes (OrderBook, Order, Trade, etc)

1.2.1

  • REST API v2: use /candles/ endpoint for candles data
  • WS API v2: Candles event provides key
  • Improve error message for nonce errors
  • Examples: added example for WS2 orders

1.2.0

  • REST API v1: Added support for /orders/hist endpoint
  • REST API v2: Added support for auth/r/trades/{symbol}/hist endpoint
  • WS API v2: Candles supports now key to identify subscription
  • REST API v1: Fix claim_position argument handling