jaggedsoft / node-binance-api

Node Binance API is an asynchronous node.js library for the Binance API designed to be easy to use.
MIT License
1.58k stars 768 forks source link

Please add websockets.userFutureData #432

Closed cocafelab closed 3 years ago

cocafelab commented 4 years ago

Currently we have 2 two functions for user account using websocket such as userData and userMarginData . So could you please add more userFutureData so that we can track user future account easily?

Thanks in advance.

jmit-modern commented 4 years ago

Yes, I also need to receive the user data stream in future account, when is it planned to be updated? Thank you

minthauzens commented 3 years ago

i think this has been implemented, ie., can be closed now

thisisloze commented 3 years ago

How do I connect to the futures userData stream?

arenddeboer commented 3 years ago

Not sure if this is the current recommended way but:

According to the source file it has the following call signature: userFutureData: function userFutureData( margin_call_callback, account_update_callback = undefined, order_update_callback = undefined, subscribed_callback = undefined ) {

After connecting to binance you can have something like this:

nodeBinanceApi.websockets.userFutureData(
      (d: any) => {
        logger.info(`userFutureData Margin call ${d}`)
      },
      (acc_upp: any) => {
        logger.info(`userFutureData Account update ${acc_upp}`)
        userFuturesStream.process(acc_upp)
      },
      (order_update: IOrderTradeUpdate) => {
        logger.info(`userFutureData Order update ${order_update}`)
        userFuturesStream.process(order_update)
      },
    )

Inside userFuturesStream.process (my own code) I have a switch statement:

public process(msg: any) {
    //  logger.info(' msg ', msg)
    switch (msg.e) {
      // ORDER_TRADE_UPDATE
      case 'ORDER_TRADE_UPDATE':
        logger.info('dispatch _onOrderTradeUpdate')
        this._onOrderTradeUpdate.dispatch(msg as IOrderTradeUpdate)
        break
      case 'ACCOUNT_UPDATE':
        logger.info('dispatch _onAccountUpdate', msg)
        this._onAccountUpdate.dispatch(msg as IAccountUpdate)
        break
      default:
        logger.fatal('Unknown msg ', msg)
    }
  }

A bit convoluted by showing my internal (typescript) code but I hope you get the drift.

thisisloze commented 3 years ago

Thank you! This helped a lot!

kanish-111 commented 3 years ago

Not sure if this is the current recommended way but:

According to the source file it has the following call signature: userFutureData: function userFutureData( margin_call_callback, account_update_callback = undefined, order_update_callback = undefined, subscribed_callback = undefined ) {

After connecting to binance you can have something like this:

nodeBinanceApi.websockets.userFutureData(
      (d: any) => {
        logger.info(`userFutureData Margin call ${d}`)
      },
      (acc_upp: any) => {
        logger.info(`userFutureData Account update ${acc_upp}`)
        userFuturesStream.process(acc_upp)
      },
      (order_update: IOrderTradeUpdate) => {
        logger.info(`userFutureData Order update ${order_update}`)
        userFuturesStream.process(order_update)
      },
    )

Inside userFuturesStream.process (my own code) I have a switch statement:

public process(msg: any) {
    //  logger.info(' msg ', msg)
    switch (msg.e) {
      // ORDER_TRADE_UPDATE
      case 'ORDER_TRADE_UPDATE':
        logger.info('dispatch _onOrderTradeUpdate')
        this._onOrderTradeUpdate.dispatch(msg as IOrderTradeUpdate)
        break
      case 'ACCOUNT_UPDATE':
        logger.info('dispatch _onAccountUpdate', msg)
        this._onAccountUpdate.dispatch(msg as IAccountUpdate)
        break
      default:
        logger.fatal('Unknown msg ', msg)
    }
  }

A bit convoluted by showing my internal (typescript) code but I hope you get the drift.

but can u get futures balance updates on that??

arenddeboer commented 3 years ago

but can u get futures balance updates on that??

Absolutely, just use the simple version like this to test: nodeBinanceApi.websockets.userFutureData(console.log,console.log,console.log)

A balance update from binance on the second console.log can look like this:


    "eventType": "ACCOUNT_UPDATE",
    "eventTime": 1631563066583,
    "transaction": 1631563066579,
    "updateData": {
        "eventReasonType": "ORDER",
        "balances": [
            {
                "asset": "USDT",
                "walletBalance": "5",
                "crossWalletBalance": "5"
            }
        ],
        "positions": [
            {
                "symbol": "DOGEUSDT",
                "positionAmount": "0",
                "entryPrice": "0.000000",
                "accumulatedRealized": "0",
                "unrealizedPnL": "0",
                "marginType": "cross",
                "isolatedWallet": "0",
                "positionSide": "BOTH"
            },
            {
                "symbol": "DOGEUSDT",
                "positionAmount": "88",
                "entryPrice": "0.2",
                "accumulatedRealized": "5",
                "unrealizedPnL": "642.7",
                "marginType": "cross",
                "isolatedWallet": "0",
                "positionSide": "LONG"
            },
            {
                "symbol": "DOGEUSDT",
                "positionAmount": "0",
                "entryPrice": "0.000000",
                "accumulatedRealized": "0",
                "unrealizedPnL": "0",
                "marginType": "cross",
                "isolatedWallet": "0",
                "positionSide": "SHORT"
            }
        ]
    }
}
kanish-111 commented 3 years ago

but can u get futures balance updates on that??

Absolutely, just use the simple version like this to test: nodeBinanceApi.websockets.userFutureData(console.log,console.log,console.log)

A balance update from binance on the second console.log can look like this:


    "eventType": "ACCOUNT_UPDATE",
    "eventTime": 1631563066583,
    "transaction": 1631563066579,
    "updateData": {
        "eventReasonType": "ORDER",
        "balances": [
            {
                "asset": "USDT",
                "walletBalance": "5",
                "crossWalletBalance": "5"
            }
        ],
        "positions": [
            {
                "symbol": "DOGEUSDT",
                "positionAmount": "0",
                "entryPrice": "0.000000",
                "accumulatedRealized": "0",
                "unrealizedPnL": "0",
                "marginType": "cross",
                "isolatedWallet": "0",
                "positionSide": "BOTH"
            },
            {
                "symbol": "DOGEUSDT",
                "positionAmount": "88",
                "entryPrice": "0.2",
                "accumulatedRealized": "5",
                "unrealizedPnL": "642.7",
                "marginType": "cross",
                "isolatedWallet": "0",
                "positionSide": "LONG"
            },
            {
                "symbol": "DOGEUSDT",
                "positionAmount": "0",
                "entryPrice": "0.000000",
                "accumulatedRealized": "0",
                "unrealizedPnL": "0",
                "marginType": "cross",
                "isolatedWallet": "0",
                "positionSide": "SHORT"
            }
        ]
    }
}

