-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
382 lines (321 loc) · 11.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
var util = require('util'),
_ = require('underscore'),
request = require('request'),
crypto = require('crypto'),
VError = require('verror'),
md5 = require('MD5');
var OKCoin = function OKCoin(api_key, secret, server, timeout)
{
this.api_key = api_key;
this.secret = secret;
this.server = server || 'https://www.okcoin.com';
this.timeout = timeout || 20000;
};
var headers = {"User-Agent": "OKCoin Javascript API Client"};
OKCoin.prototype.privateRequest = function(method, params, callback)
{
var functionName = 'OKCoin.privateRequest()',
self = this;
if(!this.api_key || !this.secret)
{
var error = new VError('%s must provide api_key and secret to make this API request.', functionName);
return callback(error);
}
if(!_.isObject(params))
{
var error = new VError('%s second parameter %s must be an object. If no params then pass an empty object {}', functionName, params);
return callback(error);
}
if (!callback || typeof(callback) != 'function')
{
var error = new VError('%s third parameter needs to be a callback function', functionName);
return callback(error);
}
params.api_key = this.api_key;
params.sign = this.signMessage(params);
var options = {
url: this.server + '/api/v1/' + method + '.do',
method: 'POST',
headers: headers,
form: params
};
var requestDesc = util.format('%s request to url %s with method %s and params %s',
options.method, options.url, method, JSON.stringify(params));
executeRequest(options, requestDesc, callback);
};
/**
* This method returns a signature for a request as a md5-encoded uppercase string
* @param {Object} params The object to encode
* @return {String} The request signature
*/
OKCoin.prototype.signMessage = function getMessageSignature(params)
{
var formattedParams = formatParameters(params);
// append secret key value pair
formattedParams += '&secret_key=' + this.secret;
return md5(formattedParams).toUpperCase();
};
/**
* This method returns the parameters as key=value pairs separated by & sorted by the key
* @param {Object} params The object to encode
* @return {String} formatted parameters
*/
function formatParameters(params)
{
var sortedKeys = [],
formattedParams = '';
// sort the properties of the parameters
sortedKeys = _.keys(params).sort();
// create a string of key value pairs separated by '&' with '=' assignement
for (i = 0; i < sortedKeys.length; i++)
{
if (i != 0) {
formattedParams += '&';
}
formattedParams += sortedKeys[i] + '=' + params[sortedKeys[i]];
}
return formattedParams;
}
OKCoin.prototype.publicRequest = function(method, params, callback)
{
var functionName = 'OKCoin.publicRequest()';
if(!_.isObject(params))
{
var error = new VError('%s second parameter %s must be an object. If no params then pass an empty object {}', functionName, params);
return callback(error);
}
if (!callback || typeof(callback) != 'function')
{
var error = new VError('%s third parameter needs to be a callback function with err and data parameters', functionName);
return callback(error);
}
var url = this.server + '/api/v1/' + method + '.do';
var options = {
url: url,
method: 'GET',
headers: headers,
timeout: this.timeout,
qs: params,
json: {} // request will parse the json response into an object
};
var requestDesc = util.format('%s request to url %s with parameters %s',
options.method, options.url, JSON.stringify(params));
executeRequest(options, requestDesc, callback)
};
function executeRequest(options, requestDesc, callback)
{
var functionName = 'OKCoin.executeRequest()';
request(options, function(err, response, data)
{
var error = null, // default to no errors
returnObject = data;
if(err)
{
error = new VError(err, '%s failed %s', functionName, requestDesc);
error.name = err.code;
}
else if (response.statusCode < 200 || response.statusCode >= 300)
{
error = new VError('%s HTTP status code %s returned from %s', functionName,
response.statusCode, requestDesc);
error.name = response.statusCode;
}
else if (options.form)
{
try {
returnObject = JSON.parse(data);
}
catch(e) {
error = new VError(e, 'Could not parse response from server: ' + data);
}
}
// if json request was not able to parse json response into an object
else if (options.json && !_.isObject(data) )
{
error = new VError('%s could not parse response from %s\nResponse: %s', functionName, requestDesc, data);
}
if (_.has(returnObject, 'error_code'))
{
var errorMessage = mapErrorMessage(returnObject.error_code);
error = new VError('%s %s returned error code %s, message: "%s"', functionName,
requestDesc, returnObject.error_code, errorMessage);
error.name = returnObject.error_code;
}
callback(error, returnObject);
});
}
//
// Public Functions
//
OKCoin.prototype.getTicker = function getTicker(callback, symbol)
{
this.publicRequest('ticker', {symbol: symbol}, callback);
};
OKCoin.prototype.getDepth = function getDepth(callback, symbol, size, merge)
{
var params = {
symbol: symbol,
size: 200,
merge: 1
};
if (!_.isUndefined(size) ) params.size = size;
if (!_.isUndefined(merge) ) params.merge = merge;
this.publicRequest('depth', params, callback);
};
OKCoin.prototype.getTrades = function getTrades(callback, symbol, since)
{
var params = {symbol: symbol};
if (since) params.since = since;
this.publicRequest('trades', params, callback);
};
OKCoin.prototype.getKline = function getKline(callback, symbol, type, size, since)
{
var params = {symbol: symbol};
if (type) params.type = type;
if (size) params.size = size;
if (since) params.since = since;
this.publicRequest('kline', params, callback);
};
OKCoin.prototype.getLendDepth = function getLendDepth(callback, symbol)
{
this.publicRequest('kline', {symbol: symbol}, callback);
};
//
// Private Functions
//
OKCoin.prototype.getUserInfo = function getUserInfo(callback)
{
this.privateRequest('userinfo', {}, callback);
};
OKCoin.prototype.addTrade = function addTrade(callback, symbol, type, amount, price)
{
var params = {
symbol: symbol,
type: type
};
if (amount) params.amount = amount;
if (price) params.price = price;
this.privateRequest('trade', params, callback);
};
OKCoin.prototype.addBatchTrades = function addBatchTrades(callback, symbol, type, orders)
{
this.privateRequest('batch_trade', {
symbol: symbol,
type: type,
orders_data: orders
}, callback);
};
OKCoin.prototype.cancelOrder = function cancelOrder(callback, symbol, order_id)
{
this.privateRequest('cancel_order', {
symbol: symbol,
order_id: order_id
}, callback);
};
OKCoin.prototype.getOrderInfo = function getOrderInfo(callback, symbol, order_id)
{
this.privateRequest('order_info', {
symbol: symbol,
order_id: order_id
}, callback);
};
OKCoin.prototype.getOrdersInfo = function getOrdersInfo(callback, symbol, type, order_id)
{
this.privateRequest('orders_info', {
symbol: symbol,
type: type,
order_id: order_id
}, callback);
};
OKCoin.prototype.getAccountRecords = function getAccountRecords(callback, symbol, type, current_page, page_length)
{
this.privateRequest('account_records', {
symbol: symbol,
type: type,
current_page: current_page,
page_length: page_length
}, callback);
};
OKCoin.prototype.getTradeHistory = function getTradeHistory(callback, symbol, since)
{
this.privateRequest('trade_history', {
symbol: symbol,
since: since
}, callback);
};
OKCoin.prototype.getOrderHistory = function getOrderHistory(callback, symbol, status, current_page, page_length)
{
this.privateRequest('order_history', {
symbol: symbol,
status: status,
current_page: current_page,
page_length: page_length
}, callback);
};
OKCoin.prototype.addWithdraw = function addWithdraw(callback, symbol, chargefee, trade_pwd, withdraw_address, withdraw_amount)
{
this.privateRequest('withdraw', {
symbol: symbol,
chargefee: chargefee,
trade_pwd: trade_pwd,
withdraw_address: withdraw_address,
withdraw_amount: withdraw_amount
}, callback);
};
OKCoin.prototype.cancelWithdraw = function cancelWithdraw(callback, symbol, withdraw_id)
{
this.privateRequest('cancel_withdraw', {
symbol: symbol,
withdraw_id: withdraw_id
}, callback);
};
/**
* Maps the OKCoin error codes to error message
* @param {Integer} error_code OKCoin error code
* @return {String} error message
*/
function mapErrorMessage(error_code)
{
var errorCodes = {
10000: 'Required parameter can not be null',
10001: 'Requests are too frequent',
10002: 'System Error',
10003: 'Restricted list request, please try again later',
10004: 'IP restriction',
10005: 'Key does not exist',
10006: 'User does not exist',
10007: 'Signatures do not match',
10008: 'Illegal parameter',
10009: 'Order does not exist',
10010: 'Insufficient balance',
10011: 'Order is less than minimum trade amount',
10012: 'Unsupported symbol (not btc_usd or ltc_usd)',
10013: 'This interface only accepts https requests',
10014: 'Order price must be between 0 and 1,000,000',
10015: 'Order price differs from current market price too much',
10016: 'Insufficient coins balance',
10017: 'API authorization error',
10026: 'Loan (including reserved loan) and margin cannot be withdrawn',
10027: 'Cannot withdraw within 24 hrs of authentication information modification',
10028: 'Withdrawal amount exceeds daily limit',
10029: 'Account has unpaid loan, please cancel/pay off the loan before withdraw',
10031: 'Deposits can only be withdrawn after 6 confirmations',
10032: 'Please enabled phone/google authenticator',
10033: 'Fee higher than maximum network transaction fee',
10034: 'Fee lower than minimum network transaction fee',
10035: 'Insufficient BTC/LTC',
10036: 'Withdrawal amount too low',
10037: 'Trade password not set',
10040: 'Withdrawal cancellation fails',
10041: 'Withdrawal address not approved',
10042: 'Admin password error',
10100: 'User account frozen',
10216: 'Non-available API',
503: 'Too many requests (Http)'};
if (!errorCodes[error_code])
{
return 'Unknown OKCoin error code: ' + error_code;
}
return( errorCodes[error_code] );
}
module.exports = OKCoin;