├── .babelrc ├── .eslintrc.js ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── __test__ └── lib │ ├── helpers │ ├── appendUpdatedId.test.js │ ├── getRequestInstance.test.js │ ├── processOrderBookSnapshot.test.js │ └── processOrderBookUpdate.test.js │ ├── orderBook.test.js │ └── services │ ├── extendUserDataSteam.test.js │ ├── getOrderBookSnapshot.test.js │ ├── getServerTime.test.js │ └── getUserDataSteam.test.js ├── package.json └── src ├── __mocks__ └── axios.js ├── app.js ├── delivery-futures-user.js ├── futures-user.js ├── index.js ├── lib ├── errors │ └── dataLostException.js ├── helpers │ ├── appendUpdatedId.js │ ├── getRequestInstance.js │ ├── processOrderBookSnapshot.js │ ├── processOrderBookUpdate.js │ └── renewListenKey.js ├── logger.js ├── orderBook.js ├── orderBookManager.js ├── requestClient.js ├── services │ ├── extendUserDataStream.js │ ├── futures │ │ ├── extendUserDataStream.js │ │ ├── getDeliveryListenKey.js │ │ └── getListenKey.js │ ├── getOrderBookSnapshot.js │ ├── getServerTime.js │ ├── getUserDataStream.js │ └── margin │ │ └── getUserDataStream.js └── socketClient.js ├── margin-user.js ├── monitor-futures.js ├── multi-stream-depth.js ├── spot ├── monitor-depth.js └── monitor-trade.js └── user.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "targets": { 7 | "node": "current" 8 | } 9 | } 10 | ] 11 | ] 12 | } -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es6: true, 5 | }, 6 | extends: [ 7 | 'airbnb-base', 8 | ], 9 | globals: { 10 | Atomics: 'readonly', 11 | SharedArrayBuffer: 'readonly', 12 | }, 13 | parserOptions: { 14 | ecmaVersion: 2018, 15 | sourceType: 'module', 16 | }, 17 | rules: { 18 | }, 19 | }; 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:10-alpine 2 | 3 | RUN mkdir /app 4 | WORKDIR /app 5 | ADD . /app 6 | ADD package.json /app 7 | ADD package-lock.json /app 8 | 9 | RUN npm install 10 | 11 | ENTRYPOINT ["/bin/sh"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Liang Shi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Binance Websocket Examples 2 | 3 | ## Local orderbook (Spot) 4 | 5 | ```bash 6 | # Cache local orderbook and echo best price 7 | # btcusdt by default 8 | npm run orderbook 9 | 10 | # or provide the trading pair 11 | SYMBOL=bnbusdt npm run orderbook 12 | 13 | ``` 14 | 15 | ## Spot user data stream 16 | 17 | ```bash 18 | # get user data steam 19 | APIKEY=xxxxxx npm run user 20 | 21 | # Get margin account update from websocket 22 | APIKEY=xxxxxx APISECRET=xxxxx npm run margin-user 23 | ``` 24 | 25 | ## Futures user data stream 26 | 27 | ```bash 28 | # Get user data steam on production 29 | APIKEY=xxxxxx APISECRET=xxxxx npm run futures-user 30 | 31 | # On testnet 32 | APIKEY=xxxxxx APISECRET=xxxxx WSS_BASE_URL="wss://stream.binancefuture.com/" HTTP_BASE_URL="https://testnet.binancefuture.com/" npm run futures-user 33 | ``` 34 | 35 | ## Delivery Futures user data stream 36 | 37 | ```bash 38 | # Get user data steam - defaults to production 39 | APIKEY=xxxxxx APISECRET=xxxxx npm run delivery-futures-user 40 | ``` 41 | 42 | ## Combined streams 43 | 44 | ```bash 45 | # Get multi pairs stream, setting the pairs in src/multi-stream-depth 46 | npm run multi-stream 47 | ``` 48 | 49 | ## Spot trade stream delay monitoring 50 | 51 | ```bash 52 | npm run monitor-spot-trade 53 | ``` 54 | 55 | ## Spot depth stream delay monitoring 56 | 57 | ```bash 58 | npm run monitor-spot-depth 59 | ``` 60 | 61 | ## Futures depth stream delay monitoring 62 | 63 | ```bash 64 | npm run monitor-futures 65 | ``` 66 | 67 | ## How to setup 68 | 69 | ```bash 70 | 71 | npm install 72 | 73 | # run test 74 | npm run test 75 | 76 | ``` 77 | 78 | ## License 79 | MIT 80 | -------------------------------------------------------------------------------- /__test__/lib/helpers/appendUpdatedId.test.js: -------------------------------------------------------------------------------- 1 | import appendUpdatedId from '../../../src/lib/helpers/appendUpdatedId'; 2 | 3 | test('appendUpdatedId', () => { 4 | const updateId = 1234567; 5 | const ask = [ 6 | [100, 1], 7 | [200, 2], 8 | ]; 9 | const bid = [ 10 | [10, 1], 11 | [20, 2], 12 | ]; 13 | const result = appendUpdatedId(updateId, ask, bid); 14 | expect(result).toEqual([ 15 | [ 16 | [100, 1, updateId], 17 | [200, 2, updateId], 18 | ], 19 | [ 20 | [10, 1, updateId], 21 | [20, 2, updateId], 22 | ], 23 | ]); 24 | }); 25 | -------------------------------------------------------------------------------- /__test__/lib/helpers/getRequestInstance.test.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | import getRequestInstance from '../../../src/lib/helpers/getRequestInstance'; 3 | 4 | it('should return axios create func', () => { 5 | expect(typeof getRequestInstance()).toBe(typeof axios); 6 | }); 7 | -------------------------------------------------------------------------------- /__test__/lib/helpers/processOrderBookSnapshot.test.js: -------------------------------------------------------------------------------- 1 | import processOrderBookSnapshot from '../../../src/lib/helpers/processOrderBookSnapshot'; 2 | 3 | describe('processOrderBookSnapshot', () => { 4 | let orderBookData; 5 | let snapshotOrderbook; 6 | beforeEach(() => { 7 | orderBookData = { 8 | ask: [ 9 | [202, 1, 1000], 10 | [210, 2, 1000], 11 | ], 12 | bid: [ 13 | [201, 1, 1000], 14 | [199, 2, 1000], 15 | ], 16 | }; 17 | 18 | snapshotOrderbook = { 19 | lastUpdateId: 999, 20 | bids: [ 21 | [201.2, 1, 999], 22 | [190, 2, 999], 23 | ], 24 | asks: [ 25 | [201.5, 2, 999], 26 | [205, 1, 999], 27 | ], 28 | }; 29 | }); 30 | 31 | test('add orderbook from snapshot into cached orderbook', () => { 32 | const result = processOrderBookSnapshot(orderBookData, snapshotOrderbook); 33 | expect(result).toEqual( 34 | { 35 | ask: [ 36 | [201.5, 2, 999], 37 | [202, 1, 1000], 38 | [205, 1, 999], 39 | [210, 2, 1000], 40 | ], 41 | bid: [ 42 | [201.2, 1, 999], 43 | [201, 1, 1000], 44 | [199, 2, 1000], 45 | [190, 2, 999], 46 | ], 47 | }, 48 | ); 49 | }); 50 | 51 | test('remove the out of date orders in cache', () => { 52 | snapshotOrderbook = { 53 | lastUpdateId: 1001, 54 | bids: [ 55 | [201.2, 1, 1001], 56 | [190, 2, 1001], 57 | ], 58 | asks: [ 59 | [201.5, 2, 1001], 60 | [205, 1, 1001], 61 | ], 62 | }; 63 | const result = processOrderBookSnapshot(orderBookData, snapshotOrderbook); 64 | expect(result).toEqual( 65 | { 66 | ask: [ 67 | [201.5, 2, 1001], 68 | [205, 1, 1001], 69 | ], 70 | bid: [ 71 | [201.2, 1, 1001], 72 | [190, 2, 1001], 73 | ], 74 | }, 75 | ); 76 | }); 77 | 78 | test('overwrite the cache order if the price is the same', () => { 79 | snapshotOrderbook = { 80 | lastUpdateId: 999, 81 | bids: [ 82 | [201, 4, 999], 83 | [190, 0, 999], 84 | ], 85 | asks: [ 86 | [201.5, 2, 999], 87 | [210, 3, 999], 88 | ], 89 | }; 90 | const result = processOrderBookSnapshot(orderBookData, snapshotOrderbook); 91 | expect(result).toEqual( 92 | { 93 | ask: [ 94 | [201.5, 2, 999], 95 | [202, 1, 1000], 96 | [210, 3, 999], 97 | ], 98 | bid: [ 99 | [201, 4, 999], 100 | [199, 2, 1000], 101 | [190, 0, 999], 102 | ], 103 | }, 104 | ); 105 | }); 106 | }); 107 | -------------------------------------------------------------------------------- /__test__/lib/helpers/processOrderBookUpdate.test.js: -------------------------------------------------------------------------------- 1 | import processOrderBookUpdate from '../../../src/lib/helpers/processOrderBookUpdate'; 2 | 3 | describe('processOrderBookUpdate', () => { 4 | let data; 5 | let bid = []; 6 | let ask = []; 7 | 8 | beforeEach(() => { 9 | data = { 10 | bid: [ 11 | [201, 1], 12 | [199, 2], 13 | ], 14 | ask: [ 15 | [202, 1], 16 | [210, 2], 17 | ], 18 | }; 19 | bid = []; 20 | ask = []; 21 | }); 22 | 23 | test('update bid', () => { 24 | bid = [ 25 | [200, 5], 26 | [180, 1], 27 | ]; 28 | const result = processOrderBookUpdate(data, bid, ask); 29 | expect(result).toEqual( 30 | { 31 | bid: [ 32 | [201, 1], 33 | [200, 5], 34 | [199, 2], 35 | [180, 1], 36 | ], 37 | ask: [ 38 | [202, 1], 39 | [210, 2], 40 | ], 41 | }, 42 | ); 43 | }); 44 | 45 | test('update bid', () => { 46 | ask = [ 47 | [200, 5], 48 | [180, 1], 49 | ]; 50 | const result = processOrderBookUpdate(data, bid, ask); 51 | expect(result).toEqual( 52 | { 53 | bid: [ 54 | [201, 1], 55 | [199, 2], 56 | ], 57 | ask: [ 58 | [180, 1], 59 | [200, 5], 60 | [202, 1], 61 | [210, 2], 62 | ], 63 | }, 64 | ); 65 | }); 66 | 67 | test('remove order with 0 volume', () => { 68 | bid = [ 69 | [201, 0], 70 | [199, 2], 71 | ]; 72 | ask = [ 73 | [180, 1], 74 | [210, 0], 75 | ]; 76 | const result = processOrderBookUpdate(data, bid, ask); 77 | expect(result).toEqual( 78 | { 79 | bid: [ 80 | [199, 2], 81 | ], 82 | ask: [ 83 | [180, 1], 84 | [202, 1], 85 | ], 86 | }, 87 | ); 88 | }); 89 | }); 90 | -------------------------------------------------------------------------------- /__test__/lib/orderBook.test.js: -------------------------------------------------------------------------------- 1 | 2 | import OrderBook from '../../src/lib/orderBook'; 3 | 4 | describe('initialize', () => { 5 | it('should initial orderbook', () => { 6 | const symbol = 'BTCUSDT'; 7 | const orderBook = new OrderBook(symbol); 8 | expect(orderBook.getSymbol()).toEqual(symbol); 9 | expect(orderBook._data.bid.length).toEqual(0); 10 | expect(orderBook._data.ask.length).toEqual(0); 11 | expect(orderBook._data.lastUpdateId).toEqual(''); 12 | expect(orderBook.justInitialized()).toBeTruthy(); 13 | }); 14 | }); 15 | 16 | describe('updateLastUpdateId', () => { 17 | let orderBook; 18 | beforeEach(() => { 19 | orderBook = new OrderBook('BTCUSDT'); 20 | }); 21 | 22 | it('should update lastUpdateId', () => { 23 | orderBook.updateLastUpdateId(12345678); 24 | expect(orderBook._data.lastUpdateId).toEqual(12345678); 25 | }); 26 | 27 | describe('updateOrderbook', () => { 28 | let orderBook; 29 | const symbol = 'BTCUSDT'; 30 | const orders = { ask: [[199, 2], [201, 1]], bid: [[210, 2], [202, 1]] }; 31 | 32 | beforeEach(() => { 33 | orderBook = new OrderBook(symbol); 34 | orderBook.updateOrderbook([[199, 2], [201, 1]], [[210, 2], [202, 1]]); 35 | }); 36 | 37 | it('should update the orderbook', () => { 38 | expect(orderBook.getOrderbook()).toEqual({ 39 | symbol, 40 | ask: orders.ask, 41 | bid: orders.bid, 42 | lastUpdateId: '', 43 | }); 44 | expect(orderBook.getBestAsk()).toEqual(199); 45 | }); 46 | 47 | it('should get best ask', () => { 48 | expect(orderBook.getBestAsk()).toEqual(199); 49 | }); 50 | 51 | it('should get best bid', () => { 52 | expect(orderBook.getBestBid()).toEqual(210); 53 | }); 54 | }); 55 | 56 | describe('updateOrderBookWithSnapshot', () => { 57 | let orderBook; 58 | const symbol = 'BTCUSDT'; 59 | const snapshot = { 60 | lastUpdateId: 110000, 61 | bids: [[210, 2], [202, 1]], 62 | asks: [[199, 2], [201, 1]], 63 | }; 64 | beforeEach(() => { 65 | orderBook = new OrderBook(symbol); 66 | orderBook.updateOrderBookWithSnapshot(snapshot); 67 | }); 68 | 69 | it('should update the orderbook', () => { 70 | expect(orderBook.getOrderbook()).toEqual({ 71 | symbol, 72 | ask: [[199, 2, 110000], [201, 1, 110000]], 73 | bid: [[210, 2, 110000], [202, 1, 110000]], 74 | lastUpdateId: '', 75 | }); 76 | expect(orderBook.getBestAsk()).toEqual(199); 77 | }); 78 | 79 | it('should get best ask', () => { 80 | expect(orderBook.getBestAsk()).toEqual(199); 81 | }); 82 | 83 | it('should get best bid', () => { 84 | expect(orderBook.getBestBid()).toEqual(210); 85 | }); 86 | }); 87 | }); 88 | -------------------------------------------------------------------------------- /__test__/lib/services/extendUserDataSteam.test.js: -------------------------------------------------------------------------------- 1 | import mockAxios from 'axios'; 2 | import extendUserDataStream from '../../../src/lib/services/extendUserDataStream'; 3 | 4 | describe('extendUserDataStream', () => { 5 | 6 | const apiKey = 'xxxx'; 7 | const apiSecret = 'yyyyy'; 8 | const resp = {}; 9 | 10 | beforeEach(() => { 11 | mockAxios.put.mockImplementationOnce(() => Promise.resolve(resp)); 12 | }); 13 | 14 | it('should extend the data stream', async () => { 15 | await expect(extendUserDataStream(apiKey, apiSecret)('xxxxx')).resolves.toBeDefined(); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /__test__/lib/services/getOrderBookSnapshot.test.js: -------------------------------------------------------------------------------- 1 | import mockAxios from 'axios'; 2 | import getOrderBookSnapshot from '../../../src/lib/services/getOrderBookSnapshot'; 3 | 4 | describe('getOrderBookSnapshot', () => { 5 | const resp = { 6 | data: { 7 | lastUpdateId: 1450000000, 8 | bids: [ 9 | [ 10 | '7498.07000000', 11 | '0.02666500', 12 | ], 13 | [ 14 | '7498.06000000', 15 | '0.22363800', 16 | ], 17 | [ 18 | '7497.98000000', 19 | '2.00000000', 20 | ], 21 | [ 22 | '7497.95000000', 23 | '2.00000000', 24 | ], 25 | [ 26 | '7497.92000000', 27 | '2.00000000', 28 | ], 29 | [ 30 | '7497.88000000', 31 | '2.00000000', 32 | ], 33 | [ 34 | '7497.83000000', 35 | '2.00000000', 36 | ], 37 | [ 38 | '7497.79000000', 39 | '2.00000000', 40 | ], 41 | [ 42 | '7496.45000000', 43 | '0.03000000', 44 | ], 45 | [ 46 | '7496.44000000', 47 | '0.20000000', 48 | ], 49 | ], 50 | asks: [ 51 | [ 52 | '7500.42000000', 53 | '2.00000000', 54 | ], 55 | [ 56 | '7500.43000000', 57 | '1.85782800', 58 | ], 59 | [ 60 | '7500.44000000', 61 | '2.00000000', 62 | ], 63 | [ 64 | '7500.45000000', 65 | '2.50000000', 66 | ], 67 | [ 68 | '7500.46000000', 69 | '1.30193900', 70 | ], 71 | [ 72 | '7500.47000000', 73 | '2.00000000', 74 | ], 75 | [ 76 | '7500.48000000', 77 | '2.00000000', 78 | ], 79 | [ 80 | '7500.52000000', 81 | '2.00000000', 82 | ], 83 | [ 84 | '7500.54000000', 85 | '2.00000000', 86 | ], 87 | [ 88 | '7500.61000000', 89 | '9.84049200', 90 | ], 91 | ], 92 | }, 93 | }; 94 | 95 | beforeEach(() => { 96 | mockAxios.get.mockImplementationOnce(() => Promise.resolve(resp)); 97 | }); 98 | 99 | it('should return orderbook snapshot data', async () => { 100 | await expect(getOrderBookSnapshot('BTCUSDT')).resolves.toEqual(resp.data); 101 | }); 102 | }); 103 | -------------------------------------------------------------------------------- /__test__/lib/services/getServerTime.test.js: -------------------------------------------------------------------------------- 1 | import mockAxios from 'axios'; 2 | import getServerTime from '../../../src/lib/services/getServerTime'; 3 | 4 | describe('getServerTime', () => { 5 | const now = Date.now(); 6 | const resp = { data: now }; 7 | 8 | beforeEach(() => { 9 | mockAxios.get.mockImplementationOnce(() => Promise.resolve(resp)); 10 | }); 11 | 12 | it('should returun server time', async () => { 13 | await expect(getServerTime()).resolves.toEqual(now); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /__test__/lib/services/getUserDataSteam.test.js: -------------------------------------------------------------------------------- 1 | import mockAxios from 'axios'; 2 | import getUserDataStream from '../../../src/lib/services/getUserDataStream'; 3 | 4 | describe('getUserDataStream', () => { 5 | 6 | const apiKey = 'xxxx'; 7 | const apiSecret = 'yyyyy'; 8 | const resp = { data: { listenKey: 'xxxxxxxx' } }; 9 | 10 | beforeEach(() => { 11 | mockAxios.post.mockImplementationOnce(() => Promise.resolve(resp)); 12 | }); 13 | 14 | it('should returun return listen key', async () => { 15 | await expect(getUserDataStream(apiKey, apiSecret)).resolves.toEqual('xxxxxxxx'); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "", 3 | "version": "", 4 | "description": "examples codes to demonstrate how to listen Binance Websocket Server", 5 | "main": "index.js", 6 | "dependencies": { 7 | "axios": "^1.6.2", 8 | "big.js": "^5.2.2", 9 | "ramda": "^0.26.1", 10 | "ws": "^7.4.6" 11 | }, 12 | "devDependencies": { 13 | "@babel/cli": "^7.12.1", 14 | "@babel/core": "^7.1.0", 15 | "@babel/node": "^7.0.0", 16 | "@babel/preset-env": "^7.1.0", 17 | "@babel/register": "^7.0.0", 18 | "babel-jest": "^27.3.1", 19 | "eslint": "^8.17.0", 20 | "eslint-config-airbnb-base": "^15.0.0", 21 | "eslint-plugin-import": "^2.18.2", 22 | "jest": "^27.3.1", 23 | "jest-watch-master": "^1.0.0", 24 | "nodemon": "^3.0.2" 25 | }, 26 | "scripts": { 27 | "orderbook": "nodemon -w ./src --exec babel-node ./src/app.js", 28 | "user": "nodemon -w ./src --exec babel-node ./src/user.js", 29 | "margin-user": "nodemon -w ./src --exec babel-node ./src/margin-user.js", 30 | "futures-user": "nodemon -w ./src --exec babel-node ./src/futures-user.js", 31 | "delivery-futures-user": "nodemon -w ./src --exec babel-node ./src/delivery-futures-user.js", 32 | "multi-stream": "nodemon -w ./src --exec babel-node ./src/multi-stream-depth.js", 33 | "monitor-spot-depth": "nodemon -w ./src --exec babel-node ./src/spot/monitor-depth.js", 34 | "monitor-spot-trade": "nodemon -w ./src --exec babel-node ./src/spot/monitor-trade.js", 35 | "monitor-futures": "nodemon -w ./src --exec babel-node ./src/monitor-futures.js", 36 | "start": "nodemon -w ./src --exec babel-node ./src/index.js", 37 | "delivery": "nodemon -w ./src --exec babel-node ./src/delivery.js", 38 | "build": "babel src -d dist", 39 | "test": "jest --watchAll" 40 | }, 41 | "jest": { 42 | "watchPlugins": [ 43 | "jest-watch-master" 44 | ] 45 | }, 46 | "author": "Liang Shi", 47 | "license": "MIT" 48 | } 49 | -------------------------------------------------------------------------------- /src/__mocks__/axios.js: -------------------------------------------------------------------------------- 1 | const mockAxios = jest.genMockFromModule('axios'); 2 | mockAxios.create = jest.fn(() => mockAxios); 3 | export default mockAxios; 4 | -------------------------------------------------------------------------------- /src/app.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import logger from './lib/logger'; 4 | import OrderBook from './lib/orderBook'; 5 | import SocketClient from './lib/socketClient'; 6 | import { orderbookUpdateFromWebsocket, orderBookUpdateFromRESTfulAPI } from './lib/orderBookManager'; 7 | 8 | const SYMBOL = process.env.SYMBOL || 'BTCUSDT'; 9 | 10 | export default async function createApp() { 11 | logger.info('Start application'); 12 | 13 | const socketApi = new SocketClient(`ws/${SYMBOL.toLowerCase()}@depth`); 14 | 15 | const orderBook = new OrderBook(SYMBOL.toUpperCase()); 16 | 17 | socketApi.setHandler('depthUpdate', (params) => orderbookUpdateFromWebsocket(params)(orderBook)); 18 | 19 | // leave a time gap to wait for websocket connection first 20 | setTimeout(() => { 21 | orderBookUpdateFromRESTfulAPI(orderBook); 22 | }, 3000); 23 | 24 | // inspection 25 | orderBook.best_price(); 26 | } 27 | 28 | createApp(); 29 | -------------------------------------------------------------------------------- /src/delivery-futures-user.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import getDeliveryListenKey from './lib/services/futures/getDeliveryListenKey'; 4 | import SocketClient from './lib/socketClient'; 5 | import logger from './lib/logger'; 6 | 7 | const APIKEY = process.env.APIKEY || ''; 8 | const APISECRET = process.env.APISECRET || ''; 9 | const WS_BASEURL = process.env.WS_BASEURL || 'wss://dstream.binance.com/'; 10 | 11 | export default async function createApp() { 12 | logger.info('start application'); 13 | const listenKey = await getDeliveryListenKey(APIKEY, APISECRET, false); 14 | 15 | logger.info('key received.', listenKey); 16 | const socketApi = new SocketClient(`ws/${listenKey}`, WS_BASEURL); 17 | socketApi.setHandler('executionReport', (params) => logger.info(JSON.stringify(params))); 18 | socketApi.setHandler('outboundAccountInfo', (params) => logger.info(JSON.stringify(params))); 19 | 20 | // renew listenkey 21 | } 22 | 23 | createApp(); 24 | -------------------------------------------------------------------------------- /src/futures-user.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import getListenKey from './lib/services/futures/getListenKey'; 4 | import extendUserDataStream from './lib/services/futures/extendUserDataStream'; 5 | import SocketClient from './lib/socketClient'; 6 | import logger from './lib/logger'; 7 | 8 | const APIKEY = process.env.APIKEY || ''; 9 | const APISECRET = process.env.APISECRET || ''; 10 | const WSS_BASE_URL = process.env.WSS_BASE_URL || 'wss://fstream.binance.com/'; 11 | const HTTP_BASE_URL = process.env.HTTP_BASE_URL || 'https://fapi.binance.com/'; 12 | 13 | export default async function createApp() { 14 | logger.info('start application'); 15 | const listenKey = await getListenKey(APIKEY, APISECRET, HTTP_BASE_URL); 16 | 17 | logger.info('key received.', listenKey); 18 | const socketApi = new SocketClient(`ws/${listenKey}`, WSS_BASE_URL); 19 | socketApi.setHandler('executionReport', (params) => logger.info(params)); 20 | socketApi.setHandler('outboundAccountInfo', (params) => logger.info(params)); 21 | 22 | // renew listenkey 23 | setInterval(() => { 24 | extendUserDataStream(APIKEY, APISECRET, HTTP_BASE_URL) 25 | .then(logger.info('ListenKey is renewed')); 26 | }, 1000 * 60 * 45); // review the key every 45 mins 27 | } 28 | 29 | createApp(); 30 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import SocketClient from './lib/socketClient'; 4 | import getServerTime from './lib/services/getServerTime'; 5 | 6 | 7 | getServerTime().then(data => console.log(data)); 8 | // getOrderBookSnapshot('BTCUSDT').then(data => console.log(data)); 9 | 10 | // const socketClient = new SocketClient('ws/btcusdt@bookTicker'); 11 | // socketClient.setHandler('depthUpdate', (params) => console.log(JSON.stringify(params))); 12 | -------------------------------------------------------------------------------- /src/lib/errors/dataLostException.js: -------------------------------------------------------------------------------- 1 | class DataLostException extends Error {} 2 | 3 | export default DataLostException; 4 | -------------------------------------------------------------------------------- /src/lib/helpers/appendUpdatedId.js: -------------------------------------------------------------------------------- 1 | const appendUpdatedId = (updateId, ask, bid) => { 2 | const insertUpdateId = (order) => { 3 | order[2] = updateId; 4 | return order; 5 | }; 6 | return [ask, bid].map((side) => side.map(insertUpdateId)); 7 | }; 8 | 9 | export default appendUpdatedId; 10 | -------------------------------------------------------------------------------- /src/lib/helpers/getRequestInstance.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | 3 | const getRequestInstance = (config) => { 4 | return axios.create({ 5 | ...config, 6 | }); 7 | }; 8 | 9 | export default getRequestInstance; 10 | -------------------------------------------------------------------------------- /src/lib/helpers/processOrderBookSnapshot.js: -------------------------------------------------------------------------------- 1 | import Big from 'big.js'; 2 | import { 3 | uniqBy, filter, cond, equals, sort, 4 | } from 'ramda'; 5 | import appendUpdatedId from './appendUpdatedId'; 6 | 7 | const processOrderBookSnapshot = (orderBookData, snapshotOrderbook) => { 8 | const { lastUpdateId, bids, asks } = snapshotOrderbook; 9 | 10 | // clean the order that is out of date 11 | const cleanOutOfDateOrder = (order) => order[2] > lastUpdateId; 12 | orderBookData.bid = filter(cleanOutOfDateOrder, orderBookData.bid); 13 | orderBookData.ask = filter(cleanOutOfDateOrder, orderBookData.ask); 14 | 15 | // append the updateId into snapshotOrderbook 16 | const snapshotOrders = appendUpdatedId(lastUpdateId, asks, bids); 17 | const compareValueFn = cond([ 18 | [equals('ask'), () => (a, b) => (new Big(a[0])).minus(b[0])], 19 | [equals('bid'), () => (a, b) => (new Big(b[0])).minus(a[0])], 20 | ]); 21 | 22 | const validateValue = (v) => Big(v[0]); 23 | orderBookData.bid = uniqBy(validateValue, [...snapshotOrders[1], ...orderBookData.bid]) 24 | .sort(compareValueFn('bid'), orderBookData.bid); 25 | 26 | orderBookData.ask = uniqBy(validateValue, [...snapshotOrders[0], ...orderBookData.ask]) 27 | .sort(compareValueFn('ask'), orderBookData.ask); 28 | 29 | 30 | return orderBookData; 31 | }; 32 | 33 | export default processOrderBookSnapshot; 34 | -------------------------------------------------------------------------------- /src/lib/helpers/processOrderBookUpdate.js: -------------------------------------------------------------------------------- 1 | import Big from 'big.js'; 2 | import { 3 | uniqBy, sort, filter, cond, equals, 4 | } from 'ramda'; 5 | 6 | const processOrderBookUpdate = (data, bid, ask) => { 7 | const validateValue = (v) => Big(v[0]); 8 | const compareValueFn = cond([ 9 | [equals('ask'), () => (a, b) => (new Big(a[0])).minus(b[0])], 10 | [equals('bid'), () => (a, b) => (new Big(b[0])).minus(a[0])], 11 | ]); 12 | const purgeEmptyVolume = (v) => Big(v[1]).gt(0); 13 | 14 | data.bid = uniqBy(validateValue, [...bid, ...data.bid]) 15 | .sort(compareValueFn('bid'), data.bid) 16 | .filter(purgeEmptyVolume, data.bid); 17 | 18 | data.ask = uniqBy(validateValue, [...ask, ...data.ask]) 19 | .sort(compareValueFn('ask'), data.ask) 20 | .filter(purgeEmptyVolume, data.ask); 21 | return data; 22 | }; 23 | 24 | export default processOrderBookUpdate; 25 | -------------------------------------------------------------------------------- /src/lib/helpers/renewListenKey.js: -------------------------------------------------------------------------------- 1 | import extendUserDataStream from '../services/extendUserDataStream'; 2 | import logger from '../logger'; 3 | 4 | const renewListenKey = (apiKey) => (listenKey) => { 5 | setInterval(() => { 6 | extendUserDataStream(apiKey)(listenKey) 7 | .then(logger.info('ListenKey is renewed')); 8 | }, 1000 * 60 * 45); // review the key every 45 mins 9 | }; 10 | 11 | export default renewListenKey; 12 | -------------------------------------------------------------------------------- /src/lib/logger.js: -------------------------------------------------------------------------------- 1 | const logger = { 2 | debug: (...arg) => { 3 | console.log((new Date()).toISOString(), 'DEBUG', ...arg); 4 | }, 5 | info: (...arg) => { 6 | console.log((new Date()).toISOString(), 'INFO', ...arg); 7 | }, 8 | warn: (...arg) => { 9 | console.log((new Date()).toISOString(), 'WARN', ...arg); 10 | }, 11 | }; 12 | 13 | export default logger; 14 | -------------------------------------------------------------------------------- /src/lib/orderBook.js: -------------------------------------------------------------------------------- 1 | import logger from './logger'; 2 | import processOrderBookUpdate from './helpers/processOrderBookUpdate'; 3 | import processOrderBookSnapshot from './helpers/processOrderBookSnapshot'; 4 | 5 | class OrderBook { 6 | constructor(symbol) { 7 | this._data = { 8 | symbol, 9 | ask: [], 10 | bid: [], 11 | lastUpdateId: '', 12 | }; 13 | } 14 | 15 | getOrderbook() { 16 | return this._data; 17 | } 18 | 19 | getSymbol() { 20 | return this._data.symbol; 21 | } 22 | 23 | getBestBid() { 24 | return this._data.bid[0][0]; 25 | } 26 | 27 | getBestAsk() { 28 | return this._data.ask[0][0]; 29 | } 30 | justInitialized() { 31 | return this._data.ask.length === 0; 32 | } 33 | 34 | updateLastUpdateId(id) { 35 | this._data.lastUpdateId = id; 36 | } 37 | 38 | updateOrderbook(ask, bid) { 39 | this._data = processOrderBookUpdate(this._data, bid, ask); 40 | } 41 | 42 | 43 | updateOrderBookWithSnapshot(snapshot) { 44 | this._data = processOrderBookSnapshot(this._data, snapshot); 45 | } 46 | 47 | inspect() { 48 | setInterval(() => { 49 | logger.info('orderbook:', this._data); 50 | }, 4000); 51 | } 52 | 53 | best_price() { 54 | setInterval(() => { 55 | if (this._data.ask.length == 0) { 56 | logger.info('waiting for warm up'); 57 | return; 58 | } 59 | logger.info('Best Ask:', this.getBestAsk()); 60 | logger.info('Best Bid:', this.getBestBid()); 61 | }, 1000); 62 | } 63 | } 64 | 65 | export default OrderBook; 66 | -------------------------------------------------------------------------------- /src/lib/orderBookManager.js: -------------------------------------------------------------------------------- 1 | import appendUpdatedId from './helpers/appendUpdatedId'; 2 | import DataLostException from './errors/dataLostException'; 3 | import getOrderBookSnapshot from './services/getOrderBookSnapshot'; 4 | import logger from './logger'; 5 | 6 | const orderBookUpdateFromRESTfulAPI = (orderBook) => { 7 | getOrderBookSnapshot(orderBook.getSymbol()).then((data) => orderBook.updateOrderBookWithSnapshot(data)); 8 | }; 9 | 10 | const validateEventUpdateId = (id) => (orderBook) => { 11 | const { lastUpdateId } = orderBook.getOrderbook(); 12 | if (id - lastUpdateId !== 1 && !orderBook.justInitialized()) { 13 | throw new DataLostException(`Event id is not continued, lastUpdateId: ${lastUpdateId}, Event Id: ${id}`); 14 | } 15 | }; 16 | 17 | const orderbookUpdateFromWebsocket = (params) => (orderBook) => { 18 | try { 19 | // has to be uppcase 'U' 20 | validateEventUpdateId(params.U)(orderBook); 21 | 22 | const orders = appendUpdatedId(params.u, params.a, params.b); 23 | orderBook.updateLastUpdateId(params.u); 24 | orderBook.updateOrderbook(...orders); 25 | } catch (e) { 26 | if (e instanceof DataLostException) { 27 | // if lastUpdateId is not continued, fetch the snapshot 28 | logger.warn(e.message); 29 | orderBookUpdateFromRESTfulAPI(orderBook); 30 | } else { 31 | throw e; 32 | } 33 | } 34 | }; 35 | 36 | export { 37 | orderbookUpdateFromWebsocket, 38 | orderBookUpdateFromRESTfulAPI, 39 | }; 40 | -------------------------------------------------------------------------------- /src/lib/requestClient.js: -------------------------------------------------------------------------------- 1 | import crypto from 'crypto'; 2 | import getRequestInstance from './helpers/getRequestInstance'; 3 | 4 | const publicRequest = () => getRequestInstance({ 5 | headers: { 6 | 'content-type': 'application/json', 7 | }, 8 | }); 9 | 10 | const spotPublicRequest = () => getRequestInstance({ 11 | baseURL: 'https://api.binance.com', 12 | headers: { 13 | 'content-type': 'application/json', 14 | }, 15 | }); 16 | 17 | 18 | const buildQueryString = (q) => (q ? `?${Object.keys(q) 19 | .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(q[k])}`) 20 | .join('&')}` : ''); 21 | 22 | const privateRequest = (apiKey, apiSecret, baseURL) => ( 23 | method = 'GET', 24 | path, 25 | data = {}, 26 | ) => { 27 | if (!apiKey) { 28 | throw new Error('API key is missing'); 29 | } 30 | 31 | if (!apiSecret) { 32 | throw new Error('API secret is missing'); 33 | } 34 | 35 | const timestamp = Date.now(); 36 | 37 | const signature = crypto 38 | .createHmac('sha256', apiSecret) 39 | .update(buildQueryString({ ...data, timestamp }).substr(1)) 40 | .digest('hex'); 41 | 42 | return getRequestInstance({ 43 | baseURL, 44 | headers: { 45 | 'content-type': 'application/json', 46 | 'X-MBX-APIKEY': apiKey, 47 | }, 48 | method, 49 | url: path, 50 | }); 51 | }; 52 | 53 | const publicDataRequest = (apiKey, baseURL) => ( 54 | method = 'GET', 55 | path, 56 | data = {}, 57 | ) => { 58 | if (!apiKey) { 59 | throw new Error('API key is missing'); 60 | } 61 | 62 | return getRequestInstance({ 63 | baseURL, 64 | headers: { 65 | 'content-type': 'application/json', 66 | 'X-MBX-APIKEY': apiKey, 67 | }, 68 | method, 69 | url: path, 70 | }); 71 | }; 72 | 73 | const spotMarketDataRequest = (apiKey, baseURL = 'https://api.binance.com') => publicDataRequest(apiKey, baseURL); 74 | const spotPrivateRequest = (apiKey, apiSecret, baseURL = 'https://api.binance.com') => privateRequest(apiKey, apiSecret, baseURL); 75 | const futuresPrivateRequest = (apiKey, apiSecret, baseURL = 'https://fapi.binance.com') => privateRequest(apiKey, apiSecret, baseURL); 76 | 77 | const deliveryFuturesPrivateRequest = (apiKey, apiSecret, testnet) => { 78 | let baseURL = 'https://dapi.binance.com'; 79 | if (testnet) { 80 | baseURL = 'https://testnet.binancefuture.com'; 81 | } 82 | return privateRequest(apiKey, apiSecret, baseURL); 83 | }; 84 | 85 | export { 86 | spotPublicRequest, 87 | publicRequest, 88 | privateRequest, 89 | spotPrivateRequest, 90 | spotMarketDataRequest, 91 | futuresPrivateRequest, 92 | deliveryFuturesPrivateRequest, 93 | }; 94 | -------------------------------------------------------------------------------- /src/lib/services/extendUserDataStream.js: -------------------------------------------------------------------------------- 1 | import { spotMarketDataRequest } from '../requestClient'; 2 | 3 | const extendUserDataStream = (apiKey) => (listenKey) => spotMarketDataRequest(apiKey)('PUT', '/api/v3/userDataStream', { listenKey }) 4 | .put(`/api/v3/userDataStream?listenKey=${listenKey}`); 5 | 6 | export default extendUserDataStream; 7 | -------------------------------------------------------------------------------- /src/lib/services/futures/extendUserDataStream.js: -------------------------------------------------------------------------------- 1 | import { futuresPrivateRequest } from '../../requestClient'; 2 | 3 | const extendUserDataStream = (apiKey, apiSecret, baseURL) => futuresPrivateRequest(apiKey, apiSecret, baseURL)('PUT', '/fapi/v1/listenKey') 4 | .put('/fapi/v1/listenKey'); 5 | 6 | export default extendUserDataStream; 7 | -------------------------------------------------------------------------------- /src/lib/services/futures/getDeliveryListenKey.js: -------------------------------------------------------------------------------- 1 | import { deliveryFuturesPrivateRequest } from '../../requestClient'; 2 | 3 | const getDeliveryListenKey = (apiKey, apiSecret, testnet = false) => deliveryFuturesPrivateRequest(apiKey, apiSecret, testnet)('POST', '/dapi/v1/listenKey') 4 | .post('/dapi/v1/listenKey') 5 | .then(({ data }) => data.listenKey); 6 | 7 | export default getDeliveryListenKey; 8 | -------------------------------------------------------------------------------- /src/lib/services/futures/getListenKey.js: -------------------------------------------------------------------------------- 1 | import { futuresPrivateRequest } from '../../requestClient'; 2 | 3 | const getListenKey = (apiKey, apiSecret, baseURL) => futuresPrivateRequest(apiKey, apiSecret, baseURL)('POST', '/fapi/v1/listenKey') 4 | .post('/fapi/v1/listenKey') 5 | .then(({ data }) => data.listenKey) 6 | .catch(error => console.log(error)); 7 | 8 | export default getListenKey; 9 | -------------------------------------------------------------------------------- /src/lib/services/getOrderBookSnapshot.js: -------------------------------------------------------------------------------- 1 | import { spotPublicRequest } from '../requestClient'; 2 | 3 | const getOrderBookSnapshot = (symbol) => spotPublicRequest() 4 | .get(`/api/v1/depth?limit=100&symbol=${symbol}`) 5 | .then(({ data }) => data); 6 | 7 | export default getOrderBookSnapshot; 8 | -------------------------------------------------------------------------------- /src/lib/services/getServerTime.js: -------------------------------------------------------------------------------- 1 | import { spotPublicRequest } from '../requestClient'; 2 | 3 | 4 | const getServerTime = () => spotPublicRequest() 5 | .get('/api/v3/time') 6 | .then(({ data }) => data) 7 | .catch((error) => console.log(error.message)); 8 | 9 | export default getServerTime; 10 | -------------------------------------------------------------------------------- /src/lib/services/getUserDataStream.js: -------------------------------------------------------------------------------- 1 | import { spotMarketDataRequest } from '../requestClient'; 2 | 3 | const getUserDataStream = (apiKey) => spotMarketDataRequest(apiKey)('POST', '/api/v3/userDataStream') 4 | .post('/api/v3/userDataStream') 5 | .then(({ data }) => data.listenKey); 6 | 7 | export default getUserDataStream; 8 | -------------------------------------------------------------------------------- /src/lib/services/margin/getUserDataStream.js: -------------------------------------------------------------------------------- 1 | import { spotPrivateRequest } from '../../requestClient'; 2 | 3 | const getUserDataStream = (apiKey, apiSecret) => spotPrivateRequest(apiKey, apiSecret)('POST', '/sapi/v1/userDataStream') 4 | .post('/sapi/v1/userDataStream') 5 | .then(({ data }) => data.listenKey); 6 | 7 | export default getUserDataStream; 8 | -------------------------------------------------------------------------------- /src/lib/socketClient.js: -------------------------------------------------------------------------------- 1 | import WebSocket from 'ws'; 2 | import logger from './logger'; 3 | 4 | class SocketClient { 5 | constructor(path, baseUrl) { 6 | this.baseUrl = baseUrl || 'wss://stream.binance.com/'; 7 | this._path = path; 8 | this._createSocket(); 9 | this._handlers = new Map(); 10 | } 11 | 12 | _createSocket() { 13 | console.log(`${this.baseUrl}${this._path}`); 14 | this._ws = new WebSocket(`${this.baseUrl}${this._path}`); 15 | 16 | this._ws.onopen = () => { 17 | logger.info('ws connected'); 18 | }; 19 | 20 | this._ws.on('pong', () => { 21 | logger.debug('receieved pong from server'); 22 | }); 23 | this._ws.on('ping', () => { 24 | logger.debug('==========receieved ping from server'); 25 | this._ws.pong(); 26 | }); 27 | 28 | this._ws.onclose = () => { 29 | logger.warn('ws closed'); 30 | }; 31 | 32 | this._ws.onerror = (err) => { 33 | logger.warn('ws error', err); 34 | }; 35 | 36 | this._ws.onmessage = (msg) => { 37 | try { 38 | const message = JSON.parse(msg.data); 39 | if (this.isMultiStream(message)) { 40 | this._handlers.get(message.stream).forEach(cb => cb(message)); 41 | } else if (message.e && this._handlers.has(message.e)) { 42 | this._handlers.get(message.e).forEach(cb => { 43 | cb(message); 44 | }); 45 | } else { 46 | logger.warn('Unknown method', message); 47 | } 48 | } catch (e) { 49 | logger.warn('Parse message failed', e); 50 | } 51 | }; 52 | 53 | this.heartBeat(); 54 | } 55 | 56 | isMultiStream(message) { 57 | return message.stream && this._handlers.has(message.stream); 58 | } 59 | 60 | heartBeat() { 61 | setInterval(() => { 62 | if (this._ws.readyState === WebSocket.OPEN) { 63 | this._ws.ping(); 64 | logger.debug("ping server"); 65 | } 66 | }, 5000); 67 | } 68 | 69 | setHandler(method, callback) { 70 | if (!this._handlers.has(method)) { 71 | this._handlers.set(method, []); 72 | } 73 | this._handlers.get(method).push(callback); 74 | } 75 | } 76 | 77 | export default SocketClient; 78 | -------------------------------------------------------------------------------- /src/margin-user.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import getUserDataStream from './lib/services/margin/getUserDataStream'; 4 | import SocketClient from './lib/socketClient'; 5 | import renewListenKey from './lib/helpers/renewListenKey'; 6 | import logger from './lib/logger'; 7 | 8 | const { APIKEY } = process.env; 9 | const { APISECRET } = process.env; 10 | 11 | export default async function createApp() { 12 | logger.info('start application to get margin user account update'); 13 | const listenKey = await getUserDataStream(APIKEY, APISECRET); 14 | 15 | logger.info('key received.'); 16 | const socketApi = new SocketClient(`ws/${listenKey}`); 17 | socketApi.setHandler('executionReport', (params) => logger.info(params)); 18 | socketApi.setHandler('outboundAccountInfo', (params) => logger.info(params)); 19 | 20 | renewListenKey(APIKEY, APISECRET)(listenKey); 21 | } 22 | 23 | createApp(); 24 | -------------------------------------------------------------------------------- /src/monitor-futures.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import logger from './lib/logger'; 4 | import SocketClient from './lib/socketClient'; 5 | 6 | const streamName = 'btcusdt@depth@100ms'; 7 | 8 | const socketClient = new SocketClient(`ws/${streamName}`, 'wss://fstream.binance.com/'); 9 | socketClient.setHandler('depthUpdate', (params) => { 10 | const current = +(new Date); 11 | const TvsNow = current - params.T; 12 | const EvsNow = current - params.E; 13 | const EvsT = params.E - params.T; 14 | console.log(`[Futures ${streamName}] delta TvsNow: ${TvsNow}, EvsNow: ${EvsNow}, EvsT: ${EvsT}`); 15 | }); 16 | -------------------------------------------------------------------------------- /src/multi-stream-depth.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import logger from './lib/logger'; 4 | import SocketClient from './lib/socketClient'; 5 | 6 | export default async function createApp() { 7 | logger.info('Start application'); 8 | 9 | let pairs = [ 10 | 'ethbtc', 11 | 'ltcbtc', 12 | 'bnbbtc', 13 | ]; 14 | 15 | pairs = pairs.map((pair) => `${pair}@depth5`); 16 | const pairString = pairs.join('/'); 17 | logger.info(pairString); 18 | 19 | const socketApi = new SocketClient(`stream?streams=${pairString}`); 20 | pairs.forEach(pair => { 21 | socketApi.setHandler(pair, (params) => logger.info(JSON.stringify(params))); 22 | }) 23 | } 24 | 25 | createApp(); 26 | -------------------------------------------------------------------------------- /src/spot/monitor-depth.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import SocketClient from '../lib/socketClient'; 4 | 5 | 6 | const streamName = 'btcusdt@depth@100ms'; 7 | 8 | const socketClient = new SocketClient(`ws/${streamName}`, 'wss://stream.binance.com:9443/'); 9 | let lastCurrent = +new Date; 10 | socketClient.setHandler('depthUpdate', (params) => { 11 | const current = +new Date; 12 | const EvsNow = current - params.E; 13 | const fromLastEvent = current - lastCurrent 14 | console.log(`[Spot ${streamName}] current:${current} fromLastEvent: ${fromLastEvent} delta EvsNow: ${EvsNow}`); 15 | lastCurrent = current; 16 | }); 17 | -------------------------------------------------------------------------------- /src/spot/monitor-trade.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import SocketClient from '../lib/socketClient'; 4 | 5 | 6 | const streamName = 'btcusdt@trade'; 7 | 8 | const socketClient = new SocketClient(`ws/${streamName}`, 'wss://stream.binance.com:9443/'); 9 | socketClient.setHandler('trade', (params) => { 10 | const current = +new Date; 11 | const TvsNow = current - params.T; 12 | const EvsNow = current - params.E; 13 | const EvsT = params.E - params.T; 14 | console.log(`[Spot ${streamName}] current:${current} delta TvsNow: ${TvsNow}, EvsNow: ${EvsNow}, EvsT: ${EvsT}`); 15 | }); 16 | -------------------------------------------------------------------------------- /src/user.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import getUserDataStream from './lib/services/getUserDataStream'; 4 | import SocketClient from './lib/socketClient'; 5 | import renewListenKey from './lib/helpers/renewListenKey'; 6 | import logger from './lib/logger'; 7 | 8 | const APIKEY = process.env.APIKEY || ''; 9 | 10 | export default async function createApp() { 11 | logger.info('start application'); 12 | const listenKey = await getUserDataStream(APIKEY); 13 | 14 | logger.info(`key received : ${listenKey}`); 15 | const socketApi = new SocketClient(`ws/${listenKey}`); 16 | socketApi.setHandler('executionReport', (params) => logger.info(params)); 17 | socketApi.setHandler('outboundAccountPosition', (params) => logger.info(params)); 18 | renewListenKey(APIKEY)(listenKey); 19 | } 20 | 21 | createApp(); 22 | --------------------------------------------------------------------------------