binancem.websockets.userFutureData(console.log, console.log, console.log); ive used this but still i dont get anything, im using testnet futures, and in the testnet panel i buy btc long / sell short, but i dont get any updates in that, but if i get the futures balance data , the balance is changes

arenddeboer commented 3 years ago

Perhaps double check if you are indeed initializing the api with test: true and perhaps manually set the futures urls. Or try a tiny order in production.

kanish-111 commented 3 years ago

Perhaps double check if you are indeed initializing the api with test: true and perhaps manually set the futures urls. Or try a tiny order in production.

i did i get disconnected and connected logs in console. but not any update on the balances.

const Binance1 = require('node-binance-api-testnet');
        const binancem = new Binance1().options({
            APIKEY: '  ',
            APISECRET: '  ',
        });
function balance_update(data) {

console.log('balance_update :',JSON.stringify(data));
}

function execution_update(data) {
console.log('exec_update :',JSON.stringify(data));

}

binancem.websockets.userFutureData(balance_update, execution_update);
binancem.websockets.userFutureData(console.log, console.log, console.log);

i did use it 2 times to make sure, but nothing is returned. i hope my code is correct

arenddeboer commented 3 years ago

In the code above you do not set test:true in the options. Hence you are not using the testnet. This should also give an API key error as you need a different testnet key/secret

kanish-111 commented 3 years ago

In the code above you do not set test:true in the options. Hence you are not using the testnet. This should also give an API key error as you need a different testnet key/secret

but ive changed in this module folder

let fapi = 'https://testnet.binancefuture.com/fapi/';
    let dapi = 'https://testnet.binancefuture.com/dapi/';
    let fapiTest = 'https://testnet.binancefuture.com/fapi/';

so its not a problem, i can even get future balances, but only this user stream is not giving anything i even get disconnected and connecting in console

arenddeboer commented 3 years ago

It is a problem, because you are only setting rest api end-points, not websocket endpoints. Try it with an unmodified module version first. with test: true and if you must change the urls, use the options.urls property. I use something like this:

