-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
92 lines (84 loc) · 2.65 KB
/
api.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
import bitvavo from "npm:bitvavo";
import { debug, log, LogType } from "./util.ts";
const APIKEY = Deno.env.get("APIKEY") || "";
const APISECRET = Deno.env.get("APISECRET") || "";
const b = new bitvavo().options({
APIKEY,
APISECRET,
ACCESSWINDOW: 10000,
RESTURL: "https://api.bitvavo.com/v2",
WSURL: "wss://ws.bitvavo.com/v2/",
DEBUGGING: debug,
});
interface BalanceResponse {
available: string;
}
interface PriceResponse {
price: string;
}
export async function sendBalanceAndPrice(socket: WebSocket): Promise<void> {
try {
const balance = await getBalance();
const price = await getPrice();
const message = { balance, price };
socket.send(JSON.stringify(message));
} catch (error) {
if (error instanceof Error) {
log(error.message, LogType.ERROR);
} else {
log(String(error), LogType.ERROR);
}
socket.close();
}
}
export async function getBalance(symbol: string = ""): Promise<BalanceResponse[] | BalanceResponse | undefined> {
try {
const response = await b.balance();
if (symbol) {
return response.find((r: { symbol: string; }) => r.symbol === symbol);
}
return response;
} catch (error) {
if (error instanceof Error) {
log(error.message, LogType.ERROR);
} else {
log(String(error), LogType.ERROR);
}
return undefined;
}
}
export async function getPrice(symbol: string = "BTC"): Promise<string | undefined> {
try {
const response: PriceResponse = await b.tickerPrice({ market: symbol + "-EUR" });
return response.price;
} catch (error) {
if (error instanceof Error) {
log(error.message, LogType.ERROR);
} else {
log(String(error), LogType.ERROR);
}
return undefined;
}
}
export async function getValue(symbol: string = ""): Promise<string | undefined> {
try {
const balance = await getBalance(symbol);
const price = await getPrice(symbol);
if (balance && price) {
if (Array.isArray(balance)) {
const totalAvailable = balance.reduce((acc, curr) => acc + Number(curr.available), 0);
return (totalAvailable * Number(price)).toFixed(2);
} else {
return (Number(balance?.available) * Number(price)).toFixed(2);
}
}
return undefined;
} catch (error) {
if (error instanceof Error) {
log(error.message, LogType.ERROR);
} else {
log(String(error), LogType.ERROR);
}
return undefined;
}
}