forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalerts.js
More file actions
156 lines (131 loc) · 4.36 KB
/
Copy pathalerts.js
File metadata and controls
156 lines (131 loc) · 4.36 KB
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
const crypto = require('crypto');
const cache = require('./cache');
const webhook = require('./webhook');
const logger = require('../logger');
const IDS_KEY = 'alerts:ids';
const COOLDOWN_MS = 5 * 60 * 1000;
function alertKey(id) {
return `alert:${id}`;
}
function generateId() {
return `alrt_${crypto.randomUUID().replace(/-/g, '').slice(0, 16)}`;
}
function isTriggered(alert, priceUsd) {
if (alert.type === 'above') return priceUsd > alert.threshold_usd;
if (alert.type === 'below') return priceUsd < alert.threshold_usd;
if (alert.type === 'change_pct') {
if (alert.baseline_price === null) return false;
const pct = Math.abs((priceUsd - alert.baseline_price) / alert.baseline_price) * 100;
return pct >= alert.threshold_usd;
}
return false;
}
async function create(data) {
const { asset, type, threshold_usd, webhook_url, webhook_secret, repeat } = data;
const id = generateId();
let baselinePrice = null;
if (type === 'change_pct') {
const cached = await cache.get(`price:${asset.toUpperCase()}`);
if (cached && cached.price) baselinePrice = cached.price;
}
const alert = {
id,
asset: asset.toUpperCase(),
type,
threshold_usd,
webhook_url,
webhook_secret,
repeat: repeat === true,
created_at: new Date().toISOString(),
last_fired_at: null,
baseline_price: baselinePrice,
};
const redis = cache.getClient();
await cache.set(alertKey(id), alert);
await redis.zadd(IDS_KEY, Date.now(), id);
return alert;
}
async function list() {
const redis = cache.getClient();
const ids = await redis.zrevrange(IDS_KEY, 0, -1);
const alerts = await Promise.all(ids.map((id) => cache.get(alertKey(id))));
return alerts.filter(Boolean);
}
async function listPaginated({ offset = 0, limit = 20 } = {}) {
const redis = cache.getClient();
const total = await redis.zcard(IDS_KEY);
const paginatedIds = await redis.zrevrange(IDS_KEY, offset, offset + limit - 1);
const alerts = await Promise.all(
paginatedIds.map((id) => cache.get(alertKey(id)))
);
return {
alerts: alerts.filter(Boolean),
total
};
}
async function remove(id) {
const redis = cache.getClient();
const existing = await cache.get(alertKey(id));
if (!existing) return null;
await cache.del(alertKey(id));
await redis.zrem(IDS_KEY, id);
return existing;
}
async function fire(alert, priceUsd) {
const payload = {
event: 'price.alert',
alert_id: alert.id,
asset: alert.asset,
type: alert.type,
threshold_usd: alert.threshold_usd,
actual_price_usd: priceUsd,
triggered_at: new Date().toISOString(),
};
logger.info('Price alert triggered', { alert_id: alert.id, asset: alert.asset, price: priceUsd });
await webhook.deliver(alert.webhook_url, alert.webhook_secret, payload);
}
function assetCooldownKey(asset) {
return `alert:cooldown:${asset.toUpperCase()}`;
}
async function evaluateForAsset(asset, priceUsd) {
const redis = cache.getClient();
const ids = await redis.zrevrange(IDS_KEY, 0, -1);
for (const id of ids) {
const alert = await cache.get(alertKey(id));
if (!alert || alert.asset !== asset.toUpperCase()) continue;
if (!isTriggered(alert, priceUsd)) continue;
if (alert.repeat) {
if (alert.last_fired_at) {
const elapsed = Date.now() - new Date(alert.last_fired_at).getTime();
if (elapsed < COOLDOWN_MS) continue;
}
const assetLastFired = await cache.get(assetCooldownKey(alert.asset));
if (assetLastFired) {
const assetElapsed = Date.now() - new Date(assetLastFired).getTime();
if (assetElapsed < COOLDOWN_MS) continue;
}
}
await fire(alert, priceUsd);
if (!alert.repeat) {
await remove(id);
} else {
const nowIso = new Date().toISOString();
alert.last_fired_at = nowIso;
if (alert.type === 'change_pct') {
alert.baseline_price = priceUsd;
}
await cache.set(alertKey(id), alert);
await cache.set(assetCooldownKey(alert.asset), nowIso);
}
}
}
async function evaluateAll() {
const allAlerts = await list();
const assets = [...new Set(allAlerts.map((a) => a.asset))];
for (const asset of assets) {
const cached = await cache.get(`price:${asset}`);
if (!cached || cached.price == null) continue;
await evaluateForAsset(asset, cached.price);
}
}
module.exports = { create, list, listPaginated, remove, evaluateForAsset, evaluateAll };