Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
233 lines (196 loc) · 6.5 KB
/
Copy pathindex.js
File metadata and controls
233 lines (196 loc) · 6.5 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
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
import WebSocket from 'ws';
import { loadConfig } from './config.js';
import { TelegramNotifier } from './telegram.js';
class PolymarketMonitor {
constructor(config) {
this.config = config;
this.ws = null;
this.telegram = new TelegramNotifier(
config.telegram.botToken,
config.telegram.chatId
);
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 10;
this.reconnectDelay = 5000;
this.isConnected = false;
this.heartbeatInterval = null;
}
async start() {
console.log('Starting Polymarket Monitor...');
console.log('Polymarket API Key:', this.config.polymarket.apiKey);
console.log('Telegram Chat ID:', this.config.telegram.chatId);
await this.telegram.sendStartupMessage();
this.connect();
}
connect() {
console.log(`Connecting to ${this.config.websocket.url}...`);
try {
this.ws = new WebSocket(this.config.websocket.url);
this.ws.on('open', () => {
console.log('WebSocket connected!');
this.isConnected = true;
this.reconnectAttempts = 0;
this.subscribe();
this.startHeartbeat();
});
this.ws.on('message', (data) => {
this.handleMessage(data);
});
this.ws.on('error', (error) => {
console.error('WebSocket error:', error);
this.telegram.sendErrorMessage(`WebSocket error: ${error.message}`);
});
this.ws.on('close', () => {
console.log('WebSocket closed');
this.isConnected = false;
this.stopHeartbeat();
this.reconnect();
});
} catch (error) {
console.error('Failed to create WebSocket:', error);
this.reconnect();
}
}
subscribe() {
const subscribeMessage = {
markets: [], // 空数组表示订阅所有市场
type: 'user',
auth: {
apiKey: this.config.polymarket.apiKey,
secret: this.config.polymarket.apiSecret,
passphrase: this.config.polymarket.apiPassphrase
}
};
console.log('Sending subscription message...');
console.log('Auth credentials:', {
apiKey: this.config.polymarket.apiKey,
secretLength: this.config.polymarket.apiSecret?.length,
passphraseLength: this.config.polymarket.apiPassphrase?.length
});
this.ws.send(JSON.stringify(subscribeMessage));
console.log('Subscription sent successfully');
}
handleMessage(data) {
const messageStr = data.toString();
// 处理 PONG 消息(心跳响应)
if (messageStr === 'PONG') {
// 静默处理 PONG 消息
return;
}
try {
const message = JSON.parse(messageStr);
console.log('Received message:', JSON.stringify(message, null, 2));
// 处理不同类型的消息
if (message.event_type === 'trade' || message.type === 'trade') {
this.handleTradeEvent(message);
} else if (message.event_type === 'order' || message.type === 'order') {
this.handleOrderEvent(message);
} else if (message.type === 'subscribed') {
console.log('Successfully subscribed to channel');
} else if (message.type === 'error') {
console.error('Server error:', message);
this.telegram.sendErrorMessage(`Server error: ${JSON.stringify(message)}`);
}
} catch (error) {
console.error('Error parsing message:', error);
console.error('Raw message:', messageStr);
}
}
handleTradeEvent(trade) {
console.log('Trade event detected!');
console.log('Trade details:', JSON.stringify(trade, null, 2));
// 提取交易信息
const tradeInfo = {
id: trade.id || trade.trade_id,
market: trade.market || trade.asset_id,
price: trade.price,
size: trade.size,
status: trade.status,
side: trade.side,
type: trade.type || 'TRADE',
timestamp: trade.timestamp || Date.now()
};
// 发送 Telegram 通知
this.telegram.notifyTrade(tradeInfo);
}
handleOrderEvent(order) {
console.log('Order event detected!');
console.log('Order details:', JSON.stringify(order, null, 2));
// 只在订单有成交时发送通知(部分成交或全部成交)
if (order.event_type === 'UPDATE' || (order.size_matched && parseFloat(order.size_matched) > 0)) {
const orderInfo = {
id: order.id || order.order_id,
market: order.market || order.asset_id,
price: order.price,
original_size: order.original_size || order.size,
size_matched: order.size_matched || order.matched,
event_type: order.event_type,
timestamp: order.timestamp || Date.now()
};
// 发送 Telegram 通知
this.telegram.notifyOrder(orderInfo);
}
}
startHeartbeat() {
// 每10秒发送一次心跳(根据官方示例)
this.heartbeatInterval = setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send('PING');
}
}, 10000);
}
stopHeartbeat() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
}
reconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error('Max reconnection attempts reached');
this.telegram.sendErrorMessage('Max reconnection attempts reached. Please restart the monitor.');
return;
}
this.reconnectAttempts++;
console.log(`Reconnecting in ${this.reconnectDelay / 1000}s... (Attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
setTimeout(() => {
this.connect();
}, this.reconnectDelay);
}
stop() {
console.log('Stopping monitor...');
this.stopHeartbeat();
if (this.ws) {
this.ws.close();
}
}
}
// 主程序入口
async function main() {
try {
const config = loadConfig();
if (!config.polymarket.apiKey || !config.polymarket.apiSecret || !config.polymarket.apiPassphrase) {
throw new Error('Polymarket API credentials not found');
}
if (!config.telegram.botToken || !config.telegram.chatId) {
throw new Error('Telegram credentials not found');
}
const monitor = new PolymarketMonitor(config);
await monitor.start();
// 优雅退出
process.on('SIGINT', () => {
console.log('\nReceived SIGINT, shutting down gracefully...');
monitor.stop();
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('\nReceived SIGTERM, shutting down gracefully...');
monitor.stop();
process.exit(0);
});
} catch (error) {
console.error('Failed to start monitor:', error);
process.exit(1);
}
}
main();