1.1.6, add github action for publish, update readme, add snippets for orderbook usage

This commit is contained in:
TS
2020-07-21 11:28:05 +01:00
parent a1da0d617b
commit ddc2bd8f78
6 changed files with 177 additions and 84 deletions

16
.github/workflow-settings.json vendored Normal file
View File

@@ -0,0 +1,16 @@
{
"EXCLUDE_MESSAGES": [
"update package version",
"update packages",
"update wp version",
"trigger workflow",
"update TOC"
],
"PROJECT": "Backlog",
"ISSUE_COLUMN": "To do",
"PR_COLUMN": "In progress",
"PR_BODY_TITLE": "## Changes",
"TOC_FOLDING": "1",
"TOC_MAX_HEADER_LEVEL": "3",
"TOC_TITLE": "Summary"
}

61
.github/workflows/npmpublish.yml vendored Normal file
View File

@@ -0,0 +1,61 @@
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
name: Publish to NPM
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
#- run: npm ci
#- run: npm test
publish-npm:
needs: build
runs-on: ubuntu-latest
steps:
- name: Package Version Updated
uses: MontyD/package-json-updated-action@1.0.1
id: version-updated
with:
path: package.json
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/checkout@v2
if: steps.version-updated.outputs.has-updated
- uses: actions/setup-node@v1
if: steps.version-updated.outputs.has-updated
with:
node-version: 12
registry-url: https://registry.npmjs.org/
#- run: npm ci
- run: npm publish
if: steps.version-updated.outputs.has-updated
env:
NODE_AUTH_TOKEN: ${{secrets.npm_token}}
#publish-gpr:
#needs: build
#runs-on: ubuntu-latest
#steps:
#- uses: actions/checkout@v2
#- uses: actions/setup-node@v1
# with:
# node-version: 12
# registry-url: https://npm.pkg.github.com/
#- run: npm ci
#- run: npm publish
# env:
# NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}

View File

