Code Monkey home page Code Monkey logo

binance-api-node's Introduction

binance-api-node build bnb

A complete API wrapper for the Binance API.

Note: This wrapper uses Promises, if they are not supported in your environment, you might want to add a polyfill for them.

For PRs or issues, head over to the source repository.

Installation

yarn add binance-api-node

Getting started

Import the module and create a new client. Passing api keys is optional only if you don't plan on doing authenticated calls. You can create an api key here.

import Binance from 'binance-api-node'

const client = Binance()

// Authenticated client, can make signed calls
const client2 = Binance({
  apiKey: 'xxx',
  apiSecret: 'xxx',
  getTime: xxx,
})

client.time().then(time => console.log(time))

If you do not have an appropriate babel config, you will need to use the basic commonjs requires.

const Binance = require('binance-api-node').default

Every REST method returns a Promise, making this library async await ready. Following examples will use the await form, which requires some configuration you will have to lookup.

Table of Contents

Init

Param Type Required Info
apiKey String false Required when making private calls
apiSecret String false Required when making private calls
getTime Function false Time generator, defaults to () => Date.now()
httpBase String false Changes the default endpoint
httpFutures String false Changes the default endpoint
wsBase String false Changes the default endpoint
wsFutures String false Changes the default endpoint

Public REST Endpoints

ping

Test connectivity to the API.

console.log(await client.ping())

time

Test connectivity to the Rest API and get the current server time.

console.log(await client.time())
Output
1508478457643

exchangeInfo

Get the current exchange trading rules and symbol information. You can optionally pass a symbol to only retrieve info of this specific one.

console.log(await client.exchangeInfo())
Param Type Required Default
symbol String false
Output
{
  "timezone": "UTC",
  "serverTime": 1508631584636,
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 1200
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "SECOND",
      "intervalNum": 1,
      "limit": 10
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "DAY",
      "intervalNum": 1,
      "limit": 100000
    }
  ],
  "exchangeFilters": [],
  "symbols": [{
    "symbol": "ETHBTC",
    "status": "TRADING",
    "baseAsset": "ETH",
    "baseAssetPrecision": 8,
    "quoteAsset": "BTC",
    "quotePrecision": 8,
    "orderTypes": ["LIMIT", "MARKET"],
    "icebergAllowed": false,
    "filters": [{
      "filterType": "PRICE_FILTER",
      "minPrice": "0.00000100",
      "maxPrice": "100000.00000000",
      "tickSize": "0.00000100"
    }, {
      "filterType": "LOT_SIZE",
      "minQty": "0.00100000",
      "maxQty": "100000.00000000",
      "stepSize": "0.00100000"
    }, {
      "filterType": "MIN_NOTIONAL",
      "minNotional": "0.00100000"
    }]
  }]
}

book

Get the order book for a symbol.

console.log(await client.book({ symbol: 'ETHBTC' }))
Param Type Required Default
symbol String true
limit Number false 100
Output
{
  lastUpdateId: 17647759,
  asks:
   [
     { price: '0.05411500', quantity: '5.55000000' },
     { price: '0.05416700', quantity: '11.80100000' }
   ],
  bids:
   [
     { price: '0.05395500', quantity: '2.70000000' },
     { price: '0.05395100', quantity: '11.84100000' }
   ]
}

candles

Retrieves Candlestick for a symbol. Candlesticks are uniquely identified by their open time.

console.log(await client.candles({ symbol: 'ETHBTC' }))
Param Type Required Default Description
symbol String true
interval String false 5m 1m, 3m, 5m, 15m, 30m, 1h, 2h,
4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
limit Number false 500 Max 1000
startTime Number false
endTime Number false
Output
;[
  {
    openTime: 1508328900000,
    open: '0.05655000',
    high: '0.05656500',
    low: '0.05613200',
    close: '0.05632400',
    volume: '68.88800000',
    closeTime: 1508329199999,
    quoteAssetVolume: '2.29500857',
    trades: 85,
    baseAssetVolume: '40.61900000',
  },
]

aggTrades

Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.

console.log(await client.aggTrades({ symbol: 'ETHBTC' }))
Param Type Required Default Description
symbol String true
fromId String false ID to get aggregate trades from INCLUSIVE.
startTime Number false Timestamp in ms to get aggregate trades from INCLUSIVE.
endTime Number false Timestamp in ms to get aggregate trades until INCLUSIVE.
limit Number false 500 Max 500

Note: If both startTime and endTime are sent, limit should not be sent AND the distance between startTime and endTime must be less than 1 hour.

Note: If frondId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.

Output
;[
  {
    aggId: 2107132,
    symbol: 'ETHBTC',
    price: '0.05390400',
    quantity: '1.31000000',
    firstId: 2215345,
    lastId: 2215345,
    timestamp: 1508478599481,
    isBuyerMaker: true,
    wasBestPrice: true,
  },
]

trades

Get recent trades of a symbol.

console.log(await client.trades({ symbol: 'ETHBTC' }))
Param Type Required Default Description
symbol String true
limit Number false 500 Max 500
Output
;[
  {
    id: 28457,
    price: '4.00000100',
    qty: '12.00000000',
    time: 1499865549590,
    isBuyerMaker: true,
    isBestMatch: true,
  },
]

dailyStats

24 hour price change statistics, not providing a symbol will return all tickers and is resource-expensive.

console.log(await client.dailyStats({ symbol: 'ETHBTC' }))
Param Type Required
symbol String false
Output
{
  symbol: 'ETHBTC',
  priceChange: '-0.00112000',
  priceChangePercent: '-1.751',
  weightedAvgPrice: '0.06324784',
  prevClosePrice: '0.06397400',
  lastPrice: '0.06285500',
  lastQty: '0.63500000',
  bidPrice: '0.06285500',
  bidQty: '0.81900000',
  askPrice: '0.06291900',
  askQty: '2.93800000',
  openPrice: '0.06397500',
  highPrice: '0.06419100',
  lowPrice: '0.06205300',
  volume: '126240.37200000',
  quoteVolume: '7984.43091340',
  openTime: 1521622289427,
  closeTime: 1521708689427,
  firstId: 45409308, // First tradeId
  lastId: 45724293, // Last tradeId
  count: 314986 // Trade count
}

avgPrice

Current average price for a symbol.

console.log(await client.avgPrice({ symbol: 'ETHBTC' }))
Param Type Required
symbol String true
Output
{
  "mins": 5,
  "price": "9.35751834"
}

prices

Latest price for a symbol, not providing the symbol will return prices for all symbols.

console.log(await client.prices())
Param Type Required
symbol String false
Output
{
  ETHBTC: '0.05392500',
  LTCBTC: '0.01041100',
  ...
}

allBookTickers

Best price/qty on the order book for all symbols.

console.log(await client.allBookTickers())
Output
{
  DASHBTC: {
    symbol: 'DASHBTC',
    bidPrice: '0.04890400',
    bidQty: '0.74100000',
    askPrice: '0.05230000',
    askQty: '0.79900000'
  },
  DASHETH: {
    symbol: 'DASHETH',
    bidPrice: '0.89582000',
    bidQty: '0.63300000',
    askPrice: '1.02328000',
    askQty: '0.99900000'
  }
  ...
}

Futures Public REST Endpoints

futures ping

Test connectivity to the API.

console.log(await client.futuresPing())

futures time

Test connectivity to the Rest API and get the current server time.

console.log(await client.futuresTime())
Output
1508478457643

futures exchangeInfo

Get the current exchange trading rules and symbol information.

console.log(await client.futuresExchangeInfo())
Output
{
  "timezone": "UTC",
  "serverTime": 1508631584636,
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 1200
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "SECOND",
      "intervalNum": 1,
      "limit": 10
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "DAY",
      "intervalNum": 1,
      "limit": 100000
    }
  ],
  "exchangeFilters": [],
  "symbols": [...]
}

futures book

Get the order book for a symbol.

console.log(await client.futuresBook({ symbol: 'BTCUSDT' }))
Param Type Required Default
symbol String true
limit Number false 100
Output
{
  lastUpdateId: 17647759,
  asks:
   [
     { price: '8000.05411500', quantity: '54.55000000' },
     { price: '8000.05416700', quantity: '1111.80100000' }
   ],
  bids:
   [
     { price: '8000.05395500', quantity: '223.70000000' },
     { price: '8000.05395100', quantity: '1134.84100000' }
   ]
}

futures candles

Retrieves Candlestick for a symbol. Candlesticks are uniquely identified by their open time.

console.log(await client.futuresCandles({ symbol: 'BTCUSDT' }))
Param Type Required Default Description
symbol String true
interval String false 5m 1m, 3m, 5m, 15m, 30m, 1h, 2h,
4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
limit Number false 500 Max 1000
startTime Number false
endTime Number false
Output
;[
  {
    openTime: 1508328900000,
    open: '0.05655000',
    high: '0.05656500',
    low: '0.05613200',
    close: '0.05632400',
    volume: '68.88800000',
    closeTime: 1508329199999,
    quoteAssetVolume: '2.29500857',
    trades: 85,
    baseAssetVolume: '40.61900000',
  },
]

futures aggTrades

Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.

console.log(await client.futuresAggTrades({ symbol: 'ETHBTC' }))
Param Type Required Default Description
symbol String true
fromId String false ID to get aggregate trades from INCLUSIVE.
startTime Number false Timestamp in ms to get aggregate trades from INCLUSIVE.
endTime Number false Timestamp in ms to get aggregate trades until INCLUSIVE.
limit Number false 500 Max 500

Note: If both startTime and endTime are sent, limit should not be sent AND the distance between startTime and endTime must be less than 24 hours.

Note: If frondId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.

Output
;[
  {
    aggId: 2107132,
    price: '0.05390400',
    quantity: '1.31000000',
    firstId: 2215345,
    lastId: 2215345,
    timestamp: 1508478599481,
    isBuyerMaker: true,
    wasBestPrice: true,
  },
]

futures trades

Get recent trades of a symbol.

console.log(await client.futuresTrades({ symbol: 'ETHBTC' }))
Param Type Required Default Description
symbol String true
limit Number false 500 Max 500
Output
;[
  {
    id: 28457,
    price: '4.00000100',
    qty: '12.00000000',
    time: 1499865549590,
    isBuyerMaker: true,
    isBestMatch: true,
  },
]

futures dailyStats

24 hour price change statistics, not providing a symbol will return all tickers and is resource-expensive.

console.log(await client.futuresDailyStats({ symbol: 'ETHBTC' }))
Param Type Required
symbol String false
Output
{
  symbol: 'BTCUSDT',
  priceChange: '-0.00112000',
  priceChangePercent: '-1.751',
  weightedAvgPrice: '0.06324784',
  prevClosePrice: '0.06397400',
  lastPrice: '0.06285500',
  lastQty: '0.63500000',
  bidPrice: '0.06285500',
  bidQty: '0.81900000',
  askPrice: '0.06291900',
  askQty: '2.93800000',
  openPrice: '0.06397500',
  highPrice: '0.06419100',
  lowPrice: '0.06205300',
  volume: '126240.37200000',
  quoteVolume: '7984.43091340',
  openTime: 1521622289427,
  closeTime: 1521708689427,
  firstId: 45409308, // First tradeId
  lastId: 45724293, // Last tradeId
  count: 314986 // Trade count
}

futures prices

Latest price for symbol, not providing a symbol will return latest price for all symbols and is resource-expensive.

console.log(await client.futuresPrices())
Param Type Required
symbol String false
Output
{
  BTCUSDT: '8590.05392500',
  ETHUSDT: '154.1100',
  ...
}

futures allBookTickers

Best price/qty on the order book for all symbols.

console.log(await client.futuresAllBookTickers())
Output
{
  BTCUSDT: {
    symbol: 'BTCUSDT',
    bidPrice: '0.04890400',
    bidQty: '0.74100000',
    askPrice: '0.05230000',
    askQty: '0.79900000'
  },
  ETHUSDT: {
    symbol: 'ETHUSDT',
    bidPrice: '0.89582000',
    bidQty: '0.63300000',
    askPrice: '1.02328000',
    askQty: '0.99900000'
  }
  ...
}

futures markPrice

Mark Price and Funding Rate.

console.log(await client.futuresMarkPrice())
Output
{
    "symbol": "BTCUSDT",
    "markPrice": "11012.80409769",
    "lastFundingRate": "-0.03750000",
    "nextFundingTime": 1562569200000,
    "time": 1562566020000
}

futures AllForceOrders

Get all Liquidation Orders.

console.log(await client.futuresAllForceOrders())
Param Type Required
symbol String false
startTime Long false
endTime Long false
limit Long false
Output
;[
  {
    symbol: 'BTCUSDT', // SYMBOL
    price: '7918.33', // ORDER_PRICE
    origQty: '0.014', // ORDER_AMOUNT
    executedQty: '0.014', // FILLED_AMOUNT
    avragePrice: '7918.33', // AVG_PRICE
    status: 'FILLED', // STATUS
    timeInForce: 'IOC', // TIME_IN_FORCE
    type: 'LIMIT',
    side: 'SELL', // DIRECTION
    time: 1568014460893,
  },
]

Delivery Public REST Endpoints

delivery ping

Test connectivity to the API.

console.log(await client.deliveryPing())

delivery time

Test connectivity to the Rest API and get the current server time.

console.log(await client.deliveryTime())
Output
1508478457643

delivery exchangeInfo

Get the current exchange trading rules and symbol information.

console.log(await client.deliveryExchangeInfo())
Output
{
  timezone: 'UTC',
  serverTime: 1663099219744,
  rateLimits: [
    {
      rateLimitType: 'REQUEST_WEIGHT',
      interval: 'MINUTE',
      intervalNum: 1,
      limit: 2400
    },
    {
      rateLimitType: 'ORDERS',
      interval: 'MINUTE',
      intervalNum: 1,
      limit: 1200
    }
  ],
  exchangeFilters: [],
  symbols: [...]
}

delivery book

Get the order book for a symbol.

console.log(await client.deliveryBook({ symbol: 'TRXUSD_PERP' }))
Param Type Required Default
symbol String true
limit Number false 500
Output
{
  lastUpdateId: 17647759,
  asks:
   [
     { price: '8000.05411500', quantity: '54.55000000' },
     { price: '8000.05416700', quantity: '1111.80100000' }
   ],
  bids:
   [
     { price: '8000.05395500', quantity: '223.70000000' },
     { price: '8000.05395100', quantity: '1134.84100000' }
   ]
}

delivery candles

Retrieves Candlestick for a symbol. Candlesticks are uniquely identified by their open time.

console.log(await client.deliveryCandles({ symbol: 'TRXUSD_PERP' }))
Param Type Required Default Description
symbol String true
interval String false 5m 1m, 3m, 5m, 15m, 30m, 1h, 2h,
4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
limit Number false 500 Max 1000
startTime Number false
endTime Number false
Output
[
  {
    openTime: 1663104600000,
    open: '0.06091',
    high: '0.06091',
    low: '0.06086',
    close: '0.06090',
    volume: '7927',
    closeTime: 1663104899999,
    baseVolume: '1302212.12820796',
    trades: 75,
    quoteAssetVolume: '386',
    baseAssetVolume: '63382.78318786'
  }
]

delivery aggTrades

Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.

console.log(await client.deliveryAggTrades({ symbol: 'TRXUSD_PERP' }))
Param Type Required Default Description
symbol String true
fromId String false ID to get aggregate trades from INCLUSIVE.
startTime Number false Timestamp in ms to get aggregate trades from INCLUSIVE.
endTime Number false Timestamp in ms to get aggregate trades until INCLUSIVE.
limit Number false 500 Max 1000

Note: If both startTime and endTime are sent, limit should not be sent AND the distance between startTime and endTime must be less than 24 hours.

Note: If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.