{
  verbose: true,
  test: true,
  hedgeMode: true,
  APIKEY: '',
  APISECRET: '',
  log: function (...args: any) {
    logger.warn(Array.prototype.slice.call(args))
  },
  urls: {
    base: "https://api.binance.com/api/",
    wapi: "https://api.binance.com/wapi/",
    sapi: "https://api.binance.com/sapi/",
    fapi: "https://testnet.binancefuture.com/fapi/",
    fapiTest: "https://testnet.binancefuture.com/fapi/",
    fstream: "wss://stream.binancefuture.com/stream?streams:",
    fstreamSingle: "wss://stream.binancefuture.com/ws/",
    stream: "wss://stream.binancefuture.com/ws/",
    combineStream: "wss://stream.binancefuture.com/stream?streams:",
  }
}

Not sure if these testnet urls are still valid as I haven't used testnet in a while.

kanish-111 commented 3 years ago

It is a problem, because you are only setting rest api end-points, not websocket endpoints. Try it with an unmodified module version first. with test: true and if you must change the urls, use the options.urls property. I use something like this:

{
  verbose: true,
  test: true,
  hedgeMode: true,
  APIKEY: '',
  APISECRET: '',
  log: function (...args: any) {
    logger.warn(Array.prototype.slice.call(args))
  },
  urls: {
    base: "https://api.binance.com/api/",
    wapi: "https://api.binance.com/wapi/",
    sapi: "https://api.binance.com/sapi/",
    fapi: "https://testnet.binancefuture.com/fapi/",
    fapiTest: "https://testnet.binancefuture.com/fapi/",
    fstream: "wss://stream.binancefuture.com/stream?streams:",
    fstreamSingle: "wss://stream.binancefuture.com/ws/",
    stream: "wss://stream.binancefuture.com/ws/",
    combineStream: "wss://stream.binancefuture.com/stream?streams:",
  }
}

Not sure if these testnet urls are still valid as I haven't used testnet in a while.

i did, still same issue

arenddeboer commented 3 years ago

I tried with a fresh project and it works without issue. Binance futures testnet: https://testnet.binancefuture.com/en/futures/BTCUSDT

Code:

const Binance = require('node-binance-api')
const binance = new Binance().options({
  test: true,
  verbose: true,
  APIKEY: '',
  APISECRET: '',
})

binance.websockets.userFutureData(console.log, console.warn, console.log)

Bought 1 BTC and got this in the terminal:

node index.js 
[
  'futuresSubscribeSingle: Subscribed to bLbHn1p6qCEh4QwzuqQq1NwmmbY13vZzGkytBxrzxRx9Z4oimWvW2ucRLWFIBTG2'
]
{
  eventType: 'ORDER_TRADE_UPDATE',
  eventTime: 1631648682134,
  transaction: 1631648682132,
  order: {
    symbol: 'BTCUSDT',
    clientOrderId: 'web_Ce3YHcv88IrBMhhjm3ED',
    side: 'BUY',
    orderType: 'MARKET',
    timeInForce: 'GTC',
    originalQuantity: '1',
    originalPrice: '0',
    averagePrice: '0',
    stopPrice: '0',
    executionType: 'NEW',
    orderStatus: 'NEW',
    orderId: 2818031385,
    orderLastFilledQuantity: '0',
    orderFilledAccumulatedQuantity: '0',
    lastFilledPrice: '0',
    commissionAsset: undefined,
    commission: undefined,
    orderTradeTime: 1631648682132,
    tradeId: 0,
    bidsNotional: '0',
    askNotional: '0',
    isMakerSide: false,
    isReduceOnly: false,
    stopPriceWorkingType: 'CONTRACT_PRICE',
    originalOrderType: 'MARKET',
    positionSide: 'LONG',
    closeAll: false,
    activationPrice: undefined,
    callbackRate: undefined,
    realizedProfit: '0'
  }
}
{
  eventType: 'ACCOUNT_UPDATE',
  eventTime: 1631648682135,
  transaction: 1631648682132,
  updateData: {
    eventReasonType: 'ORDER',
    balances: [ [Object] ],
    positions: [ [Object], [Object], [Object] ]
  }
}
{
  eventType: 'ORDER_TRADE_UPDATE',
  eventTime: 1631648682135,
  transaction: 1631648682132,
  order: {
    symbol: 'BTCUSDT',
    clientOrderId: 'web_Ce3YHcv88IrBMhhjm3ED',
    side: 'BUY',
    orderType: 'MARKET',
    timeInForce: 'GTC',
    originalQuantity: '1',
    originalPrice: '0',
    averagePrice: '46514.94000',
    stopPrice: '0',
    executionType: 'TRADE',
    orderStatus: 'FILLED',
    orderId: 2818031385,
    orderLastFilledQuantity: '1',
    orderFilledAccumulatedQuantity: '1',
    lastFilledPrice: '46514.94',
    commissionAsset: 'USDT',
    commission: '18.60597599',
    orderTradeTime: 1631648682132,
    tradeId: 199202074,
    bidsNotional: '0',
    askNotional: '0',
    isMakerSide: false,
    isReduceOnly: false,
    stopPriceWorkingType: 'CONTRACT_PRICE',
    originalOrderType: 'MARKET',
    positionSide: 'LONG',
    closeAll: false,
    activationPrice: undefined,
    callbackRate: undefined,
    realizedProfit: '0'
  }
}

