-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbtc2fiat.ts
75 lines (59 loc) · 2.04 KB
/
btc2fiat.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
export abstract class Exchange {
protected abstract getUrl(fiatSymbol: string) : string;
protected abstract parseResponse(data: any, fiatSymbol: string): number;
public async getValue(fiatSymbol: string): Promise<number> {
var response = await fetch(this.getUrl(fiatSymbol), {method: 'GET'});
var data = await response.json();
return this.parseResponse(data, fiatSymbol);
}
}
export class Binance extends Exchange {
private static _instance: Binance;
public static get Instance() {
return this._instance || (this._instance = new this());
}
private constructor() {
super();
}
getUrl(fiatSymbol: string) {
let shitcoinSymbol = fiatSymbol === 'USD' ? (fiatSymbol + 'T') : fiatSymbol;
return `https://api.binance.com/api/v3/avgPrice?symbol=BTC${shitcoinSymbol}`;
}
parseResponse(data: any, _: string): number {
return data['price'];
}
}
export class Coinbase extends Exchange {
private static _instance: Coinbase;
public static get Instance() {
return this._instance || (this._instance = new this());
}
private constructor() {
super();
}
getUrl(fiatSymbol: string) {
return `https://api.coinbase.com/v2/prices/spot?currency=${fiatSymbol}`;
}
parseResponse(data: any, _: string): number {
return data['data']['amount'];
}
}
export class Kraken extends Exchange {
private static _instance: Binance;
public static get Instance() {
return this._instance || (this._instance = new this());
}
private constructor() {
super();
}
getUrl(fiatSymbol: string) {
return `https://api.kraken.com/0/public/Ticker?pair=XBT${fiatSymbol}`;
}
parseResponse(data: any, fiatSymbol: string): number {
return data['result'][`XXBTZ${fiatSymbol}`]['c'][0];
}
}
const EXCHANGES: {[k: string]: Exchange} = {'binance': Binance.Instance, 'coinbase': Coinbase.Instance, 'kraken': Kraken.Instance};
export async function getValue(exchange: string = 'kraken', fiatSymbol = "USD") : Promise<number> {
return await EXCHANGES[exchange.toLowerCase()].getValue(fiatSymbol.toUpperCase());
}