@@ -1,25 +1,24 @@
# @pxtrn/bybit-api # bybit-api [![npm version](https://img.shields.io/npm/v/bybit-api.svg)][1] [![npm size](https://img.shields.io/bundlephobia/min/bybit-api.svg)][1] [![npm downloads](https://img.shields.io/npm/dt/orderbooks.svg)][1]
[![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/bybit-api/badge)](https://www.codefactor.io/repository/github/tiagosiebler/bybit-api)
An unofficial node.js lowlevel wrapper for the Bybit Cryptocurrency Derivative [1]: https://www.npmjs.com/package/bybit-api
exchange API.
An unofficial node.js lowlevel wrapper for the Bybit Cryptocurrency Derivative exchange API. Forked from [@pxtrn/bybit-api](https://github.com/pixtron/bybit-api), due to low activity on fixes & improvements.
## Installation ## Installation
`npm install --save bybit-api`
`npm install --save @pxtrn/bybit-api`
## Usage ## Usage
Create API credentials at bybit (obviously you need to be logged in): Create API credentials at bybit (obviously you need to be logged in):
- [Livenet](https://bybit.com/app/user/api-management) - [Livenet](https://bybit.com/app/user/api-management)
- [Testnet](https://testnet.bybit.com/app/user/api-management) - [Testnet](https://testnet.bybit.com/app/user/api-management)
## Documentation
Most of the documentation is in [Bybit's official API docs](https://bybit-exchange.github.io/docs/inverse/#t-introduction). Most of this library's methods accept objects that directly correspond to expectations from Bybit's API docs.
### Rest client ### Rest client
```javascript
```js const {RestClient} = require('bybit-api');
const {RestClient} = require('@pxtrn/bybit-api');
const API_KEY = 'xxx'; const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy'; const PRIVATE_KEY = 'yyy';
@@ -37,11 +36,9 @@ client.changeUserLeverage({leverage: 4, symbol: 'ETHUSD'})
See rest client [api docs](./doc/rest-client.md) for further information. See rest client [api docs](./doc/rest-client.md) for further information.
### Websocket client ### Websocket client
```javascript
```js const {WebsocketClient} = require('bybit-api');
const {WebsocketClient} = require('@pxtrn/bybit-api');
const API_KEY = 'xxx'; const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy'; const PRIVATE_KEY = 'yyy';
@@ -78,7 +75,7 @@ See websocket client [api docs](./doc/websocket-client.md) for further informati
Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired: Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired:
```js ```js
const { RestClient, WebsocketClient, DefaultLogger } = require('@pxtrn/bybit-api'); const { RestClient, WebsocketClient, DefaultLogger } = require('bybit-api');
// Disable all logging on the silly level // Disable all logging on the silly level
DefaultLogger.silly = () => {}; DefaultLogger.silly = () => {};
@@ -89,11 +86,23 @@ const PRIVATE_KEY = 'yyy';
const ws = new WebsocketClient({key: API_KEY, secret: PRIVATE_KEY}, DefaultLogger); const ws = new WebsocketClient({key: API_KEY, secret: PRIVATE_KEY}, DefaultLogger);
``` ```
## Donations ## Contributions & Thanks
### Donations
If this library helps you to trade better on bybit, feel free to donate a coffee, #### pixtron
or create a bybit account using my [ref link](https://www.bybit.com/app/register?ref=j8q5l). This library was started by @pixtron. If this library helps you to trade better on bybit, feel free to donate a coffee to @pixtron or create a bybit account using his [ref link](https://www.bybit.com/app/register?ref=j8q5l).
- BTC `1Fh1158pXXudfM6ZrPJJMR7Y5SgZUz4EdF` - BTC `1Fh1158pXXudfM6ZrPJJMR7Y5SgZUz4EdF`
- ETH `0x21aEdeC53ab7593b77C9558942f0c9E78131e8d7` - ETH `0x21aEdeC53ab7593b77C9558942f0c9E78131e8d7`
- LTC `LNdHSVtG6UWsriMYLJR3qLdfVNKwJ6GSLF` - LTC `LNdHSVtG6UWsriMYLJR3qLdfVNKwJ6GSLF`
#### tiagosiebler
If you found this project interesting or useful, create accounts with my referral links:
- [Bybit](https://www.bybit.com/en-US/register?affiliate_id=9410&language=en-US&group_id=0&group_type=1)
- [Binance](https://www.binance.com/en/register?ref=20983262)
Or feed my coffee addiction using any of these:
- BTC: `1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk`
- ETH (ERC20): `0xd773d8e6a50758e1ada699bb6c4f98bb4abf82da`
### Contributions & Pull Requests
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.

View File

@@ -2,8 +2,6 @@
## Class: RestClient ## Class: RestClient
### new RestClient([key][, secret][, livenet][, options]) ### new RestClient([key][, secret][, livenet][, options])
- `key` {String} Bybit API Key - `key` {String} Bybit API Key
- `secret` {String} Bybit private key - `secret` {String} Bybit private key
@@ -12,11 +10,9 @@
- `recv_window` {Number} Optional, default 5000. Increase if recv errors are seen. - `recv_window` {Number} Optional, default 5000. Increase if recv errors are seen.
- `sync_interval_ms` {Number} Optional, default 3600000. Interval at which syncTime is performed. - `sync_interval_ms` {Number} Optional, default 3600000. Interval at which syncTime is performed.
If you only use the [public endpoints](#public-endpoints) you can ommit key and secret. If you only use the [public endpoints](#public-endpoints) you can omit key and secret.
### Private enpoints ### Private enpoints
#### async placeActiveOrder(params) #### async placeActiveOrder(params)
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-placev2active) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-placev2active)
@@ -126,12 +122,10 @@ Returns symbol information (such as tick size & min notional):
Returns the time offset in ms to the server time retrieved by [`async getServerTime`](#async-getservertime). Returns the time offset in ms to the server time retrieved by [`async getServerTime`](#async-getservertime).
If positive the time on the server is ahead of the clients time, if negative the time on the server is behind the clients time. If positive the time on the server is ahead of the clients time, if negative the time on the server is behind the clients time.
## Example ## Example
```js ```javascript
const {RestClient} = require('@pxtrn/bybit-api'); const {RestClient} = require('bybit-api');
const API_KEY = 'xxx'; const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy'; const PRIVATE_KEY = 'yyy';

View File

@@ -1,13 +1,10 @@
# Websocket API # Websocket API
## Class: WebsocketClient ## Class: WebsocketClient
The `WebsocketClient` inherits from `EventEmitter`. After establishing a The `WebsocketClient` inherits from `EventEmitter`. After establishing a
connection, the client sends heartbeats in regular intervalls, and reconnects connection, the client sends heartbeats in regular intervalls, and reconnects
to the server once connection has been lost. to the server once connection has been lost.
### new WebsocketClient([options][, logger]) ### new WebsocketClient([options][, logger])
- `options` {Object} Configuration options - `options` {Object} Configuration options
- `key` {String} Bybit API Key. Only needed if private topics are subscribed - `key` {String} Bybit API Key. Only needed if private topics are subscribed
@@ -34,32 +31,23 @@ to the server once connection has been lost.
``` ```
### ws.subscribe(topics) ### ws.subscribe(topics)
- `topics` {String|Array} Single topic as string or multiple topics as array of strings. - `topics` {String|Array} Single topic as string or multiple topics as array of strings.
Subscribe to one or multiple topics. See [available topics](#available-topics) Subscribe to one or multiple topics. See [available topics](#available-topics)
### ws.unsubscribe(topics) ### ws.unsubscribe(topics)
- `topics` {String|Array} Single topic as string or multiple topics as array of strings. - `topics` {String|Array} Single topic as string or multiple topics as array of strings.
Unsubscribe from one or multiple topics. Unsubscribe from one or multiple topics.
### ws.close() ### ws.close()
Close the connection to the server. Close the connection to the server.
### Event: 'open' ### Event: 'open'
Emmited when the connection has been opened for the first time. Emmited when the connection has been opened for the first time.
### Event: 'reconnected' ### Event: 'reconnected'
Emmited when the client has been opened after a reconnect. Emmited when the client has been opened after a reconnect.
### Event: 'update' ### Event: 'update'
- `message` {Object} - `message` {Object}
- `topic` {String} the topic for which the update occured - `topic` {String} the topic for which the update occured
- `data` {Array|Object} updated data (see docs for each [topic](#available-topics)). - `data` {Array|Object} updated data (see docs for each [topic](#available-topics)).
@@ -67,9 +55,7 @@ Emmited when the client has been opened after a reconnect.
Emmited whenever an update to a subscribed topic occurs. Emmited whenever an update to a subscribed topic occurs.
### Event: 'response' ### Event: 'response'
- `response` {Object} - `response` {Object}
- `success` {Bool} - `success` {Bool}
- `ret_msg` {String} empty if operation was successfull, otherwise error message. - `ret_msg` {String} empty if operation was successfull, otherwise error message.
@@ -80,108 +66,86 @@ Emmited whenever an update to a subscribed topic occurs.
Emited when the server responds to an operation sent by the client (usually after subscribing to a topic). Emited when the server responds to an operation sent by the client (usually after subscribing to a topic).
### Event: 'close' ### Event: 'close'
Emitted when the connection has been finally closed, after a call to `ws.close()` Emitted when the connection has been finally closed, after a call to `ws.close()`
### Event: 'reconnect' ### Event: 'reconnect'
Emitted when the connection has been closed, but the client will try to reconnect. Emitted when the connection has been closed, but the client will try to reconnect.
### Event: 'error' ### Event: 'error'
- `error` {Error} - `error` {Error}
Emitted when an error occurs. Emitted when an error occurs.
## Available Topics ## Available Topics
Generaly all [public](https://bybit-exchange.github.io/docs/inverse/#t-publictopics) and [private](https://bybit-exchange.github.io/docs/inverse/#t-privatetopics) Generaly all [public](https://bybit-exchange.github.io/docs/inverse/#t-publictopics) and [private](https://bybit-exchange.github.io/docs/inverse/#t-privatetopics)
topics are available. topics are available.
### Private topics ### Private topics
#### Positions of your account #### Positions of your account
All positions of your account. All positions of your account.
Topic: `position` Topic: `position`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketposition) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketposition)
#### Execution message #### Execution message
Execution message, whenever an order has been (partially) filled. Execution message, whenever an order has been (partially) filled.
Topic: `execution` Topic: `execution`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketexecution) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketexecution)
#### Update for your orders #### Update for your orders
Updates for your active orders Updates for your active orders
Topic: `order` Topic: `order`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketorder) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketorder)
#### Update for your conditional orders #### Update for your conditional orders
Updates for your active conditional orders Updates for your active conditional orders
Topic: `stop_order` Topic: `stop_order`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketstoporder) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketstoporder)
### Public topics ### Public topics
#### Candlestick chart #### Candlestick chart
Candlestick OHLC "candles" for selected symbol and interval. Candlestick OHLC "candles" for selected symbol and interval.
Example topic: `klineV2.BTCUSD.1m` Example topic: `klineV2.BTCUSD.1m`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketklinev2) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketklinev2)
#### Real-time trading information #### Real-time trading information
All trades as they occur. All trades as they occur.
Topic: `trade` Topic: `trade`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websockettrade) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websockettrade)
#### Daily insurance fund update #### Daily insurance fund update
Topic: `insurance` Topic: `insurance`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketinsurance) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketinsurance)
#### OrderBook of 25 depth per side #### OrderBook of 25 depth per side
OrderBook for selected symbol OrderBook for selected symbol
Example topic: `orderBookL2_25.BTCUSD` Example topic: `orderBookL2_25.BTCUSD`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketorderbook25) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketorderbook25)
#### OrderBook of 200 depth per side #### OrderBook of 200 depth per side
OrderBook for selected symbol OrderBook for selected symbol
Example topic: `orderBook_200.100ms.BTCUS` Example topic: `orderBook_200.100ms.BTCUS`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketorderbook200) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketorderbook200)
#### Latest information for symbol #### Latest information for symbol
Latest information for selected symbol Latest information for selected symbol
Example topic: `instrument_info.100ms.BTCUSD` Example topic: `instrument_info.100ms.BTCUSD`
[See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketinstrumentinfo) [See bybit documentation](https://bybit-exchange.github.io/docs/inverse/#t-websocketinstrumentinfo)
## Examples
## Example ### Klines
```javascript
```js const {WebsocketClient} = require('bybit-api');
const {WebsocketClient} = require('@pxtrn/bybit-api');
const API_KEY = 'xxx'; const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy'; const PRIVATE_KEY = 'yyy';
@@ -211,3 +175,49 @@ ws.on('error', function(err) {
console.error('ERR', err); console.error('ERR', err);
}); });
``` ```
### OrderBook Events
```javascript
const { WebsocketClient, DefaultLogger } = require('bybit-api');
const { OrderBooksStore, OrderBookLevel } = require('orderbooks');
const OrderBooks = new OrderBooksStore({ traceLog: true, checkTimestamps: false });
// connect to a websocket and relay orderbook events to handlers
DefaultLogger.silly = () => {};
const ws = new WebsocketClient({ livenet: true });
ws.on('update', message => {
if (message.topic.toLowerCase().startsWith('orderbook')) {
return handleOrderbookUpdate(message);
}
});
ws.subscribe('orderBookL2_25.BTCUSD');
// parse orderbook messages, detect snapshot vs delta, and format properties using OrderBookLevel
const handleOrderbookUpdate = message => {
const { topic, type, data, timestamp_e6 } = message;
const [ topicKey, symbol ] = topic.split('.');
if (type == 'snapshot') {
return OrderBooks.handleSnapshot(symbol, data.map(mapBybitBookSlice), timestamp_e6 / 1000, message).print();
}
if (type == 'delta') {
const deleteLevels = data.delete.map(mapBybitBookSlice);
const updateLevels = data.update.map(mapBybitBookSlice);
const insertLevels = data.insert.map(mapBybitBookSlice);
return OrderBooks.handleDelta(
symbol,
deleteLevels,
updateLevels,
insertLevels,
timestamp_e6 / 1000
).print();
}
}
// Low level map of exchange properties to expected local properties
const mapBybitBookSlice = level => {
return OrderBookLevel(level.symbol, +level.price, level.side, level.size);
};
```

