GithubHelp home page GithubHelp logo

tiagosiebler / binance Goto Github PK

View Code? Open in Web Editor NEW
718.0 27.0 257.0 1.19 MB

Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & browser support, integration tests, beautification & more.

License: MIT License

JavaScript 0.58% TypeScript 99.42%
binance binance-api binance-exchange cryptocurrency cryptocurrency-exchanges typescript bitcoin trading exchange api

binance's Introduction

Node.js & JavaScript SDK for Binance REST APIs & WebSockets

Build & Test npm version npm size npm downloads last commit CodeFactor

connector logo

Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets:

  • Extensive integration with Binance REST APIs and WebSockets.
  • TypeScript support (with type declarations for most API requests & responses).
  • Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, USDM & CoinM Futures.
    • Strongly typed on most requests and responses.
    • Automated end-to-end tests on most API calls, ensuring no breaking changes are released.
  • Extremely robust & performant JavaScript/Node.js Binance SDK with significant trading volume in production (livenet).
  • Actively maintained with a modern, promise-driven interface.
  • Support for seamless HMAC and RSA authentication for private Binance REST API and WebSocket calls.
    • Passing a private key as a secret will automatically revert to RSA authentication.
  • Supports Websockets for Binance Spot, Margin, Isolated Margin, USDM & CoinM Futures.
    • Event driven messaging.
    • Smart websocket persistence
      • Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.
      • Automatically handle listenKey persistence and expiration/refresh.
      • Emit reconnected event when dropped connection is restored.
    • Strongly typed on most websocket events, with typeguards available for TypeScript users.
    • Optional:
      • Automatic beautification of Websocket events (from one-letter keys to descriptive words, and strings with floats to numbers).
      • Automatic beautification of REST responses (parsing numbers in strings to numbers).
  • Heavy automated end-to-end testing with real API calls.
    • End-to-end testing before any release.
    • Real API calls in e2e tests.
  • Proxy support via axios integration.
  • Active community support & collaboration in telegram: Node.js Algo Traders.

Installation

npm install binance --save

Examples

Refer to the examples folder for implementation demos.

Issues & Discussion

  • Issues? Check the issues tab.
  • Discuss & collaborate with other node devs? Join our Node.js Algo Traders engineering community on telegram.
  • Questions about Binance APIs & WebSockets? Ask in the official Binance API group on telegram.

Related projects

Check out my related projects:

Documentation

Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation.

Structure

This project uses typescript. Resources are stored in 3 key structures:

  • src - the whole connector written in typescript
  • lib - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release.
  • dist - the packed bundle of the project for use in browser environments.

Usage

Create API credentials at Binance

REST API Clients

There are several REST API modules as there are some differences in each API group.

  1. MainClient for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management.
  2. USDMClient for USD-M futures APIs.
  3. CoinMClient for COIN-M futures APIs.

Vanilla Options connectors are not yet available, though contributions are welcome!

REST Spot/Margin/etc

Start by importing the spot client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.

const { MainClient } = require('binance');

const API_KEY = 'xxx';
const API_SECRET = 'yyy';

const client = new MainClient({
  api_key: API_KEY,
  api_secret: API_SECRET,
});

client
  .getAccountTradeList({ symbol: 'BTCUSDT' })
  .then((result) => {
    console.log('getAccountTradeList result: ', result);
  })
  .catch((err) => {
    console.error('getAccountTradeList error: ', err);
  });

client
  .getExchangeInfo()
  .then((result) => {
    console.log('getExchangeInfo inverse result: ', result);
  })
  .catch((err) => {
    console.error('getExchangeInfo inverse error: ', err);
  });

See spot-client.ts for further information.

REST USD-M Futures

Start by importing the usd-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.

const { USDMClient } = require('binance');

const API_KEY = 'xxx';
const API_SECRET = 'yyy';

const client = new USDMClient({
  api_key: API_KEY,
  api_secret: API_SECRET,
});

client
  .getBalance()
  .then((result) => {
    console.log('getBalance result: ', result);
  })
  .catch((err) => {
    console.error('getBalance error: ', err);
  });

client
  .get24hrChangeStatististics()
  .then((result) => {
    console.log('get24hrChangeStatististics inverse futures result: ', result);
  })
  .catch((err) => {
    console.error('get24hrChangeStatististics inverse futures error: ', err);
  });

See usdm-client.ts for further information.