If this doesn't work for you then I'm afraid I can't help you short of asking you to double check the api keys you provide in code and the ones you see here https://testnet.binancefuture.com/en/futures/BTCUSDT

kanish-111 commented 3 years ago

I tried with a fresh project and it works without issue. Binance futures testnet: https://testnet.binancefuture.com/en/futures/BTCUSDT

Code:

const Binance = require('node-binance-api')
const binance = new Binance().options({
  test: true,
  verbose: true,
  APIKEY: '',
  APISECRET: '',
})

binance.websockets.userFutureData(console.log, console.warn, console.log)

Bought 1 BTC and got this in the terminal:

node index.js 
[
  'futuresSubscribeSingle: Subscribed to bLbHn1p6qCEh4QwzuqQq1NwmmbY13vZzGkytBxrzxRx9Z4oimWvW2ucRLWFIBTG2'
]
{
  eventType: 'ORDER_TRADE_UPDATE',
  eventTime: 1631648682134,
  transaction: 1631648682132,
  order: {
    symbol: 'BTCUSDT',
    clientOrderId: 'web_Ce3YHcv88IrBMhhjm3ED',
    side: 'BUY',
    orderType: 'MARKET',
    timeInForce: 'GTC',
    originalQuantity: '1',
    originalPrice: '0',
    averagePrice: '0',
    stopPrice: '0',
    executionType: 'NEW',
    orderStatus: 'NEW',
    orderId: 2818031385,
    orderLastFilledQuantity: '0',
    orderFilledAccumulatedQuantity: '0',
    lastFilledPrice: '0',
    commissionAsset: undefined,
    commission: undefined,
    orderTradeTime: 1631648682132,
    tradeId: 0,
    bidsNotional: '0',
    askNotional: '0',
    isMakerSide: false,
    isReduceOnly: false,
    stopPriceWorkingType: 'CONTRACT_PRICE',
    originalOrderType: 'MARKET',
    positionSide: 'LONG',
    closeAll: false,
    activationPrice: undefined,
    callbackRate: undefined,
    realizedProfit: '0'
  }
}
{
  eventType: 'ACCOUNT_UPDATE',
  eventTime: 1631648682135,
  transaction: 1631648682132,
  updateData: {
    eventReasonType: 'ORDER',
    balances: [ [Object] ],
    positions: [ [Object], [Object], [Object] ]
  }
}
{
  eventType: 'ORDER_TRADE_UPDATE',
  eventTime: 1631648682135,
  transaction: 1631648682132,
  order: {
    symbol: 'BTCUSDT',
    clientOrderId: 'web_Ce3YHcv88IrBMhhjm3ED',
    side: 'BUY',
    orderType: 'MARKET',
    timeInForce: 'GTC',
    originalQuantity: '1',
    originalPrice: '0',
    averagePrice: '46514.94000',
    stopPrice: '0',
    executionType: 'TRADE',
    orderStatus: 'FILLED',
    orderId: 2818031385,
    orderLastFilledQuantity: '1',
    orderFilledAccumulatedQuantity: '1',
    lastFilledPrice: '46514.94',
    commissionAsset: 'USDT',
    commission: '18.60597599',
    orderTradeTime: 1631648682132,
    tradeId: 199202074,
    bidsNotional: '0',
    askNotional: '0',
    isMakerSide: false,
    isReduceOnly: false,
    stopPriceWorkingType: 'CONTRACT_PRICE',
    originalOrderType: 'MARKET',
    positionSide: 'LONG',
    closeAll: false,
    activationPrice: undefined,
    callbackRate: undefined,
    realizedProfit: '0'
  }
}

If this doesn't work for you then I'm afraid I can't help you short of asking you to double check the api keys you provide in code and the ones you see here https://testnet.binancefuture.com/en/futures/BTCUSDT

thank u so much, it worked on normal module but doesnt work on node-binance-api-testnet, idk y, but ok ill use the org module .

doppelgunner commented 1 year ago

How to cancel listening to userFutureData()?