Note : Only market trades will be aggregated and returned, which means the insurance fund trades and ADL trades won't be aggregated.

Output
[
  {
    aggId: 14642023,
    symbol: 'TRXUSD_PERP',
    price: '0.06087',
    quantity: '50',
    firstId: 26319898,
    lastId: 26319898,
    timestamp: 1663105187120,
    isBuyerMaker: false,
  }
]

delivery trades

Get recent trades of a symbol.

console.log(await client.deliveryTrades({ symbol: 'TRXUSD_PERP' }))
Param Type Required Default Description
symbol String true
limit Number false 500 Max 1000
Output
;[
  {
    id: 26319660,
    price: '0.06097',
    qty: '28',
    baseQty: '4592.42250287',
    time: 1663103746267,
    isBuyerMaker: true
  },
]

delivery dailyStats

24 hour price change statistics, not providing a symbol will return all tickers and is resource-expensive.

console.log(await client.deliveryDailyStats({ symbol: 'TRXUSD_PERP' }))
Param Type Required
symbol String false
pair String false
Output
{
  symbol: 'TRXUSD_PERP',
  pair: 'TRXUSD',
  priceChange: '-0.00277',
  priceChangePercent: '-4.353',
  weightedAvgPrice: '0.06248010',
  lastPrice: '0.06087',
  lastQty: '4',
  openPrice: '0.06364',
  highPrice: '0.06395',
  lowPrice: '0.06069',
  volume: '545316',
  baseVolume: '87278342.48218514',
  openTime: 1663019640000,
  closeTime: 1663106045576,
  firstId: 26308774,
  lastId: 26320065,
  count: 11292
}

delivery prices

Latest price for all symbols.

console.log(await client.futuresPrices())
Output
{
  BTCUSDT: '8590.05392500',
  ETHUSDT: '154.1100',
  ...
}

delivery allBookTickers

Best price/qty on the order book for all symbols.

console.log(await client.deliveryAllBookTickers())
Output
{
  BTCUSD_PERP: {
    symbol: 'BTCUSD_PERP',
    pair: 'BTCUSD',
    bidPrice: '20120.9',
    bidQty: '13673',
    askPrice: '20121.0',
    askQty: '2628',
    time: 1663106372658
  },
  ETHUSD_PERP: {
    symbol: 'ETHUSD_PERP',
    pair: 'ETHUSD',
    bidPrice: '1593.63',
    bidQty: '7210',
    askPrice: '1593.64',
    askQty: '27547',
    time: 1663106372667
  }
  ...
}

delivery markPrice

Mark Price and Funding Rate.

console.log(await client.deliveryMarkPrice())
Output
[
  {
    symbol: 'BTCUSD_221230',
    pair: 'BTCUSD',
    markPrice: '20158.81560758',
    indexPrice: '20152.05327273',
    estimatedSettlePrice: '20147.96717735',
    lastFundingRate: '',
    interestRate: '',
    nextFundingTime: 0,
    time: 1663106459005
  },
  {
    symbol: 'FILUSD_PERP',
    pair: 'FILUSD',
    markPrice: '5.88720470',
    indexPrice: '5.89106242',
    estimatedSettlePrice: '5.89377086',
    lastFundingRate: '0.00010000',
    interestRate: '0.00010000',
    nextFundingTime: 1663113600000,
    time: 1663106459005
  }
  ...
]

Authenticated REST Endpoints

Note that for all authenticated endpoints, you can pass an extra parameter useServerTime set to true in order to fetch the server time before making the request.

order

Creates a new order.

console.log(
  await client.order({
    symbol: 'XLMETH',
    side: 'BUY',
    quantity: '100',
    price: '0.0002',
  }),
)
Param Type Required Default Description
symbol String true
side String true BUY,SELL
type String false LIMIT LIMIT, MARKET
quantity String true
price String true Optional for MARKET orders
timeInForce String false GTC FOK, GTC, IOC
newClientOrderId String false A unique id for the order. Automatically generated if not sent.
stopPrice Number false Used with stop orders
activationPrice Number false Used with TRAILING_STOP_MARKET
callbackRate Number false Used with TRAILING_STOP_MARKET
newOrderRespType String false RESULT Returns more complete info of the order. ACK, RESULT, or FULL
icebergQty Number false Used with iceberg orders
recvWindow Number false

Additional mandatory parameters based on type:

Type Additional mandatory parameters
LIMIT timeInForce, quantity, price
MARKET quantity
STOP quantity, price, stopPrice
STOP_LOSS_LIMIT timeInForce, quantity, price, stopPrice
STOP_LOSS_MARKET stopPrice
TAKE_PROFIT quantity, price, stopPrice
TAKE_PROFIT_MARKET stopPrice
STOP_PROFIT_LIMIT timeInForce, quantity, price, stopPrice
LIMIT_MAKER quantity, price
TRAILING_STOP_MARKET callbackRate, activationPrice
  • LIMIT_MAKER are LIMIT orders that will be rejected if they would immediately match and trade as a taker.
  • STOP and TAKE_PROFIT will execute a MARKET order when the stopPrice is reached.
  • Any LIMIT or LIMIT_MAKER type order can be made an iceberg order by sending an icebergQty.
  • Any order with an icebergQty MUST have timeInForce set to GTC.
Output
{
  symbol: 'XLMETH',
  orderId: 1740797,
  clientOrderId: '1XZTVBTGS4K1e',
  transactTime: 1514418413947,
  price: '0.00020000',
  origQty: '100.00000000',
  executedQty: '0.00000000',
  status: 'NEW',
  timeInForce: 'GTC',
  type: 'LIMIT',
  side: 'BUY'
}

orderTest

Test new order creation and signature/recvWindow. Creates and validates a new order but does not send it into the matching engine.

Same API as above, but does not return any output on success.

orderOco

Creates a new OCO order.

console.log(
  await client.orderOco({
    symbol: 'XLMETH',
    side: 'SELL',
    quantity: 100,
    price: 0.0002,
    stopPrice: 0.0001,
    stopLimitPrice: 0.0001,
  }),
)
Param Type Required Description
symbol String true
listClientOrderId String false A unique Id for the entire orderList
side String true BUY,SELL
quantity Number true
limitClientOrderId String false A unique Id for the limit order
price Number true
limitIcebergQty Number false Used to make the LIMIT_MAKER leg an iceberg order.
stopClientOrderId String false A unique Id for the stop loss/stop loss limit leg
stopPrice Number true
stopLimitPrice Number false If provided, stopLimitTimeInForce is required.
stopIcebergQty Number false Used with STOP_LOSS_LIMIT leg to make an iceberg order.
stopLimitTimeInForce String false FOK, GTC, IOC
newOrderRespType String false Returns more complete info of the order. ACK, RESULT, or FULL
recvWindow Number false The value cannot be greater than 60000

Additional Info:

  • Price Restrictions:
    • SELL: Limit Price > Last Price > Stop Price
    • BUY: Limit Price < Last Price < Stop Price
  • Quantity Restrictions:
    • Both legs must have the same quantity.
    • ICEBERG quantities however do not have to be the same
Output
{
  "orderListId": 0,
  "contingencyType": "OCO",
  "listStatusType": "EXEC_STARTED",
  "listOrderStatus": "EXECUTING",
  "listClientOrderId": "JYVpp3F0f5CAG15DhtrqLp",
  "transactionTime": 1514418413947,
  "symbol": "XLMETH",
  "orders": [
    {
      "symbol": "XLMETH",
      "orderId": 1740797,
      "clientOrderId": "1XZTVBTGS4K1e"
    },
    {
      "symbol": "XLMETH",
      "orderId": 1740798,
      "clientOrderId": "1XZTVBTGS4K1f"
    }
  ],
  "orderReports": [
    {
      "symbol": "XLMETH",
      "orderId": 1740797,
      "orderListId": 0,
      "clientOrderId": "1XZTVBTGS4K1e",
      "transactTime": 1514418413947,
      "price": "0.000000",
      "origQty": "100",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "STOP_LOSS",
      "side": "SELL",
      "stopPrice": "0.0001"
    },
    {
      "symbol": "XLMETH",
      "orderId": 1740798,
      "orderListId": 0,
      "clientOrderId": "1XZTVBTGS4K1f",
      "transactTime": 1514418413947,
      "price": "0.0002",
      "origQty": "100",
      "executedQty": "0.000000",
      "cummulativeQuoteQty": "0.000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "LIMIT_MAKER",
      "side": "SELL"
    }
  ]
}

getOrder

Check an order's status.

console.log(
  await client.getOrder({
    symbol: 'BNBETH',
    orderId: 50167927,
  }),
)
Param Type Required Description
symbol String true
orderId Number true Not required if origClientOrderId is used
origClientOrderId String false
recvWindow Number false
Output
{
  clientOrderId: 'NkQnNkdBV1RGjUALLhAzNy',
  cummulativeQuoteQty: '0.16961580',
  executedQty: '3.91000000',
  icebergQty: '0.00000000',
  isWorking: true,
  orderId: 50167927,
  origQty: '3.91000000',
  price: '0.04338000',
  side: 'SELL',
  status: 'FILLED',
  stopPrice: '0.00000000',
  symbol: 'BNBETH',
  time: 1547075007821,
  timeInForce: 'GTC',
  type: 'LIMIT',
  updateTime: 1547075016737
}

getOrderOco

Retrieves a specific OCO based on provided optional parameters

console.log(
  await client.getOrderOco({
    orderListId: 27,
  }),
)
Param Type Required Description
orderListId Number true Not required if listClientOrderId is used
listClientOrderId String false
recvWindow Number false
Output
{
  orderListId: 27,
  contingencyType: 'OCO',
  listStatusType: 'EXEC_STARTED',
  listOrderStatus: 'EXECUTING',
  listClientOrderId: 'h2USkA5YQpaXHPIrkd96xE',
  transactionTime: 1565245656253,
  symbol: 'LTCBTC',
  orders: [
    {
      symbol: 'LTCBTC',
      orderId: 4,
      clientOrderId: 'qD1gy3kc3Gx0rihm9Y3xwS'
    },
    {
      symbol: 'LTCBTC',
      orderId: 5,
      clientOrderId: 'ARzZ9I00CPM8i3NhmU9Ega'
    }
  ]
}

cancelOrder

Cancels an active order.

console.log(
  await client.cancelOrder({
    symbol: 'ETHBTC',
    orderId: 1,
  }),
)
Param Type Required Description
symbol String true
orderId Number true Not required if origClientOrderId is used
origClientOrderId String false
newClientOrderId String false Used to uniquely identify this cancel. Automatically generated by default.
recvWindow Number false
Output
{
  symbol: 'ETHBTC',
  origClientOrderId: 'bnAoRHgI18gRD80FJmsfNP',
  orderId: 1,
  clientOrderId: 'RViSsQPTp1v3WmLYpeKT11'
}

cancelOrderOco

Cancel an entire Order List.

console.log(
  await client.cancelOrderOco({
    symbol: 'ETHBTC',
    orderListId: 0,
  }),
)
Param Type Required Description
symbol String true
orderListId Number true Not required if listClientOrderId is used
listClientOrderId String false
newClientOrderId String false Used to uniquely identify this cancel. Automatically generated by default.
recvWindow Number false
Output
{
  orderListId: 0,
  contingencyType: 'OCO',
  listStatusType: 'ALL_DONE',
  listOrderStatus: 'ALL_DONE',
  listClientOrderId: 'C3wyj4WVEktd7u9aVBRXcN',
  transactionTime: 1574040868128,
  symbol: 'LTCBTC',
  orders: [
    {
      symbol: 'LTCBTC',
      orderId: 2,
      clientOrderId: 'pO9ufTiFGg3nw2fOdgeOXa'
    },
    {
      symbol: 'LTCBTC',
      orderId: 3,
      clientOrderId: 'TXOvglzXuaubXAaENpaRCB'
    }
  ],
  orderReports: [
    {
      symbol: 'LTCBTC',
      origClientOrderId: 'pO9ufTiFGg3nw2fOdgeOXa',
      orderId: 2,
      orderListId: 0,
      clientOrderId: 'unfWT8ig8i0uj6lPuYLez6',
      price: '1.00000000',
      origQty: '10.00000000',
      executedQty: '0.00000000',
      cummulativeQuoteQty: '0.00000000',
      status: 'CANCELED',
      timeInForce: 'GTC',
      type: 'STOP_LOSS_LIMIT',
      side: 'SELL',
      stopPrice: '1.00000000'
    },
    {
      symbol: 'LTCBTC',
      origClientOrderId: 'TXOvglzXuaubXAaENpaRCB',
      orderId: 3,
      orderListId: 0,
      clientOrderId: 'unfWT8ig8i0uj6lPuYLez6',
      price: '3.00000000',
      origQty: '10.00000000',
      executedQty: '0.00000000',
      cummulativeQuoteQty: '0.00000000',
      status: 'CANCELED',
      timeInForce: 'GTC',
      type: 'LIMIT_MAKER',
      side: 'SELL'
    }
  ]
}

cancelOpenOrders

Cancels all active orders on a symbol. This includes OCO orders.

console.log(
  await client.cancelOpenOrders({
    symbol: 'ETHBTC'
  }),
)
Param Type Required
symbol String true
Output
[
  {
    symbol: 'ETHBTC',
    origClientOrderId: 'bnAoRHgI18gRD80FJmsfNP',
    orderId: 1,
    clientOrderId: 'RViSsQPTp1v3WmLYpeKT11'
  },
  {
    symbol: 'ETHBTC',
    origClientOrderId: 'IDbzcGmfwSCKihxILK1snu',
    orderId: 2,
    clientOrderId: 'HKFcuWAm9euMgRuwVGR8CL'
  }
]

openOrders

Get all open orders on a symbol.

console.log(
  await client.openOrders({
    symbol: 'XLMBTC',
  }),
)
Param Type Required
symbol String true
recvWindow Number false
Output
;[
  {
    symbol: 'XLMBTC',
    orderId: 11271740,
    clientOrderId: 'ekHkROfW98gBN80LTfufQZ',
    price: '0.00001081',
    origQty: '1331.00000000',
    executedQty: '0.00000000',
    status: 'NEW',
    timeInForce: 'GTC',
    type: 'LIMIT',
    side: 'BUY',
    stopPrice: '0.00000000',
    icebergQty: '0.00000000',
    time: 1522682290485,
    isWorking: true,
  },
]

allOrders

Get all account orders on a symbol; active, canceled, or filled.

console.log(
  await client.allOrders({
    symbol: 'ETHBTC',
  }),
)
Param Type Required Default Description
symbol String true
orderId Number false If set, it will get orders >= that orderId. Otherwise most recent orders are returned.
limit Number false 500 Max 500
recvWindow Number false
Output
;[
  {
    symbol: 'ENGETH',
    orderId: 191938,
    clientOrderId: '1XZTVBTGS4K1e',
    price: '0.00138000',
    origQty: '1.00000000',
    executedQty: '1.00000000',
    status: 'FILLED',
    timeInForce: 'GTC',
    type: 'LIMIT',
    side: 'SELL',
    stopPrice: '0.00000000',
    icebergQty: '0.00000000',
    time: 1508611114735,
    isWorking: true,
  },
]

allOrdersOCO

Retrieves all OCO based on provided optional parameters