View File

@@ -1,5 +1,5 @@
{ {
"name": "@pxtrn/bybit-api", "name": "bybit-api",
"version": "1.1.6", "version": "1.1.6",
"description": "An unofficial node.js lowlevel wrapper for the Bybit Cryptocurrency Derivative exchange API", "description": "An unofficial node.js lowlevel wrapper for the Bybit Cryptocurrency Derivative exchange API",
"main": "index.js", "main": "index.js",
@@ -8,7 +8,7 @@
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/pixtron/bybit-api.git" "url": "git+https://github.com/tiagosiebler/bybit-api.git"
}, },
"keywords": [ "keywords": [
"bybit", "bybit",
@@ -17,11 +17,14 @@
"rest" "rest"
], ],
"author": "Stefan Aebischer <os@pixtron.ch> (https://pixtron.ch)", "author": "Stefan Aebischer <os@pixtron.ch> (https://pixtron.ch)",
"contributors": [
"Tiago Siebler (https://github.com/tiagosiebler)"
]
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://github.com/pixtron/bybit-api/issues" "url": "https://github.com/tiagosiebler/bybit-api/issues"
}, },
"homepage": "https://github.com/pixtron/bybit-api#readme", "homepage": "https://github.com/tiagosiebler/bybit-api#readme",
"dependencies": { "dependencies": {
"request": "^2.88.0", "request": "^2.88.0",
"ws": "^7.1.2" "ws": "^7.1.2"