Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewBarba committed Oct 17, 2018
0 parents commit cd23345
Show file tree
Hide file tree
Showing 15 changed files with 1,541 additions and 0 deletions.
18 changes: 18 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = {
env: {
es6: true,
node: true,
mocha: true
},
extends: 'eslint:recommended',
parserOptions: {
ecmaVersion: '2018',
sourceType: 'module',
},
rules: {
'arrow-parens': ['error', 'as-needed'],
'comma-dangle': ['error', 'never'],
semi: ['error', 'never'],
strict: ['error', 'never']
}
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
node_modules
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Change Log
==========

`bitmex-node` follows [Semantic Versioning](http://semver.org/)

---

## [1.0.0](https://github.com/AndrewBarba/bitmex-node/releases/tag/1.0.0)

Initial release
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 AndrewBarba

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# bitmex-node

[![wercker status](https://app.wercker.com/status/feb7e7d87d5a4a29ea9c04b4a1350a44/s/master "wercker status")](https://app.wercker.com/project/byKey/feb7e7d87d5a4a29ea9c04b4a1350a44)

A full-featured Bitmex API client for Node.js

- [x] Realtime and Rest clients
- [x] 100% unit-test coverage
- [x] Heavily documented
- [x] Promise based with async/await

If you're using the Bitmex REST API, I can assure you this is the only library worth using. Here's why:

- It doesn't make you parse the Bitmex response and look for errors
- It properly parses all timestamps to JavaScript Date objects
- It uses proper JavaScript and Node conventions
- It throws proper errors when parameters are missing
- It uses a single https client with Keep-Alive enabled
- It's faster than every other node Bitmex library

## Initialize Client

#### Combined

```javascript
const Bitmex = require('bitmex-node')

let bitmex = new Bitmex({
apiKey: '12345',
apiSecret: 'abcde'
})

bitmex.rest.request(...)

bitmex.realtime.on('message', () => {})
```

#### Seperately

```javascript
const bitmex = require('bitmex-node')

let restClient = new bitmex.RestClient({
apiKey: '12345',
apiSecret: 'abcde'
})

let realtimeClient = new bitmex.RealtimeClient({
apiKey: '12345',
apiSecret: 'abcde'
})
```
41 changes: 41 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "bitmex-node",
"version": "1.0.0",
"description": "Bitmex API client for Node.js",
"author": "Andrew Barba <[email protected]>",
"license": "MIT",
"main": "src/index.js",
"engines": {
"node": ">=8.10.0"
},
"keywords": [
"bitmex",
"crypto",
"exchange",
"rest",
"nodejs",
"axios",
"https",
"rest",
"realtime",
"websocket"
],
"repository": {
"url": "https://github.com/AndrewBarba/bitmex-node"
},
"dependencies": {
"axios": "0.18.0",
"bufferutil": "4.0.0",
"utf-8-validate": "5.0.1",
"ws": "6.1.0"
},
"devDependencies": {
"eslint": "5.7.0",
"mocha": "5.2.0",
"should": "13.2.3"
},
"scripts": {
"lint": "npx eslint ./",
"test": "npx mocha --exit --bail --slow 1000 --timeout 10000 ./test"
}
}
71 changes: 71 additions & 0 deletions src/bitmex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const RestClient = require('./rest-client')
const RealtimeClient = require('./realtime-client')

class Bitmex {

/**
* @static
* @param {RestClient} RestClient
*/
static get RestClient() {
return RestClient
}

/**
* @static
* @param {RealtimeClient} RealtimeClient
*/
static get RealtimeClient() {
return RealtimeClient
}

/**
* @constructor
*/
constructor() {
this._rest = new RestClient(...arguments)
this._realtime = new RealtimeClient(...arguments)
this._deadManInterval = null
}

/**
* @param {RestClient} rest
*/
get rest() {
return this._rest
}

/**
* @param {RealtimeClient} realtime
*/
get realtime() {
return this._realtime
}

/**
* @method startDeadMansSwitch
* @param {Number} [timeout=60000]
* @return {Promise}
*/
async startDeadMansSwitch(timeout = 60000) {
let interval = (timeout / 4)
let deadManRequest = () => this.realtime.request('cancelAllAfter', timeout)
this._deadManInterval = setInterval(deadManRequest, interval)
return deadManRequest()
}

/**
* @method stopDeadMansSwitch
* @param {Boolean} [keepOrders=false]
* @return {Promise}
*/
async stopDeadMansSwitch(keepOrders = false) {
clearInterval(this._deadManInterval)
this._deadManInterval = null
if (keepOrders) {
await this.realtime.request('cancelAllAfter', 0)
}
}
}

module.exports = Bitmex
23 changes: 23 additions & 0 deletions src/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const crypto = require('crypto')

/**
* @method sign
* @param {String} options.method
* @param {String} options.url
* @param {Number} options.expires
* @param {String} [options.body]
* @return {String}
*/
exports.requestSignature = (secret, { method, url, expires, body = '' }) => {
let hmac = crypto.createHmac('sha256', secret)
return hmac.update(`${method}${url}${expires}${body}`).digest('hex')
}

/**
* @method time
* @param {Number} [offset=60]
* @return {Number}
*/
exports.time = (offset = 60) => {
return parseInt(Date.now() / 1000) + offset
}
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('./bitmex')
150 changes: 150 additions & 0 deletions src/realtime-client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
const EventEmitter = require('events')
const WebSocket = require('ws')
const helpers = require('./helpers')

class RealtimeClient extends EventEmitter {

/**
* @constructor
* @param {String} options.apiKey
* @param {String} options.apiSecret
* @param {Boolean} [options.testnet=false]
*/
constructor({ apiKey, apiSecret, testnet = false } = {}) {
if (!apiKey) throw new Error('apiKey is required')
if (!apiSecret) throw new Error('apiSecret is required')
super()
this._apiKey = apiKey
this._apiSecret = apiSecret
this._testnet = testnet
this._pingInterval = null
this.connect()
}

/**
* @param {Number} readyState
*/
get readyState() {
if (!this._socket) return -1
return this._socket.readyState
}

/**
* @param {Boolean} isReady
*/
get isReady() {
return this.readyState === 1
}

/**
* @method connect
*/
connect() {
let url = this._testnet ? 'wss://testnet.bitmex.com/realtime' : 'wss://www.bitmex.com/realtime'
this._socket = new WebSocket(url)
this._socket.on('open', () => {
this.emit('ready')
if (this._apiKey) this.authenticate()
})
this._socket.on('close', () => this.emit('close'))
this._socket.on('error', () => this.emit('error'))
this._socket.on('message', text => this._onMessage(text))
}

/**
* @method disconnect
*/
disconnect() {
clearInterval(this._pingInterval)
this._socket.close()
this._socket = null
}

/**
* @private
* @method _onMessage
* @param {String} data
*/
_onMessage(text) {
let message
try {
message = JSON.parse(text)
} catch(error) {
return this.emit('message.error', { error })
}

this._touchPingInterval()

this.emit('message', message)

if (message.subscribe)
this.emit(`message.subscribe.${message.subscribe}`, message)

if (message.table)
this.emit(`message.table.${message.table}`, message)

if (message.error)
this.emit(`message.error`, message)

if (message.request)
this.emit(`message.request.${message.request.op}`, message)

if (message.request && message.request.op === 'authKeyExpires')
this.emit('authenticated', message)
}

/**
* @method authenticate
* @param {Number} [expires]
* @return {Promise}
*/
authenticate(expires = helpers.time()) {
let signature = helpers.requestSignature(this._apiSecret, { method: 'GET', url: '/realtime', expires })
return this.request('authKeyExpires', [this._apiKey, expires, signature])
}

/**
* @method subscribe
* @param {String} table
* @param {Function} callback
* @return {Promise}
*/
async subscribe(table, callback) {
let promise = new Promise((resolve, reject) => {
this.once(`message.subscribe.${table}`, result => {
if (!result.success) return reject(result)
this.on(`message.table.${table}`, callback)
resolve(result)
})
})
await this.request('subscribe', table)
return promise
}

/**
* @method request
* @param {String} op
* @param {Array|String} [args]
* @return {Promise}
*/
request(op, args = []) {
return new Promise((resolve, reject) => {
let data = JSON.stringify({ op, args })
this._socket.send(data, err => {
if (err) return reject(err)
resolve()
})
})
}

/**
* @private
* @method _touchPingInterval
*/
_touchPingInterval() {
clearInterval(this._pingInterval)
this._pingInterval = setInterval(() => this._socket.ping(), 5000)
}
}

module.exports = RealtimeClient
Loading

0 comments on commit cd23345

Please sign in to comment.