console.log(
  await client.allOrdersOCO({
    timestamp: 1565245913483,
  }),
)
Param Type Required Default Description
timestamp Number true
startTime Number false
endTime Number false
limit Integer false 500 Max 1000
recvWindow Number false The value cannot be greater than 60000
formId Number false If supplied, neither startTime or endTime can be provided
Output
;[
  {
    "orderListId": 29,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "amEEAXryFzFwYF1FeRpUoZ",
    "transactionTime": 1565245913483,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 4,
        "clientOrderId": "oD7aesZqjEGlZrbtRpy5zB"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 5,
        "clientOrderId": "Jr1h6xirOxgeJOUuYQS7V3"
      }
    ]
  },
  {
    "orderListId": 28,
    "contingencyType": "OCO",
    "listStatusType": "EXEC_STARTED",
    "listOrderStatus": "EXECUTING",
    "listClientOrderId": "hG7hFNxJV6cZy3Ze4AUT4d",
    "transactionTime": 1565245913407,
    "symbol": "LTCBTC",
    "orders": [
      {
        "symbol": "LTCBTC",
        "orderId": 2,
        "clientOrderId": "j6lFOfbmFMRjTYA7rRJ0LP"
      },
      {
        "symbol": "LTCBTC",
        "orderId": 3,
        "clientOrderId": "z0KCjOdditiLS5ekAFtK81"
      }
    ]
  }
]

accountInfo

Get current account information.

console.log(await client.accountInfo())
Param Type Required
recvWindow Number false
Output
{
  makerCommission: 10,
  takerCommission: 10,
  buyerCommission: 0,
  sellerCommission: 0,
  canTrade: true,
  canWithdraw: true,
  canDeposit: true,
  balances: [
    { asset: 'BTC', free: '0.00000000', locked: '0.00000000' },
    { asset: 'LTC', free: '0.00000000', locked: '0.00000000' },
  ]
}

myTrades

Get trades for the current authenticated account and symbol.

console.log(
  await client.myTrades({
    symbol: 'ETHBTC',
  }),
)
Param Type Required Default Description
symbol String true
limit Number false 500 Max 1000
fromId Number false TradeId to fetch from. Default gets most recent trades.
orderId Number false This can only be used in combination with symbol.
startTime Number false
endTime Number false
recvWindow Number false 5000 The value cannot be greater than 60000.
Output
;[
  {
    id: 9960,
    orderId: 191939,
    price: '0.00138000',
    qty: '10.00000000',
    commission: '0.00001380',
    commissionAsset: 'ETH',
    time: 1508611114735,
    isBuyer: false,
    isMaker: false,
    isBestMatch: true,
  },
]

dailyAccountSnapshot

Get asset snapshot for the current authenticated account.

console.log(
  await client.accountSnapshot({
    "type": "SPOT"
  });
)
Param Type Required Default Description
type String true
startTime Number false
endTime Number false
limit Number false 5 min 5, max 30, default 5
recvWindow Number false
Output
{
   "code":200, // 200 for success; others are error codes
   "msg":"", // error message
   "snapshotVos":[
      {
         "data":{
            "balances":[
               {
                  "asset":"BTC",
                  "free":"0.09905021",
                  "locked":"0.00000000"
               },
               {
                  "asset":"USDT",
                  "free":"1.89109409",
                  "locked":"0.00000000"
               }
            ],
            "totalAssetOfBtc":"0.09942700"
         },
         "type":"spot",
         "updateTime":1576281599000
      }
   ]
}

tradesHistory

Lookup symbol trades history.

console.log(await client.tradesHistory({ symbol: 'ETHBTC' }))
Param Type Required Default Description
symbol String true
limit Number false 500 Max 500
fromId Number false null TradeId to fetch from. Default gets most recent trades.
Output
;[
  {
    id: 28457,
    price: '4.00000100',
    qty: '12.00000000',
    time: 1499865549590,
    isBuyerMaker: true,
    isBestMatch: true,
  },
]

withdrawHistory

Get the account withdraw history.

console.log(await client.withdrawHistory())
Param Type Required Description
asset String false
status Number false 0 (0: Email Sent, 1: Cancelled 2: Awaiting Approval, 3: Rejected, 4: Processing, 5: Failure, 6: Completed)
offset Number false
limit Number false
startTime Number false
endTime Number false
recvWindow Number false
Output
[
    {
        "address": "0x94df8b352de7f46f64b01d3666bf6e936e44ce60",
        "amount": "8.91000000",
        "applyTime": "2019-10-12 11:12:02",
        "coin": "USDT",
        "id": "b6ae22b3aa844210a7041aee7589627c",
        "withdrawOrderId": "WITHDRAWtest123", // will not be returned if there's no withdrawOrderId for this withdraw.
        "network": "ETH", 
        "transferType": 0,   // 1 for internal transfer, 0 for external transfer   
        "status": 6,
        "txId": "0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268"
    },
    {
        "address": "1FZdVHtiBqMrWdjPyRPULCUceZPJ2WLCsB",
        "amount": "0.00150000",
        "applyTime": "2019-09-24 12:43:45",
        "coin": "BTC",
        "id": "156ec387f49b41df8724fa744fa82719",
        "network": "BTC",
        "status": 6,
        "txId": "60fd9007ebfddc753455f95fafa808c4302c836e4d1eebc5a132c36c1d8ac354"
    }
]

withdraw

Triggers the withdraw process (untested for now).

console.log(
  await client.withdraw({
    asset: 'ETH',
    address: '0xfa97c22a03d8522988c709c24283c0918a59c795',
    amount: 100,
  }),
)
Param Type Required Description
asset String true
address String true
amount Number true
name String false Description of the address
recvWindow Number false
Output
{
    "id":"7213fea8e94b4a5593d507237e5a555b"
}

depositAddress

Fetch deposit address with network.

console.log(await client.depositAddress({ coin: 'NEO' }))
Param Type Required Description
coin String true The coin name
network String false The network name
Output
{
  address: 'AM6ytPW78KYxQCmU2pHYGcee7GypZ7Yhhc',
  coin: 'NEO',
  tag: '',
  url: 'https://neoscan.io/address/AM6ytPW78KYxQCmU2pHYGcee7GypZ7Yhhc'
}

depositHistory

Fetch deposit address with network.

console.log(await client.depositHistory())
Param Type Required Description
coin String false The coin name
status Number false 0 (0:pending, 6: credited but cannot withdraw, 1:success)
startTime Number false Default: 90 days from current timestamp
endTime Number false Default: present timestamp
offset Number false default: 0
limit Number false
recvWindow Number false
Output
[
    {
        "amount": "0.00999800",
        "coin": "PAXG",
        "network": "ETH",
        "status": 1,
        "address": "0x788cabe9236ce061e5a892e1a59395a81fc8d62c",
        "addressTag": "",
        "txId": "0xaad4654a3234aa6118af9b4b335f5ae81c360b2394721c019b5d1e75328b09f3",
        "insertTime": 1599621997000,
        "transferType": 0,
        "confirmTimes": "12/12"
    },
    {
        "amount": "0.50000000",
        "coin": "IOTA",
        "network": "IOTA",
        "status": 1,
        "address": "SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLNW",
        "addressTag": "",
        "txId": "ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999",
        "insertTime": 1599620082000,
        "transferType": 0,
        "confirmTimes": "1/1"
    }
]

tradeFee

Retrieve the account trade Fee per asset.

console.log(await client.tradeFee())
Output
[
    {
      "symbol": "ADABNB",
      "makerCommission": 0.9000,
      "takerCommission": 1.0000
    },
    {
      "symbol": "BNBBTC",
      "makerCommission": 0.3000,
      "takerCommission": 0.3000
    }
]

capitalConfigs

Get information of coins (available for deposit and withdraw) for user.

console.log(await client.capitalConfigs())
Output
[
  {
    'coin': 'CTR',
    'depositAllEnable': false,
    'free': '0.00000000',
    'freeze': '0.00000000',
    'ipoable': '0.00000000',
    'ipoing': '0.00000000',
    'isLegalMoney': false,
    'locked': '0.00000000',
    'name': 'Centra',
    'networkList': [
      {
        'addressRegex': '^(0x)[0-9A-Fa-f]{40}$',
        'coin': 'CTR',
        'depositDesc': 'Delisted, Deposit Suspended',
        'depositEnable': false,
        'isDefault': true,
        'memoRegex': '',
        'minConfirm': 12,
        'name': 'ERC20',
        'network': 'ETH',
        'resetAddressStatus': false,
        'specialTips': '',
        'unLockConfirm': 0,
        'withdrawDesc': '',
        'withdrawEnable': true,
        'withdrawFee': '35.00000000',
        'withdrawIntegerMultiple': '0.00000001',
        'withdrawMax': '0.00000000',
        'withdrawMin': '70.00000000'
      }
    ],
    'storage': '0.00000000',
    'trading': false,
    'withdrawAllEnable': true,
    'withdrawing': '0.00000000'
  }
]

universalTransfer

You need to enable Permits Universal Transfer option for the api key which requests this endpoint.

console.log(await client.universalTransfer({ type: 'MAIN_C2C', asset: 'USDT', amount: '1000' }))
Param Type Required Description
type String true
asset String true
amount String true
recvWindow Number false
Output
{
  tranId:13526853623
}

universalTransferHistory

console.log(await client.universalTransferHistory({ type: 'MAIN_C2C' }))
Param Type Required Description
type String true
startTime Number false
endTime Number false
current Number false Default 1
size Number false Default 10, Max 100
recvWindow Number false
Output
{
  "total": 2,
  "rows": [
    {
      "asset":"USDT",
      "amount":"1",
      "type":"MAIN_C2C"
      "status": "CONFIRMED",
      "tranId": 11415955596,
      "timestamp":1544433328000
    },
    {
      "asset":"USDT",
      "amount":"2",
      "type":"MAIN_C2C",
      "status": "CONFIRMED",
      "tranId": 11366865406,
      "timestamp":1544433328000
    }
  ]
}

assetDetail

console.log(await client.assetDetail())
Param Type Required Description
recvWindow Number false
Output
{
        "CTR": {
            "minWithdrawAmount": "70.00000000", //min withdraw amount
            "depositStatus": false,//deposit status (false if ALL of networks' are false)
            "withdrawFee": 35, // withdraw fee
            "withdrawStatus": true, //withdraw status (false if ALL of networks' are false)
            "depositTip": "Delisted, Deposit Suspended" //reason
        },
        "SKY": {
            "minWithdrawAmount": "0.02000000",
            "depositStatus": true,
            "withdrawFee": 0.01,
            "withdrawStatus": true
        }   
}

getBnbBurn

console.log(await client.getBnbBurn())
Param Type Required Description
recvWindow Number false No more than 60000
Output
{
   "spotBNBBurn":true,
   "interestBNBBurn": false
}

setBnbBurn

console.log(await client.setBnbBurn({ spotBNBBurn: "true" }))
Param Type Required Description
spotBNBBurn String false "true" or "false"; Determines whether to use BNB to pay for trading fees on SPOT
interestBNBBurn String false "true" or "false"; Determines whether to use BNB to pay for margin loan's interest
recvWindow Number false No more than 60000
Output
{
   "spotBNBBurn":true,
   "interestBNBBurn": false
}

dustLog

console.log(await client.dustLog())
Param Type Required Description
startTime Number false
endTime Number false
recvWindow Number false
Output
{
        "total": 8,   //Total counts of exchange
        "userAssetDribblets": [
            {
                "operateTime": 1615985535000,
                "totalTransferedAmount": "0.00132256",
                "totalServiceChargeAmount": "0.00002699",
                "transId": 45178372831,
                "userAssetDribbletDetails": [
                    {
                        "transId": 4359321,
                        "serviceChargeAmount": "0.000009",
                        "amount": "0.0009",
                        "operateTime": 1615985535000,
                        "transferedAmount": "0.000441",
                        "fromAsset": "USDT"
                    },
                    {
                        "transId": 4359321,
                        "serviceChargeAmount": "0.00001799",
                        "amount": "0.0009",
                        "operateTime": 1615985535000,
                        "transferedAmount": "0.00088156",
                        "fromAsset": "ETH"
                    }
                ]
            },
            {
                "operateTime":1616203180000,
                "totalTransferedAmount": "0.00058795",
                "totalServiceChargeAmount": "0.000012",
                "transId": 4357015,
                "userAssetDribbletDetails": [
                    {
                        "transId": 4357015,
                        "serviceChargeAmount": "0.00001",
                        "amount": "0.001",
                        "operateTime": 1616203180000,
                        "transferedAmount": "0.00049",
                        "fromAsset": "USDT"
                    },
                    {
                        "transId": 4357015,
                        "serviceChargeAmount": "0.000002",
                        "amount": "0.0001",
                        "operateTime": 1616203180000,
                        "transferedAmount": "0.00009795",
                        "fromAsset": "ETH"
                    }
                ]
            }
        ]
    }
}

dustTransfer

console.log(await client.dustTransfer({ asset: ['ETH', 'LTC', 'TRX'] }))
Param Type Required Description
asset [String] true
recvWindow Number false
Output
{
    "totalServiceCharge":"0.02102542",
    "totalTransfered":"1.05127099",
    "transferResult":[
        {
            "amount":"0.03000000",
            "fromAsset":"ETH",
            "operateTime":1563368549307,
            "serviceChargeAmount":"0.00500000",
            "tranId":2970932918,
            "transferedAmount":"0.25000000"
        },
        {
            "amount":"0.09000000",
            "fromAsset":"LTC",
            "operateTime":1563368549404,
            "serviceChargeAmount":"0.01548000",
            "tranId":2970932918,
            "transferedAmount":"0.77400000"
        },
        {
            "amount":"248.61878453",
            "fromAsset":"TRX",
            "operateTime":1563368549489,
            "serviceChargeAmount":"0.00054542",
            "tranId":2970932918,
            "transferedAmount":"0.02727099"
        }
    ]
}   

accountCoins

Retrieve account coins related information. Implemented as getAll in Binance Docs.

console.log(await client.accountCoins())
Param Type Required Description
recvWindow Number false
Output
[
    {
        "coin": "BTC",
        "depositAllEnable": true,
        "free": "0.08074558",
        "freeze": "0.00000000",
        "ipoable": "0.00000000",
        "ipoing": "0.00000000",
        "isLegalMoney": false,
        "locked": "0.00000000",
        "name": "Bitcoin",
        "networkList": [
            {
                "addressRegex": "^(bnb1)[0-9a-z]{38}$",
                "coin": "BTC",
                "depositDesc": "Wallet Maintenance, Deposit Suspended", // shown only when "depositEnable" is false.
                "depositEnable": false,
                "isDefault": false,
                "memoRegex": "^[0-9A-Za-z\\-_]{1,120}$",
                "minConfirm": 1,  // min number for balance confirmation
                "name": "BEP2",
                "network": "BNB",
                "resetAddressStatus": false,
                "specialTips": "Both a MEMO and an Address are required to successfully deposit your BEP2-BTCB tokens to Binance.",
                "unLockConfirm": 0,  // confirmation number for balance unlock 
                "withdrawDesc": "Wallet Maintenance, Withdrawal Suspended", // shown only when "withdrawEnable" is false.
                "withdrawEnable": false,
                "withdrawFee": "0.00000220",
                "withdrawMin": "0.00000440"
            },
            {
                "addressRegex": "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^(bc1)[0-9A-Za-z]{39,59}$",
                "coin": "BTC",
                "depositEnable": true,
                "insertTime": 1563532929000,
                "isDefault": true,
                "memoRegex": "",
                "minConfirm": 1,
                "name": "BTC",
                "network": "BTC",
                "resetAddressStatus": false,
                "specialTips": "",
                "unLockConfirm": 2,
                "updateTime": 1571014804000, 
                "withdrawEnable": true,
                "withdrawFee": "0.00050000",
                "withdrawIntegerMultiple": "0.00000001",
                "withdrawMin": "0.00100000"
            }
        ],
        "storage": "0.00000000",
        "trading": true,
        "withdrawAllEnable": true,
        "withdrawing": "0.00000000"
    }
]

lendingAccount

Get information of lending assets for user.

