├── .gitignore ├── .babelrc ├── .editorconfig ├── test.mjs ├── .eslintrc.js ├── LICENSE ├── package.json ├── index.mjs └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | index.js 3 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "transform-es2015-modules-commonjs" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | end_of_line = lf 10 | max_line_length = null 11 | -------------------------------------------------------------------------------- /test.mjs: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-console */ 2 | import { BitMexPlus } from '.'; 3 | 4 | (async function test() { 5 | const bitmex = new BitMexPlus({ 6 | // Get your API key at https://www.bitmex.com/app/apiKeys 7 | apiKeyID: '', // REPLACE ME 8 | apiKeySecret: '', // REPLACE ME 9 | }); 10 | 11 | if (bitmex.options.apiKeyID) { 12 | const pos = (await bitmex.makeRequest('GET', 'position', { 13 | filter: { symbol: 'XBTUSD' }, 14 | columns: ['currentQty', 'liquidationPrice'], 15 | })); 16 | console.log(pos); 17 | } 18 | 19 | const [bucket] = (await bitmex.makeRequest('GET', 'quote/bucketed', { 20 | binSize: '1m', 21 | symbol: 'XBTUSD', 22 | reverse: true, 23 | count: 1, 24 | columns: ['bidPrice', 'askPrice'], 25 | })); 26 | console.log(bucket); 27 | 28 | bitmex.monitorStream('XBTUSD', 'trade', data => console.log(data.price)); 29 | 30 | setTimeout(() => { process.exit(0); }, 5000); 31 | 32 | }()); 33 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parserOptions: { 3 | ecmaVersion: 8, 4 | }, 5 | env: { 6 | browser: false, 7 | node: true, 8 | }, 9 | extends: ['airbnb-base'], 10 | rules: { 11 | 'max-len': ['warn', { code: 130, ignoreUrls: true }], 12 | indent: ['error', 2], 13 | curly: ['warn', 'multi', 'consistent'], 14 | 'no-multi-spaces': ['error', { ignoreEOLComments: true }], 15 | 'space-before-function-paren': ['error', { anonymous: 'always', named: 'never' }], 16 | 'padded-blocks': 'off', 17 | 'import/prefer-default-export': 'off', 18 | 'arrow-parens': ['warn', 'as-needed'], 19 | 'prefer-arrow-callback': ['error', { allowNamedFunctions: true }], 20 | 'prefer-template': 'off', 21 | 'no-plusplus': 'off', 22 | 'one-var': 'off', 23 | 'one-var-declaration-per-line': 'off', 24 | 'object-property-newline': 'off', 25 | 'function-paren-newline': 'off', 26 | 'quote-props': ['warn', 'consistent-as-needed'], 27 | }, 28 | }; 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Ben 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 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bitmex-plus", 3 | "version": "1.3.1", 4 | "description": "BitMEX (un)authenticated REST and WebSocket helper methods", 5 | "main": "index", 6 | "scripts": { 7 | "lint": "eslint *.mjs", 8 | "prepare": "babel index.mjs --out-file index.js", 9 | "test": "node --experimental-modules test.mjs" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "https://github.com/bomper/bitmex-plus" 14 | }, 15 | "files": [ 16 | "index.mjs", 17 | "index.js" 18 | ], 19 | "keywords": [ 20 | "BitMEX", 21 | "API", 22 | "client", 23 | "library", 24 | "cryptocurrency", 25 | "Bitcoin", 26 | "BTC", 27 | "crypto" 28 | ], 29 | "author": { 30 | "name": "Ben Bomper", 31 | "url": "https://github.com/bomper" 32 | }, 33 | "license": "MIT", 34 | "dependencies": { 35 | "bitmex-realtime-api": "^0.3.0", 36 | "node-fetch": "^1.7.3", 37 | "qs": "^6.5.1" 38 | }, 39 | "devDependencies": { 40 | "babel-cli": "^6.26.0", 41 | "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", 42 | "eslint": "^4.15.0", 43 | "eslint-config-airbnb-base": "^12.1.0", 44 | "eslint-plugin-import": "^2.8.0" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /index.mjs: -------------------------------------------------------------------------------- 1 | import BitMEXWs from 'bitmex-realtime-api'; 2 | import crypto from 'crypto'; 3 | import qs from 'qs'; 4 | import fetch from 'node-fetch'; 5 | 6 | export class BitMexPlus extends BitMEXWs { 7 | constructor(options) { 8 | super(options); 9 | this.options = options; 10 | } 11 | 12 | /** 13 | * Subscribe to a stream and call a callback for every new item 14 | * @param {String} [symbol='XBTUSD'] 15 | * @param {String} tableName - e.g. 'trade', 'quote', 'orderBookL2', 'instrument' etc. 16 | * @param {Function} callback(data) 17 | */ 18 | monitorStream(symbol = 'XBTUSD', tableName, callback) { 19 | let lastItem; 20 | this.addStream(symbol, tableName, data => { 21 | if (!data.length) return; 22 | if (tableName === 'orderBookL2') 23 | callback(); // callback must deal with the entire data array returned by getData(), no need to pass it anything 24 | else 25 | // On the first piece(s) of data, lastItem is undefined so lastIndexOf + 1 === 0. 26 | // Same if maxTableLen was too small (the lastItem would be splice'd out). 27 | for (let i = data.lastIndexOf(lastItem) + 1; i < data.length; i++) 28 | callback(data[i]); 29 | lastItem = data[data.length - 1]; 30 | }); 31 | } 32 | 33 | /** 34 | * Send a request to the BitMEX REST API. See https://www.bitmex.com/api/explorer/. 35 | * @param {string} verb - GET/PUT/POST/DELETE 36 | * @param {string} endpoint - e.g. `/user/margin` 37 | * @param {object} data - JSON 38 | * @returns {Promise} - JSON response 39 | */ 40 | makeRequest(verb, endpoint, data = {}) { 41 | const apiRoot = '/api/v1/'; 42 | 43 | let query = '', postBody = ''; 44 | if (verb === 'GET') 45 | query = '?' + qs.stringify(data); 46 | else 47 | // Pre-compute the postBody so we can be sure that we're using *exactly* the same body in the request 48 | // and in the signature. If you don't do this, you might get differently-sorted keys and blow the signature. 49 | postBody = JSON.stringify(data); 50 | 51 | const headers = { 52 | 'content-type': 'application/json', 53 | 'accept': 'application/json', 54 | // This example uses the 'expires' scheme. You can also use the 'nonce' scheme. 55 | // See https://www.bitmex.com/app/apiKeysUsage for more details. 56 | }; 57 | 58 | if (this.options.apiKeyID && this.options.apiKeySecret) { 59 | const expires = new Date().getTime() + (60 * 1000); // 1 min in the future 60 | const signature = crypto.createHmac('sha256', this.options.apiKeySecret) 61 | .update(verb + apiRoot + endpoint + query + expires + postBody).digest('hex'); 62 | headers['api-expires'] = expires; 63 | headers['api-key'] = this.options.apiKeyID; 64 | headers['api-signature'] = signature; 65 | } 66 | 67 | const requestOptions = { 68 | method: verb, 69 | headers, 70 | }; 71 | if (verb !== 'GET') requestOptions.body = postBody; // GET/HEAD requests can't have body 72 | 73 | const apiBase = this.options.testnet ? 'https://testnet.bitmex.com' : 'https://www.bitmex.com'; 74 | const url = apiBase + apiRoot + endpoint + query; 75 | 76 | return fetch(url, requestOptions).then(response => response.json()).then( 77 | response => { 78 | if ('error' in response) 79 | throw new Error(`${response.error.message} during ${verb} ${endpoint} with ${JSON.stringify(data)}`); 80 | return response; 81 | }, error => { 82 | throw new Error(error); 83 | }, 84 | ); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bitmex-plus 2 | 3 | This package provides several helper methods for the [REST](https://www.bitmex.com/app/restAPI) and [WebSocket](https://www.bitmex.com/app/wsAPI) BitMEX APIs. You can think of it as a lightweight, [easy to audit](https://github.com/ccxt/ccxt/issues/943), combination of `ccxt` (which it doesn't use) and the official `bitmex-realtime-api`. 4 | 5 | Features: 6 | 7 | * minimal dependencies 8 | * both authenticated and unauthenticated REST requests 9 | * real-time WebSocket API wrappers around the official [bitmex-realtime-api](https://github.com/BitMEX/api-connectors/tree/master/official-ws/nodejs) library 10 | 11 | The module works in Node, but not in the browser, because BitMEX doesn't serve CORS headers on the API. 12 | 13 | # Usage 14 | 15 | npm install bitmex-plus 16 | 17 | See the [bitmex-realtime-api](https://github.com/BitMEX/api-connectors/tree/master/official-ws/nodejs#new-bitmexclientobject-options) documentation for parameters. 18 | 19 | ```js 20 | import { BitMexPlus } from 'bitmex-plus'; 21 | 22 | const bitmex = new BitMexPlus({ 23 | apiKeyID: '...', 24 | apiKeySecret: '...', 25 | }); 26 | ``` 27 | 28 | The API key constructor parameters are optional. You only need to specify them if you make authenticated requests. 29 | 30 | The [bitmex-realtime-api](https://github.com/BitMEX/api-connectors/tree/master/official-ws/nodejs) library that this module wraps will automatically connect to the web socket, so your script won't exit until all listeners are removed. If you only make REST requests, or when you're done with the WebSocket API, you can simply call `process.exit(0)`. 31 | 32 | 33 | # Methods 34 | 35 | ## makeRequest(verb, endpoint, data) 36 | 37 | Make a GET/PUT/POST/DELETE request to the REST API. See the [API explorer](https://www.bitmex.com/api/explorer/) for available endpoints and parameters. 38 | 39 | Sample unauthenticated request to get the bid/ask [over the last minute](https://www.bitmex.com/api/explorer/#!/Quote/Quote_getBucketed): 40 | 41 | ```js 42 | import { BitMexPlus } from 'bitmex-plus'; 43 | 44 | const bitmex = new BitMexPlus(); 45 | 46 | (async function () => { 47 | const [bucket] = (await bitmex.makeRequest('GET', 'quote/bucketed', { 48 | binSize: '1m', 49 | symbol: 'XBTUSD', 50 | reverse: true, 51 | count: 1, 52 | columns: ['bidPrice', 'askPrice'], 53 | })); 54 | console.log(bucket); 55 | }()); 56 | 57 | process.exit(0); 58 | ``` 59 | 60 | Authenticated request to get your XBTUSD position: 61 | 62 | ```js 63 | import { BitMexPlus } from 'bitmex-plus'; 64 | 65 | const bitmex = new BitMexPlus({ 66 | // Get your API key at https://www.bitmex.com/app/apiKeys 67 | apiKeyID: 'REPLACE_ME', 68 | apiKeySecret: 'REPLACE_ME', 69 | }); 70 | 71 | (async function () { 72 | const [pos] = (await bitmex.makeRequest('GET', 'position', { 73 | filter: { symbol: 'XBTUSD' }, // remove to get all positions 74 | // limit returned columns, except for several that are always returned: 75 | // account, symbol, currency, timestamp, simpleQty and markPrice 76 | columns: ['currentQty', 'liquidationPrice'], })); 77 | console.log(pos); 78 | }()); 79 | 80 | process.exit(0) 81 | ``` 82 | 83 | ## monitorStream(symbol, table, callback) 84 | 85 | [Add a stream](https://github.com/BitMEX/api-connectors/tree/master/official-ws/nodejs#clientaddstreamstring-symbol-string-tablename-function-callback) and call the callback for each new data item added to the table (e.g. each new trade). This provides more granular processing than the official library, which calls the callback for chunks of data of unspecified length. The callback is passed a `data` parameter (e.g. a trade object). 86 | 87 | Note that if you monitor the `orderBookL2` stream, the callback will be called only once, without any parameters. This is because with order book entries, you need to deal with the entire data array returned by [getData()](https://github.com/BitMEX/api-connectors/tree/master/official-ws/nodejs#clientgetdatastring-symbol-string-tablename), since orders might have been removed, changed, or inserted. 88 | 89 | ```js 90 | bitmex.monitorStream('XBTUSD', 'trade', data => console.log(data.price)); 91 | ``` 92 | 93 | # LICENSE 94 | 95 | MIT. Copyright 2018 [Ben Bomper](https://github.com/bomper). 96 | --------------------------------------------------------------------------------