-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
121 lines (104 loc) · 2.35 KB
/
main.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
import * as CoinbasePro from 'coinbase-pro';
import axios from 'axios';
import { config } from 'dotenv';
config();
if (!process.env.PASSPHRASE) {
throw new Error('Missing process.env.PASSPHRASE');
}
if (!process.env.SECRET) {
throw new Error('Missing process.env.SECRET');
}
if (!process.env.API_KEY) {
throw new Error('Missing process.env.API_KEY');
}
const key = process.env.API_KEY;
const passphrase = process.env.PASSPHRASE;
const secret = process.env.SECRET;
const slackUrl = process.env.SLACK_WEBHOOK_URL;
const apiURI = 'https://api.pro.coinbase.com';
type SupportedProducts = 'BTC-EUR' | 'ETH-EUR';
const purchase = async (crypto: SupportedProducts, amount: number) => {
const client = new CoinbasePro.AuthenticatedClient(
key,
secret,
passphrase,
apiURI
);
const order: any = {
side: 'buy',
funds: amount,
product_id: crypto,
type: 'market',
};
console.log(order);
try {
const response = await client.placeOrder(order);
console.log(response);
await postMessageToSlack(
`✅ ✅ ✅ ✅ ✅ Purchased ${crypto} for ${amount}`,
response
);
} catch (e) {
console.error(e);
await postMessageToSlack(
`❌ ❌ ❌ ❌ ❌ Failed buying crypto for ${amount}`,
e
);
}
};
const postMessageToSlack = (text: string, markdown: any) => {
if (!slackUrl) {
return;
}
const body = {
text,
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: text,
},
},
],
};
if (markdown) {
body.blocks.push({
type: 'section',
text: {
type: 'mrkdwn',
text: '```' + JSON.stringify(markdown) + '```',
},
});
}
return axios
.post(slackUrl, JSON.stringify(body), {
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log('SUCCEEDED: Sent slack webhook: \n', response.data);
})
.catch((error) => {
console.log('FAILED: Send slack webhook', error.message);
});
};
export const run = async () => {
const orders: {
crypto: SupportedProducts;
amount: number;
}[] = [
{
crypto: 'ETH-EUR',
amount: 2.5,
},
{
crypto: 'BTC-EUR',
amount: 1.5,
},
];
await Promise.all(
orders.map((order) => purchase(order.crypto, order.amount))
);
};