console.log(await client.lendingAccount())
Output
{
    "positionAmountVos": [
        {
            "amount": "75.46000000",
            "amountInBTC": "0.01044819",
            "amountInUSDT": "75.46000000",
            "asset": "USDT"
        },
        {
            "amount": "1.67072036",
            "amountInBTC": "0.00023163",
            "amountInUSDT": "1.67289230",
            "asset": "BUSD"
        }
    ],
    "totalAmountInBTC": "0.01067982",
    "totalAmountInUSDT": "77.13289230",
    "totalFixedAmountInBTC": "0.00000000",
    "totalFixedAmountInUSDT": "0.00000000",
    "totalFlexibleInBTC": "0.01067982",
    "totalFlexibleInUSDT": "77.13289230"
 }

fundingWallet

Query funding wallet, includes Binance Pay, Binance Card, Binance Gift Card, Stock Token.

console.log(await client.fundingWallet())
Param Type Required Description
asset String false
needBtcValuation String false 'true' or 'false'
Output
[
    {
        "asset": "USDT",
        "free": "1",
        "locked": "0",
        "freeze": "0",
        "withdrawing": "0",  
        "btcValuation": "0.00000091"  
    }
]

apiPermission

Get API Key Permission.

console.log(await client.apiPermission())
Param Type Required Description
recvWindow Number false
Output
{
   "ipRestrict": false,
   "createTime": 1623840271000,   
   "enableWithdrawals": false,   // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to withdrawals
   "enableInternalTransfer": true,  // This option authorizes this key to transfer funds between your master account and your sub account instantly
   "permitsUniversalTransfer": true,  // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization
   "enableVanillaOptions": false,  //  Authorizes this key to Vanilla options trading
   "enableReading": true,
   "enableFutures": false,  //  API Key created before your futures account opened does not support futures API service
   "enableMargin": false,   //  This option can be adjusted after the Cross Margin account transfer is completed
   "enableSpotAndMarginTrading": false, // Spot and margin trading
   "tradingAuthorityExpirationTime": 1628985600000  // Expiration time for spot and margin trading permission
}

Margin

marginAccountInfo

Query cross margin account details (USER_DATA)

console.log(await client.marginAccountInfo());
Param Type Required Description
recvWindow Number false No more than 60000
Output
{
      "borrowEnabled": true,
      "marginLevel": "11.64405625",
      "totalAssetOfBtc": "6.82728457",
      "totalLiabilityOfBtc": "0.58633215",
      "totalNetAssetOfBtc": "6.24095242",
      "tradeEnabled": true,
      "transferEnabled": true,
      "userAssets": [
          {
              "asset": "BTC",
              "borrowed": "0.00000000",
              "free": "0.00499500",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00499500"
          },
          {
              "asset": "BNB",
              "borrowed": "201.66666672",
              "free": "2346.50000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "2144.83333328"
          },
          {
              "asset": "ETH",
              "borrowed": "0.00000000",
              "free": "0.00000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00000000"
          },
          {
              "asset": "USDT",
              "borrowed": "0.00000000",
              "free": "0.00000000",
              "interest": "0.00000000",
              "locked": "0.00000000",
              "netAsset": "0.00000000"
          }
      ]
}

marginLoan

Create a loan for margin account.

console.log(await client.marginLoan({ asset: 'BTC', amount:'0.0001' }));
Param Type Required Description
asset String true The asset name
amount Number true
Output
{
    "tranId": 100000001 //transaction id
}

marginRepay

Repay loan for margin account.

console.log(await client.marginRepay({ asset: 'BTC', amount:'0.0001' }));
Param Type Required Description
asset String true The asset name
amount Number true
Output
{
    "tranId": 100000001 //transaction id
}

marginIsolatedAccount

Query Isolated Margin Account Info

console.log(await client.marginIsolatedAccount({ symbols: 'BTCUSDT'}));
Param Type Required Description
symbols String false Max 5 symbols can be sent; separated by ","
recvWindow Number false No more than 60000
Output
{
   "assets":[
      {
        "baseAsset": 
        {
          "asset": "BTC",
          "borrowEnabled": true,
          "borrowed": "0.00000000",
          "free": "0.00000000",
          "interest": "0.00000000",
          "locked": "0.00000000",
          "netAsset": "0.00000000",
          "netAssetOfBtc": "0.00000000",
          "repayEnabled": true,
          "totalAsset": "0.00000000"
        },
        "quoteAsset": 
        {
          "asset": "USDT",
          "borrowEnabled": true,
          "borrowed": "0.00000000",
          "free": "0.00000000",
          "interest": "0.00000000",
          "locked": "0.00000000",
          "netAsset": "0.00000000",
          "netAssetOfBtc": "0.00000000",
          "repayEnabled": true,
          "totalAsset": "0.00000000"
        },
        "symbol": "BTCUSDT"
        "isolatedCreated": true, 
        "marginLevel": "0.00000000", 
        "marginLevelStatus": "EXCESSIVE", // "EXCESSIVE", "NORMAL", "MARGIN_CALL", "PRE_LIQUIDATION", "FORCE_LIQUIDATION"
        "marginRatio": "0.00000000",
        "indexPrice": "10000.00000000"
        "liquidatePrice": "1000.00000000",
        "liquidateRate": "1.00000000"
        "tradeEnabled": true
      }
    ],
    "totalAssetOfBtc": "0.00000000",
    "totalLiabilityOfBtc": "0.00000000",
    "totalNetAssetOfBtc": "0.00000000" 
}

disableMarginAccount

Inactive Isolated Margin trading pair for symbol

console.log(await client.disableMarginAccount({ symbol: 'BTCUSDT' }));
Param Type Required Description
symbol String true
recvWindow Number false No more than 60000
Output
{
   "success": true,
   "symbol": "BTCUSDT"
}
#### enableMarginAccount

Active Isolated Margin trading pair for symbol

console.log(await client.enableMarginAccount({ symbol: 'BTCUSDT' }));
Param Type Required Description
symbol String true
recvWindow Number false No more than 60000
Output
{
   "success": true,
   "symbol": "BTCUSDT"
}

marginMaxBorrow

If isolatedSymbol is not sent, crossed margin data will be sent.

console.log(await client.marginMaxBorrow({ asset: 'BTC', isolatedSymbol: 'BTCUSDT'}));
Param Type Required Description
asset String true
isolatedSymbol String false
recvWindow Number false No more than 60000
Output
{
  "amount": "1.69248805", // account's currently max borrowable amount with sufficient system availability
  "borrowLimit": "60" // max borrowable amount limited by the account level
}

marginCreateIsolated

console.log(await client.marginCreateIsolated({ base: 'BTC', quote: 'USDT'}));
Param Type Required Description
base String true Base asset of symbol
quote String true Quote asset of symbol
recvWindow Number false No more than 60000
Output
{
    "success": true,
    "symbol": "BTCUSDT"
}

marginIsolatedTransfer

console.log(await client.marginIsolatedTransfer({ asset: 'USDT', symbol: 'BNBUSDT', transFrom: 'ISOLATED_MARGIN', transTo: 'SPOT', amount: 1}));
Param Type Required Description
asset String true asset,such as BTC
symbol String true
transFrom String true "SPOT", "ISOLATED_MARGIN"
transTo String true "SPOT", "ISOLATED_MARGIN"
amount Number true
recvWindow Number false No more than 60000
Output
{
    //transaction id
    "tranId": 100000001
}

marginIsolatedTransferHistory

console.log(await client.marginIsolatedTransferHistory({ symbol: 'BNBUSDT'}));
Param Type Required Description
asset String false asset,such as BTC
symbol String true
transFrom String false "SPOT", "ISOLATED_MARGIN"
transTo String false "SPOT", "ISOLATED_MARGIN"
startTime Number false
endTime Number false
current Number false Current page, default 1
size Number false Default 10, max 100
recvWindow Number false No more than 60000
Output
{
  "rows": [
    {
      "amount": "0.10000000",
      "asset": "BNB",
      "status": "CONFIRMED",
      "timestamp": 1566898617000,
      "txId": 5240372201,
      "transFrom": "SPOT",
      "transTo": "ISOLATED_MARGIN"
    },
    {
      "amount": "5.00000000",
      "asset": "USDT",
      "status": "CONFIRMED",
      "timestamp": 1566888436123,
      "txId": 5239810406,
      "transFrom": "ISOLATED_MARGIN",
      "transTo": "SPOT"
    }
  ],
  "total": 2
}

marginOrder

console.log(await client.marginOrder({ 
  symbol: 'BTCUSDT', 
  type: 'MARKET',
  side: 'SELL',
  quantity: '10',
  }));
Param Type Required Description
symbol String true asset, such as BTC
isIsolated String false for isolated margin or not, TRUE, FALSE, default FALSE
side String true BUY SELL
type String true
quantity String false
quoteOrderQty String false
price String false
stopPrice String false Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.
newClientOrderId String false A unique id among open orders. Automatically generated if not sent.
icebergQty Boolean false Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
newOrderRespType String false Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.
sideEffectType String false NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY; default NO_SIDE_EFFECT.
timeInForce String false GTC,IOC,FOK
recvWindow Number false No more than 60000
Output
{
  "symbol": "BTCUSDT",
  "orderId": 28,
  "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
  "transactTime": 1507725176595,
  "price": "1.00000000",
  "origQty": "10.00000000",
  "executedQty": "10.00000000",
  "cummulativeQuoteQty": "10.00000000",
  "status": "FILLED",
  "timeInForce": "GTC",
  "type": "MARKET",
  "side": "SELL",
  "marginBuyBorrowAmount": 5,       // will not return if no margin trade happens
  "marginBuyBorrowAsset": "BTC",    // will not return if no margin trade happens
  "isIsolated": true,       // if isolated margin
  "fills": [
    {
      "price": "4000.00000000",
      "qty": "1.00000000",
      "commission": "4.00000000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3999.00000000",
      "qty": "5.00000000",
      "commission": "19.99500000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3998.00000000",
      "qty": "2.00000000",
      "commission": "7.99600000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3997.00000000",
      "qty": "1.00000000",
      "commission": "3.99700000",
      "commissionAsset": "USDT"
    },
    {
      "price": "3995.00000000",
      "qty": "1.00000000",
      "commission": "3.99500000",
      "commissionAsset": "USDT"
    }
  ]
}

marginOrderOco

console.log(await client.marginOrderOco({ 
  symbol: 'AUDIOUSDT', 
  type: 'MARKET',
  side: 'SELL',
  quantity: '10',
  }));
Param Type Required Description
symbol String true asset, such as BTC
isIsolated String false for isolated margin or not, TRUE, FALSE, default FALSE
side String true BUY SELL
type String true
quantity String false
quoteOrderQty String false
price String false
stopPrice String false Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.
stopLimitPrice String false Used with STOP_LOSS_LIMIT orders.
newClientOrderId String false A unique id among open orders. Automatically generated if not sent.
icebergQty Boolean false Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
newOrderRespType String false Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.
sideEffectType String false NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY; default NO_SIDE_EFFECT.
timeInForce String false GTC,IOC,FOK
recvWindow Number false No more than 60000
Output
{
  "orderListId": 45514668,
  "contingencyType": 'OCO',
  "listStatusType": 'EXEC_STARTED',
  "listOrderStatus": 'EXECUTING',
  "listClientOrderId": 'CD9UzEJfmcGZ4kLfZT2ga2',
  "transactionTime": 1632192162785,
  "symbol": 'AUDIOUSDT',
  "isIsolated": true,
  "orders": [
    {
      "symbol": 'AUDIOUSDT',
      "orderId": 239313661,
      "clientOrderId": 'ZbUwgKv6UB8eMzf2yfXENl'
    },
    {
      "symbol": 'AUDIOUSDT',
      "orderId": 239313662,
      "clientOrderId": 'f5u1RIHAPRd4W3fFhFykBo'
    }
  ],
  "orderReports": [
    {
      "symbol": 'AUDIOUSDT',
      "orderId": 239313661,
      "orderListId": 45514668,
      "clientOrderId": 'ZbUwgKv6UB8eMzf2yfXENl',
      "transactTime": 1632192162785,
      "price": '2.20000000',
      "origQty": '12.80000000',
      "executedQty": '0',
      "cummulativeQuoteQty": '0',
      "status": 'NEW',
      "timeInForce": 'GTC',
      "type": 'STOP_LOSS_LIMIT',
      "side": 'SELL',
      "stopPrice": '2.20000000'
    },
    {
      "symbol": 'AUDIOUSDT',
      "orderId": 239313662,
      "orderListId": 45514668,
      "clientOrderId": 'f5u1RIHAPRd4W3fFhFykBo',
      "transactTime": 1632192162785,
      "price": '2.50000000',
      "origQty": '12.80000000',
      "executedQty": '0',
      "cummulativeQuoteQty": '0',
      "status": 'NEW',
      "timeInForce": 'GTC',
      "type": 'LIMIT_MAKER',
      "side": 'SELL'
    }
  ]
}

marginGetOrder

Query Margin Account's Order

console.log(await client.marginGetOrder({ 
  symbol: 'BNBBTC', 
  orderId: '213205622',
  }));
Param Type Required Description
symbol String true asset,such as BTC
isIsolated String false for isolated margin or not, TRUE, FALSE, default FALSE
orderId String false
origClientOrderId String false
recvWindow Number false The value cannot be greater than 60000
Output
{
   "clientOrderId": "ZwfQzuDIGpceVhKW5DvCmO",
   "cummulativeQuoteQty": "0.00000000",
   "executedQty": "0.00000000",
   "icebergQty": "0.00000000",
   "isWorking": true,
   "orderId": 213205622,
   "origQty": "0.30000000",
   "price": "0.00493630",
   "side": "SELL",
   "status": "NEW",
   "stopPrice": "0.00000000",
   "symbol": "BNBBTC",
   "isIsolated": true,
   "time": 1562133008725,
   "timeInForce": "GTC",
   "type": "LIMIT",
   "updateTime": 1562133008725
}

Portfolio Margin Endpoints

Only Portfolio Margin Account is accessible to these endpoints.

getPortfolioMarginAccountInfo

Get a Portfolio Margin Account Info.

console.log(await client.getPortfolioMarginAccountInfo())
Output
{
    "uniMMR": "1.87987800",        // Portfolio margin account maintenance margin rate
    "accountEquity": "122607.35137903",   // Account equity, unit:USD
    "accountMaintMargin": "23.72469206", // Portfolio margin account maintenance margin, unit:USD
    "accountStatus": "NORMAL"   // Portfolio margin account status:"NORMAL", "MARGIN_CALL", "SUPPLY_MARGIN", "REDUCE_ONLY", "ACTIVE_LIQUIDATION", "FORCE_LIQUIDATION", "BANKRUPTED"
}

Futures Authenticated REST endpoints

futuresGetOrder

Check an order's status.

  • These orders will not be found
    • order status is CANCELED or EXPIRED, AND
    • order has NO filled trade, AND
    • created time + 7 days < current time
Name Type Mandatory Description
symbol STRING YES The pair name
orderId LONG NO
origClientOrderId STRING NO
recvWindow LONG NO

Either orderId or origClientOrderId must be sent.

console.log(
  await client.futuresGetOrder({
    symbol: 'BNBETH',
    orderId: 50167927,
  })
)
Output
{
    "avgPrice": "0.00000",
    "clientOrderId": "abc",
    "cumQuote": "0",
    "executedQty": "0",
    "orderId": 1917641,
    "origQty": "0.40",
    "origType": "TRAILING_STOP_MARKET",
    "price": "0",
    "reduceOnly": false,
    "side": "BUY",
    "positionSide": "SHORT",
    "status": "NEW",
    "stopPrice": "9300",                // please ignore when order type is TRAILING_STOP_MARKET
    "closePosition": false,             // if Close-All
    "symbol": "BTCUSDT",
    "time": 1579276756075,              // order time
    "timeInForce": "GTC",
    "type": "TRAILING_STOP_MARKET",
    "activatePrice": "9020",            // activation price, only return with TRAILING_STOP_MARKET order
    "priceRate": "0.3",                 // callback rate, only return with TRAILING_STOP_MARKET order
    "updateTime": 1579276756075,        // update time
    "workingType": "CONTRACT_PRICE",
    "priceProtect": false               // if conditional order trigger is protected   
}

