Binance connector in Nodejs
This is a lightweight library that works as a connector to Binance public API. It’s designed to be simple, clean, and easy to use with minimal dependencies.
- Supported APIs:
/api/*
/sapi/*
- Spot Websocket Market Stream
- Spot User Data Stream
- Inclusion of test cases and examples
- Customizable base URL, request timeout and HTTP proxy
- Response metadata can be displayed
- Customizable Logger
Installation
npm install @nevgeniy/binance-socks-connector
Documentation
https://binance.github.io/binance-connector-node/
RESTful APIs
const { Spot } = require('@nevgeniy/binance-socks-connector')
const apiKey = ''
const apiSecret = ''
const client = new Spot(
apiKey,
apiSecret,
{
socks: {
hostname: '127.0.0.1',
port: 1080,
username: 'test',
password: '123456'
}
}
)
client.account().then(response => client.logger.log(response.data))
client.newOrder('BNBUSDT', 'BUY', 'LIMIT', {
price: '350',
quantity: 1,
timeInForce: 'GTC'
}).then(response => client.logger.log(response.data))
.catch(error => client.logger.error(error))
Please find examples
folder to check for more endpoints.
Testnet
While /sapi/*
endpoints don't have testnet environment yet, /api/*
endpoints can be tested in
Spot Testnet. You can use it by changing the base URL:
const client = new Spot(apiKey, apiSecret, { baseURL: 'https://testnet.binance.vision'})
Base URL
If base_url
is not provided, it defaults to api.binance.com
.
It's recommended to pass in the base_url
parameter, even in production as Binance provides alternative URLs in case of performance issues:
https://api1.binance.com
https://api2.binance.com
https://api3.binance.com
Optional Parameters
Optional parameters are encapsulated to a single object as the last function parameter.
const { Spot } = require('@nevgeniy/binance-socks-connector')
const apiKey = ''
const apiSecret = ''
const client = new Spot(apiKey, apiSecret, socks:{hostname:'127.0.0.1', port: 1080, username: 'test', password: '123456'})
client.account({ recvWindow: 2000 }).then(response => client.logger.log(response.data))
Response Metadata
The Binance API server provides weight usages in the headers of each response. This information can be fetched from headers
property. x-mbx-used-weight
and x-mbx-used-weight-1m
show the total weight consumed within 1 minute.
// client initialization is skipped
client.exchangeInfo().then(response => client.logger.log(response.headers['x-mbx-used-weight-1m']))
Custom Logger Integration
const Spot = require('@binance/connector')
const fs = require('fs')
const { Console } = require('console')
const output = fs.createWriteStream('./logs/stdout.log')
const errorOutput = fs.createWriteStream('./logs/stderr.log')
const logger = new Console({ stdout: output, stderr: errorOutput })
const client = new Spot('', '', {logger: logger})
client.exchangeInfo().then(response => client.logger.log(response.data))
The default logger defined in the package is Node.js Console class. Its output is sent to process.stdout
and process.stderr
, same as the global console.
Error
There are 2 types of error that may be returned from the API server and the user has to handle it properly:
Websocket
const { Spot } = require('@binance/connector')
const client = new Spot('', '', {
wsURL: 'wss://testnet.binance.vision'
})
const callbacks = {
open: () => client.logger.log('open'),
close: () => client.logger.log('closed'),
message: data => client.logger.log(data)
}
const aggTrade = client.aggTradeWS('bnbusdt', callbacks)
setTimeout(() => client.unsubscribe(aggTrade), 3000)
const combinedStreams = client.combinedStreams(['btcusdt@miniTicker', 'ethusdt@tikcer'], callbacks)
More websocket examples are available in the examples
folder
Unsubscribe a Stream
Unsubscription is achieved by closing the connection. If this method is called without any connection established, the console will output a message No connection to close.
// client initialization is skipped
const wsRef = client.aggTradeWS('bnbusdt', callbacks)
// The connection (bnbusdt@aggTrade) is closed after 3 secs.
setTimeout(() => client.unsubscribe(wsRef), 3000)
Auto Reconnect
If there is a close event not initiated by the user, the reconnection mechanism will be triggered in 5 secs.
Custom Logger Integration
const { Console } = require('console')
const fs = require('fs')
const Spot = require('@binance/connector')
const output = fs.createWriteStream('./logs/stdout.log')
const errorOutput = fs.createWriteStream('./logs/stderr.log')
const logger = new Console({ stdout: output, stderr: errorOutput })
const client = new Spot('', '', {logger})
const callbacks = {
open: () => client.logger.log('open'),
close: () => client.logger.log('closed'),
message: data => client.logger.log(data)
}
const wsRef = client.aggTradeWS('bnbusdt', callbacks)
setTimeout(() => client.unsubscribe(wsRef), 5000)
The default logger defined in the package is Node.js Console class. Its output is sent to process.stdout
and process.stderr
, same as the global console.
Note that when the connection is initialized, the console outputs a list of callbacks in the form of listen to event: <event_name>
.
Test
npm install
npm run test
Limitation
Futures and Vanilla Options APIs are not supported:
/fapi/*
/dapi/*
/vapi/*
- Associated Websocket Market and User Data Streams