-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
248 lines (248 loc) · 8.7 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
"use strict";
/// <reference path="./index.d.ts" />
Object.defineProperty(exports, "__esModule", { value: true });
const buffer_1 = require("buffer");
const querystring = require("querystring");
const crypto_1 = require("crypto");
const request = require("request");
const cheerio = require("cheerio");
const VError = require("verror");
class BTCMarkets {
constructor(key, secret, server = 'https://api.btcmarkets.net', timeout = 20000) {
this.key = key;
this.secret = secret;
this.server = server;
this.timeout = timeout;
}
privateRequest(path, params = {}) {
if (!this.key || !this.secret) {
throw new VError('must provide key and secret to make this API request.');
}
let method = 'POST';
// HTTP GET is used instead of POST for endpoints
// under /account/ eg /account/balance or /account/{instrument}/{currency}/tradingfee
// or /fundtransfer/history
if (path.split('/')[1] === 'account' ||
path === '/fundtransfer/history') {
method = 'GET';
}
// milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date
const timestamp = (new Date()).getTime();
let message;
if (method === 'POST') {
message = path + "\n" +
timestamp + "\n" +
JSON.stringify(params);
}
else if (Object.keys(params).length > 0) {
message = path + "\n" +
querystring.stringify(params) + "\n" +
timestamp + "\n";
}
else {
message = path + "\n" +
timestamp + "\n";
}
const signer = crypto_1.createHmac('sha512', new buffer_1.Buffer(this.secret, 'base64'));
const signature = signer.update(message).digest('base64');
const headers = {
"User-Agent": "BTC Markets Javascript API Client",
"apikey": this.key,
"timestamp": timestamp,
"signature": signature
};
const options = {
url: this.server + path,
method: method,
headers: headers,
timeout: this.timeout,
json: params
};
if (method === 'GET') {
options.qs = params;
}
const requestDesc = `${options.method} request to url ${options.url} with message ${message}`;
return this.executeRequest(options, requestDesc);
}
publicRequest(instrument, currency, action, params) {
const headers = { "User-Agent": "BTC Markets Javascript API Client" };
const path = '/market/' + instrument + '/' + currency + '/' + action;
const options = {
url: this.server + path,
method: 'GET',
headers: headers,
timeout: this.timeout,
json: {},
qs: params
};
const requestDesc = `${options.method} request to url ${options.url} with parameters ${JSON.stringify(params)}`;
return this.executeRequest(options, requestDesc);
}
;
executeRequest(options, requestDesc) {
return new Promise((resolve, reject) => {
request(options, function (err, response, data) {
let error = null; // default to no errors
if (err) {
error = new VError(err, `failed ${requestDesc} with error message ${err.message}`);
error.name = err.code;
}
else if (response.statusCode < 200 || response.statusCode >= 300) {
error = new VError(`HTTP status code ${response.statusCode} returned from ${requestDesc}. Status message: ${response.statusMessage}`);
error.name = response.statusCode.toString();
}
else if (!data) {
error = new VError(`failed ${requestDesc}. No data returned.`);
}
// if request was not able to parse json response into an object
else if (data !== Object(data)) {
// try and parse HTML body form response
const $ = cheerio.load(data);
const responseBody = $('body').text();
if (responseBody) {
error = new VError(err, `Could not parse response body from ${requestDesc}\nResponse body: ${responseBody}`);
error.name = responseBody;
}
else {
error = new VError(err, `Could not parse json or HTML response from ${requestDesc}`);
}
}
else if (data.hasOwnProperty('success') && !data.success) {
error = new VError(`failed ${requestDesc}. Success: ${data.success}. Error message: ${data.errorMessage}`);
error.name = data.errorMessage;
}
if (error)
reject(error);
resolve(data);
});
});
}
//
// Public API functions
//
getTick(instrument, currency) {
// @ts-ignore
return this.publicRequest(instrument, currency, 'tick');
}
;
getOrderBook(instrument, currency) {
// @ts-ignore
return this.publicRequest(instrument, currency, 'orderbook');
}
;
getTrades(instrument, currency, since) {
// @ts-ignore
return this.publicRequest(instrument, currency, 'trades', {
since: since
});
}
;
//
// Private API functions
//
createOrder(instrument, currency, price = 0, // price is not needed if a market order
volume, orderSide, ordertype, clientRequestId = "", // if no client id then set to an empty string
triggerPrice) {
const params = {
currency: currency,
instrument: instrument,
price: ordertype == 'Market' ? 0 : price,
volume: volume,
orderSide: orderSide,
ordertype: ordertype,
clientRequestId: clientRequestId,
triggerPrice: triggerPrice
};
// @ts-ignore
return this.privateRequest('/order/create', params);
}
;
cancelOrders(orderIds) {
// @ts-ignore
return this.privateRequest('/order/cancel', {
orderIds: orderIds
});
}
;
getOrderDetail(orderIds) {
// @ts-ignore
return this.privateRequest('/order/detail', {
orderIds: orderIds
});
}
;
getOpenOrders(instrument, currency, limit = 10, since = null) {
// @ts-ignore
return this.privateRequest('/order/open', {
currency: currency,
instrument: instrument,
limit: limit,
since: since
});
}
;
getOrderHistory(instrument, currency, limit = 100, since = null) {
// @ts-ignore
return this.privateRequest('/order/history', {
currency: currency,
instrument: instrument,
limit: limit,
since: since
});
}
;
getTradeHistory(instrument, currency, limit = 100, since = null) {
// @ts-ignore
return this.privateRequest('/order/trade/history', {
currency: currency,
instrument: instrument,
limit: limit,
since: since
});
}
;
getAccountBalances() {
// @ts-ignore
return this.privateRequest('/account/balance');
}
;
getTradingFee(instrument, currency) {
// @ts-ignore
return this.privateRequest('/account/' + instrument + "/" + currency + "/" + 'tradingfee');
}
;
withdrawCrypto(amount, address, crypto) {
// @ts-ignore
return this.privateRequest('/fundtransfer/withdrawCrypto', {
amount: amount,
address: address,
currency: crypto
});
}
;
withdrawEFT(accountName, accountNumber, bankName, bsbNumber, amount) {
// @ts-ignore
return this.privateRequest('/fundtransfer/withdrawEFT', {
accountName: accountName,
accountNumber: accountNumber,
bankName: bankName,
bsbNumber: bsbNumber,
amount: amount,
currency: "AUD"
});
}
;
withdrawHistory(limit, since, indexForward) {
// @ts-ignore
return this.privateRequest('/fundtransfer/history', {
limit: limit,
since: since,
indexForward: indexForward
});
}
;
}
// used to convert decimal numbers to BTC Market integers. eg 0.001 BTC is 100000 when used in the BTC Markets API
BTCMarkets.numberConverter = 100000000; // one hundred million
exports.default = BTCMarkets;
//# sourceMappingURL=index.js.map