futuresAllOrders

Get all account orders; active, canceled, or filled.

  • These orders will not be found
    • order status is CANCELED or EXPIRED, AND
    • order has NO filled trade, AND
    • created time + 7 days < current time
Name Type Mandatory Description
symbol STRING YES The pair name
orderId LONG NO
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
recvWindow LONG NO

If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.

console.log(
  await client.futuresAllOrders({
    symbol: 'BNBETH',
    orderId: 50167927,
    startTime: 1579276756075,
    limit: 700,
  })
)
Output
[
  {
    "avgPrice": "0.00000",
    "clientOrderId": "abc",
    "cumQuote": "0",
    "executedQty": "0",
    "orderId": 1917641,
    "origQty": "0.40",
    "origType": "TRAILING_STOP_MARKET",
    "price": "0",
    "reduceOnly": false,
    "side": "BUY",
    "positionSide": "SHORT",
    "status": "NEW",
    "stopPrice": "9300",                // please ignore when order type is TRAILING_STOP_MARKET
    "closePosition": false,             // if Close-All
    "symbol": "BTCUSDT",
    "time": 1579276756075,              // order time
    "timeInForce": "GTC",
    "type": "TRAILING_STOP_MARKET",
    "activatePrice": "9020",            // activation price, only return with TRAILING_STOP_MARKET order
    "priceRate": "0.3",                 // callback rate, only return with TRAILING_STOP_MARKET order
    "updateTime": 1579276756075,        // update time
    "workingType": "CONTRACT_PRICE",
    "priceProtect": false               // if conditional order trigger is protected   
  }
]

futuresBatchOrders

Place multiple orders

Name Type Mandatory Description
batchOrders LIST YES order list. Max 5 orders

futuresCancelBatchOrders

Cancel multiple orders

Name Type Mandatory Description
symbol STRING YES The pair name
orderIdList STRING NO max length 10
e.g. '[1234567,2345678]'
origClientOrderIdList STRING NO max length 10
e.g. '["my_id_1","my_id_2"]', encode the double quotes. No space after comma.

futuresLeverage

Change user's initial leverage of specific symbol market.

Name Type Mandatory Description
symbol STRING YES The pair name
leverage INT YES target initial leverage: int from 1 to 125
recvWindow LONG NO
console.log(
  await client.futuresLeverage({
    symbol: 'BTCUSDT',
    leverage: 21,
  })
)
Output
{
    "leverage": 21,
    "maxNotionalValue": "1000000",
    "symbol": "BTCUSDT"
}

futuresMarginType

Change margin type.

Name Type Mandatory Description
symbol STRING YES The pair name
marginType ENUM YES ISOLATED, CROSSED
recvWindow LONG NO
console.log(
  await client.futuresMarginType({
    symbol: 'BTCUSDT',
    marginType: 'ISOLATED',
  })
)
Output
{
    "code": 200,
    "msg": "success"
}

futuresPositionMargin

Modify isolated position margin.

Name Type Mandatory Description
symbol STRING YES The pair name
positionSide ENUM NO Default BOTH for One-way Mode;
LONG or SHORT for Hedge Mode.
It must be sent with Hedge Mode.
amount DECIMAL YES
type INT YES 1: Add position margin,2: Reduce position margin
recvWindow LONG NO

Only for isolated symbol.

console.log(
  await client.futuresPositionMargin({
    symbol: 'BTCUSDT',
    amount: 100,
    type: 1,
  })
)
Output
{
    "amount": 100.0,
    "code": 200,
    "msg": "Successfully modify position margin.",
    "type": 1
}

futuresMarginHistory

Get position margin change history.

Name Type Mandatory Description
symbol STRING YES The pair name
type INT NO 1: Add position margin,2: Reduce position margin
startTime LONG NO
endTime LONG NO
limit INT NO Default 500;
recvWindow LONG NO
console.log(
  await client.futuresMarginHistory({
    symbol: 'BTCUSDT',
    type: 1,
    startTime: 1579276756075,
    limit: 700,
  })
)
Output
[
    {
        "amount": "23.36332311",
        "asset": "USDT",
        "symbol": "BTCUSDT",
        "time": 1578047897183,
        "type": 1,
        "positionSide": "BOTH"
    },
    {
        "amount": "100",
        "asset": "USDT",
        "symbol": "BTCUSDT",
        "time": 1578047900425,
        "type": 1,
        "positionSide": "LONG"
    }
]

futuresIncome

Get income history.

Name Type Mandatory Description
symbol STRING NO The pair name
incomeType STRING NO "TRANSFER","WELCOME_BONUS", "REALIZED_PNL",
"FUNDING_FEE", "COMMISSION", and "INSURANCE_CLEAR"
startTime LONG NO Timestamp in ms to get funding from INCLUSIVE.
endTime LONG NO Timestamp in ms to get funding until INCLUSIVE.
limit INT NO Default 100; max 1000
recvWindow LONG NO
  • If incomeType is not sent, all kinds of flow will be returned
  • "trandId" is unique in the same incomeType for a user
console.log(
  await client.futuresIncome({
    symbol: 'BTCUSDT',
    startTime: 1579276756075,
    limit: 700,
  })
)
Output
[
    {
        "symbol": "",                   // trade symbol, if existing
        "incomeType": "TRANSFER",       // income type
        "income": "-0.37500000",        // income amount
        "asset": "USDT",                // income asset
        "info":"TRANSFER",              // extra information
        "time": 1570608000000,      
        "tranId":"9689322392",          // transaction id
        "tradeId":""                    // trade id, if existing
    },
    {
        "symbol": "BTCUSDT",
        "incomeType": "COMMISSION", 
        "income": "-0.01000000",
        "asset": "USDT",
        "info":"COMMISSION",
        "time": 1570636800000,
        "tranId":"9689322392",
        "tradeId":"2059192"
    }
]

futuresAccountBalance

Get futures account balance

console.log(await client.futuresAccountBalance());
Output
[
  {
    "accountAlias": "SgsR",    // unique account code
    "asset": "USDT",    // asset name
    "balance": "122607.35137903", // wallet balance
    "crossWalletBalance": "23.72469206", // crossed wallet balance
    "crossUnPnl": "0.00000000"  // unrealized profit of crossed positions
    "availableBalance": "23.72469206",       // available balance
    "maxWithdrawAmount": "23.72469206"     // maximum amount for transfer out
  }
]

futuresUserTrades

Get trades for a specific account and symbol.

console.log(
  await client.futuresUserTrades({
    symbol: 'ETHBTC',
  }),
)
Param Type Mandatory Description
symbol STRING YES
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
fromId LONG NO Trade id to fetch from. Default gets most recent trades.
recvWindow LONG NO
Output
[
  {
    "buyer": false,
    "commission": "-0.07819010",
    "commissionAsset": "USDT",
    "id": 698759,
    "maker": false,
    "orderId": 25851813,
    "price": "7819.01",
    "qty": "0.002",
    "quoteQty": "15.63802",
    "realizedPnl": "-0.91539999",
    "side": "SELL",
    "positionSide": "SHORT",
    "symbol": "BTCUSDT",
    "time": 1569514978020
  }
]

futuresLeverageBracket

Get notional and leverage brackets.

console.log(
  await client.futuresLeverageBracket({
    symbol: 'ETHBTC', // Optional
  }),
)
Param Type Mandatory Description
symbol STRING NO Use if you are only interested in brackets for one symbol
recvWindow LONG NO
Output
[
    {
        "symbol": "ETHUSDT",
        "brackets": [
            {
                "bracket": 1,   // Notional bracket
                "initialLeverage": 75,  // Max initial leverage for this bracket
                "notionalCap": 10000,  // Cap notional of this bracket
                "notionalFloor": 0,  // Notional threshold of this bracket 
                "maintMarginRatio": 0.0065, // Maintenance ratio for this bracket
                "cum":0 // Auxiliary number for quick calculation 

            },
        ]
    }
]

Delivery Authenticated REST endpoints

deliveryGetOrder

Check an order's status.

  • These orders will not be found
    • order status is CANCELED or EXPIRED, AND
    • order has NO filled trade, AND
    • created time + 7 days < current time
Name Type Mandatory Description
symbol STRING YES
orderId LONG NO
origClientOrderId STRING NO
recvWindow LONG NO

Either orderId or origClientOrderId must be sent.

console.log(
  await client.deliveryGetOrder({
    symbol: 'BTCUSD_200925',
    orderId: 1917641,
  })
)
Output
{
    "avgPrice": "0.0",
    "clientOrderId": "abc",
    "cumBase": "0",
    "executedQty": "0",
    "orderId": 1917641,
    "origQty": "0.40",
    "origType": "TRAILING_STOP_MARKET",
    "price": "0",
    "reduceOnly": false,
    "side": "BUY",
    "status": "NEW",
    "stopPrice": "9300",                // please ignore when order type is TRAILING_STOP_MARKET
    "closePosition": false,             // if Close-All
    "symbol": "BTCUSD_200925",
    "pair": "BTCUSD",
    "time": 1579276756075,              // order time
    "timeInForce": "GTC",
    "type": "TRAILING_STOP_MARKET",
    "activatePrice": "9020",            // activation price, only return with TRAILING_STOP_MARKET order
    "priceRate": "0.3",                 // callback rate, only return with TRAILING_STOP_MARKET order
    "updateTime": 1579276756075,        // update time
    "workingType": "CONTRACT_PRICE",
    "priceProtect": false               // if conditional order trigger is protected
}

deliveryAllOrders

Get all account orders; active, canceled, or filled.

  • These orders will not be found
    • order status is CANCELED or EXPIRED, AND
    • order has NO filled trade, AND
    • created time + 7 days < current time
Name Type Mandatory Description
symbol STRING YES The pair name
orderId LONG NO
startTime LONG NO
endTime LONG NO
limit INT NO Default 500; max 1000.
recvWindow LONG NO

If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.

console.log(
  await client.deliveryAllOrders({ symbol: 'BTCUSD_200925' })
)
Output
[
  {
    "avgPrice": "0.0",
    "clientOrderId": "abc",
    "cumBase": "0",
    "executedQty": "0",
    "orderId": 1917641,
    "origQty": "0.40",
    "origType": "TRAILING_STOP_MARKET",
    "price": "0",
    "reduceOnly": false,
    "side": "BUY",
    "positionSide": "SHORT",
    "status": "NEW",
    "stopPrice": "9300",                // please ignore when order type is TRAILING_STOP_MARKET
    "closePosition": false,             // if Close-All
    "symbol": "BTCUSD_200925",
    "pair": "BTCUSD",
    "time": 1579276756075,              // order time
    "timeInForce": "GTC",
    "type": "TRAILING_STOP_MARKET",
    "activatePrice": "9020",            // activation price, only return with TRAILING_STOP_MARKET order
    "priceRate": "0.3",                 // callback rate, only return with TRAILING_STOP_MARKET order
    "updateTime": 1579276756075,        // update time
    "workingType": "CONTRACT_PRICE",
    "priceProtect": false               // if conditional order trigger is protected
  }
  ...
]

deliveryBatchOrders

Place multiple orders

Name Type Mandatory Description
batchOrders LIST YES order list. Max 5 orders

deliveryCancelBatchOrders

Cancel multiple orders

Name Type Mandatory Description
symbol STRING YES The pair name
orderIdList STRING NO max length 10
e.g. '[1234567,2345678]'
origClientOrderIdList STRING NO max length 10
e.g. '["my_id_1","my_id_2"]', encode the double quotes. No space after comma.

deliveryLeverage

Change user's initial leverage of specific symbol market.

Name Type Mandatory Description
symbol STRING YES The pair name
leverage INT YES target initial leverage: int from 1 to 125
recvWindow LONG NO
console.log(
  await client.deliveryLeverage({
    symbol: 'BTCUSD_200925',
    leverage: 21,
  })
)
Output
{
    "leverage": 21,
    "maxQty": "1000",  // maximum quantity of base asset
    "symbol": "BTCUSD_200925"
}

deliveryMarginType

Change margin type.

Name Type Mandatory Description
symbol STRING YES The pair name
marginType ENUM YES ISOLATED, CROSSED
recvWindow LONG NO
console.log(
  await client.futuresMarginType({
    symbol: 'BTCUSD_200925',
    marginType: 'ISOLATED',
  })
)
Output
{
    "code": 200,
    "msg": "success"
}

deliveryPositionMargin

Modify isolated position margin.

Name Type Mandatory Description
symbol STRING YES The pair name
positionSide ENUM NO Default BOTH for One-way Mode;
LONG or SHORT for Hedge Mode.
It must be sent with Hedge Mode.
amount DECIMAL YES
type INT YES 1: Add position margin,2: Reduce position margin
recvWindow LONG NO

Only for isolated symbol.

console.log(
  await client.deliveryPositionMargin({
    symbol: 'BTCUSD_200925',
    amount: 100,
    type: 1,
  })
)
Output
{
    "amount": 100.0,
    "code": 200,
    "msg": "Successfully modify position margin.",
    "type": 1
}

deliveryMarginHistory

Get position margin change history.

Name Type Mandatory Description
symbol STRING YES The pair name
type INT NO 1: Add position margin,2: Reduce position margin
startTime LONG NO
endTime LONG NO
limit INT NO Default 50;
recvWindow LONG NO
console.log(
  await client.deliveryMarginHistory({
    symbol: 'BTCUSD_200925',
    type: 1,
    startTime: 1578047897180,
    limit: 10,
  })
)
Output
[
    {
        "amount": "23.36332311",
        "asset": "BTC",
        "symbol": "BTCUSD_200925",
        "time": 1578047897183,
        "type": 1,
        "positionSide": "BOTH"
    },
    {
        "amount": "100",
        "asset": "BTC",
        "symbol": "BTCUSD_200925",
        "time": 1578047900425,
        "type": 1,
        "positionSide": "LONG"
    }
    ...
]

deliveryIncome

Get income history.

Name Type Mandatory Description
symbol STRING NO The pair name
incomeType STRING NO "TRANSFER","WELCOME_BONUS", "REALIZED_PNL",
"FUNDING_FEE", "COMMISSION", and "INSURANCE_CLEAR"
startTime LONG NO Timestamp in ms to get funding from INCLUSIVE.
endTime LONG NO Timestamp in ms to get funding until INCLUSIVE.
limit INT NO Default 100; max 1000
recvWindow LONG NO
  • If incomeType is not sent, all kinds of flow will be returned
  • trandId is unique in the same incomeType for a user
  • The interval between startTime and endTime can not exceed 200 days:
    • If startTime and endTime are not sent, the last 200 days will be returned
console.log(
  await client.deliveryIncome({
    symbol: 'BTCUSD_200925',
    startTime: 1570608000000,
    limit: 700,
  })
)
Output
[
    {
        "symbol": "",               // trade symbol, if existing
        "incomeType": "TRANSFER",   // income type
        "income": "-0.37500000",    // income amount
        "asset": "BTC",             // income asset
        "info":"WITHDRAW",          // extra information
        "time": 1570608000000,
        "tranId":"9689322392",      // transaction id
        "tradeId":""                // trade id, if existing
    },
    {
        "symbol": "BTCUSD_200925",
        "incomeType": "COMMISSION", 
        "income": "-0.01000000",
        "asset": "BTC",
        "info":"",
        "time": 1570636800000,
        "tranId":"9689322392",
        "tradeId":"2059192"
    }
]

deliveryAccountBalance

Get delivery account balance

