-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathadvanced_monitoring.py
More file actions
337 lines (273 loc) Β· 12.5 KB
/
Copy pathadvanced_monitoring.py
File metadata and controls
337 lines (273 loc) Β· 12.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"""
Comprehensive example demonstrating advanced GMGN API features.
This example shows:
- Real-time data streaming with filtering
- Data export capabilities
- Monitoring and statistics
- Alert configuration
- Multiple channel subscriptions
Built with Chipa Editor - https://chipaeditor.com/?utm_source=code&utm_medium=example&utm_campaign=gmgn_api&utm_term=advanced&utm_content=docstring
"""
import asyncio
import logging
from decimal import Decimal
from pathlib import Path
from gmgnapi import (
GmGnEnhancedClient,
TokenFilter,
DataExportConfig,
AlertConfig,
MonitoringStats,
)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class AdvancedGmGnMonitor:
"""Advanced monitoring class with comprehensive features."""
def __init__(self):
# Configure advanced token filtering
self.token_filter = TokenFilter(
min_market_cap=Decimal("50000"), # Minimum $50k market cap
min_liquidity=Decimal("10000"), # Minimum $10k liquidity
min_volume_24h=Decimal("5000"), # Minimum $5k 24h volume
min_holder_count=10, # Minimum 10 holders
exchanges=["raydium", "orca", "jupiter"], # Only these exchanges
exclude_symbols=["SCAM", "TEST", "FAKE"], # Exclude obvious scams
max_risk_score=0.7, # Maximum risk score
)
# Configure data export
self.export_config = DataExportConfig(
enabled=True,
format="json", # Could be "csv" or "database"
file_path="./gmgn_exports",
max_file_size_mb=50,
rotation_interval_hours=6,
compress=True,
include_metadata=True,
)
# Configure alerts
self.alert_config = AlertConfig(
enabled=True,
webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
conditions=[
{
"type": "new_pool",
"min_liquidity": 100000, # Alert for pools > $100k liquidity
"description": "High liquidity new pool detected"
},
{
"type": "volume_spike",
"threshold_multiplier": 5.0, # 5x volume increase
"description": "Volume spike detected"
}
],
rate_limit_seconds=300, # Max 1 alert per 5 minutes
)
# Initialize client with advanced features
self.client = GmGnEnhancedClient(
chain="sol",
auto_reconnect=True,
reconnect_interval=3.0,
token_filter=self.token_filter,
export_config=self.export_config,
alert_config=self.alert_config,
rate_limit=100, # Max 100 messages/second
max_queue_size=5000,
)
# Statistics tracking
self.interesting_pools = []
self.volume_spikes = []
self.large_trades = []
async def setup_handlers(self):
"""Setup event handlers for different data types."""
# New pool handler with advanced filtering
self.client.on_new_pool(self.handle_new_pool)
# Pair update handler for price monitoring
self.client.on_pair_update(self.handle_pair_update)
# Token launch handler
self.client.on_token_launch(self.handle_token_launch)
# Chain statistics handler
self.client.on_chain_stats(self.handle_chain_stats)
# Wallet trades handler (requires authentication)
self.client.on_wallet_trades(self.handle_wallet_trades)
# General message handler for debugging
self.client.on_message(self.handle_general_message)
async def handle_new_pool(self, pool_info):
"""Handle new pool creation events."""
try:
if not pool_info.pools:
return
pool = pool_info.pools[0]
token_info = pool.bti
if not token_info:
return
# Extract relevant information
symbol = getattr(token_info, 's', 'Unknown')
name = getattr(token_info, 'n', 'Unknown')
market_cap = getattr(token_info, 'mc', 0)
liquidity = getattr(pool, 'il', 0)
logger.info(
f"π New Pool: {symbol} ({name}) | "
f"Market Cap: ${market_cap:,.0f} | "
f"Liquidity: ${liquidity:,.0f} | "
f"Pool: {pool.a[:8]}..."
)
# Track interesting pools
if market_cap and market_cap > 100000: # $100k+ market cap
self.interesting_pools.append({
'symbol': symbol,
'name': name,
'market_cap': market_cap,
'liquidity': liquidity,
'pool_address': pool.a,
'token_address': pool.ba,
'timestamp': pool_info.model_dump(),
})
logger.warning(
f"π₯ HIGH VALUE POOL: {symbol} with ${market_cap:,.0f} market cap!"
)
except Exception as e:
logger.error(f"Error handling new pool: {e}")
async def handle_pair_update(self, pair_data):
"""Handle trading pair updates."""
try:
# Extract price and volume information
if hasattr(pair_data, 'volume_24h_usd') and pair_data.volume_24h_usd:
volume = pair_data.volume_24h_usd
# Check for volume spikes
if volume > Decimal("500000"): # $500k+ volume
logger.warning(
f"οΏ½ HIGH VOLUME: {pair_data.pair_address[:8]}... | "
f"24h Volume: ${volume:,.0f}"
)
self.volume_spikes.append({
'pair_address': pair_data.pair_address,
'volume_24h': float(volume),
'timestamp': pair_data.updated_at,
})
except Exception as e:
logger.error(f"Error handling pair update: {e}")
async def handle_token_launch(self, launch_data):
"""Handle token launch events."""
try:
logger.info(
f"π Token Launch: {launch_data.symbol} ({launch_data.name}) | "
f"Address: {launch_data.token_address[:8]}..."
)
if launch_data.initial_price_usd:
logger.info(f" Initial Price: ${launch_data.initial_price_usd}")
if launch_data.market_cap_usd:
logger.info(f" Market Cap: ${launch_data.market_cap_usd:,.0f}")
except Exception as e:
logger.error(f"Error handling token launch: {e}")
async def handle_chain_stats(self, stats_data):
"""Handle blockchain statistics."""
try:
logger.info(f"π Chain Stats Update: {stats_data}")
except Exception as e:
logger.error(f"Error handling chain stats: {e}")
async def handle_wallet_trades(self, trade_data):
"""Handle wallet trading activity."""
try:
for trade in trade_data.trades:
if trade.amount_usd > Decimal("10000"): # $10k+ trades
logger.warning(
f"π LARGE TRADE: {trade.trade_type.upper()} | "
f"${trade.amount_usd:,.0f} | "
f"Wallet: {trade.wallet_address[:8]}..."
)
self.large_trades.append({
'type': trade.trade_type,
'amount_usd': float(trade.amount_usd),
'wallet': trade.wallet_address,
'token': trade.token_address,
'timestamp': trade.timestamp,
})
except Exception as e:
logger.error(f"Error handling wallet trades: {e}")
async def handle_general_message(self, message):
"""Handle all messages for debugging."""
# Only log every 100th message to avoid spam
if hasattr(self, '_message_count'):
self._message_count += 1
else:
self._message_count = 1
if self._message_count % 100 == 0:
logger.debug(f"Processed {self._message_count} messages")
async def print_periodic_stats(self):
"""Print statistics every 60 seconds."""
while True:
await asyncio.sleep(60)
try:
stats = self.client.get_monitoring_stats()
logger.info("="*60)
logger.info("π MONITORING STATISTICS")
logger.info("="*60)
logger.info(f"Total Messages: {stats.total_messages:,}")
logger.info(f"Messages/Minute: {stats.messages_per_minute:.1f}")
logger.info(f"Unique Tokens: {stats.unique_tokens_seen}")
logger.info(f"Unique Pools: {stats.unique_pools_seen}")
logger.info(f"Connection Uptime: {stats.connection_uptime:.0f}s")
logger.info(f"Error Count: {stats.error_count}")
if stats.last_message_time:
logger.info(f"Last Message: {stats.last_message_time}")
# Custom statistics
logger.info(f"Interesting Pools Found: {len(self.interesting_pools)}")
logger.info(f"Volume Spikes Detected: {len(self.volume_spikes)}")
logger.info(f"Large Trades Seen: {len(self.large_trades)}")
# Show recent interesting pools
if self.interesting_pools:
logger.info("\nπ₯ Recent High-Value Pools:")
for pool in self.interesting_pools[-5:]: # Last 5
logger.info(
f" {pool['symbol']}: ${pool['market_cap']:,.0f} market cap"
)
logger.info("="*60)
except Exception as e:
logger.error(f"Error printing stats: {e}")
async def run(self):
"""Run the advanced monitoring system."""
try:
logger.info("π Starting Advanced GMGN Monitor")
logger.info("="*60)
logger.info("Features enabled:")
logger.info(f" β’ Token Filtering: {bool(self.token_filter.min_market_cap)}")
logger.info(f" β’ Data Export: {self.export_config.enabled}")
logger.info(f" β’ Alerts: {self.alert_config.enabled}")
logger.info(f" β’ Rate Limiting: {self.client.rate_limit} msg/s")
logger.info("="*60)
# Setup event handlers
await self.setup_handlers()
# Connect to WebSocket
await self.client.connect()
# Subscribe to all available channels
await self.client.subscribe_all_channels()
# Start periodic statistics
stats_task = asyncio.create_task(self.print_periodic_stats())
logger.info("β
Connected and monitoring... Press Ctrl+C to stop")
# Keep running until interrupted
try:
while True:
await asyncio.sleep(1)
except KeyboardInterrupt:
logger.info("π Shutdown signal received")
# Cleanup
stats_task.cancel()
await self.client.disconnect()
# Final statistics
final_stats = self.client.get_monitoring_stats()
logger.info(f"π Final Stats: {final_stats.total_messages:,} messages processed")
logger.info(f"οΏ½ Discovered {len(self.interesting_pools)} interesting pools")
except Exception as e:
logger.error(f"β Error in monitoring: {e}")
raise
async def main():
"""Main entry point."""
monitor = AdvancedGmGnMonitor()
await monitor.run()
if __name__ == "__main__":
# Run the advanced monitoring system
asyncio.run(main())