lbank-connector 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +215 -0
- package/package.json +24 -0
- package/src/APIBase.js +134 -0
- package/src/Spot.js +25 -0
- package/src/WebSocketAPI.js +28 -0
- package/src/WebSocketAPIBase.js +129 -0
- package/src/constants.js +84 -0
- package/src/errors/LbankClientError.js +15 -0
- package/src/errors/LbankConnectorError.js +8 -0
- package/src/errors/MissingParameterError.js +12 -0
- package/src/index.js +6 -0
- package/src/modules/spot/Market.js +192 -0
- package/src/modules/spot/Subscribe.js +34 -0
- package/src/modules/spot/Trade.js +183 -0
- package/src/modules/spot/Wallet.js +152 -0
- package/src/modules/websocket/Account.js +23 -0
- package/src/modules/websocket/Market.js +80 -0
- package/src/modules/websocket/Trade.js +25 -0
- package/src/modules/websocket/WebSocketModuleBase.js +11 -0
- package/src/node.js +50 -0
- package/src/utils/defaultLogger.js +9 -0
- package/src/utils/isEmptyValue.js +11 -0
- package/src/utils/request.js +84 -0
- package/src/utils/validation.js +34 -0
package/README.md
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# LBank Public API connector NodeJS
|
|
2
|
+
|
|
3
|
+
This is a lightweight library that works as a connector to the [LBank public API](https://www.lbank.com/en-US/docs/index.html).
|
|
4
|
+
|
|
5
|
+
It supports the following APIs:
|
|
6
|
+
|
|
7
|
+
- Spot Rest API;
|
|
8
|
+
- Spot WebSocket API;
|
|
9
|
+
|
|
10
|
+
Additionally, it includes test cases and examples.
|
|
11
|
+
|
|
12
|
+
## Documentation
|
|
13
|
+
|
|
14
|
+
[https://www.lbank.com/en-US/docs/index.html](https://www.lbank.com/en-US/docs/index.html)
|
|
15
|
+
|
|
16
|
+
## Examples
|
|
17
|
+
|
|
18
|
+
The examples are located under **examples**. Before running any of it, `config.js` must be set up correctly with `API_KEY` and` SECRET_KEY` and `SIGN_METHOD` .
|
|
19
|
+
|
|
20
|
+
Note that this `config.js` is only used for examples, you should have your own configuration file when using the library.
|
|
21
|
+
|
|
22
|
+
### REST APIs
|
|
23
|
+
|
|
24
|
+
#### Market Endpoint: Exchange Information
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
const { Spot } = require('@lbankcom/lbank-connector')
|
|
28
|
+
|
|
29
|
+
const BASE_URL = ''
|
|
30
|
+
|
|
31
|
+
const client = new Spot({
|
|
32
|
+
baseURL: BASE_URL
|
|
33
|
+
})
|
|
34
|
+
const result = client.createMarket().bookTicker({})
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
#### Trade Endpoint: Testing a new order
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
const { Spot } = require('@lbankcom/lbank-connector')
|
|
41
|
+
const { Console } = require('console')
|
|
42
|
+
|
|
43
|
+
const logger = new Console({
|
|
44
|
+
stdout: process.stdout,
|
|
45
|
+
stderr: process.stderr
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const BASE_URL = ''
|
|
49
|
+
const API_KEY = ''
|
|
50
|
+
const SECRET_KEY = ''
|
|
51
|
+
const SIGN_METHOD = ''
|
|
52
|
+
|
|
53
|
+
const spot = new Spot({
|
|
54
|
+
// REST API baseURL, see: https://www.lbank.com/en-US/docs/index.html#url
|
|
55
|
+
baseURL: BASE_URL,
|
|
56
|
+
// Get api key & secretKey from: https://www.lbank.com/zh-TW/my/api-management
|
|
57
|
+
apiKey: API_KEY,
|
|
58
|
+
secretKey: SECRET_KEY,
|
|
59
|
+
// Signature method: 'RSA' | 'HmacSHA256'.
|
|
60
|
+
signMethod: SIGN_METHOD,
|
|
61
|
+
logger
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
return (
|
|
65
|
+
spot
|
|
66
|
+
// Create a trade endpoints
|
|
67
|
+
.createTrade()
|
|
68
|
+
.createOrderTest({
|
|
69
|
+
symbol: 'eth_btc',
|
|
70
|
+
type: 'buy',
|
|
71
|
+
price: 100,
|
|
72
|
+
amount: 10
|
|
73
|
+
})
|
|
74
|
+
.then(res => {
|
|
75
|
+
logger.debug(res.data)
|
|
76
|
+
})
|
|
77
|
+
.catch(e => {
|
|
78
|
+
logger.error(res.data)
|
|
79
|
+
})
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Please find `examples` folder to check for more endpoints.
|
|
84
|
+
|
|
85
|
+
#### Custom Logger Integration
|
|
86
|
+
|
|
87
|
+
```javascript
|
|
88
|
+
const { Spot } = require('@lbankcom/lbank-connector')
|
|
89
|
+
const fs = require('fs')
|
|
90
|
+
const { Console } = require('console')
|
|
91
|
+
|
|
92
|
+
// make sure the logs/ folder is created beforehand
|
|
93
|
+
const output = fs.createWriteStream('./logs/stdout.log')
|
|
94
|
+
const errorOutput = fs.createWriteStream('./logs/stderr.log')
|
|
95
|
+
|
|
96
|
+
const logger = new Console({ stdout: output, stderr: errorOutput })
|
|
97
|
+
const client = new Spot('', '', { logger: logger })
|
|
98
|
+
|
|
99
|
+
client
|
|
100
|
+
.creatMarket()
|
|
101
|
+
.currencyPairs()
|
|
102
|
+
.then(response => client.logger.log(response.data))
|
|
103
|
+
// check the output file
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### WebSocket API
|
|
107
|
+
|
|
108
|
+
```js
|
|
109
|
+
const { Console } = require('console')
|
|
110
|
+
|
|
111
|
+
const logger = new Console({
|
|
112
|
+
stdout: process.stdout,
|
|
113
|
+
stderr: process.stderr
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
const WS_API_URL = ''
|
|
117
|
+
|
|
118
|
+
const webSocketAPI = new WebSocketAPI(WS_API_URL, {
|
|
119
|
+
logger,
|
|
120
|
+
open() {
|
|
121
|
+
webSocketAPI.ping()
|
|
122
|
+
},
|
|
123
|
+
message(msg) {
|
|
124
|
+
logger.info(msg)
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
setTimeout(() => {
|
|
129
|
+
logger.info('disconnect')
|
|
130
|
+
webSocketAPI.disconnect()
|
|
131
|
+
}, 100000)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
If `requestId` is empty (`""`), `null` or not sent, this library will generate a `UUID` string for it.
|
|
135
|
+
|
|
136
|
+
Different types of WebSocket callbacks are available.
|
|
137
|
+
|
|
138
|
+
#### Auto Reconnect
|
|
139
|
+
|
|
140
|
+
If there is a close event not initiated by the user, the reconnection mechanism will be triggered in 5 secs.
|
|
141
|
+
|
|
142
|
+
#### Ping Server
|
|
143
|
+
|
|
144
|
+
It is possible to ping server from client, and expect to receive a PONG message.
|
|
145
|
+
|
|
146
|
+
```javascript
|
|
147
|
+
webSocketAPI.ping()
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Features
|
|
151
|
+
|
|
152
|
+
### Optional parameters
|
|
153
|
+
|
|
154
|
+
Parameters can be set in any implementation of `{}` interface, where `string` represents the parameter name and `Object` the parameter value. These parameters should have the same naming as in the API doc."
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
const parameters = {
|
|
158
|
+
symbol: 'eth_btc',
|
|
159
|
+
type: 'buy',
|
|
160
|
+
price: 100,
|
|
161
|
+
amount: 10
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Types of Signature Generator
|
|
166
|
+
|
|
167
|
+
When creating `SpotClient` you use one of the following types of Signature to create signatures (for SIGNED endpoints) based on your security preference:
|
|
168
|
+
|
|
169
|
+
- `HmacSHA256` - Use of API Key and Secret Key.
|
|
170
|
+
|
|
171
|
+
```js
|
|
172
|
+
const client = new Spot({
|
|
173
|
+
baseURL: config.BASE_URL,
|
|
174
|
+
apiKey: config.API_KEY,
|
|
175
|
+
secretKey: config.SECRET_KEY,
|
|
176
|
+
signMethod: 'HmacSHA256'
|
|
177
|
+
})
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
- `RSA` - Use of API Key and RSA algorithm keys.
|
|
181
|
+
|
|
182
|
+
```js
|
|
183
|
+
const client = new Spot({
|
|
184
|
+
baseURL: config.BASE_URL,
|
|
185
|
+
apiKey: config.API_KEY,
|
|
186
|
+
secretKey: config.SECRET_KEY,
|
|
187
|
+
signMethod: 'RSA'
|
|
188
|
+
})
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Errors
|
|
192
|
+
|
|
193
|
+
There are 2 types of error which may be thrown by this library.
|
|
194
|
+
|
|
195
|
+
- `MissingParameterError`
|
|
196
|
+
- This is thrown when there is a validation error for parameters.For instance, mandatory parameter not sent. This error will be thrown before the request is sent to the server.
|
|
197
|
+
- `LbankClientError`
|
|
198
|
+
- The error consists of these 3 objects which will help in debugging the error:
|
|
199
|
+
- `errorCode` - API Server's error code, e.g. `-10000`
|
|
200
|
+
|
|
201
|
+
```js
|
|
202
|
+
client
|
|
203
|
+
.createTrade()
|
|
204
|
+
.createOrderTest(parameters)
|
|
205
|
+
.then(res => {
|
|
206
|
+
logger.info(result)
|
|
207
|
+
})
|
|
208
|
+
.catch(e => {
|
|
209
|
+
logger.error(e)
|
|
210
|
+
})
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
## Test Cases
|
|
214
|
+
|
|
215
|
+
`npm run test`
|
package/package.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "lbank-connector",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "This is a lightweight library that works as a connector to the LBank public API.",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
8
|
+
"preinstall": "node ./src/node.js"
|
|
9
|
+
},
|
|
10
|
+
"author": "LBank",
|
|
11
|
+
"license": "ISC",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "https://github.com/LBank-exchange/lbank-connector-nodejs.git"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"LBank",
|
|
18
|
+
"API"
|
|
19
|
+
],
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/LBank-exchange/lbank-connector-nodejs/issues"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/LBank-exchange/lbank-connector-nodejs#readme"
|
|
24
|
+
}
|
package/src/APIBase.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto')
|
|
4
|
+
const {
|
|
5
|
+
removeEmptyValue,
|
|
6
|
+
buildQueryString,
|
|
7
|
+
sendRequest,
|
|
8
|
+
randomString,
|
|
9
|
+
encodeUrlParameters
|
|
10
|
+
} = require('./utils/request')
|
|
11
|
+
const LbankConnectorError = require('./errors/LbankConnectorError')
|
|
12
|
+
const { SignMethod } = require('./constants')
|
|
13
|
+
const defaultLogger = require('./utils/defaultLogger')
|
|
14
|
+
|
|
15
|
+
class APIBase {
|
|
16
|
+
constructor ({
|
|
17
|
+
apiKey,
|
|
18
|
+
secretKey,
|
|
19
|
+
baseURL,
|
|
20
|
+
logger,
|
|
21
|
+
timeout,
|
|
22
|
+
proxy,
|
|
23
|
+
httpsAgent,
|
|
24
|
+
signMethod
|
|
25
|
+
}) {
|
|
26
|
+
this.logger = logger || defaultLogger()
|
|
27
|
+
this.options = {
|
|
28
|
+
apiKey,
|
|
29
|
+
secretKey,
|
|
30
|
+
baseURL,
|
|
31
|
+
// default is 0 (no timeout)
|
|
32
|
+
timeout: timeout || 0,
|
|
33
|
+
proxy: proxy || false,
|
|
34
|
+
httpsAgent,
|
|
35
|
+
signMethod: signMethod || SignMethod.RSA,
|
|
36
|
+
logger: this.logger
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
sendPublicRequest (method, path, params = {}) {
|
|
41
|
+
params = removeEmptyValue(params)
|
|
42
|
+
params = buildQueryString(params)
|
|
43
|
+
if (params !== '') {
|
|
44
|
+
path = `${path}?${params}`
|
|
45
|
+
}
|
|
46
|
+
const { options } = this
|
|
47
|
+
return sendRequest({
|
|
48
|
+
method,
|
|
49
|
+
baseURL: options.baseURL,
|
|
50
|
+
url: path,
|
|
51
|
+
timeout: options.timeout,
|
|
52
|
+
proxy: options.proxy,
|
|
53
|
+
httpsAgent: options.httpsAgent
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Send a signed request (apiKey, secretKey, and signMethod parameters are required when instantiating the class).
|
|
59
|
+
* @param {string} method 请求方法 GET, POST
|
|
60
|
+
* @param {string} path 请求路径
|
|
61
|
+
* @param {Object} [params] 请求参数
|
|
62
|
+
*/
|
|
63
|
+
sendSignRequest (method, path, params = {}) {
|
|
64
|
+
params = removeEmptyValue(params)
|
|
65
|
+
const { options } = this
|
|
66
|
+
const timestamp = Date.now()
|
|
67
|
+
const echostr = randomString()
|
|
68
|
+
const queryString = buildQueryString({
|
|
69
|
+
...params,
|
|
70
|
+
timestamp,
|
|
71
|
+
echostr,
|
|
72
|
+
signature_method: options.signMethod,
|
|
73
|
+
api_key: options.apiKey
|
|
74
|
+
})
|
|
75
|
+
const md5 = crypto.createHash('md5')
|
|
76
|
+
const preparedStr = md5.update(queryString).digest('hex').toUpperCase()
|
|
77
|
+
let signature
|
|
78
|
+
|
|
79
|
+
if (options.signMethod === SignMethod.HmacSHA256) {
|
|
80
|
+
signature = crypto
|
|
81
|
+
.createHmac('sha256', options.secretKey)
|
|
82
|
+
.update(preparedStr)
|
|
83
|
+
.digest('hex')
|
|
84
|
+
} else {
|
|
85
|
+
if (options.signMethod === SignMethod.RSA) {
|
|
86
|
+
const NodeRSA = require('node-rsa')
|
|
87
|
+
|
|
88
|
+
const key = new NodeRSA({
|
|
89
|
+
b: 1024
|
|
90
|
+
})
|
|
91
|
+
key.importKey(options.secretKey, 'pkcs8')
|
|
92
|
+
key.setOptions({ signingScheme: 'sha256' })
|
|
93
|
+
signature = key.sign(Buffer.from(preparedStr), 'base64')
|
|
94
|
+
|
|
95
|
+
// signature = crypto
|
|
96
|
+
// .sign("RSA-SHA256", Buffer.from(preparedStr), Buffer.from(options.secretKey,options.secretKey))
|
|
97
|
+
// .toString("base64");
|
|
98
|
+
} else {
|
|
99
|
+
throw new LbankConnectorError(
|
|
100
|
+
"signMethod must be either 'RSA' or 'HmacSHA256'"
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const data = {
|
|
106
|
+
...encodeUrlParameters(params),
|
|
107
|
+
api_key: options.apiKey,
|
|
108
|
+
sign: signature
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// this.logger.info(queryString, preparedStr, data, {
|
|
112
|
+
// timestamp,
|
|
113
|
+
// echostr,
|
|
114
|
+
// signature_method: options.signMethod,
|
|
115
|
+
// });
|
|
116
|
+
|
|
117
|
+
return sendRequest({
|
|
118
|
+
method,
|
|
119
|
+
baseURL: options.baseURL,
|
|
120
|
+
url: `${path}`,
|
|
121
|
+
headers: {
|
|
122
|
+
timestamp,
|
|
123
|
+
echostr,
|
|
124
|
+
signature_method: options.signMethod
|
|
125
|
+
},
|
|
126
|
+
data,
|
|
127
|
+
timeout: options.timeout,
|
|
128
|
+
proxy: options.proxy,
|
|
129
|
+
httpsAgent: options.httpsAgent
|
|
130
|
+
})
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
module.exports = APIBase
|
package/src/Spot.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const APIBase = require('./APIBase')
|
|
2
|
+
const Market = require('./modules/spot/Market')
|
|
3
|
+
const Subscribe = require('./modules/spot/Subscribe')
|
|
4
|
+
const Trade = require('./modules/spot/Trade')
|
|
5
|
+
const Wallet = require('./modules/spot/Wallet')
|
|
6
|
+
|
|
7
|
+
class Spot extends APIBase {
|
|
8
|
+
createMarket () {
|
|
9
|
+
return new Market(this.options)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
createWallet () {
|
|
13
|
+
return new Wallet(this.options)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
createTrade () {
|
|
17
|
+
return new Trade(this.options)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
createSubscribe () {
|
|
21
|
+
return new Subscribe(this.options)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
module.exports = Spot
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const WebSocketAPIBase = require('./WebSocketAPIBase')
|
|
2
|
+
const Market = require('./modules/websocket/Market')
|
|
3
|
+
const Account = require('./modules/websocket/Account')
|
|
4
|
+
const Trade = require('./modules/websocket/Trade')
|
|
5
|
+
const { randomString } = require('./utils/request')
|
|
6
|
+
|
|
7
|
+
class WebSocketAPI extends WebSocketAPIBase {
|
|
8
|
+
market () {
|
|
9
|
+
return new Market(this)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
account () {
|
|
13
|
+
return new Account(this)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
trade () {
|
|
17
|
+
return new Trade(this)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
ping (id = randomString()) {
|
|
21
|
+
this.sendMessage({
|
|
22
|
+
action: 'ping',
|
|
23
|
+
ping: id
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
module.exports = WebSocketAPI
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
const WebSocketClient = require('ws')
|
|
2
|
+
const defaultLogger = require('./utils/defaultLogger')
|
|
3
|
+
|
|
4
|
+
class WebSocketAPIBase {
|
|
5
|
+
constructor (baseUrl, options = {}) {
|
|
6
|
+
this.baseUrl = baseUrl
|
|
7
|
+
this.logger = options.logger || defaultLogger()
|
|
8
|
+
this.events = {
|
|
9
|
+
open: options.open,
|
|
10
|
+
message: options.message,
|
|
11
|
+
ping: options.ping,
|
|
12
|
+
pong: options.pong,
|
|
13
|
+
error: options.error,
|
|
14
|
+
close: options.close
|
|
15
|
+
}
|
|
16
|
+
this.reconnectDelay = options.reconnectDelay || 5000
|
|
17
|
+
if (options.autoConnect !== false) {
|
|
18
|
+
this.connect()
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
isConnected () {
|
|
23
|
+
return !(!this.ws || this.ws.readyState !== WebSocketClient.OPEN)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
isConnecting () {
|
|
27
|
+
return !!(this.ws && this.ws.readyState === WebSocketClient.CONNECTING)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
connect () {
|
|
31
|
+
const url = this.baseUrl
|
|
32
|
+
const ws = new WebSocketClient(url)
|
|
33
|
+
this.logger.info(`Sending Websocket connection to: ${url}`)
|
|
34
|
+
this.ws = ws
|
|
35
|
+
this.closeInitiated = false
|
|
36
|
+
|
|
37
|
+
ws.on('open', () => {
|
|
38
|
+
this.logger.info(`Connected to the Websocket Server: ${url}`)
|
|
39
|
+
this.events.open && this.events.open(this)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
// handle data message. Pass the data to the call back method from user
|
|
43
|
+
// It could be useful to store the original messages from server for debug
|
|
44
|
+
ws.on('message', data => {
|
|
45
|
+
const message = data.toString()
|
|
46
|
+
let obj
|
|
47
|
+
if (message.startsWith('{') && message.endsWith('}')) {
|
|
48
|
+
try {
|
|
49
|
+
obj = JSON.parse(message)
|
|
50
|
+
// 客户端收到PING消息后,需发送PONG消息回应
|
|
51
|
+
if (obj && obj.action === 'ping') {
|
|
52
|
+
this.logger.info('Send PONG to server', {
|
|
53
|
+
action: 'pong',
|
|
54
|
+
pong: obj.ping
|
|
55
|
+
})
|
|
56
|
+
this.sendMessage(
|
|
57
|
+
JSON.stringify({
|
|
58
|
+
action: 'pong',
|
|
59
|
+
pong: obj.ping
|
|
60
|
+
})
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
} catch (error) {
|
|
64
|
+
this.logger.error(error)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
this.events.message && this.events.message(obj || message)
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
ws.on('ping', () => {
|
|
71
|
+
// As ping pong is very important for maintaining the connection, log them as INFO level
|
|
72
|
+
this.logger.info('Received PING from server')
|
|
73
|
+
this.events.ping && this.events.ping()
|
|
74
|
+
ws.pong()
|
|
75
|
+
this.logger.info("Responded PONG to server's PING message")
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
ws.on('pong', () => {
|
|
79
|
+
this.logger.info('Received PONG from server')
|
|
80
|
+
this.events.pong && this.events.pong()
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
ws.on('error', err => {
|
|
84
|
+
this.logger.error('Received error from server')
|
|
85
|
+
this.events.error && this.events.error()
|
|
86
|
+
this.logger.error(err)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
ws.on('close', (closeEventCode, reason) => {
|
|
90
|
+
if (!this.closeInitiated) {
|
|
91
|
+
this.events.close && this.events.close()
|
|
92
|
+
this.logger.warn(
|
|
93
|
+
`Connection close due to ${closeEventCode}: ${reason}.`
|
|
94
|
+
)
|
|
95
|
+
this.reconnectTimer = setTimeout(() => {
|
|
96
|
+
this.reconnectTimer = null
|
|
97
|
+
this.logger.debug('Reconnect to the server.')
|
|
98
|
+
this.connect(url)
|
|
99
|
+
}, this.reconnectDelay || 5000)
|
|
100
|
+
} else {
|
|
101
|
+
this.closeInitiated = false
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
disconnect () {
|
|
107
|
+
if (this.reconnectTimer) {
|
|
108
|
+
clearTimeout(this.reconnectTimer)
|
|
109
|
+
this.reconnectTimer = null
|
|
110
|
+
}
|
|
111
|
+
if (!this.isConnected() && !this.isConnecting()) {
|
|
112
|
+
this.logger.warn('No connection to close.')
|
|
113
|
+
} else {
|
|
114
|
+
this.closeInitiated = true
|
|
115
|
+
this.ws.close()
|
|
116
|
+
this.logger.info('Disconnected with Lbank Websocket Server')
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
sendMessage (params = {}) {
|
|
121
|
+
if (!this.isConnected()) {
|
|
122
|
+
this.logger.warn('Send only can be sent when connection is ready.')
|
|
123
|
+
} else {
|
|
124
|
+
this.ws.send(typeof params === 'string' ? params : JSON.stringify(params))
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
module.exports = WebSocketAPIBase
|
package/src/constants.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const packageJson = require('../package.json')
|
|
4
|
+
|
|
5
|
+
const appName = packageJson.name + '-node'
|
|
6
|
+
const appVersion = packageJson.version
|
|
7
|
+
|
|
8
|
+
const SignMethod = {
|
|
9
|
+
RSA: 'RSA',
|
|
10
|
+
HmacSHA256: 'HmacSHA256'
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const HttpMethod = {
|
|
14
|
+
GET: 'GET',
|
|
15
|
+
POST: 'POST'
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const ErrorCode = {
|
|
19
|
+
'00000': 'return success',
|
|
20
|
+
10000: 'Internal error',
|
|
21
|
+
10001: 'The required parameters can not be empty',
|
|
22
|
+
10002: 'Validation Failed',
|
|
23
|
+
10003: 'Invalid parameter',
|
|
24
|
+
10004: 'Request too frequent',
|
|
25
|
+
10005: 'Secret key does not exist',
|
|
26
|
+
10006: 'User does not exist',
|
|
27
|
+
10007: 'Invalid signature',
|
|
28
|
+
10008: 'Invalid Trading Pair',
|
|
29
|
+
10009: 'Price and/or Amount are required for limit order',
|
|
30
|
+
10010: 'Price and/or Amount must less than minimum require',
|
|
31
|
+
10011: 'Buy at market price, price must be passed',
|
|
32
|
+
10012: 'Sell at market price, amount must be passed',
|
|
33
|
+
10013: 'Order quantity lower than minimum transaction quantity',
|
|
34
|
+
10014: 'Insufficient amount of money in account',
|
|
35
|
+
10015: 'Invalid order type',
|
|
36
|
+
10016: 'Insufficient account balance',
|
|
37
|
+
10017: 'Server Error',
|
|
38
|
+
10018: 'Page size should be between 1 and 50',
|
|
39
|
+
10019: 'Cancel NO more than 3 orders in one request',
|
|
40
|
+
10020: 'Volume < 0.001',
|
|
41
|
+
10021: 'Price < 0.01',
|
|
42
|
+
10022: 'Invalid authorization',
|
|
43
|
+
10023: 'Market Order is not supported yet',
|
|
44
|
+
10024: 'User cannot trade on this pair',
|
|
45
|
+
10025: 'Order has been filled',
|
|
46
|
+
10026: 'Order has been cancelld',
|
|
47
|
+
10027: 'Order is cancelling',
|
|
48
|
+
10028: 'Wrong query time',
|
|
49
|
+
10029: "'from' is not in the query time",
|
|
50
|
+
10030: "'from' do not match the transaction type of inqury",
|
|
51
|
+
10031: 'echostr length must be valid and length must be from 30 to 40',
|
|
52
|
+
10032: 'The order number does not exist',
|
|
53
|
+
10033: 'Failed to create order',
|
|
54
|
+
10036: 'customID duplicated',
|
|
55
|
+
10037: 'Order has been cancelled or completed',
|
|
56
|
+
10039: 'Order timeout cancellation',
|
|
57
|
+
10066: 'Please check the chain name',
|
|
58
|
+
10100: 'Has no privilege to withdraw',
|
|
59
|
+
10101: 'Invalid fee rate to withdraw',
|
|
60
|
+
10102: 'Too little to withdraw',
|
|
61
|
+
10103: 'Exceed daily limitation of withdraw',
|
|
62
|
+
10104: 'Cancel was rejected',
|
|
63
|
+
10105: 'Request has been cancelled',
|
|
64
|
+
10106: 'None trade time',
|
|
65
|
+
10107: 'Start price exception',
|
|
66
|
+
10108: 'can not create order',
|
|
67
|
+
10109: 'wallet address is not mapping',
|
|
68
|
+
10110: 'transfer fee is not mapping',
|
|
69
|
+
10111: 'mount > 0',
|
|
70
|
+
10112: 'fee is too lower',
|
|
71
|
+
10113: 'transfer fee is 0',
|
|
72
|
+
10114: 'Incorrect precision of withdrawal quantity',
|
|
73
|
+
10116: 'Upgrading in progress, please try again later',
|
|
74
|
+
10117: 'Station withdrawal not enabled',
|
|
75
|
+
10119: 'Interface upgrade, please use /v2/supplement/withdraw.do',
|
|
76
|
+
10120: 'Less than the minimum transaction limit',
|
|
77
|
+
10600: 'intercepted by replay attacks filter, check timestamp',
|
|
78
|
+
10601: 'Interface closed unavailable',
|
|
79
|
+
10701: 'invalid asset code',
|
|
80
|
+
10702: 'not allowed deposit',
|
|
81
|
+
10801: 'Withdrawal address whitelist verify failed'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = { SignMethod, HttpMethod, ErrorCode, appName, appVersion }
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const { ErrorCode } = require('../constants')
|
|
2
|
+
|
|
3
|
+
class LbankClientError extends Error {
|
|
4
|
+
constructor (errorCode, response) {
|
|
5
|
+
const message = ErrorCode[errorCode] || errorCode
|
|
6
|
+
super(message)
|
|
7
|
+
this.name = 'LbankClientError'
|
|
8
|
+
this.errorCode = errorCode
|
|
9
|
+
this.data = response.data
|
|
10
|
+
this.httpStatusCode = response.status
|
|
11
|
+
this.path = response.request?.path
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = LbankClientError
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
class MissingParameterError extends Error {
|
|
2
|
+
constructor (paramNames) {
|
|
3
|
+
super(
|
|
4
|
+
`One or more of required parameters is missing: ${
|
|
5
|
+
paramNames ? paramNames.slice().join(', ') : ''
|
|
6
|
+
} `
|
|
7
|
+
)
|
|
8
|
+
this.name = 'MissingParameterError'
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
module.exports = MissingParameterError
|