console.log(await client.deliveryAccountBalance());
Output
[
  {
    "accountAlias": "SgsR",    // unique account code
    "asset": "BTC",
    "balance": "0.00250000",
    "withdrawAvailable": "0.00250000",
    "crossWalletBalance": "0.00241969",
    "crossUnPnl": "0.00000000",
    "availableBalance": "0.00241969",
    "updateTime": 1592468353979
  }
  ...
]

deliveryUserTrades

Get trades for a specific account and symbol.

console.log(
  await client.deliveryUserTrades({
    symbol: 'BTCUSD_200626',
  }),
)
Param Type Mandatory Description
symbol STRING NO
pair STRING NO
startTime LONG NO
endTime LONG NO
limit INT NO Default 50; max 1000.
fromId LONG NO Trade id to fetch from. Default gets most recent trades.
recvWindow LONG NO
  • Either symbol or pair must be sent
  • Symbol and pair cannot be sent together
  • Pair and fromId cannot be sent together
  • If a pair is sent,tickers for all symbols of the pair will be returned
  • The parameter fromId cannot be sent with startTime or endTime
Output
[
  {
    'symbol': 'BTCUSD_200626',
    'id': 6,
    'orderId': 28,
    'pair': 'BTCUSD',
    'side': 'SELL',
    'price': '8800',
    'qty': '1',
    'realizedPnl': '0',
    'marginAsset': 'BTC',
    'baseQty': '0.01136364',
    'commission': '0.00000454',
    'commissionAsset': 'BTC',
    'time': 1590743483586,
    'positionSide': 'BOTH',
    'buyer': false,
    'maker': false
  }
    ...
]

deliveryLeverageBracket

Get the pair's default notional bracket list.

console.log(
  await client.deliveryLeverageBracket({
    pair: 'BTCUSD', // Optional
  }),
)
Param Type Mandatory Description
symbol STRING NO Use if you are only interested in brackets for one symbol
recvWindow LONG NO
Output
[
    {
        "pair": "BTCUSD",
        "brackets": [
            {
                "bracket": 1,   // bracket level
                "initialLeverage": 125,  // the maximum leverage
                "qtyCap": 50,  // upper edge of base asset quantity
                "qtylFloor": 0,  // lower edge of base asset quantity
                "maintMarginRatio": 0.004 // maintenance margin rate
                "cum": 0.0  // Auxiliary number for quick calculation 
            },
        ]
    }
]

WebSockets

Every websocket utility returns a function you can call to close the opened connection and avoid memory issues.

const clean = client.ws.depth('ETHBTC', depth => {
  console.log(depth)
})

// After you're done
clean()

depth

Live depth market data feed. The first parameter can either be a single symbol string or an array of symbols. If you wish to specify the update speed (can either be 1000ms or 100ms) of the stream then append the speed at the end of the symbol string as follows: ETHBTC@100ms

client.ws.depth('ETHBTC', depth => {
  console.log(depth)
})
Output
{
  eventType: 'depthUpdate',
  eventTime: 1508612956950,
  symbol: 'ETHBTC',
  firstUpdateId: 18331140,
  finalUpdateId: 18331145,
  bidDepth: [
    { price: '0.04896500', quantity: '0.00000000' },
    { price: '0.04891100', quantity: '15.00000000' },
    { price: '0.04891000', quantity: '0.00000000' } ],
  askDepth: [
    { price: '0.04910600', quantity: '0.00000000' },
    { price: '0.04910700', quantity: '11.24900000' }
  ]
}

customSubStream

You can add custom sub streams by view docs

client.ws.customSubStream('!markPrice@arr@1s', console.log)

partialDepth

Top levels bids and asks, pushed every second. Valid levels are 5, 10, or 20. Accepts an array of objects for multiple depths. If you wish to specify the update speed (can either be 1000ms or 100ms) of the stream then append the speed at the end of the symbol string as follows: ETHBTC@100ms

client.ws.partialDepth({ symbol: 'ETHBTC', level: 10 }, depth => {
  console.log(depth)
})
Output
{
  symbol: 'ETHBTC',
  level: 10,
  bids: [
    { price: '0.04896500', quantity: '0.00000000' },
    { price: '0.04891100', quantity: '15.00000000' },
    { price: '0.04891000', quantity: '0.00000000' }
  ],
  asks: [
    { price: '0.04910600', quantity: '0.00000000' },
    { price: '0.04910700', quantity: '11.24900000' }
  ]
}

ticker

24hr Ticker statistics for a symbol pushed every second. Accepts an array of symbols.

client.ws.ticker('HSRETH', ticker => {
  console.log(ticker)
})
Output
{
  eventType: '24hrTicker',
  eventTime: 1514670820924,
  symbol: 'HSRETH',
  priceChange: '-0.00409700',
  priceChangePercent: '-11.307',
  weightedAvg: '0.03394946',
  prevDayClose: '0.03623500',
  curDayClose: '0.03213800',
  closeTradeQuantity: '7.02000000',
  bestBid: '0.03204200',
  bestBidQnt: '78.00000000',
  bestAsk: '0.03239800',
  bestAskQnt: '7.00000000',
  open: '0.03623500',
  high: '0.03659900',
  low: '0.03126000',
  volume: '100605.15000000',
  volumeQuote: '3415.49097353',
  openTime: 1514584420922,
  closeTime: 1514670820922,
  firstTradeId: 344803,
  lastTradeId: 351380,
  totalTrades: 6578
}

allTickers

Retrieves all the tickers.

client.ws.allTickers(tickers => {
  console.log(tickers)
})

miniTicker

24hr Mini Ticker statistics for a symbol pushed every second. Accepts an array of symbols.

client.ws.miniTicker('HSRETH', ticker => {
  console.log(ticker)
})
Output
{
  eventType: '24hrMiniTicker',
  eventTime: 1514670820924,
  symbol: 'HSRETH',
  curDayClose: '0.03213800',
  open: '0.03623500',
  high: '0.03659900',
  low: '0.03126000',
  volume: '100605.15000000',
  volumeQuote: '3415.49097353'
}

allMiniTickers

Retrieves all the mini tickers.

client.ws.allMiniTickers(tickers => {
  console.log(tickers)
})

bookTicker

Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. Accepts a single symbol or an array of symbols.

client.ws.bookTicker('BTCUSDT', ticker => {
  console.log(ticker)
})
Output
{
  updateId: 23099391508,
  symbol: 'BTCUSDT',
  bestBid: '21620.03000000',
  bestBidQnt: '0.09918000',
  bestAsk: '21621.65000000',
  bestAskQnt: '0.06919000'
}

candles

Live candle data feed for a given interval. You can pass either a symbol string or a symbol array.

client.ws.candles('ETHBTC', '1m', candle => {
  console.log(candle)
})
Output
{
  eventType: 'kline',
  eventTime: 1508613366276,
  symbol: 'ETHBTC',
  open: '0.04898000',
  high: '0.04902700',
  low: '0.04898000',
  close: '0.04901900',
  volume: '37.89600000',
  trades: 30,
  interval: '5m',
  isFinal: false,
  quoteVolume: '1.85728874',
  buyVolume: '21.79900000',
  quoteBuyVolume: '1.06838790'
}

trades

Live trade data feed. Pass either a single symbol string or an array of symbols. The trade streams push raw trade information; each trade has a unique buyer and seller.

client.ws.trades(['ETHBTC', 'BNBBTC'], trade => {
  console.log(trade)
})
Output
{
  eventType: 'trade',
  eventTime: 1508614495052,
  tradeTime: 1508614495050,
  symbol: 'ETHBTC',
  price: '0.04923600',
  quantity: '3.43500000',
  isBuyerMaker: true,
  maker: true,
  tradeId: 2148226,
  buyerOrderId: 390876,
  sellerOrderId: 390752
}

aggTrades

Live trade data feed. Pass either a single symbol string or an array of symbols. The aggregate trade streams push trade information that is aggregated for a single taker order.

client.ws.aggTrades(['ETHBTC', 'BNBBTC'], trade => {
  console.log(trade)
})
Output
{
  eventType: 'aggTrade',
  eventTime: 1508614495052,
  aggId: 2148226,
  price: '0.04923600',
  quantity: '3.43500000',
  firstId: 37856,
  lastId: 37904,
  timestamp: 1508614495050,
  symbol: 'ETHBTC',
  isBuyerMaker: false,
  wasBestPrice: true
}

user

Live user messages data feed.

Requires authentication

const clean = await client.ws.user(msg => {
  console.log(msg)
})

There is also equivalent function to query the margin wallet:

client.ws.marginUser()

Note that this method return a promise which will resolve the clean callback.

Output
{
  eventType: 'account',
  eventTime: 1508614885818,
  balances: {
    '123': { available: '0.00000000', locked: '0.00000000' },
    '456': { available: '0.00000000', locked: '0.00000000' },
    BTC: { available: '0.00000000', locked: '0.00000000' },
  }
}

Futures WebSockets

Every websocket utility returns a function you can call to close the opened connection and avoid memory issues.

const clean = client.ws.futuresDepth('ETHBTC', depth => {
  console.log(depth)
})

// After you're done
clean()

Each websocket utility supports the ability to get a clean callback without data transformation, for this, pass the third attribute FALSE.

const clean = client.ws.futuresDepth('ETHBTC', depth => {
  console.log(depth)
}, false)
Output
{
  "e": "depthUpdate", // Event type
  "E": 123456789,     // Event time
  "T": 123456788,     // transaction time 
  "s": "BTCUSDT",      // Symbol
  "U": 157,           // First update ID in event
  "u": 160,           // Final update ID in event
  "pu": 149,          // Final update Id in last stream(ie `u` in last stream)
  "b": [              // Bids to be updated
    [
      "0.0024",       // Price level to be updated
      "10"            // Quantity
    ]
  ],
  "a": [              // Asks to be updated
    [
      "0.0026",       // Price level to be updated
      "100"          // Quantity
    ]
  ]
}

futuresDepth

Live futuresDepth market data feed. The first parameter can either be a single symbol string or an array of symbols.

client.ws.futuresDepth('ETHBTC', depth => {
  console.log(depth)
})
Output
{
  eventType: 'depthUpdate',
  eventTime: 1508612956950,
  symbol: 'ETHBTC',
  firstUpdateId: 18331140,
  finalUpdateId: 18331145,
  bidDepth: [
    { price: '0.04896500', quantity: '0.00000000' },
    { price: '0.04891100', quantity: '15.00000000' },
    { price: '0.04891000', quantity: '0.00000000' } ],
  askDepth: [
    { price: '0.04910600', quantity: '0.00000000' },
    { price: '0.04910700', quantity: '11.24900000' }
  ]
}

futuresPartialDepth

Top levels bids and asks, pushed every second. Valid levels are 5, 10, or 20. Accepts an array of objects for multiple depths.

client.ws.futuresPartialDepth({ symbol: 'ETHBTC', level: 10 }, depth => {
  console.log(depth)
})
Output
{

  eventType: 'depthUpdate',
  eventTime: 1508612956950,
  symbol: 'ETHBTC',
  level: 10,
  firstUpdateId: 18331140,
  finalUpdateId: 18331145,
  bidDepth: [
    { price: '0.04896500', quantity: '0.00000000' },
    { price: '0.04891100', quantity: '15.00000000' },
    { price: '0.04891000', quantity: '0.00000000' } ],
  askDepth: [
    { price: '0.04910600', quantity: '0.00000000' },
    { price: '0.04910700', quantity: '11.24900000' }
  ]
}

futuresTicker

24hr Ticker statistics for a symbol pushed every 500ms. Accepts an array of symbols.

client.ws.futuresTicker('HSRETH', ticker => {
  console.log(ticker)
})
Output
{
  eventType: '24hrTicker',
  eventTime: 123456789,
  symbol: 'BTCUSDT',
  priceChange: '0.0015',
  priceChangePercent: '250.00',
  weightedAvg: '0.0018',
  curDayClose: '0.0025',
  closeTradeQuantity: '10',
  open: '0.0010',
  high: '0.0025',
  low: '0.0010',
  volume: '10000',
  volumeQuote: '18',
  openTime: 0,
  closeTime: 86400000,
  firstTradeId: 0,
  lastTradeId: 18150,
  totalTrades: 18151,
}

futuresAllTickers

Retrieves all the tickers.

client.ws.futuresAllTickers(tickers => {
  console.log(tickers)
})

futuresCandles

Live candle data feed for a given interval. You can pass either a symbol string or a symbol array.

client.ws.futuresCandles('ETHBTC', '1m', candle => {
  console.log(candle)
})
Output
{
  eventType: 'kline',
  eventTime: 1508613366276,
  symbol: 'ETHBTC',
  open: '0.04898000',
  high: '0.04902700',
  low: '0.04898000',
  close: '0.04901900',
  volume: '37.89600000',
  trades: 30,
  interval: '5m',
  isFinal: false,
  quoteVolume: '1.85728874',
  buyVolume: '21.79900000',
  quoteBuyVolume: '1.06838790'
}

futuresAggTrades

Live trade data feed. Pass either a single symbol string or an array of symbols. The Aggregate Trade Streams push trade information that is aggregated for a single taker order every 100 milliseconds.

client.ws.futuresAggTrades(['ETHBTC', 'BNBBTC'], trade => {
  console.log(trade)
})
Output
{
  eventType: 'aggTrade',
  eventTime: 1508614495052,
  aggId: 2148226,
  price: '0.04923600',
  quantity: '3.43500000',
  firstId: 37856,
  lastId: 37904,
  timestamp: 1508614495050,
  symbol: 'ETHBTC',
  isBuyerMaker: false,
}

futuresLiquidations

Live liquidation data feed. Pass either a single symbol string or an array of symbols. The Liquidation Order Streams push force liquidation order information for specific symbol(s).

client.ws.futuresLiquidations(['ETHBTC', 'BNBBTC'], liquidation => {
  console.log(liquidation)
})
Output
{
  symbol: string
  price: '0.04923600',
  origQty: '3.43500000',
  lastFilledQty: '3.43500000',
  accumulatedQty: '3.43500000',
  averagePrice: '0.04923600',
  status: 'FILLED',
  timeInForce: 'IOC',
  type: 'LIMIT',
  side: 'SELL',
  time: 1508614495050
}

futuresAllLiquidations

Live liquidation data feed. Pass either a single symbol string or an array of symbols. The All Liquidation Order Streams push force liquidation order information for all symbols in the market.

client.ws.futuresAllLiquidations(liquidation => {
  console.log(liquidation)
})
Output
{
  symbol: string
  price: '0.04923600',
  origQty: '3.43500000',
  lastFilledQty: '3.43500000',
  accumulatedQty: '3.43500000',
  averagePrice: '0.04923600',
  status: 'FILLED',
  timeInForce: 'IOC',
  type: 'LIMIT',
  side: 'SELL',
  time: 1508614495050
}

futuresCustomSubStream

You can add custom sub streams by view docs

client.ws.futuresCustomSubStream(['!markPrice@arr','ETHBTC@markPrice@1s'], console.log)

futuresUser

Live user messages data feed.

Requires authentication

const futuresUser = await client.ws.futuresUser(msg => {
  console.log(msg)
})
Output
{
  eventTime: 1564745798939,
  transactionTime: 1564745798938,
  eventType: 'ACCOUNT_UPDATE',
  eventReasonType: 'ORDER',
  balances: [
    {
      asset:'USDT',
      walletBalance:'122624.12345678',
      crossWalletBalance:'100.12345678'
    },
    {
      asset:'BNB',           
      walletBalance:'1.00000000',
      crossWalletBalance:'0.00000000'         
    }
  ],
  positions: [
    {
      symbol:'BTCUSDT',
      positionAmount:'0',
      entryPrice:'0.00000',
      accumulatedRealized:'200',
      unrealizedPnL:'0',
      marginType:'isolated',
      isolatedWallet:'0.00000000',
      positionSide:'BOTH'
    },
    {
      symbol:'BTCUSDT',
      positionAmount:'20',
      entryPrice:'6563.66500',
      accumulatedRealized:'0',
      unrealizedPnL:'2850.21200',
      marginType:'isolated',
      isolatedWallet:'13200.70726908',
      positionSide:'LONG'
    }
  ],
}

