Code Monkey home page Code Monkey logo

bitfinex-api-node's Introduction

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

bitfinex-api-node's People

Contributors

acterry avatar androng avatar askmike avatar avsek477 avatar belfordz avatar cameronlockey avatar claus avatar cwolters avatar ezewer avatar f3rno avatar gasolin avatar haehnchen avatar jacobplaster avatar jaybutera avatar jeliasson avatar joshuarossi avatar leepupu avatar maxsvargal avatar mjesuele avatar motocarota avatar mplanes avatar prdn avatar robertkowalski avatar silentrob avatar spro avatar tetradeca avatar vansergen avatar vigan-abd avatar yagop avatar zimkaru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bitfinex-api-node's Issues

maximum length (depth) of raw orderbook (ws)

Hi,
Would you please let me know what is the maximum length (depth) of raw orderbook that can be received on WebSocket.
Have tried a few values higher than 100, but I'm getting the error "length: invalid".

Thank you!

Change API endpoints

@joshuarossi please make sure that all URLs match

wss://api.bitfinex.com/ws/ for websocket v1
wss://api.bitfinex.com/ws/2 for websocket v2
wss://api.bitfinex.com/v1/... for rest v1
wss://api.bitfinex.com/v2/... for rest v2

TypeError: cb is not a function on new_order

[bitfinex@gene bot]$ node bit.js
/home/bitfinex/bot/node_modules/bitfinex-api-node/rest.js:67
return cb(new Error(result.message));
^