REST COIN-M Futures

Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.

const { CoinMClient } = require('binance');

const API_KEY = 'xxx';
const API_SECRET = 'yyy';

const client = new CoinMClient({
  api_key: API_KEY,
  api_secret: API_SECRET,
});

client
  .getSymbolOrderBookTicker()
  .then((result) => {
    console.log('getSymbolOrderBookTicker result: ', result);
  })
  .catch((err) => {
    console.error('getSymbolOrderBookTicker error: ', err);
  });

See coinm-client.ts for further information.

WebSockets

All websockets are accessible via the shared WebsocketClient. As before, API credentials are optional unless the user data stream is required.

const { WebsocketClient } = require('binance');

const API_KEY = 'xxx';
const API_SECRET = 'yyy';

// optionally override the logger
const logger = {
  ...DefaultLogger,
  silly: (...params) => {},
};

const wsClient = new WebsocketClient(
  {
    api_key: key,
    api_secret: secret,
    beautify: true,
    // Disable ping/pong ws heartbeat mechanism (not recommended)
    // disableHeartbeat: true
  },
  logger,
);

// receive raw events
wsClient.on('message', (data) => {
  console.log('raw message received ', JSON.stringify(data, null, 2));
});

// notification when a connection is opened
wsClient.on('open', (data) => {
  console.log('connection opened open:', data.wsKey, data.ws.target.url);
});

// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats.
wsClient.on('formattedMessage', (data) => {
  console.log('formattedMessage: ', data);
});

// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS)
wsClient.on('reply', (data) => {
  console.log('log reply: ', JSON.stringify(data, null, 2));
});

// receive notification when a ws connection is reconnecting automatically
wsClient.on('reconnecting', (data) => {
  console.log('ws automatically reconnecting.... ', data?.wsKey);
});

// receive notification that a reconnection completed successfully (e.g use REST to check for missing data)
wsClient.on('reconnected', (data) => {
  console.log('ws has reconnected ', data?.wsKey);
});

// Recommended: receive error events (e.g. first reconnection failed)
wsClient.on('error', (data) => {
  console.log('ws saw error ', data?.wsKey);
});

// Call methods to subcribe to as many websockets as you want.
// Each method spawns a new connection, unless a websocket already exists for that particular request topic.
// wsClient.subscribeSpotAggregateTrades(market);
// wsClient.subscribeSpotTrades(market);
// wsClient.subscribeSpotKline(market, interval);
// wsClient.subscribeSpotSymbolMini24hrTicker(market);
// wsClient.subscribeSpotAllMini24hrTickers();
// wsClient.subscribeSpotSymbol24hrTicker(market);
// wsClient.subscribeSpotAll24hrTickers();
// wsClient.subscribeSpotSymbolBookTicker(market);
// wsClient.subscribeSpotAllBookTickers();
// wsClient.subscribeSpotPartialBookDepth(market, 5);
// wsClient.subscribeSpotDiffBookDepth(market);

wsClient.subscribeSpotUserDataStream();
wsClient.subscribeMarginUserDataStream();
wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT');

wsClient.subscribeUsdFuturesUserDataStream();

// each method also restores the WebSocket object, which can be interacted with for more control
// const ws1 = wsClient.subscribeSpotSymbolBookTicker(market);
// const ws2 = wsClient.subscribeSpotAllBookTickers();
// const ws3 = wsClient.subscribeSpotUserDataStream(listenKey);

// optionally directly open a connection to a URL. Not recommended for production use.
// const ws4 = wsClient.connectToWsUrl(`wss://stream.binance.com:9443/ws/${listenKey}`, 'customDirectWsConnection1');

See websocket-client.ts for further information. Also see ws-userdata.ts for user data examples.


Customise Logging

Pass a custom logger which supports the log methods silly, debug, notice, info, warning and error, or override methods from the default logger as desired.

const { WebsocketClient, DefaultLogger } = require('binance');

// Enable all logging on the silly level
DefaultLogger.silly = (...params) => {
  console.log('sillyLog: ', params);
};

const ws = new WebsocketClient(
  api_key: 'xxx',
  api_secret: 'yyyy',
  DefaultLogger
);

Browser/Frontend Usage

Import