Delivery WebSockets

Every websocket utility returns a function you can call to close the opened connection and avoid memory issues.

const clean = client.ws.deliveryDepth('BTCUSD_200626', depth => {
  console.log(depth)
})

// After you're done
clean()

Each websocket utility supports the ability to get a clean callback without data transformation, for this, pass the third attribute FALSE.

const clean = client.ws.deliveryDepth('BTCUSD_200626', depth => {
  console.log(depth)
}, false)
Output
{
  "e": "depthUpdate",           // Event type
  "E": 1591270260907,           // Event time
  "T": 1591270260891,           // Transction time
  "s": "BTCUSD_200626",         // Symbol
  "ps": "BTCUSD",               // Pair
  "U": 17285681,                // First update ID in event
  "u": 17285702,                // Final update ID in event
  "pu": 17285675,               // Final update Id in last stream(ie `u` in last stream)
  "b": [                        // Bids to be updated
    [
      "9517.6",                 // Price level to be updated
      "10"                      // Quantity
    ]
  ],
  "a": [                        // Asks to be updated
    [
      "9518.5",                 // Price level to be updated
      "45"                      // Quantity
    ]
  ]
}

deliveryDepth

Live futuresDepth market data feed. The first parameter can either be a single symbol string or an array of symbols.

client.ws.deliveryDepth('TRXUSD_PERP', depth => {
  console.log(depth)
})
Output
{
  eventType: 'depthUpdate',
  eventTime: 1663111254317,
  transactionTime: 1663111254138,
  symbol: 'TRXUSD_PERP',
  pair: 'TRXUSD',
  firstUpdateId: 558024151999,
  finalUpdateId: 558024152633,
  prevFinalUpdateId: 558024150524,
  bidDepth: [
    { price: '0.06052', quantity: '1805' },
    { price: '0.06061', quantity: '313' }
  ],
  askDepth: [
    { price: '0.06062', quantity: '314' },
    { price: '0.06063', quantity: '790' },
    { price: '0.06065', quantity: '1665' },
    { price: '0.06066', quantity: '2420' }
  ]
}

deliveryPartialDepth

Top bids and asks. Valid levels are 5, 10, or 20. Update Speed : 250ms, 500ms or 100ms. Accepts an array of objects for multiple depths.

client.ws.deliveryPartialDepth({ symbol: 'TRXUSD_PERP', level: 10 }, depth => {
  console.log(depth)
})
Output
{
  level: 10,
  eventType: 'depthUpdate',
  eventTime: 1663111554598,
  transactionTime: 1663111554498,
  symbol: 'TRXUSD_PERP',
  pair: 'TRXUSD',
  firstUpdateId: 558027933795,
  finalUpdateId: 558027935097,
  prevFinalUpdateId: 558027932895,
  bidDepth: [
    { price: '0.06063', quantity: '604' },
    { price: '0.06062', quantity: '227' },
    { price: '0.06061', quantity: '327' }
  ],
  askDepth: [
    { price: '0.06064', quantity: '468' },
    { price: '0.06065', quantity: '131' }
  ]
}

deliveryTicker

24hr rollwing window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Accepts an array of symbols.

client.ws.deliveryTicker('BNBUSD_PERP', ticker => {
  console.log(ticker)
})
Output
{
  eventType: '24hrTicker',
  eventTime: 1664834148221,
  symbol: 'BNBUSD_PERP',
  pair: 'BNBUSD',
  priceChange: '0.130',
  priceChangePercent: '0.046',
  weightedAvg: '286.02648763',
  curDayClose: '285.745',
  closeTradeQuantity: '1',
  open: '285.615',
  high: '289.050',
  low: '282.910',
  volume: '9220364',
  volumeBase: '322360.49452795',
  openTime: 1664747700000,
  closeTime: 1664834148215,
  firstTradeId: 179381113,
  lastTradeId: 179462069,
  totalTrades: 80957
}

deliveryAllTickers

Retrieves all the tickers.

client.ws.deliveryAllTickers(tickers => {
  console.log(tickers)
})

deliveryCandles

Live candle data feed for a given interval. You can pass either a symbol string or a symbol array.

client.ws.deliveryCandles('ETHUSD_PERP', '1m', candle => {
  console.log(candle)
})
Output
{
  eventType: 'kline',
  eventTime: 1664834318306,
  symbol: 'ETHUSD_PERP',
  startTime: 1664834280000,
  closeTime: 1664834339999,
  firstTradeId: 545784425,
  lastTradeId: 545784494,
  open: '1317.68',
  high: '1317.91',
  low: '1317.68',
  close: '1317.91',
  volume: '6180',
  trades: 70,
  interval: '1m',
  isFinal: false,
  baseVolume: '46.89730466',
  buyVolume: '5822',
  baseBuyVolume: '44.18040830'
}

deliveryAggTrades

Live trade data feed. Pass either a single symbol string or an array of symbols. The Aggregate Trade Streams push trade information that is aggregated for a single taker order every 100 milliseconds.

client.ws.deliveryAggTrades(['ETHUSD_PERP', 'BNBUSD_PERP'], trade => {
  console.log(trade)
})
Output
{
  eventType: 'aggTrade',
  eventTime: 1664834403682,
  symbol: 'ETHUSD_PERP',
  aggId: 216344302,
  price: '1317.57',
  quantity: '1318',
  firstId: 545784591,
  lastId: 545784591,
  timestamp: 1664834403523,
  isBuyerMaker: false
}

deliveryCustomSubStream

You can add custom sub streams by view docs

client.ws.deliveryCustomSubStream(['!miniTicker@arr','ETHUSD_PERP@markPrice@1s'], console.log)

deliveryUser

Live user messages data feed. For different event types, see official documentation

Requires authentication

const deliveryUser = await client.ws.deliveryUser(msg => {
  console.log(msg)
})
Output
{
  eventTime: 1664834883117,
  transactionTime: 1664834883101,
  eventType: 'ACCOUNT_UPDATE',
  eventReasonType: 'ORDER',
  balances: [
    {
      asset: 'BUSD',
      walletBalance: '123.45678901',
      crossWalletBalance: '123.45678901',
      balanceChange: '0'
    },
    {
      asset: 'BNB',
      walletBalance: '0.12345678',
      crossWalletBalance: '0.12345678',
      balanceChange: '0'
    }
  ],
  positions: [
    {
      symbol: 'ETHBUSD',
      positionAmount: '420.024',
      entryPrice: '1234.56789',
      accumulatedRealized: '9000.12345678',
      unrealizedPnL: '0.38498800',
      marginType: 'cross',
      isolatedWallet: '0',
      positionSide: 'BOTH'
    }
  ]
}

Common

getInfo

To get information about limits from response headers call getInfo()

console.log(client.getInfo())
Output
{
  futures: {
     futuresLatency: "2ms",
     orderCount1m: "10",
     usedWeigh1m: "1",
  },
  spot: {
     orderCount1d: "347",
     orderCount10s: "1",
     usedWeigh1m: "15",
  },
  delivery: {
    usedWeight1m: '13',
    responseTime: '4ms',
    orderCount1m: '1'
  }
}

ErrorCodes

An utility error code map is also being exported by the package in order for you to make readable conditionals upon specific errors that could occur while using the API.

import Binance, { ErrorCodes } from 'binance-api-node'

console.log(ErrorCodes.INVALID_ORDER_TYPE) // -1116

binance-api-node's People

Contributors

amibenson avatar anwebdevelopers avatar balthazar avatar barhun avatar bennycode avatar bramvbilsen avatar breitsmiley avatar chunyolin avatar datatypevoid avatar gelito avatar haehnchen avatar hp8wvvvgnj6asjm7 avatar ivancsicsmarkus avatar jestersimpps avatar jinusean avatar jonathanloscalzo avatar jstoeffler avatar klauspaiva avatar krolov avatar luckypal avatar maxah avatar phl3x0r avatar snf avatar srbrahma avatar timofloettmann avatar toant13 avatar tony-ho avatar vsly-ru avatar vtrifonov avatar yovanoc 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

binance-api-node's Issues

Closing a connection

Currently if a connection is created, there is no way to disconnect it.
For a long running application, which may need to reconnect this will slowly eat up a large amount of memory.

// FROM websocket.js line ~103
var trades = function trades(payload, cb) {
  return (Array.isArray(payload) ? payload : [payload]).forEach(function (symbol) {
    var w = new _ws2.default(BASE + '/' + symbol.toLowerCase() + '@aggTrade');
    w.on('message', function (msg) {
      var _JSON$parse3 = JSON.parse(msg),
          eventType = _JSON$parse3.e,
          eventTime = _JSON$parse3.E,
          symbol = _JSON$parse3.s,
          price = _JSON$parse3.p,
          quantity = _JSON$parse3.q,
          maker = _JSON$parse3.m,
          tradeId = _JSON$parse3.a;

      cb({
        eventType: eventType,
        eventTime: eventTime,
        symbol: symbol,
        price: price,
        quantity: quantity,
        maker: maker,
        tradeId: tradeId
      });
    });
  });
};

The returned value is undefined since forEach does not return anything.

Is there a recommended way of closing out the connection?

Strategy to avoid "INVALID_TIMESTAMP"

Binance is pretty strict about the timestamp which is sent to the server on every request.

To avoid the "Request used an outdated timestamp" error, we could sync our own time with an online atomic clock service to determine our clock drift (which can then be used to adjust the timestamps).

.orderTest() returning empty object

Is this intended? The documentation states that the output of this test call will return the same output as .order() which is not the case. Is the documentation wrong or is this an oversight? Awesome library thank you!

What are "quantity" units?

On aggrTrades, is quantity quoted in the base currency or the quote currency?

For instance, in a trade of ETHBTC, price == 0.091077 and quantity == 0.316 - is it BTC or ETH?

ERROR: TIMESTAMP FOR THIS REQUEST WAS 1000MS AHEAD OF THE SERVER'S TIME.

I'm getting the following error when placing a purchase order

ERROR: TIMESTAMP FOR THIS REQUEST WAS 1000MS AHEAD OF THE SERVER'S TIME.
  return new Binance({
    apiKey,
    apiSecret,
    useServerTime: true, // It should solve the above problem.
  });

Has anyone had this problem while using it in production? In tests everything is OK, but when I change orderTest to order the above error occurs.

Sending data to my server running:

{
	"symbol": "LTCETH",
	"quantity": 0.00190000,
	"userId": "5ac9c2ad41a43a3770beb263"
}

FetchError: Unhandled promise rejection (ENOTFOUND)

I tested the Binance API in a real-world scenario where internet connections can get interrupted. In these cases, the "binance-api-node" library fails with a Unhandled promise rejection which can cause Node.js application crashes.

Here is a little code demo which shows the issue:

const Binance = require('binance-api-node').default
const dotenv = require('dotenv')

if (!process.env.BINANCE_API_KEY) dotenv.load()

process.on('unhandledRejection', error => {
  console.error('Catched Binance error', error)
  process.exit(1)
})

const client = Binance({
  apiKey: process.env.BINANCE_API_KEY,
  apiSecret: process.env.BINANCE_API_SECRET,
})

async function getOrder() {
  const order = await client.getOrder({symbol: 'TRXETH', orderId: 20123533})
  console.log(`order (${Date.now()})`, order)
  setTimeout(getOrder, 2000)
}

getOrder()

Just run the code and turn off your internet connection (airplane mode) while the code is running.

We need to come up with a concept, where this scenario is detected and where Promises will be continued once internet is back again.

Unknown Processing Error

Getting this error but not sure where from:

error: Unhandled Rejection at: Promise  Promise {
  <rejected> Error: An unknown error occured while processing the request.
    at /home/jafri/binance-api/node_modules/binance-api-node/dist/http.js:47:13
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7) } Error: An unknown error occured while processing the request.
    at /home/jafri/binance-api/node_modules/binance-api-node/dist/http.js:47:13
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

withdraw error

{ msg: 'The operation failed, please try again later.',
success: false,
id: 'bb1f91a7bd1b448ca7f8143b7dcac8e2' }

Unhandled Promise Rejection when trying to establish a websocket connection (when cannot reach the Binance server)

When the Node.js server (for some reason) cannot reach the Binance server, and you try opening a websocket (say for example ws.depth), the function call throws an Unhandled Promise Rejection leading to the Node.js server to crash.

Looking at the Websocket documentation this happens when the event error is emitted by the underlying socket. Ideally, the function that tries to open a websocket should try and handle the error event by subscribing to the websocket_instance.on("error", message => {...}) callback, which is missing in every function in the websocket.js module.

There is no way other than process.on('uncaughtException', error => {...}) to catch such errors. In an ideal case, the functions in websocket.js should return a promise, that should be resolved only when the websocket connection is successfully established, or else should send a rejection. Something like below

const depth = (payload, cb) => {
  return new Promise((fulfill, reject) => {
    const cache = [];
    let count = 0;
    let payload = Array.isArray(payload) ? payload : [payload];
    (payload).forEach(symbol => {
      const w = new WebSocket(`${BASE}/${symbol.toLowerCase()}@depth`)
      cache.push(w);
      
      w.on('open', msg => {
        count++;
        if (count === payload.length) fulfill(() => cache.forEach(w => w.close()));
      });

      w.on('message', msg => {
        const {
          e: eventType,
          E: eventTime,
          s: symbol,
          u: finalUpdateId,
          U: firstUpdateId,
          b: bidDepth,
          a: askDepth,
        } = JSON.parse(msg)

        cb({
          eventType,
          eventTime,
          symbol,
          firstUpdateId,
          finalUpdateId,
          bidDepth: bidDepth.map(b => zip(['price', 'quantity'], b)),
          askDepth: askDepth.map(a => zip(['price', 'quantity'], a)),
        })
      });

      w.on('error', msg => {
        reject(msg);
      });
    })
  });
}

syntaxerror import

When trying this sample in node js:

import Binance from 'binance-api-node'
const client = Binance()

client.time().then(time => console.log(time))

I get this error:

import Binance from 'binance-api-node'
^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

Upon investigating on the net, I found that node js doesn't natively support ES6.
One workaround is to use require instead:

const Binance = require('binance-api-node')
const client = Binance()

client.time().then(time => console.log(time))

But this then gets me this error:

const client = Binance()
               ^

TypeError: Binance is not a function
    at Object.<anonymous> (C:\Trader\Logic\Random\test.js:9:16)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

Another workaround would be to use babel, but I don't have any knowledge regarding that.
Is there an easy fix?

Thanks,
Wannes

Catch error in buy/sell

If an order is placed which is immediately rejected (for example, insufficient balance) - there doesn't appear to be a way to catch it?

The returned promise results in a permanent pending state - even though internally something has been rejected.

I've tried to catch it every which way i could think of, but the code never makes it out that far.

For example, here's all the ways i've tried to catch the error at my level (mind the craziness, i was starting to just try everything possible)

// Wrap whole thing in TRY/CATCH
try {
  var p = new Promise(async resolve => {
    let result = await authedClient.order(params);
    // WRAP result of .order call in TRY/CATCH
    try {
      result = await authedClient.order(params);
    } catch(e) {
      // THIS IS NEVER REACHED
      console.log("Error:", e);
    }
    resolve(result);
  })
  .catch(function(reason) {
    // THIS IS ALSO NEVER REACHED
    console.log("Error:", e);
  })
  .finally(()=>{
    // This is also never reached
    console.log("Finally")
  })
  // wrap the whole promise within a Promise.all call
  Promise.all([p]).then( () => console.log("NEVER REACHED"))

} catch(e) {
  // THIS IS NEVER REACHED
  debugger;
}

