UNPKG

binance

Version:

Professional Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & end-to-end tests.

402 lines (401 loc) 21.4 kB
import { ExchangeInfo, SpotAmendKeepPriorityResult } from './types/spot'; import { WSAPIResponse, WSAPIUserDataListenKeyRequest } from './types/websockets/ws-api'; import { WSAPIAccountCommissionWSAPIRequest, WSAPIAccountInformationRequest, WSAPIAllOrderListsRequest, WSAPIAllOrdersRequest, WSAPIAvgPriceRequest, WSAPIExchangeInfoRequest, WSAPIFuturesOrderBookRequest, WSAPIFuturesOrderCancelRequest, WSAPIFuturesOrderModifyRequest, WSAPIFuturesOrderStatusRequest, WSAPIFuturesPositionRequest, WSAPIFuturesPositionV2Request, WSAPIFuturesTickerBookRequest, WSAPIFuturesTickerPriceRequest, WSAPIKlinesRequest, WSAPIMyAllocationsRequest, WSAPIMyPreventedMatchesRequest, WSAPIMyTradesRequest, WSAPINewFuturesOrderRequest, WSAPINewSpotOrderRequest, WSAPIOpenOrdersCancelAllRequest, WSAPIOpenOrdersStatusRequest, WSAPIOrderAmendKeepPriorityRequest, WSAPIOrderBookRequest, WSAPIOrderCancelReplaceRequest, WSAPIOrderCancelRequest, WSAPIOrderListCancelRequest, WSAPIOrderListPlaceOCORequest, WSAPIOrderListPlaceOTOCORequest, WSAPIOrderListPlaceOTORequest, WSAPIOrderListPlaceRequest, WSAPIOrderListStatusRequest, WSAPIOrderStatusRequest, WSAPIOrderTestRequest, WSAPIRecvWindowTimestamp, WSAPISOROrderPlaceRequest, WSAPISOROrderTestRequest, WSAPITicker24hrRequest, WSAPITickerBookRequest, WSAPITickerPriceRequest, WSAPITickerRequest, WSAPITickerTradingDayRequest, WSAPITradesAggregateRequest, WSAPITradesHistoricalRequest, WSAPITradesRecentRequest } from './types/websockets/ws-api-requests'; import { WSAPIAccountCommission, WSAPIAccountInformation, WSAPIAggregateTrade, WSAPIAllocation, WSAPIAvgPrice, WSAPIBookTicker, WSAPIFullTicker, WSAPIFuturesAccountBalanceItem, WSAPIFuturesAccountStatus, WSAPIFuturesBookTicker, WSAPIFuturesOrder, WSAPIFuturesOrderBook, WSAPIFuturesPosition, WSAPIFuturesPositionV2, WSAPIFuturesPriceTicker, WSAPIKline, WSAPIMiniTicker, WSAPIOrder, WSAPIOrderBook, WSAPIOrderCancel, WSAPIOrderCancelReplaceResponse, WSAPIOrderListCancelResponse, WSAPIOrderListPlaceResponse, WSAPIOrderListStatusResponse, WSAPIOrderTestResponse, WSAPIOrderTestWithCommission, WSAPIPreventedMatch, WSAPIPriceTicker, WSAPIRateLimit, WSAPIServerTime, WSAPISessionStatus, WSAPISOROrderPlaceResponse, WSAPISOROrderTestResponse, WSAPISOROrderTestResponseWithCommission, WSAPISpotOrderResponse, WSAPITrade } from './types/websockets/ws-api-responses'; import { WSClientConfigurableOptions } from './types/websockets/ws-general'; import { DefaultLogger } from './util/logger'; import { WSAPIWsKey, WSAPIWsKeyMain } from './util/websockets/websocket-util'; import { WebsocketClient } from './websocket-client'; /** * Configurable options specific to only the REST-like WebsocketAPIClient */ export interface WSAPIClientConfigurableOptions { /** * Default: true * * If requestSubscribeUserDataStream() was used, automatically resubscribe if reconnected */ resubscribeUserDataStreamAfterReconnect: boolean; /** * Default: 2 seconds * * Delay automatic userdata resubscribe by x seconds. */ resubscribeUserDataStreamDelaySeconds: number; /** * Default: true * * Attach default event listeners, which will console log any high level * events (opened/reconnecting/reconnected/etc). * * If you disable this, you should set your own event listeners * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. */ attachEventListeners: boolean; } /** * This is a minimal Websocket API wrapper around the WebsocketClient. * * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should * be used to transmit that message. This is only useful if you wish to use an alternative wss * domain that is supported by the SDK. * * Note: To use testnet, don't set the wsKey - use `testnet: true` in * the constructor instead. * * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some * may find the below methods slightly more intuitive. * * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: * https://github.com/tiagosiebler/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108 */ export declare class WebsocketAPIClient { /** * Minimal state store around automating sticky "userDataStream.subscribe" sessions */ private subscribedUserDataStreamState; private wsClient; private logger; private options; constructor(options?: WSClientConfigurableOptions & Partial<WSAPIClientConfigurableOptions>, logger?: DefaultLogger); getWSClient(): WebsocketClient; setTimeOffsetMs(newOffset: number): void; /** * Test connectivity to the WebSocket API */ testSpotConnectivity(wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<object>>; /** * Test connectivity to the WebSocket API and get the current server time */ getSpotServerTime(wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIServerTime>>; /** * Query current exchange trading rules, rate limits, and symbol information */ getSpotExchangeInfo(params?: WSAPIExchangeInfoRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<ExchangeInfo>>; /** * Get current order book * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams */ getSpotOrderBook(params: WSAPIOrderBookRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderBook>>; /** * Get recent trades * Note: If you need access to real-time trading activity, consider using WebSocket Streams */ getSpotRecentTrades(params: WSAPITradesRecentRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPITrade[]>>; /** * Get historical trades * Note: If fromId is not specified, the most recent trades are returned */ getSpotHistoricalTrades(params: WSAPITradesHistoricalRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPITrade[]>>; /** * Get aggregate trades * Note: An aggregate trade represents one or more individual trades that fill at the same time */ getSpotAggregateTrades(params: WSAPITradesAggregateRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIAggregateTrade[]>>; /** * Get klines (candlestick bars) * Note: If you need access to real-time kline updates, consider using WebSocket Streams */ getSpotKlines(params: WSAPIKlinesRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIKline[]>>; /** * Get klines (candlestick bars) optimized for presentation * Note: This request is similar to klines, having the same parameters and response */ getSpotUIKlines(params: WSAPIKlinesRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIKline[]>>; /** * Get current average price for a symbol */ getSpotAveragePrice(params: WSAPIAvgPriceRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIAvgPrice>>; /** * Get 24-hour rolling window price change statistics * Note: If you need to continuously monitor trading statistics, consider using WebSocket Streams */ getSpot24hrTicker(params?: WSAPITicker24hrRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[]>>; /** * Get price change statistics for a trading day */ getSpotTradingDayTicker(params: WSAPITickerTradingDayRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[]>>; /** * Get rolling window price change statistics with a custom window * Note: Window size precision is limited to 1 minute */ getSpotTicker(params: WSAPITickerRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[]>>; /** * Get the latest market price for a symbol * Note: If you need access to real-time price updates, consider using WebSocket Streams */ getSpotSymbolPriceTicker(params?: WSAPITickerPriceRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIPriceTicker | WSAPIPriceTicker[]>>; /** * Get the current best price and quantity on the order book * Note: If you need access to real-time order book ticker updates, consider using WebSocket Streams */ getSpotSymbolOrderBookTicker(params?: WSAPITickerBookRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIBookTicker | WSAPIBookTicker[]>>; getSpotSessionStatus(wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPISessionStatus>>; /** * Submit a spot order */ submitNewSpotOrder(params: WSAPINewSpotOrderRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPISpotOrderResponse>>; /** * Test order placement * Note: Validates new order parameters and verifies your signature but does not send the order into the matching engine */ testSpotOrder(params: WSAPIOrderTestRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderTestResponse | WSAPIOrderTestWithCommission>>; /** * Check execution status of an order * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used */ getSpotOrderStatus(params: WSAPIOrderStatusRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrder>>; /** * Cancel an active order * Note: If both orderId and origClientOrderId parameters are specified, only orderId is used */ cancelSpotOrder(params: WSAPIOrderCancelRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderCancel>>; /** * Cancel an existing order and immediately place a new order * Note: If both cancelOrderId and cancelOrigClientOrderId parameters are specified, only cancelOrderId is used */ cancelReplaceSpotOrder(params: WSAPIOrderCancelReplaceRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderCancelReplaceResponse>>; /** * Reduce the quantity of an existing open order. * * Read for more info: https://developers.binance.com/docs/binance-spot-api-docs/faqs/order_amend_keep_priority */ amendSpotOrderKeepPriority(params: WSAPIOrderAmendKeepPriorityRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<SpotAmendKeepPriorityResult>>; /** * Query execution status of all open orders * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams */ getSpotOpenOrders(params: WSAPIOpenOrdersStatusRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrder[]>>; /** * Cancel all open orders on a symbol * Note: This includes orders that are part of an order list */ cancelAllSpotOpenOrders(params: WSAPIOpenOrdersCancelAllRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<(WSAPIOrderCancel | WSAPIOrderListCancelResponse)[]>>; /** * Place a new order list * Note: This is a deprecated endpoint, consider using placeOCOOrderList instead */ placeSpotOrderList(params: WSAPIOrderListPlaceRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderListPlaceResponse>>; /** * Place a new OCO (One-Cancels-the-Other) order list * Note: Activation of one order immediately cancels the other */ placeSpotOCOOrderList(params: WSAPIOrderListPlaceOCORequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderListPlaceResponse>>; /** * Place a new OTO (One-Triggers-the-Other) order list * Note: The pending order is placed only when the working order is fully filled */ placeSpotOTOOrderList(params: WSAPIOrderListPlaceOTORequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderListPlaceResponse>>; /** * Place a new OTOCO (One-Triggers-One-Cancels-the-Other) order list * Note: The pending orders are placed only when the working order is fully filled */ placeSpotOTOCOOrderList(params: WSAPIOrderListPlaceOTOCORequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderListPlaceResponse>>; /** * Check execution status of an order list * Note: If both origClientOrderId and orderListId parameters are specified, only origClientOrderId is used */ getSpotOrderListStatus(params: WSAPIOrderListStatusRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderListStatusResponse>>; /** * Cancel an active order list * Note: If both orderListId and listClientOrderId parameters are specified, only orderListId is used */ cancelSpotOrderList(params: WSAPIOrderListCancelRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderListCancelResponse>>; /** * Query execution status of all open order lists * Note: If you need to continuously monitor order status updates, consider using WebSocket Streams */ getSpotOpenOrderLists(params: WSAPIRecvWindowTimestamp, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderListStatusResponse[]>>; /** * Place a new order using Smart Order Routing (SOR) * Note: Only supports LIMIT and MARKET orders. quoteOrderQty is not supported */ placeSpotSOROrder(params: WSAPISOROrderPlaceRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPISOROrderPlaceResponse>>; /** * Test new order creation and signature/recvWindow using Smart Order Routing (SOR) * Note: Creates and validates a new order but does not send it into the matching engine */ testSpotSOROrder(params: WSAPISOROrderTestRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPISOROrderTestResponse | WSAPISOROrderTestResponseWithCommission>>; /** * Query information about your account, including balances * Note: Weight: 20 */ getSpotAccountInformation(params: WSAPIAccountInformationRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIAccountInformation>>; /** * Query your current unfilled order count for all intervals * Note: Weight: 40 */ getSpotOrderRateLimits(params: WSAPIRecvWindowTimestamp, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIRateLimit[]>>; /** * Query information about all your orders – active, canceled, filled – filtered by time range * Note: Weight: 20 */ getSpotAllOrders(params: WSAPIAllOrdersRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrder[]>>; /** * Query information about all your order lists, filtered by time range * Note: Weight: 20 */ getSpotAllOrderLists(params: WSAPIAllOrderListsRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIOrderListStatusResponse[]>>; /** * Query information about all your trades, filtered by time range * Note: Weight: 20 */ getSpotMyTrades(params: WSAPIMyTradesRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPITrade[]>>; /** * Displays the list of orders that were expired due to STP * Note: Weight varies based on query type (2-20) */ getSpotPreventedMatches(params: WSAPIMyPreventedMatchesRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIPreventedMatch[]>>; /** * Retrieves allocations resulting from SOR order placement * Note: Weight: 20 */ getSpotAllocations(params: WSAPIMyAllocationsRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIAllocation[]>>; /** * Get current account commission rates * Note: Weight: 20 */ getSpotAccountCommission(params: WSAPIAccountCommissionWSAPIRequest, wsKey?: WSAPIWsKeyMain): Promise<WSAPIResponse<WSAPIAccountCommission>>; /** * Get current order book for futures * Note: If you need to continuously monitor order book updates, consider using WebSocket Streams */ getFuturesOrderBook(params: WSAPIFuturesOrderBookRequest): Promise<WSAPIResponse<WSAPIFuturesOrderBook>>; /** * Get latest price for a futures symbol or symbols * Note: If symbol is not provided, prices for all symbols will be returned */ getFuturesSymbolPriceTicker(params?: WSAPIFuturesTickerPriceRequest): Promise<WSAPIResponse<WSAPIFuturesPriceTicker | WSAPIFuturesPriceTicker[]>>; /** * Get best price/qty on the order book for a futures symbol or symbols * Note: If symbol is not provided, bookTickers for all symbols will be returned */ getFuturesSymbolOrderBookTicker(params?: WSAPIFuturesTickerBookRequest): Promise<WSAPIResponse<WSAPIFuturesBookTicker | WSAPIFuturesBookTicker[]>>; /** * Submit a futures order * * This endpoint is used for both USDM and COINM futures. */ submitNewFuturesOrder(market: 'usdm' | 'coinm', params: WSAPINewFuturesOrderRequest): Promise<WSAPIResponse<WSAPIFuturesOrder>>; /** * Modify an existing futures order * * This endpoint is used for both USDM and COINM futures. */ modifyFuturesOrder(market: 'usdm' | 'coinm', params: WSAPIFuturesOrderModifyRequest): Promise<WSAPIResponse<WSAPIFuturesOrder>>; /** * Cancel a futures order * * This endpoint is used for both USDM and COINM futures. */ cancelFuturesOrder(market: 'usdm' | 'coinm', params: WSAPIFuturesOrderCancelRequest): Promise<WSAPIResponse<WSAPIFuturesOrder>>; /** * Query futures order status * * This endpoint is used for both USDM and COINM futures. */ getFuturesOrderStatus(market: 'usdm' | 'coinm', params: WSAPIFuturesOrderStatusRequest): Promise<WSAPIResponse<WSAPIFuturesOrder>>; /** * Get current position information (V2) * Note: Only symbols that have positions or open orders will be returned */ getFuturesPositionV2(params: WSAPIFuturesPositionV2Request): Promise<WSAPIResponse<WSAPIFuturesPositionV2[]>>; /** * Get current position information * Note: Only symbols that have positions or open orders will be returned * * This endpoint is used for both USDM and COINM futures. */ getFuturesPosition(market: 'usdm' | 'coinm', params: WSAPIFuturesPositionRequest): Promise<WSAPIResponse<WSAPIFuturesPosition[]>>; /** * Get account balance information (V2) * Note: Returns balance information for all assets */ getFuturesAccountBalanceV2(params: WSAPIRecvWindowTimestamp): Promise<WSAPIResponse<WSAPIFuturesAccountBalanceItem[]>>; /** * Get account balance information * Note: Returns balance information for all assets * * This endpoint is used for both USDM and COINM futures. */ getFuturesAccountBalance(market: 'usdm' | 'coinm', params: WSAPIRecvWindowTimestamp): Promise<WSAPIResponse<WSAPIFuturesAccountBalanceItem[]>>; /** * Get account information (V2) * Note: Returns detailed account information including positions and assets */ getFuturesAccountStatusV2(params: WSAPIRecvWindowTimestamp): Promise<WSAPIResponse<WSAPIFuturesAccountStatus>>; /** * Get account information * Note: Returns detailed account information including positions and assets * * This endpoint is used for both USDM and COINM futures. */ getFuturesAccountStatus(market: 'usdm' | 'coinm', params: WSAPIRecvWindowTimestamp): Promise<WSAPIResponse<WSAPIFuturesAccountStatus>>; /** * Start the user data stream for an apiKey (passed as param). * * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead. * * @param params * @param wsKey * @returns listenKey */ startUserDataStreamForKey(params: { apiKey: string; }, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<{ listenKey: string; }>>; /** * Attempt to "ping" a listen key. * * Note: for "Spot" markets, the listenKey workflow is deprecated, use `subscribeUserDataStream()` instead. * * @param params * @param wsKey * @returns */ pingUserDataStreamForKey(params: WSAPIUserDataListenKeyRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<object>>; /** * Stop the user data stream listen key. * * @param params * @param wsKey * @returns */ stopUserDataStreamForKey(params: WSAPIUserDataListenKeyRequest, wsKey?: WSAPIWsKey): Promise<WSAPIResponse<object>>; /** * Request user data stream subscription on the currently authenticated connection. * * If reconnected, this will automatically resubscribe unless you unsubscribe manually. */ subscribeUserDataStream(wsKey: WSAPIWsKey): Promise<WSAPIResponse<object>>; /** * Unsubscribe from the user data stream subscription on the currently authenticated connection. * * If reconnected, this will also stop it from automatically resubscribing after reconnect. */ unsubscribeUserDataStream(wsKey: WSAPIWsKey): Promise<WSAPIResponse<{ listenKey: string; }>>; /** * * * * * * * * Private methods for handling some of the convenience/automation provided by the WS API Client * * * * * * * */ private setupDefaultEventListeners; private tryResubscribeUserDataStream; private getSubscribedUserDataStreamState; private handleWSReconnectedEvent; }