TypeError: cb is not a function
at Request._callback (/home/bitfinex/bot/node_modules/bitfinex-api-node/rest.js:67:20)
at Request.self.callback (/home/bitfinex/bot/node_modules/request/request.js:186:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request. (/home/bitfinex/bot/node_modules/request/request.js:1081:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage. (/home/bitfinex/bot/node_modules/request/request.js:1001:12)
at IncomingMessage.g (events.js:291:16)
at emitNone (events.js:91:20)

Source code of bit.js:

//Bitfinex REST
var BFX = require('bitfinex-api-node')
var client
client = new BFX.APIRest('testQssd1uasdwe293saedsd4cR', 'testds5rIS5uvsdsdsad65asGkAjdsdx1jU8')

//Trade
client.new_order('btcusd', 0.01, 0.01, 'bitfinex', 'buy', 'exchange limit', false, false, 0)

Exchange or trade?

/mytrades returns object that has "exchange" property. It always empty.
It should be boolean if transaction was trade or exchange.
Fix it please

ws.js and ws2.js do not return correct info on ws and ps

The current code returns each element of data[0] separately, while it should return the whole array as response :

 if (Array.isArray(data[0])) {
            data[0].forEach(function (ele) {
                debug('Emitting \'%s\' %j', event, ele);
                this.emit(event, ele);
            }.bind(this));

This is the fixed code :

if (Array.isArray(data) && Array.isArray(data[0])) {
            data.forEach(function (ele) {
                debug('Emitting \'%s\' %j', event, ele);
                this.emit(event, ele);
            }.bind(this));

How to pass parameters to payload?

I am having problems accessing the API v1. Maybe I am starting on the wrong foot buy my goal is to fetch all orders done for a auth user.

I thought of using past_trades which has a few parameters: symbol, timestamp, until, limit_trades, reverse. How do I actually pass the parameters? If I do something like:

bfx.past_trades('BTCUSD',{'timestamp': 1440191855}, function(error, response){
//returns only a few trades, for this current month
})

The call I do, returns only a few trades and not since timestamp.

  1. What am I doing wrong in passing the timestamp? How can I pass other parameters too, like reverse?
  2. Is there a better way to obtain all done orders history for the auth user?

orderbook not sorted properly

example:
'2734.4': { PRICE: 2734.4, COUNT: 2, AMOUNT: -10,5990971},
'2734.8': { PRICE: 2734.8, COUNT: 1, AMOUNT: -0,11},
'2734.3': { PRICE: 2734.3, COUNT: 1, AMOUNT: -4.260452},
'2736.9': { PRICE: 2736.9, COUNT: 1, AMOUNT: -0,01068},

same sort error on bids/asks

api proposal: constructor & options

Right now the main-entry point, index.js initiates both the websocket and rest clients. This is usually unnecessary, as users will go with the rest or the ws client and leads to side effects.

For instance, when initialising the class, and using the http client in an integration test, the websocket code will cause the node.js process to wait & listen and not to exit.

Proposal:

Return the initiated client depending which method is called. The API should support chaining.

const bfx = require('bitfinex-api-node')
const client = new Bfx(options).http()

const cb = () => {}
client.tracker(cb)

// chaining:

new Bfx(options).http().tracker()

For websockets:

const BFX = new Bfx(options)
const client = BFX.ws()

What do you think?

Feedback over fork implementations

Hey

I recently saw that this repository was a bit stale (but I guess was proved me wrong ;), and started doing some work on the library, you can find over at this fork.

To summarize what has been done:

  • Removes the v1 clients: we don't really want to support them indefinitely and encourage people to switch to the newest API's. This would require a major release.
  • Transform the rest client class into a simple factory and simplify internal logic
  • Minor refactors of the ws client but still a class since it extends EventEmitter
  • Integrates candles
  • Integrates normalization process directly in the transformer
  • Readme polishing

I understand that it's a good chunk of changes, so totally willing to discuss/adapt and send separate diffs.

REST version 1 SyntaxError: Unexpected token =

const BFX = require('bitfinex-api-node')
const bfx = new BFX()
const bfx_rest = bfx.rest

sends me this error:

...node_modules/bitfinex-api-node/index.js:11
  constructor (apiKey, apiSecret, opts = { version: 1, transform: false }) {
                                       ^
SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/home/rebootfin/test/zenbot/extensions/bitfinex/exchange.js:1:75)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)

Could someone provide usage examples for REST?

Thanks for building this. Could the README be expanded to demonstrate usage of the REST endpoints?

I realize it may well be basic node conventions that I am missing, but I am trying to inspect the data response for an authenticated REST endpoint (movements), and can't figure out how to see whether I got the data response I expect.

const rest = new BFX(API_KEY, API_SECRET, opts).rest
var yesterday = moment().subtract(1, 'days').unix();
var today = moment().startOf('day').unix();

movement_opts = {
  "since": yesterday,
  "until": today
};

response = rest.movements('BTCUSD', movement_opts, function(error, data){
  console.log(error);
  console.log(data);
});

When I run this, I get:

vagrant@localhost:/vagrant/bitfinex$ node bitfinex-test.js
null
[]

Examples are inconsistent with Readme and Docs

Readme:

bitfinexWebsocket = bitfinexApiNode.websocket

  • requiring with .websocket
  • no info on init

Example:

var BitfinexWS = require ('bitfinex-api-node').WS;
var bws = new BitfinexWS();
  • requiring with WS
  • init without key & secret

Docs

new BitfinexWS(APIKey, APISecret)

  • init with key & secret

Looking into the index.js reveals how it should be used:

BitfinexApi = require('bitfinex-api-node');
bitfinexApi = new BitfinexApi(options.apiKey, options.apiSecret);
bitfinexWebsocketApi = bitfinexApi.ws;
bitfinexRestApi = bitfinexApi.rest;

Authed, but order is not submited as intended.

Order is submited like that:

bws.on('open', () => {
  bws.auth()
  bws.on('message', (auth_msg) => { //a MUST otherwise we get { event: 'error', msg: 'auth: invalid', code: 10100 }
    console.log('Messages:\n', auth_msg);
    })
bws.on('auth', (msg) => { //may also use 'os', 'ws', 'hos'
  bws.submitOrder(order)
  console.log('submitOrder:\n', msg)
})
bws.on('error', console.error)

but it is not submited like that and we get error - { event: 'error', msg: 'auth: invalid', code: 10100 }:

bws.on('open', () => {
  bws.auth()
  bws.on('message', (auth_msg) => { //a MUST otherwise we get { event: 'error', msg: 'auth: invalid', code: 10100 }
    console.log('Messages:\n', auth_msg);
    })
  bws.submitOrder(order)
})
bws.on('error', console.error)

Documentation update

I cant find anything in the documentation about how to submit or cancel orders?
Should provide some examples.

  bws.on('oc', (id) => {
    // ???
  }); 

STOP state Json parsing error

I'm getting the following error randomly when running the websocket for an extensive amount of time and can't figure out where it's coming from:
stream.js:74
throw er; // Unhandled stream error in pipe.
^
Error: Invalid JSON (Unexpected "T" at position 0 in state STOP)
at Parser.proto.charError (node_modules\jsonparse\jsonparse.js:90:16)
at Parser.proto.write (node_modules\jsonparse\jsonparse.js:154:23)
at Stream. (node_modules\JSONStream\index.js:23:12)
at Stream.stream.write (node_modules\through\index.js:26:11)
at Request.ondata (stream.js:31:26)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage. node_modules\request\request.js:1088:12)
at emitOne (events.js:96:13)
at IncomingMessage.emit (events.js:188:7)
at IncomingMessage.Readable.read (_stream_readable.js:381:10)
at flow (stream_readable.js:761:34)
at resume
(_stream_readable.js:743:3)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback

Are you handling the 20051, 20060, and 20061 codes from the websocket mentioned under info codes: http://docs.bitfinex.com/docs/ws-general? I imagine the websocket sends an HTML response in that case and the json parse is thus erroring.

Thanks for taking a look!

RangeError: out of range index

I'm getting this error but I can't understand the problem, do you have any hint?

RangeError: out of range index
    at RangeError (native)
    at fastCopy (/home/xxx/node_modules/bitfinex-api-node/node_modules/ws/lib/Receiver.js:386:24)
    at Receiver.add (/home/xxx/node_modules/bitfinex-api-node/node_modules/ws/lib/Receiver.js:86:3)
    at TLSSocket.realHandler (/home/xxx/node_modules/bitfinex-api-node/node_modules/ws/lib/WebSocket.js:800:20)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at TLSSocket.Readable.push (_stream_readable.js:134:10)
    at TLSWrap.onread (net.js:543:20)
/home/xxx/node_modules/bitfinex-api-node/node_modules/ws/lib/Receiver.js:386
    default: srcBuffer.copy(dstBuffer, dstOffset, 0, length); break;

wrong invocation context (this) in _processUserEvent

this.emit(event, ele) in function _processUserEvent throws error due wrong invocation context (this) in forEach.
forEachshould be called with second parameter this:

            data[0].forEach(function (ele) {
                debug('Emitting \'%s\' %j', event, ele);
                this.emit(event, ele);
            }, this);

examples/orderbook.js not properly formed

ouput of orderbook.js is not well formed, meaning
all orders are under bid
its like this
orderbook{
bid : {
{bids-data},
asl : { ask-data}
}
}

...never mind... AL OK!

How to submit new order?

Please, help me submit order, as documentation here is poor. My code (secret and key are hidden):

'use strict'
const BFX = require('bitfinex-api-node')
const API_KEY = 'my-secret'
const API_SECRET = 'my-secret'

const opts = {
  version: 2,
  transform: true
}

const bws = new BFX(API_KEY, API_SECRET, opts).ws

bws.on('open', () => {
  bws.auth()
  bws.subscribeTrades('BTCUSD')
//  bws.subscribeOrderBook('BTCUSD')
//  bws.subscribeTicker('BTCUSD')
})

var trades = msg.map(function (msg) {
  return {
        trade_id: msg.ID,
        time: msg.MTS,
        size: Math.abs(msg.AMOUNT),
        price: msg.PRICE,
        side: msg.AMOUNT > 0 ? 'buy' : 'sell'
      }
    })
//        console.log('Trades', trades)

})

bws.on('ticker', (pair, ticker) => {
  var ticks = {bid: ticker.BID, ask: ticker.ASK}
//  console.log('Ticker:', ticks)
})


bws.on('subscribed', (data) => {
  console.log('New subscription', data)
})

var order = ([
  0,
  'on',
  null,
  {
    type: 'EXCHANGE LIMIT',
    symbol: 'btcusd',
    amount: '0.01',
    price: 0.01,
    hidden: 0,
    postonly: 0
  }
])
bws.on('open', () => {
  bws.submitOrder(order)
  console.log(order);
})

bws.on('error', console.error)

I get this error:

[ 0,
  'on',
  null,
  { type: 'EXCHANGE LIMIT',
    symbol: 'btcusd',
    amount: '0.01',
    price: 0.01,
    hidden: 0,
    postonly: 0 } ]
{ event: 'error', msg: 'auth: invalid', code: 10100 }

Thanks!

Add keys to ws2 responses

Not every user wants to use plain lists or add the corresponding keys on their own.

Provide a way to add the keys on the client side.

The mapping should be reusable for other tasks as well.

REST2 Authed Endpoints ['error', 10100, 'apikey: invalid'] vs REST no error.

Hello,
I'm sorry I am so frequent Issue generator, but I have strange issues and I'd like to figure them out.
My code:

'use strict'
const BFX = require('bitfinex-api-node')
const API_KEY = 'somekey'
const API_SECRET = 'somesecret'
const opts = {  version: 2,  transform: true }
const bfx = new BFX(API_KEY, API_SECRET, opts).rest
const bfx_rest = new BFX(API_KEY, API_SECRET, {version: 1}).rest

//REST AUTHENTICATED ENDPOINT
bfx_rest.active_orders(function (err, body){
  if (err) return console.log(err)
  console.log('active', body);
})

//REST2 AUTHENTICATED ENDPOINT
bfx.makeAuthRequest('/auth/r/orders', function (err, body) {
  if (err) return console.log(err)
  console.log(body)
})

Output:

[nedievas@nedievas zenbot]$ node rtest.js
null [ 'error', 10100, 'apikey: invalid' ]
REST [ { id: 3007395328,
    cid: 20184473749,
    cid_date: '2017-07-09',
    gid: null,
    symbol: 'xrpusd',
    exchange: null,
    price: '0.29',
    avg_execution_price: '0.0',
    side: 'sell',
    type: 'exchange limit',
    timestamp: '1499578585.0',
    is_live: true,
    is_cancelled: false,
    is_hidden: false,
    oco_order: null,
    was_forced: false,
    original_amount: '1190.0',
    remaining_amount: '1190.0',
    executed_amount: '0.0',
    src: 'web' },
  { id: 3058462591,
    cid: 61242974575,
    cid_date: '2017-07-14',
    gid: null,
    symbol: 'btcusd',
    exchange: null,
    price: '2300.0',
    avg_execution_price: '0.0',
    side: 'sell',
    type: 'exchange limit',
    timestamp: '1500051643.0',
    is_live: true,
    is_cancelled: false,
    is_hidden: false,
    oco_order: null,
    was_forced: false,
    original_amount: '0.28',
    remaining_amount: '0.28',
    executed_amount: '0.0',
    src: 'web' } ]
^C

Thank you.

Error: unexpected server response (429)

From time to time, I am getting a 429 error from WS even making a REST request.

That also crash the script.

`events.js:182
throw er; // Unhandled 'error' event
^

Error: unexpected server response (429)
at ClientRequest._req.on (/home/cards4magic/public_html/soredigitmedia/btc/node/node_modules/bitfinex-api-node/node_modules/ws/lib/WebSocket.js:649:26)
at emitOne (events.js:115:13)
at ClientRequest.emit (events.js:210:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:563:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
at TLSSocket.socketOnData (_http_client.js:452:20)
at emitOne (events.js:115:13)
at TLSSocket.emit (events.js:210:7)
at addChunk (_stream_readable.js:250:12)
at readableAddChunk (_stream_readable.js:237:11)
at TLSSocket.Readable.push (_stream_readable.js:195:10)
at TLSWrap.onread (net.js:586:20)`

Any ideia on why this is happenning and what I can do to mitigate it or even make it catch this error and don't crash the script?

Build failing

Build failing with SyntaxError: Identifier 'url' has already been declared. Getting this on my installation. Also seen in the travis build.

get all currencies and ticker data for all pairs

How do I go about getting all the currency pairs on bitfinex and the ticker data for each one through websockets.
The code below only does BTC USD, I would like it to be dynamic where it queries all the available pairs at any given time and then queries each.

bws.on('open', () => {
  bws.subscribeTicker('BTCUSD')
})

Thank you for your answer in advance

Issue With Available Balance

Hello,

This really doesn't have to do with an issue with this library, but more of an understanding of the Bitfinex API and what's happening on their end.

Right now I listen for wallet updates:

bws.on('wu', (msg) => {
*Place Order*
});

Once the wallet update comes in for a certain currency, I instantly try to sell it (using the balance in the wallet update). Every time I get "Invalid order: not enough exchange balance". Sometimes this happens because Bitfinex doesn't take the fees out of the amount given to me yet, but I get a second wallet update anytime the fees are taken out, so I can just relaunch the sell attempt again. But I still get the same error. I've even tried using the "use_all_available" parameter that is available on their API (not included in this package currently but I added it), it uses the right amount, but I still get the error.

Anyone else ever run into similar issues?

It's as if the wallet update event doesn't truly reflect when I have funds available to trade. Is there a different websocket event I should be listening for that is a better indicator?

WS2: auth failed

Almost everytime I start my code i got this error:

{ event: 'auth', status: 'FAILED', chanId: 0, code: 10100, msg: 'apikey: invalid' }

this is part of my full code:

var bws_API_SECRET = '###'
var bws = new BFX(bws_API_KEY, bws_API_SECRET, {version: 2,transform: true, autoOpen: false}).ws

bws.open();

bws.on('open', () => {
  bws.subscribeTicker('BTCUSD')
  bws.auth()
})

bws.on('auth', () => {
  console.log('authenticated')
})

i need to restart my code lots of time until i don't get this error message.

Provide an example to sort the orderbook

From #83:

It's not obvious that the data in the Hashmap is not sorted by price and that you need to create some kind of sorted lists in order to have a sorted list with the orderbook values.

Provide an additional method that takes the current data and merges it back into a list.

[Error: Key type should be a string.]

Hi. When I try to execute new_order, I get this error. I have no problem in executing multiple orders.

 buy: function (opts, cb) {
      var client = authedClient()
      var pair = joinProduct(opts.product_id)
      var amount = n(opts.size).format('0.000000')
      var price = n(opts.price).format('0.000000')
      client.new_order(pair, amount.toString(), price.toString(), 'buy', 'exchange limit', false, function (err, body) {
        if (err) return cb(err)
        cb(null, body)
      })
            console.log(pair, opts)
    },

    sell: function (opts, cb) {
      var client = authedClient()
            if (typeof opts.type === 'undefined') {
                    opts.type = 'exchange limit'
            }
      var pair = joinProduct(opts.product_id)
      var params = [{
                    symbol: pair,
                    amount: n(opts.size).format('0.000000'),
                    price: n(opts.price).format('0.000000'),
                    side: 'sell',
                    type: opts.type
                  }]
      client.multiple_new_orders(params, function (err, body) {
         if (err) return cb(err)
         cb(null, body)
      })
            console.log(pair, opts)
    },

console.log output:

XRPUSD { price: '0.3',
  size: '1000',
  orig_size: '1000',
  orig_price: '0.3',
  product_id: 'XRP-USD',
  post_only: true }

TypeError: format.replace is not a function

Hello, I get this error:

/home/bitfinex/zenbot/node_modules/numbro/numbro.js:183
            escapedFormat = format.replace(/\{[^\{\}]*\}/g, '');
                                   ^

TypeError: format.replace is not a function
    at formatNumbro (/home/bitfinex/zenbot/node_modules/numbro/numbro.js:183:36)
    at Object.format (/home/bitfinex/zenbot/node_modules/numbro/numbro.js:1144:20)
    at /home/bitfinex/zenbot/lib/engine.js:398:87
    at /home/bitfinex/zenbot/lib/engine.js:341:11
    at /home/bitfinex/zenbot/extensions/exchanges/bitfinex/exchange.js:83:9
    at Request.error1 [as _callback] (/home/bitfinex/zenbot/node_modules/bitfinex-api-node/rest.js:89:12)
    at Request.self.callback (/home/bitfinex/zenbot/node_modules/request/request.js:188:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (/home/bitfinex/zenbot/node_modules/request/request.js:1171:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (/home/bitfinex/zenbot/node_modules/request/request.js:1091:12)
    at IncomingMessage.g (events.js:292:16)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)

for this part of code with new version pull:

client.ticker(pair, function (err, body) {
        if (err) return cb(err)
        cb(null, {bid: body.bid, ask: body.ask})
      })

Bitfinex saying I don't have enough funds when I do.

When I send the following payload:

{'request': '/v1/order/new', 'nonce': '1497120802327946.5', 'exchange': 'bitfinex', 'symbol': 'ethbtc', 'type': 'market', 'price': '100000', 'side': 'buy', 'amount': '0.01'}

I am greeted with the following mesage:

This pair cannot be traded on margin.

I have tried making it a limit order, making the symbol ltcbtc, making the amount or price very small, etc etc. Every time I get the above error. I have about 0.2 btc in my exchange account. Why is this happening? Do you have a payload that works for you? Could you share it so that I might be able to tell what is wrong with mine?

error: Invalid path

invalid character is used and error received in windows

c:@personal\Projects>git clone https://github.com/bitfinexcom/bitfinex-api-node.git
Cloning into 'bitfinex-api-node'...
remote: Counting objects: 1844, done.
remote: Compressing objects: 100% (3/3), done.
Receiving objects: 99% (1826/1844), 1.54 MiB | 332.00 KiB/s 8R41
Receiving objects: 100% (1844/1844), 1.60 MiB | 332.00 KiB/s, done.
Resolving deltas: 100% (1077/1077), done.
Checking connectivity... done.
error: Invalid path 'source/images/coveragelcov-report/prettify.css'
error: Invalid path 'source/images/coveragelcov-report/prettify.js'
error: Invalid path 'source/images/coveragelcov-report/sort-arrow-sprite.png'
error: Invalid path 'source/images/coveragelcov-report/sorter.js'
error: Invalid path 'source/images/coveragelcov.info'

c:@personal\Projects>

'orderbook' ws event issues the snapshot as a series of update events

'orderbook' ws event issues the snapshot as a series of update events.
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/ws.js#L276-L308

The API documentation recommends:

  1. subscribe to channel with R0 precision
  2. receive the raw book snapshot and create your in-memory book structure
  3. when price > 0 then you have to add or update the order
  4. when price = 0 then you have to delete the order

since the snapshot is issued as a series of 'orderbook' updates it's not possible to know when the "in-memory book structure" has been built and reliable to use.

Can the snapshot be sent as a single event (as also indicated in the API documentation and sent by Bitfinex server), instead of decomposing the snapshot into a series of multiple update events?

What does 'order' look like in ws2?

I want to use 'submitOrder(order)' function in ws2. But I cannot find what 'order' looks like in this repo. I tried to use the doc (http://docs.bitfinex.com/v2/reference/#ws-auth-order-new) and tried json:
{ "gid": 1, "cid": 12345, "type": "LIMIT", "symbol": "tBTCUSD", "amount": "1.0", "price": "500", "hidden": 0 }
as an order. But I got this error:

Error: Uncaught, unspecified "error" event. ([object Object])
at BitfinexWS2.emit (events.js:163:17)
at BitfinexWS2.onMessage (/Users/hurryhx/tmp/node_modules/bitfinex-api-node/ws2.js:81:14)
at emitTwo (events.js:106:13)
at WebSocket.emit (events.js:191:7)
at Receiver.ontext (/Users/hurryhx/tmp/node_modules/ws/lib/WebSocket.js:816:10)
at /Users/hurryhx/tmp/node_modules/ws/lib/Receiver.js:477:18
at Receiver.applyExtensions (/Users/hurryhx/tmp/node_modules/ws/lib/Receiver.js:364:5)
at /Users/hurryhx/tmp/node_modules/ws/lib/Receiver.js:466:14
at Receiver.flush (/Users/hurryhx/tmp/node_modules/ws/lib/Receiver.js:340:3)
at Receiver.finish (/Users/hurryhx/tmp/node_modules/ws/lib/Receiver.js:482:12)
at Receiver.expectHandler (/Users/hurryhx/tmp/node_modules/ws/lib/Receiver.js:457:31)
at Receiver.add (/Users/hurryhx/tmp/node_modules/ws/lib/Receiver.js:95:24)
at TLSSocket.realHandler (/Users/hurryhx/tmp/node_modules/ws/lib/WebSocket.js:800:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
at TLSWrap.onread (net.js:551:20)

So can you help me use submitOrder in ws2? Thanks!

dependencies mistaked?

hi.
this is great module when use bitfinex.

but, maybe forgot --save option when npm install debug?
i use with npm install debug on project local.
i hope to resolve this problem, but i can't know really required version of debug module...

thanks.

API crashes without error message

Hi everyone,
When I run my node server, it works find gathering tickers, order books and trades but then it crashes 5 minutes later without displaying any error. Shouldn't it be running forever if I don't kill it by hand ?
I am running v2.
Thanks for your advice

'orderbook' event emitting / array handling

Right now we geht a snapshot and after that updates.

Formats:

snapshot:

[[[ 1773.8, 1, -0.1 ]]]

update:

[ 1775.9, 1, -50 ]

note: both are arrays

we now process them with the following code:

  _processBookEvent (msg, event) {
    if (Array.isArray(msg[0])) {
      msg[0].forEach((bookLevel) => {
        debug('Emitting orderbook, %s, %j', event.symbol, bookLevel)
        this.emit('orderbook', event.symbol, bookLevel)
      })
    } else if (msg[0] === 'hb') { // HeatBeart
      debug('Received HeatBeart in %s book channel', event.symbol)
    } else if (msg.length > 2) {
      debug('Emitting orderbook, %s, %j', event.symbol, msg)
      this.emit('orderbook', event.symbol, msg)
    }
  }

As both are arrays, we are always process the data with the forEach loop. The

else if (msg.length > 2)

branch is never called and dead code.

That leads me to the assumption that we have a bug here, as the emitted data for updates look like this:

1770
0
-1

which is not very user friendly and leads to errors as soon as multiple orderbooks are subscribed, as each number is emitted alone.

Proposal:

Emit snapshots as an array, and emit other data as tuples / lists to keep them in consistent relation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.