-
Notifications
You must be signed in to change notification settings - Fork 18
/
BittrexApi.ts
241 lines (215 loc) · 5.83 KB
/
BittrexApi.ts
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
import CryptoJS from 'crypto-js';
import fetch, { Headers, Response } from 'node-fetch';
import {
Balance,
BalanceResponse,
Candle,
CandleInterval,
CandleResponse,
CreatedOrder,
Market,
MarketSummary,
MarketTicker,
MarketTickerResponse,
NewOrder
} from './types';
interface BittrexClientOptions {
baseUrl: string;
/**
* Option to use Bittrex credits for the order
* Orders with insufficient credits will fail
*/
useAwards: boolean;
}
/**
* https://bittrex.github.io/api/v3
*/
export default class BittrexApi {
apiKey: string;
apiSecret: string;
options: BittrexClientOptions;
constructor(apiKey: string, apiSecret: string) {
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.options = {
baseUrl: 'https://api.bittrex.com/v3',
useAwards: false
};
}
/**
* https://bittrex.github.io/api/v3#topic-Authentication
* @param uri
* @param method
* @param body
*/
fetchAuthenticated = async (
uri: string,
method: 'GET' | 'POST' | 'DELETE',
body?: {}
): Promise<Response> => {
const timestamp = new Date().getTime();
const content = body ? JSON.stringify(body) : '';
const contentHash = CryptoJS.SHA512(content).toString(CryptoJS.enc.Hex);
const preSign = [timestamp, uri, method, contentHash].join('');
const signature = CryptoJS.HmacSHA512(preSign, this.apiSecret).toString(
CryptoJS.enc.Hex
);
const headers = new Headers({
'Api-Key': this.apiKey,
'Api-Timestamp': `${timestamp}`,
'Api-Content-Hash': contentHash,
'Api-Signature': signature,
'Content-Type': 'application/json'
});
if (method === 'POST') {
return fetch(uri, {
headers,
method,
body: content
});
}
return fetch(uri, {
headers,
method
});
};
getBalance = async (currencySymbol: string): Promise<Balance> => {
const response = await this.fetchAuthenticated(
`${this.options.baseUrl}/balances/${currencySymbol}`,
'GET'
);
const data: BalanceResponse = await response.json();
return {
available: parseFloat(data.available),
currencySymbol: data.currencySymbol,
total: parseFloat(data.total),
updatedAt: new Date(data.updatedAt)
};
};
getBalances = async (): Promise<Balance[]> => {
const response = await this.fetchAuthenticated(
`${this.options.baseUrl}/balances`,
'GET'
);
const data: BalanceResponse[] = await response.json();
return data.map((d) => ({
available: parseFloat(d.available),
currencySymbol: d.currencySymbol,
total: parseFloat(d.total),
updatedAt: new Date(d.updatedAt)
}));
};
getMarket = async (marketSymbol: string): Promise<Market> => {
const response = await fetch(
`${this.options.baseUrl}/markets/${marketSymbol}`
);
return response.json();
};
getMarkets = async (): Promise<Market[]> => {
const response = await fetch(`${this.options.baseUrl}/markets`);
return response.json();
};
getMarketSummaries = async (): Promise<MarketSummary[]> => {
const response = await fetch(`${this.options.baseUrl}/markets/summaries`);
return response.json();
};
getMarketTicker = async (marketSymbol: string): Promise<MarketTicker> => {
const response = await fetch(
`${this.options.baseUrl}/markets/${marketSymbol}/ticker`
);
const data: MarketTickerResponse = await response.json();
return {
symbol: data.symbol,
askRate: parseFloat(data.askRate),
bidRate: parseFloat(data.bidRate),
lastTradeRate: parseFloat(data.lastTradeRate)
};
};
getCandles = async (
marketSymbol: string,
candleInterval: CandleInterval
): Promise<Candle[]> => {
const response = await fetch(
`${this.options.baseUrl}/markets/${marketSymbol}/candles/${candleInterval}/recent`
);
const data: CandleResponse[] = await response.json();
return data.map((d) => ({
close: parseFloat(d.close),
high: parseFloat(d.high),
low: parseFloat(d.low),
open: parseFloat(d.open),
quoteVolume: parseFloat(d.quoteVolume || '0'),
startsAt: new Date(d.startsAt),
volume: parseFloat(d.volume || '0')
}));
};
/**
* https://bittrex.github.io/api/v3#topic-Placing-Orders
* @param marketSymbol
* @param quantity
* @param limit
*/
buyLimit = async (
marketSymbol: string,
quantity: number,
limit: number
): Promise<CreatedOrder> => {
const body: NewOrder = {
direction: 'BUY',
marketSymbol,
quantity,
timeInForce: 'GOOD_TIL_CANCELLED',
type: 'LIMIT',
limit
};
const response = await this.fetchAuthenticated(
`${this.options.baseUrl}/orders`,
'POST',
body
);
return response.json();
};
/**
* https://bittrex.github.io/api/v3#topic-Placing-Orders
* @param marketSymbol
* @param quantity
* @param limit
*/
sellLimit = async (
marketSymbol: string,
quantity: number,
limit: number
): Promise<CreatedOrder> => {
const body: NewOrder = {
direction: 'SELL',
marketSymbol,
quantity,
timeInForce: 'FILL_OR_KILL',
type: 'LIMIT',
limit
};
const response = await this.fetchAuthenticated(
`${this.options.baseUrl}/orders`,
'POST',
body
);
return response.json();
};
/**
* Use this for reporting history
* @param USDT - total amount of USDT when you would sell all your assets now for LATEST price
* @param BTC - current market USDT price of BTC
*/
report = async (USDT: number, BTC: number) => {
await fetch('https://YOUR_URL_HERE', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({
totalBalance: Math.floor(USDT),
currentMarketBTC: Math.floor(BTC)
})
});
};
}