This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support.

  1. Install these dependencies
    npm install crypto-browserify stream-browserify
  2. Add this to your tsconfig.json
    {
      "compilerOptions": {
        "paths": {
          "crypto": [
            "./node_modules/crypto-browserify"
          ],
          "stream": [
            "./node_modules/stream-browserify"
          ]
    }
  3. Declare this in the global context of your application (ex: in polyfills for angular)
    (window as any).global = window;

Webpack

This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website.

Build a bundle using webpack:

  • npm install
  • npm build
  • npm pack

The bundle can be found in dist/. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.

However, note that browser usage will lead to CORS errors due to Binance.


Contributions & Thanks

Donations

tiagosiebler

If you found this project interesting or useful, do consider sponsoring me on github or registering with my referral link. Thank you!

Or buy me a coffee using any of these:

  • BTC: 1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk
  • ETH (ERC20): 0xd773d8e6a50758e1ada699bb6c4f98bb4abf82da

Contributions & Pull Requests

Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.

Star History

Star History Chart

binance's People

Contributors

0xsmartcrypto avatar a-ndy-git avatar aloysius-pgast avatar arsunicsoft avatar aymantaybi avatar dependabot[bot] avatar dutu avatar dylansproule avatar emiliocr90 avatar ethyaan avatar giveerr avatar harsh132 avatar jkyin avatar jule64 avatar laurynas-karvelis avatar lobobruno avatar locnguyen avatar martomcfly avatar mkosir avatar pouyaazi avatar qbkjovfnek avatar sebastianboehler avatar skliarovartem avatar snyk-bot avatar sykar-f avatar t0chk avatar tiagosiebler avatar watch-janick avatar xavier59 avatar zoeyg 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

binance's Issues

Create examples for how to use each library method

I'm trying to get the quantity and price to place an order but I'm failing miserably. Math is really not my thing...
I have the exchange Info with the filters for each pair... whatt i want to achieve in this particular order (although I'd like a universal solution) is to get balance from btc, place order with that amount. then get balance of bought asset and sell that amount.

the problem is I'm failing to get the right amount to place the order, need to round it based on the min quantity and min notonial.

can someone please share some solution/suggestion for this?

Consistency in naming?

bestBidPrice is called bestBid.

This is inconsistent with bestAskPrice defining the bestAskPrice in beautify.

The result of "onAllTickers" Websocket method give me a string

I am using the "onAllTickers" Web-socket method to check conditions in the markets. The method works fine, normally I receive the Array with the values like it is expected to work. But suddenly I receive a String and not a Array.

You can try the following code, to see what I am trying to explain.

const api = require('binance')
const ws = new api.BinanceWS(true)

ws.onAllTickers(data => {
  console.log(typeof data)
})

CORS w/Unsigned Endpoints

Problem:
Because of CORS and Binance's server config, a server is currently required for accessing any endpoint. While this makes total sense for signed endpoints, its a bit overkill for unsigned endpoints (allPrices, etc).

Solution:
I see that you guys are running on nginx. You can allow cross origin requests for specific endpoints:

location /api/v1/ticker/allPrices {
        add_header 'Access-Control-Allow-Origin' '*';
}

This will allow people to contribute much simpler apps, widgets, etc. without having to spin up a server instance ๐Ÿค˜๐Ÿป

User data socket closes after 1 hour of inactivity

Hello! Loving this implementation so far! I've been playing with the user data websocket and I've noticed that after 1 hour of inactivity it closes with code 1006. This is the full object passed through the onclose event of the socket:

{
	"target": {
		"domain": null,
		"_events": {
			"error": [null, null, null],
			"close": [null, null]
		},
		"_eventsCount": 3,
		"readyState": 3,
		"bytesReceived": 87667,
		"extensions": {},
		"protocol": "",
		"_binaryType": "nodebuffer",
		"_closeFrameReceived": false,
		"_closeFrameSent": false,
		"_closeMessage": "",
		"_closeTimer": null,
		"_finalized": true,
		"_closeCode": 1006,
		"_receiver": {
			"_binaryType": "nodebuffer",
			"_extensions": null,
			"_maxPayload": 0,
			"_bufferedBytes": 0,
			"_buffers": null,
			"_compressed": false,
			"_payloadLength": 6882,
			"_fragmented": 0,
			"_masked": false,
			"_fin": true,
			"_mask": null,
			"_opcode": 1,
			"_totalPayloadLength": 0,
			"_messageLength": 0,
			"_fragments": null,
			"_cleanupCallback": null,
			"_hadError": false,
			"_dead": true,
			"_loop": false,
			"onmessage": null,
			"onclose": null,
			"onerror": null,
			"onping": null,
			"onpong": null,
			"_state": 0
		},
		"_sender": null,
		"_socket": null,
		"_ultron": null,
		"protocolVersion": 13,
		"_isServer": false,
		"url": "wss://stream.binance.com:9443/ws/somethingosmething",
		"_req": null
	},
	"type": "close",
	"wasClean": false,
	"reason": "",
	"code": 1006
}

I've reduced the keep alive timer to 30000 ms, in case that may be a factor, but it doesn't seem related as the timing remains 1 hour after the last activity. Hope the onclose event object is useful in diagnosing this. This is with the latest version (1.3.3).

Passing custom parameters to be returned back on the callback

I am writing a order manager and I need a way to keep track of orders as they enter the api and complete calling back out the callback. I am currently adding a guid but I don't want to have to edit every function to accept passing in a new parameter that it passes back later. Any work around you could think of? I want the ability to track the same buy order duplicated but two totally different orders.

TypeError: Cannot read property 'statusCode' of undefined

Here is the full error:

**[PATH REDACTED]**\gekko\node_modules\binance\lib\rest.js:78
                    if (response.statusCode === 400 && payload.code === -1021 &&
                                 ^

TypeError: Cannot read property 'statusCode' of undefined
    at Request.request [as _callback] (**[PATH REDACTED]**\gekko\node_modules\binance\lib\rest.js:78:34)
    at self.callback (**[PATH REDACTED]**\gekko\node_modules\request\request.js:186:22)
    at Request.emit (events.js:160:13)
    at ClientRequest.<anonymous> (**[PATH REDACTED]**\gekko\node_modules\request\request.js:816:16)
    at Object.onceWrapper (events.js:255:19)
    at ClientRequest.emit (events.js:160:13)
    at TLSSocket.emitTimeout (_http_client.js:708:34)
    at Object.onceWrapper (events.js:255:19)
    at TLSSocket.emit (events.js:160:13)
    at TLSSocket.Socket._onTimeout (net.js:412:8)

cross post from askmike/gekko#1781.

Question: cancelling partially filled orders

I don't know if this is the right place to ask, in case it's not just close the ticket.

What I'm trying to understand is what happens when I cancel a partially filled order.
Let me explain: I know that a part of the order is bought and another part is cancelled but I'm wondering if the order status will still be PARTIALLY_FILLED or it becomes CANCELED and how to handle that case.

Thanks!

maker vs isBuyerMaker

There is already a question about this here... But I still couldn't get my head around it.

My observation:

maker: true // The trade should be marked RED ?
maker: false // The trade should be marked GREEN ?
isBuyerMaker: true // I don't know what this is or what it's used for ?

I just found contradictory information about it, please someone clarify.

I mean what should it mean "IS BUYER MAKER" ? What I buy my own order ?
I buy what I made? What kind of vocabulary is this?

TypeError: Cannot read property 'statusCode' of undefined

I've been running Gekko with Binance v1.3.1
and the app stopped with this code

/node_modules/binance/lib/rest.js:78
if (response.statusCode === 400 && payload.code === -1021 &&
TypeError: Cannot read property 'statusCode' of undefined

Unable to properly close onUserData websocket api due to setInterval function inside it

Even after closing the onUserData websocket , a keepAlive request is still sent by the setInterval function inside this api.

Can someone please explain how to properly close this. Thanks.

Here is a demo code -

binanceWS.onUserData(binanceRest, (data) => {
    console.log(data)
},60000) // Optional, how often the keep alive should be sent in milliseconds 
.then((ws1) => {
    // websocket instance available here
    console.log(ws1)
});

//Close this socket after 10 secs
setTimeout(function deleteUserStream(){    
    binanceRest.closeUserDataStream({
        listenKey:'/////listen key/////'
    })
    .then((r3) => {
       //ws.close();
       console.log(r3);
    })
    .catch((err) => {
        console.error(err);
    });
},10*1000);

Setup the websocket to handle reconnects

Need to figure out how to do this, which indications are given by ws that there's been a connection error. A number of the routes push data every second. Should be possible to attempt a reconnect if nothing is received for X amount of seconds. Maybe have incremental back off on the reconnects. More info/inspiration here: issc29@76bfeaf

User data Websocket

Hi, can't seem to get user data websocket to work.
I tried the example on github but i get:

    ^

TypeError: Cannot read property 'then' of undefined

if i comment out 'then' it does nothing...

Error: Unexpected server response: 504

Hello! I'm trying to set up websockets to monitor order books (depth = 10) and this error keeps killing my code:

Error: Unexpected server response: 504
at ClientRequest.req.on (/Users/me/Desktop/code/binance/node_modules/ws/lib/websocket.js:590:5)
at emitOne (events.js:116:13)
at ClientRequest.emit (events.js:211:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:551:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
at TLSSocket.socketOnData (_http_client.js:440:20)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)

Occasionally it's 502, as well.

Is there a way to catch the error in my code? I don't see an onError event or anything. I tried putting the .onDepthLevelUpdate function in a try/catch block, to no avail.

Thanks!
Jason

Editing to add some additional detail: It's intermittent (as expected from 502/504 errors) but typically happens ~20-30 seconds after I start the sockets.

Callback err and data

Hey, as usual I was trying out this wrapper, and before reading the documentation, my blind guess for (eg:) allOrders method was this;

binanceRest.allOrders('BNBBTC', (data) => {
        console.log(data);
});

Which does not work should have had error as first parameter, having the "error" as the first parameter looked kinda weird, wanted to give feedback about it. What about swapping them, or having an error message of "No error" in order to lead the developers blindly guessing, because in my example all I see in the console is "null" string.

Thank you for the wrapper by the way!

any proxy support?

Hello
Is it possible to use "socks-proxy-agent" or "https-proxy-agent"?
I added a proxy agent object to binance constructor options as "agent" -like how i do in ccxt- but it doesn't work.

Issue with timestamp request on a buy order

Hi,

I first create a call to check /api/v1/ticker/24hr and then try to issue a buy but I get the following error.

buyObj { symbol: 'APPCBTC', side: 'BUY', type: 'LIMIT', timeInForce: 'IOC', quantity: '4.40760', price: 0.00018150460000000002, timestamp: 1515391995190 }

ERR in buy {"code":-1111,"msg":"Precision is over the maximum defined for this asset."} :: { BINANCE }

What do I need to adjust to have this work?

Thank you

#withdraw returns {"code":-1022,"msg":"Signature for this request is not valid."} when I use characters within the name that need to be escaped

Hi, I'm trying to withdraw some funds but they always answer me with the code 1022. Used version 1.3.3

What have I investigated yet?

  1. Checked if my API keys are correct (I did #newOrder which is SIGNED as well and it worked)
  2. Checked if mandatory permissions have been enabled for those keys (had to tick withdrawal option on the permissions list and restrict my IP address)
  3. Changed recvWindow to many different values between 5000-60000 with no results
  4. Changed handleDrift to true with no result
  5. Changed the _getTime() function to return new Date().getTime() + 10000; with no results (based on @zoeyg suggestion located in https://github.com/zoeyg/binance/issues/34)

My current configuration:

image

My withdrawal function:

image

Please advise

Update

Finally, I figured out what happened there. By adding a 'name' param like '[${STAGE}]: Main KS's wallet in ETH' it seems that your library does something wrong with building URL params because of the escape codes.

I suggest to fix it as it may cause unexpected and difficult to detect bugs.

Thanks!

An Error!

when i run the demo follow the README
`node_modules/binance/lib/rest.js:8
class BinanceRest {
^^^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
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)`

Why are REST options logged to console?

When running the package in Heroku, the REST call parameters (options object) is logged to the console. Do you know why this might be so? Is there anywhere you are logging to stdout? I checked the request package dependency and although it has a debug switch, it does not seem to be the culprit.

For example the user data stream keep alive sends this to the console output:

2018-01-28T14:50:39.176301+00:00 app[worker.1]: {"url":"https://api.binance.com/api/v1/userDataStream?listenKey=xxxxxx","timeout":15000,"headers":{"X-MBX-APIKEY":"xxxxxx"},"method":"PUT"}

error from RVS

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

Error: RSV2 and RSV3 must be clear
    at Receiver.getInfo (/Users/xxx/Documents/czJxARI/node_modules/binance/node_modules/ws/lib/Receiver.js:184:18)
    at Receiver.startLoop (/Users/xxx/Documents/czJxARI/node_modules/binance/node_modules/ws/lib/Receiver.js:153:16)
    at Receiver.add (/Users/xxx/Documents/czJxARI/node_modules/binance/node_modules/ws/lib/Receiver.js:139:10)
    at TLSSocket._ultron.on (/Users/xxx/Documents/czJxARI/node_modules/binance/node_modules/ws/lib/WebSocket.js:138:22)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at TLSSocket.Readable.push (_stream_readable.js:208:10)
    at TLSWrap.onread (net.js:594:20)

got error from the console.

Ticker return multiple symbol?

for single symbol

https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC
{
  "symbol": "LTCBTC",
  "price": "4.00000200"
}

how to get the result 2 or more symbols?

[
  {
    "symbol": "LTCBTC",
    "price": "4.00000200"
  },
  {
    "symbol": "ETHBTC",
    "price": "0.07946600"
  }
]

How to use?

I thought it was plain JavaScript which I can simply link and use.

  1. Installed Node
  2. cd binance-master
  3. npm install

I have never used node but I am good with JavaScript. Can you list down in few steps that how to use/run this?

Making /api/v3/myTrades work without passing a specific symbol

I would like to retrieve all my past trades, but I don't remember all the symbols I have traded with. Right now it's not possible to get all my trades without passing a symbol, so to do that I have to get all the available symbols in Binance and then loop through and make a request to myTrades for each symbol. Besides making too many requests, many of them return of course an empty response.

Do you plan to fix this anytime soon?

Thanks

No 'Access-Control-Allow-Origin' header is present on

How can I solve this issue for streaming the API and it is also doing same for REST API?

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

image

Time synchronization with Binance

I'm seeing a number if reports with ZenBot, Gekko and the CCXT projects of Binance users getting a Response Code 400 due to their internal system clocks skewing by more than 1 second. Apparently Binance required the timestamps on all signed requests to be within 1000ms of their internal time. The issue arises for Windows users where time syncrhronization is either turned off, or whose clocks have a large skew (as the time sync service in windows only updates once a day).

For this reason it may be a good idea to implement an NIST time sync based service directly into the binance module and use an internal clock for generating timestamps over the system clock.

For reference see the following issues

askmike/gekko#1663
ccxt/ccxt#936

I will admit that I am unsure of the feasibility of this task, but probably we shouldn't ever update the computer's system time as part of the process.

TypeScript typings

I use TypeScript for my Node backends. Are you interested in a PR to add typings to this project?

Add jsdoc comments

Specifically needs the BinanceWS object and methods. Should likely accompany the work for 2.0 that changes the class.

Rewriting in functional style

I wonder about the interest to simplify this library with functional style.

Here is essentially complete implementation for the websocket part, without beautifier
(which would be a composition with another transformer):

const { map, curry, pipe, compose } = require('ramda')
const BASE_URL = 'wss://stream.binance.com:9443/ws/'

// the url getter is independent of the rest of the code
const getUrl = (type, symbol) => [
  BASE_URL, 
  symbol.toLowerCase(),
  `@`,
  type
].join('')

// general purpose websocket factory
const WebSocket = require('ws')
const createWS = path => cb => 
  new WebSocket(path).on('message', cb)

// Functor structure on the CPS (continuation-passing-style) functions
const cpsMap = f => cpsFn => 
  // new CPS function
  cb => cpsFn(compose(cb, f))

// Final WS stream from Binance as functional composition
const getStream = pipe
(
  getUrl
, createWS // returns f: cb -> void
// apply map from the CPS functor
, cpsMap(JSON.parse)
)

// start WS stream and pass the callback
getStream('trade', 'BNBBTC')(console.log)

Inconsistent open/start & close/end time parameters in the kline REST & WS data

Is openTime the same as startTime? If so, does the same also apply to closeTime & endTime?

https://github.com/aarongarvey/binance/blob/master/lib/beautifier.js#L18
https://github.com/aarongarvey/binance/blob/master/lib/beautifier.js#L75

What are your thoughts in normalising the differences in both beautifier sections for consistency, if they are indeed the same? It's less overhead for developers looking to combine both websocket and historic data. Right now I'm assuming they are the same, and simply changing the var in the response before passing it to the DB.

There's also these:

  • quoteAssetVolume & quoteVolume
  • volumeActive & quoteVolumeActive & takerBaseAssetVolume & takerQuoteAssetVolume

I assume the latter are related but I'm not sure. Thanks!

Error: Response code 400 - code: -1022, msg: 'Signature for this request is not valid.'

Hey,

The binance module (1.3.1) is not working for me:

const binance = require('binance');

const client = new binance.BinanceRest({
  key: 'x',
  secret: 'y',
  timeout: 15000,
  recvWindow: 60000, // suggested by binance
  disableBeautification: false,
  handleDrift: true
});

client.account({}, console.log);

Returns the following:

Error: Response code 400
    at Request.request [as _callback] (/Users/pear/projects/gekko/node_modules/binance/lib/rest.js:90:34)
    at Request.self.callback (/Users/pear/projects/gekko/node_modules/request/request.js:186:22)
    at emitTwo (events.js:125:13)
    at Request.emit (events.js:213:7)
    at Request.<anonymous> (/Users/pear/projects/gekko/node_modules/request/request.js:1163:10)
    at emitOne (events.js:115:13)
    at Request.emit (events.js:210:7)
    at IncomingMessage.<anonymous> (/Users/pear/projects/gekko/node_modules/request/request.js:1085:12)
    at Object.onceWrapper (events.js:312:19)
    at emitNone (events.js:110:20) { code: -1022, msg: 'Signature for this request is not valid.' }

Setting this line to 1022 instead of 1021 did not fix it for me. Do you have any ideas?

receiving timestamp error

code: -1021, msg: 'Timestamp for this request is not valid.

Receiving this from binance when using binanceRest.account()

websocket.close() ?

I may be missing something here, but is there no way to do the following?

const ws = new Binance.BinanceWS

...

// Manually close the socket
ws.close()

new crash

Hi,

I made a search here and didn't find this crash before. Also, I'm using the version 1.3.0, that I believe is the last one.

Users/gekko/node_modules/binance/lib/rest.js:78
                    if (response.statusCode === 400 && payload.code === -1021 &&
                                ^

TypeError: Cannot read property 'statusCode' of undefined
    at Request.request [as _callback] (/Users/gekko/node_modules/binance/lib/rest.js:78:33)
    at self.callback (/Users/gekko/node_modules/request/request.js:186:22)
    at emitOne (events.js:115:13)
    at Request.emit (events.js:210:7)
    at Timeout._onTimeout (/Usersgekko/node_modules/request/request.js:849:16)
    at ontimeout (timers.js:469:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:264:5)

updates order status?

Could you please help me to understand how to track order updates and status?
Or at least what to use or where to look at?

what should I use if I need to track all updates continuously?

I tried to find something in docs, but didn't succeed. Please help

Crashing when used with Electron

I've made a bug related to this in electron-compile: #286

Below is the same thing I put in that issue.


I've run into a situation where when I do two simultaneous rest calls from the binance package I shortly after encounter a crash.

Repository: https://github.com/apexearth/electron-binance-crash

Drobos-MBP:electron-binance-crash apexearth$ npm start

> [email protected] start /Users/apexearth/WebstormProjects/electron-binance-crash
> electron .

2018-01-06 10:13:57.051 Electron Helper[7161:513265] Couldn't set selectedTextBackgroundColor from default ()
[7160:0106/101405.604007:FATAL:partition_alloc.cc(934)] Check failed: page->num_allocated_slots != -1. 
0   Electron Framework                  0x000000010ff7621c crashpad::CloseMultipleNowOrOnExec(int, int) + 970204
1   Electron Framework                  0x000000010ff3da33 crashpad::CloseMultipleNowOrOnExec(int, int) + 738803
2   Electron Framework                  0x000000010ff55491 crashpad::CloseMultipleNowOrOnExec(int, int) + 835665
3   Electron Framework                  0x0000000112bf2b9c crashpad::CloseMultipleNowOrOnExec(int, int) + 47617884
4   libnode.dylib                       0x000000011462f021 v8::internal::DeferredHandles::Iterate(v8::internal::ObjectVisitor*) + 19633
5   libnode.dylib                       0x0000000114ab9179 v8::internal::AllocationSpaceName(v8::internal::AllocationSpace) + 21993
6   libnode.dylib                       0x0000000114ac72d0 v8::internal::AllocationSpaceName(v8::internal::AllocationSpace) + 79680
7   libnode.dylib                       0x0000000114ab9f70 v8::internal::AllocationSpaceName(v8::internal::AllocationSpace) + 25568
8   libnode.dylib                       0x0000000114ab2717 v8::internal::operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, v8::internal::MachineType) + 73127
9   libnode.dylib                       0x0000000114ab030e v8::internal::operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, v8::internal::MachineType) + 63902
10  libnode.dylib                       0x00000001148cdaa3 v8::internal::Heap::CreateFillerObjectAt(unsigned char*, int, v8::internal::ClearRecordedSlots) + 7555
11  libnode.dylib                       0x00000001148cc2d5 v8::internal::Heap::CreateFillerObjectAt(unsigned char*, int, v8::internal::ClearRecordedSlots) + 1461
12  libnode.dylib                       0x00000001148cb813 v8::internal::DeferredHandleScope::Detach() + 110595
13  libnode.dylib                       0x00000001148da7be v8::internal::Heap::CreateFillerObjectAt(unsigned char*, int, v8::internal::ClearRecordedSlots) + 60062
14  libnode.dylib                       0x0000000114978ec6 v8::internal::IdentityMapBase::NextIndex(int) const + 950
15  Electron Framework                  0x000000010ff86da1 crashpad::CloseMultipleNowOrOnExec(int, int) + 1038689
16  Electron Framework                  0x0000000112b9417f crashpad::CloseMultipleNowOrOnExec(int, int) + 47230271
17  Electron Framework                  0x0000000112b921d2 crashpad::CloseMultipleNowOrOnExec(int, int) + 47222162
18  Electron Framework                  0x000000010ff86da1 crashpad::CloseMultipleNowOrOnExec(int, int) + 1038689
19  Electron Framework                  0x000000010ff4f15b crashpad::CloseMultipleNowOrOnExec(int, int) + 810267
20  Electron Framework                  0x000000010ff4f4ac crashpad::CloseMultipleNowOrOnExec(int, int) + 811116
21  Electron Framework                  0x000000010ff4f863 crashpad::CloseMultipleNowOrOnExec(int, int) + 812067
22  Electron Framework                  0x000000010ff52cea crashpad::CloseMultipleNowOrOnExec(int, int) + 825514
23  Electron Framework                  0x000000010ff01eaa crashpad::CloseMultipleNowOrOnExec(int, int) + 494186
24  Electron Framework                  0x000000010ff5270f crashpad::CloseMultipleNowOrOnExec(int, int) + 824015
25  CoreFoundation                      0x00007fff4b16e5a1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
26  CoreFoundation                      0x00007fff4b22835c __CFRunLoopDoSource0 + 108
27  CoreFoundation                      0x00007fff4b151040 __CFRunLoopDoSources0 + 208
28  CoreFoundation                      0x00007fff4b1504bd __CFRunLoopRun + 1293
29  CoreFoundation                      0x00007fff4b14fd23 CFRunLoopRunSpecific + 483
30  Foundation                          0x00007fff4d22fb76 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 277
31  Electron Framework                  0x000000010ff5338e crashpad::CloseMultipleNowOrOnExec(int, int) + 827214
32  Electron Framework                  0x000000010ff52b4c crashpad::CloseMultipleNowOrOnExec(int, int) + 825100
33  Electron Framework                  0x000000010ff4ee2e crashpad::CloseMultipleNowOrOnExec(int, int) + 809454
34  Electron Framework                  0x000000010ff67f63 crashpad::CloseMultipleNowOrOnExec(int, int) + 912163
35  Electron Framework                  0x00000001108b7bac crashpad::CloseMultipleNowOrOnExec(int, int) + 10676076
36  Electron Framework                  0x000000011012446b crashpad::CloseMultipleNowOrOnExec(int, int) + 2732075
37  Electron Framework                  0x0000000111be7288 crashpad::CloseMultipleNowOrOnExec(int, int) + 30793288
38  Electron Framework                  0x00000001101236c4 crashpad::CloseMultipleNowOrOnExec(int, int) + 2728580
39  Electron Framework                  0x000000010fcfa98a AtomMain + 74
40  Electron Helper                     0x000000010fcf4f26 main + 38
41  libdyld.dylib                       0x00007fff729a0115 start + 1
42  ???                                 0x0000000000000011 0x0 + 17

^C

Does trade.isBuyerMaker = true imply this trade was completed by a sell?

Am I correct to infer that a trade with isBuyerMaker = true implies that this trade was completed by a sell?
I.e.: a buyer added an order to the depthbook and this trade is completed by a taker of said order (implying a sell)

Similarly, does aggTrade.maker= true imply this aggtrade is completed by a sell?

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.