// Returned promise P is stuck in permanent `pending` state - even though internally it has failed

Unhandled promise rejection when trying to clean user data stream websocket

Reproduce the issue with this code :

import Binance from 'binance-api-node';

const client = Binance({
  apiKey: 'Igj71woxxxxxxxxxxxxxxxxx',
  apiSecret: 'gkFWlxxxxxxxxxxxxxxxxx'
});

let clean;

setInterval(async () => {
  clean && clean();
  clean = await client.ws.user(() => {});
}, 5e3);

Once in a while (about 1 out of 5 times) the server responds with a 500 status code and this happens :
(node:22103) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: An unknown error occured while processing the request.

It comes from the closeDataStream call
https://github.com/HyperCubeProject/binance-api-node/blob/47c65c1e5cb8659b6e0f16ad49e6c882413aaa75/src/websocket.js#L245
and the exact unhandled promise rejection comes from here :
https://github.com/HyperCubeProject/binance-api-node/blob/47c65c1e5cb8659b6e0f16ad49e6c882413aaa75/src/http.js#L21-L28

As a temporary workaround I just completely removed the closeDataStream() call since it seems it isn't really necessary. It turns out the server will return the same listenKey on getDataStream() call if it is still alive and you haven't deleted it.

Requires babel-polyfill since 0.5.1

Updated from 0.5.0 to 0.5.2, trader won't start.
Error:

C:\Trader\Logic\node_modules\binance-api-node\dist\http.js:105
    var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(path) {
                                                ^

ReferenceError: regeneratorRuntime is not defined
    at C:\Trader\Logic\node_modules\binance-api-node\dist\http.js:105:49
    at privateCall (C:\Trader\Logic\node_modules\binance-api-node\dist\http.js:168:4)
    at exports.default (C:\Trader\Logic\node_modules\binance-api-node\dist\http.js:235:15)
    at new exports.default (C:\Trader\Logic\node_modules\binance-api-node\dist\index.js:21:42)
    at C:\Trader\Logic\Trader_Crypto.js:74:53
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)

Downgraded back to 0.5.0, working again.

Exchange Info Endpoint

Hi,

Can we get support for /api/v1/exchangeInfo endpoint that provides information about the LOT_SIZE and other exchange info on every pair.

Thanks

Error: Invalid symbol.

Today I tried to sell XLM using binance-api-node. I tried to execute it this way:

const Binance = require('binance-api-node').default;

const client = Binance({
  apiKey: process.env.BINANCE_API_KEY,
  apiSecret: process.env.BINANCE_API_SECRET
});

const order = { 
  symbol: 'XLM',
  side: 'SELL',
  type: 'LIMIT',
  quantity: 48,
  price: 0.00031337
};

client.order(order).then(response => console.log('Success'));

Unfortunately I am always receiving the following error:

Error: Invalid symbol.
at D:\dev\projects\bennyn\trading-bot-framework\node_modules\binance-api-node\dist\http.js:47:13
at
at process._tickCallback (internal/process/next_tick.js:188:7)

What am I doing wrong?

I logged error.code (https://github.com/binance-exchange/binance-official-api-docs/blob/master/errors.md) but it's undefined. 😢

Enums for error codes

I would like to discuss the idea of mapping error codes into error types.

In my TypeScript application I created an enum list for that purpose:

enum BinanceErrorCode {
  UNKNOWN = -1000,
  DISCONNECTED = -1001,
  UNAUTHORIZED = -1002,
  TOO_MANY_REQUESTS = -1003,
  UNEXPECTED_RESP = -1006,
  TIMEOUT = -1007,
  INVALID_MESSAGE = -1013,
  UNKNOWN_ORDER_COMPOSITION = -1014,
  TOO_MANY_ORDERS = -1015,
  SERVICE_SHUTTING_DOWN = -1016,
  UNSUPPORTED_OPERATION = -1020,
  INVALID_TIMESTAMP = -1021,
  INVALID_SIGNATURE = -1022,
  ILLEGAL_CHARS = -1100,
  TOO_MANY_PARAMETERS = -1101,
  MANDATORY_PARAM_EMPTY_OR_MALFORMED = -1102,
  UNKNOWN_PARAM = -1103,
  UNREAD_PARAMETERS = -1104,
  PARAM_EMPTY = -1105,
  PARAM_NOT_REQUIRED = -1106,
  NO_DEPTH = -1112,
  TIF_NOT_REQUIRED = -1114,
  INVALID_TIF = -1115,
  INVALID_ORDER_TYPE = -1116,
  INVALID_SIDE = -1117,
  EMPTY_NEW_CL_ORD_ID = -1118,
  EMPTY_ORG_CL_ORD_ID = -1119,
  BAD_INTERVAL = -1120,
  BAD_SYMBOL = -1121,
  INVALID_LISTEN_KEY = -1125,
  MORE_THAN_XX_HOURS = -1127,
  OPTIONAL_PARAMS_BAD_COMBO = -1128,
  INVALID_PARAMETER = -1130,
  BAD_API_ID = -2008,
  DUPLICATE_API_KEY_DESC = -2009,
  INSUFFICIENT_BALANCE = -2010,
  CANCEL_ALL_FAIL = -2012,
  NO_SUCH_ORDER = -2013,
  BAD_API_KEY_FMT = -2014,
  REJECTED_MBX_KEY = -2015,
}

export default BinanceErrorCode

With binance-api-node v0.7.1 it gives me the ability to do the following:

if (error.code === BinanceErrorCode.INSUFFICIENT_BALANCE) {
  this.logger.warn(`Operation "SELL" for symbol "${pair.asString()}" failed. Account has insufficient balance."`)
} 

Instead of maintaining my own enum list it would be great if we can expose something like this from "binance-api-node". We would need to find a smart way on how to export such list of codes.

Telling from the error documentation there should be also -9xxx error codes which I haven't seen in production yet. The docs state that these are being used for filter errors such as LOT_SIZE but I get error message "Filter failure: LOT_SIZE" along with error code "-1013" (INVALID_MESSAGE). 🐺

Error: Account has insufficient balance for requested action

I am getting error "Error: Account has insufficient balance for requested action" when executing the order function, below is the implemented code example.

import Binance from 'binance-api-node'

const SIDE_OPTIONS = {
  BUY: 'BUY',
  SELL: 'SELL',
};

function runBinance(apiKey, apiSecret) {
  return Binance({
    apiKey,
    apiSecret,
  });
}

export async function buyOrder(
  binanceApiKey,
  binanceApiSecret,
  symbol,
  quantity,
  price,
  type,
) {
  try {
    await runBinance(binanceApiKey, binanceApiSecret)
      .order({
        symbol,
        side: SIDE_OPTIONS.BUY,
        quantity,
        type,
        price,
      });

    return;
  } catch (error) {
    return {
      error: {
        status: 400,
        message: error,
      }
    }
  }
}

Can anyone tell me if the test flag is working anyway? I do not want to use resources from my wallet for now.

Websocket handshake Error

I'm trying to use the websockets:

const client = Binance()
const disconnect = client.ws.ticker('ETHBTC', ticker => {
  console.log(ticker)
})

and I'm running into some unexpected errors:

WebSocket connection to 'wss://stream.binance.com:9443/ws/ethbtc@ticker' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received

Not sure how to go about fixing this, though I tried uninstalling binance-api-node and installing again. Using npm version 5.6.0 and node version v9.4.0.

can't get the example running

Hey,

i really like that you ported the project to async.
But i cant get it running.
What is it, i have to do to compile the project correctly?

After i installed binance-api.node and running a server.js file with the following code

import Binance from 'binance-api-node'

i get the error message

>node server.js                                                                                               [±master ●●]
/home/mod/code/projects/traders-friend/api/app/server.js:1
(function (exports, require, module, __filename, __dirname) { import Binance from 'binance-api-node'
                                                                     ^^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:152:10)
    at Module._compile (module.js:605:28)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
    at Function.Module.runMain (module.js:682:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:613:3

i am running node version 9.0.0.
thx in advance!

More typings

I wrote some method typings which were missing.

declare module 'binance-api-node' {
    interface MyTrade {
        id: number;
        orderId: number;
        price: string;
        qty: string;
        commission: string;
        commissionAsset: string;
        time: number;
        isBuyer: boolean;
        isMaker: boolean;
        isBestMatch: boolean;
    }

    interface QueryOrderResult {
        symbol: string;
        orderId: number;
        clientOrderId: string;
        price: string;
        origQty: string;
        executedQty: string;
        status: string;
        timeInForce: string;
        type: string;
        side: string;
        stopPrice: string;
        icebergQty: string;
        time: number;
        isWorking: boolean;
    }

    interface CancelOrderResult {
        symbol: string;
        origClientOrderId: string;
        orderId: number;
        clientOrderId: string;
    }

    interface Binance {
        myTrades(params: { symbol: string, limit?: number, fromId?: number }): Promise<MyTrade[]>;

        getOrder(params: { symbol: string; orderId: number }): Promise<QueryOrderResult>;

        cancelOrder(params: { symbol: string; orderId: number }): Promise<CancelOrderResult>;

        openOrders(params: { symbol: string }): Promise<QueryOrderResult[]>;
    }
}

I can make a PR if needed.

orderTest does not return anything

Not sure if this is intended, but is the orderTest function supposed to return an empty object {}?

Using the code:

        console.log(await client.orderTest({
          symbol: 'ADABTC',
          side: 'BUY',
          quantity: 100,
          price: 0.0002,
          recvWindow: 5000
        }))

ws.depth does not return "First update ID"

According to official binanace documentation WebSocket depth stream recieves in payload "First update ID in event" as "U" key, but in api wrapper we have only "u" key "Final update ID in event".
So there are not any possibility to update local order book by using data from this stream.

Also I can't verify that sequence data from depth stream are consistent and there aren't any packet wich would be miss

Also I can't verify that sequence of data from depth stream are continuous and there aren't any packet which was missed. If I recieve first packet with updateId=100 and next with updateId=108 I will not rely on this sequence? because I don't know there were between these packets others that were missed.
But If I got these packets with additional field firstUpdateId and finalUpdateId (instead of updateId) I can verify this.

For example, two packets

{firstUpdateId: 95, finalUpdateId: 100} 
{fistUpdateId: 101, finalUpdateId: 108}

In this case I see that sequence of changes is continuous: 95-100_101-108

I propose to modify depth method something like this:

File: binance-api-node/src/websocket.js

const depth = (payload, cb) => {
  const cache = (Array.isArray(payload) ? payload : [payload]).map(symbol => {
    const w = new WebSocket(`${BASE}/${symbol.toLowerCase()}@depth`)
    w.on('message', msg => {
      const {
        e: eventType,
        E: eventTime,
        s: symbol,
 //       u: updateId,          // - remove 
        U: firstUpdateId,     // + add 
        u: finalUpdateId,     // + add 
        b: bidDepth,
        a: askDepth,
      } = JSON.parse(msg)

      cb({
        eventType,
        eventTime,
        symbol,
//        updateId,           // - remove 
        firstUpdateId,       // + add 
        finalUpdateId,       // + add 
        bidDepth: bidDepth.map(b => zip(['price', 'quantity'], b)),
        askDepth: askDepth.map(a => zip(['price', 'quantity'], a)),
      })
    })

    return w
  })

  return () => cache.forEach(w => w.close())
}

Type definitions

Hi @balthazar, I am a big fan of your Binance API. It's really easy to handle and I like that it uses Promises.

The only thing which I am missing so far are type definitions for TypeScript. I would therefore like to create TypeScript definitions for this library and contribute them in various Pull Request (one for each section). But before I start with it I would like to know if you think that it is a good thing to do?

Best,
Benny

Return individual WebSocket connections

When opening a WebSocket connection, I get a clean handle which then can be used to close all open WebSocket connections at once:

return () => cache.forEach(w => w.close(1000, 'Close handle was called', { keepClosed: true }))

That's a great encapsulation but it also prevents me from closing individual WebSocket connections.

In my application I am watching the candles of different trading symbols (ETHBTC, BNBBTC, BNTBTC, ...). Sometimes I want to stop watching a symbol (like BNBBTC) but I cannot stop this WebSocket connection without stopping all the others too. We should find a solution to it. WDYT, @balthazar?

Websocket PartialDepth Symbols

When examining multiple markets we should have a secondary "symbol" return parameter so we can see which update this is for, at the moment we can only get depth.

Compiled with 2 warnings [win 7 platform]

i'm use vue-cli boilerplate (https://github.com/vuejs/vue-cli)
after vue init webpack client
a'm install the library:

  • yarn add binance-api-node

  • yarn run dev

WARNING Compiled with 2 warnings 17:

These dependencies were not found:

  • bufferutil in ./node_modules/ws/lib/BufferUtil.js
  • utf-8-validate in ./node_modules/ws/lib/Validation.js

To install them, you can run: npm install --save bufferutil utf-8-validate

  • yarn add bufferutil utf-8-validate

  • yarn run dev

WARNING Compiled with 2 warnings 17:49

warning in ./node_modules/bindings/bindings.js

81:22-40 Critical dependency: the request of a dependency is an expression

warning in ./node_modules/bindings/bindings.js

81:43-53 Critical dependency: the request of a dependency is an expression

how fix that error?

Websocket request returns 400

I'm getting a 400 when trying to open a websocket. I'm using
client.ws.depth('ETHBTC', depth => { console.log(depth) }) to test, but getting a 400 response. I tested the url it is creating with Simple Websocket Client. The wss:// protocol seems to be getting changed into https:// protocol somehow. In the Chrome Dev Tools I found the network request and it is "https://stream.binance.com:9443/ws/ethbtc@depth". So, in Simple Websocket Client extension I changed "https://" to "wss://" and it works. Just don't know how to fix it in this lib since it calls other dependencies that seem to be transforming the protocol and causing 400. Maybe I am doing something wrong.

Error codes

I have seen that the Binance API provides error codes. However, I cannot access them using error.code. Is binance-api-node eating up these codes from the backend response?

Currently I am checking errors like this error.message === 'Filter failure: LOT_SIZE' & error.message === 'Account has insufficient balance for requested action.', but I would like to check against error codes because messages are more likely to change.

Websockets state

Is there anyway to determine the state of the websocket (closed, connecting, connected, ..)?

Error: Filter failure: PRICE_FILTER

any idea why do I get this error?

{ Error: Filter failure: PRICE_FILTER
    at C:\Users\herve\OneDrive\Documents\GitHub\xxx\node_modules\binance-api-node\dist\http.js:47:19
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7) code: -1013 }

CORS issue with Public api call

Hello, when I make a public api call (ping, time or exchangeInfo, etc..) I receive a CORS error and the logged error is 'TypeError: Failed to fetch'. Not sure what Im doing wrong. Im trying to avoid using API keys in this particular project. Thank you.

Reconnect websocket

Sometimes the websocket stops receiving data, or times out.

Would it be possible to give us an easy way to disconnect, and afterwards reconnect, the existing socket?

Determine what price a market order was executed at

Hugely appreciate the work on this module, it's a fantastic way to interface with the binance API.

Is there a way to determine at what price a market order was executed without invoking the myTrades endpoint? It seems that getOrder always returns 0.000 for the price attribute in the case of a market order (which makes data-structure-wise given that it is a market order, it's just inconvenient for analytical purposes)

I gather that this question is probably more closely related to the actual workings of the API itself, rather than this specific client; but for future reference and documentation purposes it surely couldn't hurt to get a clear picture of how this would work.

clean() - Cannot read property 'forEach' of undefined

In next example clean() function fired error

(node:45) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined

const clean = client.ws.depth('ETHBTC', depth => {
  console.log(depth)
})

// After you're done
clean()

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.