import asyncio
import base64
import json
from typing import Dict, Optional, List, Set, Tuple
from decimal import Decimal
import time
import aiohttp
import websockets
import torch
from dataclasses import dataclass, field
from concurrent.futures import ThreadPoolExecutor
from collections import deque
import os
import logging
from solana_rust_bot import TradingCore, TradeParams
from solana_logger import SolanaLogger
from mempool_analyzer import EnhancedMempoolAnalyzer
from config_loader import config
logger = SolanaLogger(name)
@dataclass
class RateLimiter:
trades_per_second: int = int(os.getenv('MAX_TRADES_PER_SECOND', '2'))
trades_per_minute: int = int(os.getenv('MAX_TRADES_PER_MINUTE', '120'))
api_calls_per_minute: int = int(os.getenv('HELIUS_API_CALLS_PER_MINUTE', '150'))
last_trade: float = field(default_factory=time.time)
trade_count: int = 0
api_count: int = 0
last_reset: float = field(default_factory=time.time)
@dataclass
class TradeOpportunity:
pool_address: str
amount_in: Decimal
impact: Decimal
profit: Decimal
priority: int
timestamp: float
front_size: Decimal
back_size: Decimal
signature: str
confidence: float = 0.0
@dataclass
class ScalpState:
current_price: Decimal
bid_price: Decimal
ask_price: Decimal
buyer_volume: Decimal
seller_volume: Decimal
timestamp: float
side: Optional[str] = None # 'buy' or 'sell'
class HeliusWbSocketClient:
def init(self, trading_core: TradingCore, mempool_analyzer: EnhancedMempoolAnalyzer):
"""Initialize Helius client with enhanced monitoring and GPU acceleration"""
self.trading_core = trading_core
self.mempool_analyzer = mempool_analyzer
self.ws_helius = None
self.ws_quicknode = None
self.active = True
self.session = None
self.last_message_time = time.time()
# State
self.scalp_state = None
self.active_scalps = []
self.price_history = deque(maxlen=1000)
# Configuration
self._load_config()
self._load_scalp_config()
# Metrics tracking
self.metrics = {
'messages_processed': 0,
'opportunities_found': 0,
'trades_executed': 0,
'failed_trades': 0,
'api_calls': {'helius': 0, 'quicknode': 0},
'errors': {'ws': 0, 'parse': 0, 'execution': 0},
'latency': [],
'last_gc': time.time(),
'scalp_trades': 0,
'scalp_profit': Decimal('0'),
'mev_profit': Decimal('0')
}
# Setup
self._setup_gpu()
self.validated_pools: Set[str] = set()
self.rate_limiter = RateLimiter()
self.recent_opportunities = deque(maxlen=1000)
self.thread_pool = ThreadPoolExecutor(max_workers=4)
logger.info("HeliusClient initialized successfully")
def _load_config(self):
"""Load configuration from environment"""
self.helius_url = os.getenv('HELIUS_WS_URL')
self.quicknode_url = os.getenv('QUICKNODE_WEBSOCKET')
self.raydium_program = os.getenv('RAYDIUM_PROGRAM_ID')
self.wsol_account = os.getenv('WSOL_TOKEN_ACCOUNT')
self.min_profit = float(os.getenv('MIN_PROFIT_PCT', '1.5')) / 100
self.max_impact = float(os.getenv('MAX_PRICE_IMPACT', '0.004'))
self.max_latency = float(os.getenv('MAX_LATENCY', '0.1'))
if not all([self.helius_url, self.quicknode_url, self.raydium_program, self.wsol_account]):
raise ValueError("Missing required environment variables")
def _load_scalp_config(self):
"""Load scalping configuration"""
self.SCALP_CONFIG = {
'min_profit_pct': float(os.getenv('MIN_PROFIT_PCT', '4.0'))/100,
'max_loss_pct': float(os.getenv('STOP_LOSS_PCT', '2.5'))/100,
'min_buyer_ratio': float(os.getenv('MIN_BUYER_RATIO', '0.45')),
'max_buyer_ratio': float(os.getenv('MAX_BUYER_RATIO', '0.65')),
'min_24h_volume': float(os.getenv('MIN_24H_VOLUME', '10000')),
'position_size': float(os.getenv('POSITION_SIZE', '0.1')),
'max_active_scalps': int(os.getenv('MAX_ACTIVE_TRADES', '4'))
}
def _setup_gpu(self):
"""Initialize GPU acceleration"""
if torch.cuda.is_available():
self.device = torch.device('cuda')
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.benchmark = True
self.streams = {
'compute': torch.cuda.Stream(),
'validation': torch.cuda.Stream(),
'execution': torch.cuda.Stream(),
'scalp': torch.cuda.Stream()
}
self.buffers = {
'price_history': torch.zeros((1000,), device=self.device, dtype=torch.float16),
'volume_history': torch.zeros((1000,), device=self.device, dtype=torch.float16),
'mempool': torch.zeros((128, 256), device=self.device, dtype=torch.float16)
}
logger.info("GPU acceleration enabled", extra={
'device': torch.cuda.get_device_name(0),
'memory': torch.cuda.get_device_properties(0).total_memory
})
else:
self.device = torch.device('cpu')
logger.warning("GPU not available, using CPU")
async def start(self):
"""Start websocket connections and monitoring"""
self.session = aiohttp.ClientSession()
tasks = [
self._process_helius_messages(),
self._process_quicknode_messages(),
self._monitor_connections(),
self._monitor_performance(),
self._monitor_active_scalps()
]
await asyncio.gather(*tasks)
async def _process_helius_messages(self):
"""Process messages from Helius websocket"""
retry_count = 0
while self.active:
try:
async with websockets.connect(self.helius_url, ping_interval=20, ping_timeout=5) as ws:
self.ws_helius = ws
await self._subscribe_helius()
retry_count = 0
async for msg in ws:
await self._handle_helius_message(msg)
except Exception as e:
retry_count += 1
await asyncio.sleep(min(30, 2 ** retry_count))
async def _process_quicknode_messages(self):
"""Process messages from QuickNode websocket"""
retry_count = 0
while self.active:
try:
async with websockets.connect(self.quicknode_url, ping_interval=20, ping_timeout=5) as ws:
self.ws_quicknode = ws
await self._subscribe_quicknode()
retry_count = 0
async for msg in ws:
await self._handle_quicknode_message(msg)
except Exception as e:
retry_count += 1
await asyncio.sleep(min(30, 2 ** retry_count))
async def _subscribe_helius(self):
"""Subscribe to Helius feeds"""
subscribe_msg = {
"jsonrpc": "2.0",
"id": 1,
"method": "logsSubscribe",
"params": [
{"mentions": [self.raydium_program]},
{"commitment": "processed"}
]
}
await self.ws_helius.send(json.dumps(subscribe_msg))
async def _subscribe_quicknode(self):
"""Subscribe to QuickNode feeds"""
# Market data subscription
market_sub = {
"jsonrpc": "2.0",
"id": 1,
"method": "subscribeMarketData",
"params": [
os.getenv('SOL_WSOL_MARKET'),
{"trades": True, "l2": True, "l3": False}
]
}
await self.ws_quicknode.send(json.dumps(market_sub))
# Mempool subscription
mempool_sub = {
"jsonrpc": "2.0",
"id": 2,
"method": "subscribeMempool"
}
await self.ws_quicknode.send(json.dumps(mempool_sub))
async def _handle_helius_message(self, msg: str):
"""Process Helius message"""
try:
data = json.loads(msg)
if "params" in data and "result" in data["params"]:
result = data["params"]["result"]
if "data" in result:
decoded = base64.b64decode(result["data"])
await self._process_mempool_data(decoded)
self.metrics['messages_processed'] += 1
self.metrics['api_calls']['helius'] += 1
except Exception as e:
self.metrics['errors']['parse'] += 1
logger.error(f"Helius message error: {e}")
async def _handle_quicknode_message(self, msg: str):
"""Process QuickNode message"""
try:
data = json.loads(msg)
# Handle market data updates
if "method" == "marketData" in data:
await self._handle_market_update(data["params"])
# Handle mempool updates
elif "method" == "mempoolTx" in data:
await self._handle_mempool_update(data["params"])
self.metrics['api_calls']['quicknode'] += 1
except Exception as e:
self.metrics['errors']['parse'] += 1
logger.error(f"QuickNode message error: {e}")
async def _handle_market_update(self, update: Dict):
"""Process market data update"""
try:
# Update price
if "lastPrice" in update:
price = Decimal(str(update["lastPrice"]))
volume = Decimal(str(update.get("volume24h", 0)))
self.scalp_state = ScalpState(
current_price=price,
bid_price=Decimal(str(update.get("bestBid", price))),
ask_price=Decimal(str(update.get("bestAsk", price))),
buyer_volume=volume * Decimal(str(update.get("buyVolume", 0))),
seller_volume=volume * Decimal(str(update.get("sellVolume", 0))),
timestamp=time.time()
)
# Update price history
self.price_history.append((float(price), float(volume), time.time()))
# Check for scalping opportunity
if await self._should_scalp():
await self._execute_scalp()
except Exception as e:
logger.error(f"Market update error: {e}")
@torch.jit.script
def calculate_scalp_signals(self, prices: torch.Tensor, volumes: torch.Tensor) -> torch.Tensor:
"""Calculate scalping signals with JIT"""
short_mom = (prices[-1] - prices[-10]) / prices[-10]
med_mom = (prices[-1] - prices[-50]) / prices[-50]
volume_weight = volumes / torch.sum(volumes)
vwap = torch.sum(prices * volume_weight)
price_to_vwap = (prices[-1] - vwap) / vwap
return torch.stack([short_mom, med_mom, price_to_vwap])
async def _should_scalp(self) -> bool:
"""Check if we should enter a scalp trade"""
try:
if not self.scalp_state or len(self.active_scalps) >= self.SCALP_CONFIG['max_active_scalps']:
return False
with torch.cuda.stream(self.streams['scalp']):
prices = torch.tensor([p[0] for p in self.price_history], device=self.device)
volumes = torch.tensor([p[1] for p in self.price_history], device=self.device)
signals = self.calculate_scalp_signals(prices, volumes)
short_mom, med_mom, price_to_vwap = signals
# Long entry
if (short_mom > 0.002 and med_mom > 0.005 and price_to_vwap < -0.002):
self.scalp_state.side = 'buy'
return True
# Short entry
if (short_mom < -0.002 and med_mom < -0.005 and price_to_vwap > 0.002):
self.scalp_state.side = 'sell'
return True
return False
except Exception as e:
logger.error(f"Scalp check error: {e}")
return False
async def _execute_scalp(self):
"""Execute scalp trade"""
try:
if not await self._check_rate_limits(trade=True):
return
size = self.SCALP_CONFIG['position_size']
entry_price = float(self.scalp_state.current_price)
params = TradeParams(
pool_address=os.getenv('SOL_WSOL_AMM_ID'),
amount_in=size,
min_amount_out=0,
wsol_account=self.wsol_account
)
signature = await self.trading_core.execute_trade(params)
if signature:
self.active_scalps.append({
'entry_price': entry_price,
'size': size,
'side': self.scalp_state.side,
'target': entry_price * (1 + self.SCALP_CONFIG['min_profit_pct']),
'stop': entry_price * (1 - self.SCALP_CONFIG['max_loss_pct']),
'entry_time': time.time()
})
self.metrics['scalp_trades'] += 1
logger.info(f"Entered {self.scalp_state.side} scalp at {entry_price}")
except Exception as e:
logger.error(f"Scalp execution error: {e}")
async def _monitor_active_scalps(self):
"""Monitor and manage active scalp positions"""
while self.active:
try:
if not self.scalp_state:
await asyncio.sleep(0.1)
continue
price = float(self.scalp_state.current_price)
for scalp in self.active_scalps[:]:
# Check exit conditions
if ((scalp['side'] == 'buy' and price >= scalp['target']) or
(scalp['side'] == 'sell' and price <= scalp['target']) or
(scalp['side'] == 'buy' and price <= scalp['stop']) or
(scalp['side'] == 'sell' and price >= scalp['stop'])):
await self._close_scalp(scalp)
except Exception as e:
logger.error(f"Scalp monitoring error: {e}")
await asyncio.sleep(0.1)
async def _close_scalp(self, scalp: Dict):
"""Close scalp position"""
try:
params = TradeParams(
pool_address=os.getenv('SOL_WSOL_AMM_ID'),
amount_in=scalp['size'],
min_amount_out=0,
wsol_account=self.wsol_account
)
signature = await self.trading_core.execute_trade(params)
if signature:
exit_price = float(self.scalp_state.current_price)
pnl = (exit_price - scalp['entry_price']) * scalp['size']
self.metrics['scalp_profit'] += Decimal(str(pnl))
self.active_scalps.remove(scalp)
logger.info(f"Closed scalp position, PnL: {pnl}")
except Exception as e:
logger.error(f"Scalp close error: {e}")
async def cleanup(self):
"""
Cleanup resources and gracefully shut down the client.
Closes websocket connections, thread pools, and logs final metrics.
"""
try:
# Set active flag to false to stop background tasks
self.active = False
# Close websocket connections
if self.ws_helius:
await self.ws_helius.close()
if self.ws_quicknode:
await self.ws_quicknode.close()
# Close aiohttp session if exists
if self.session:
await self.session.close()
# Shutdown thread pool
if self.thread_pool:
self.thread_pool.shutdown(wait=True)
# Log final metrics
logger.info("Final Metrics:", extra={
'messages_processed': self.metrics['messages_processed'],
'opportunities_found': self.metrics['opportunities_found'],
'trades_executed': self.metrics['trades_executed'],
'scalp_trades': self.metrics['scalp_trades'],
'total_scalp_profit': self.metrics['scalp_profit'],
'total_mev_profit': self.metrics['mev_profit']
})
except Exception as e:
logger.error(f"Error during cleanup: {e}")
finally:
# Clear GPU resources if available
if torch.cuda.is_available():
torch.cuda.empty_cache()
async def _monitor_connections(self):
"""
Monitor websocket connection health and reconnect if necessary.
"""
while self.active:
try:
# Check last message time
current_time = time.time()
if current_time - self.last_message_time > 60: # 1-minute timeout
logger.warning("No messages received. Reconnecting...")
await self.cleanup()
await self.start()
# Check error metrics
if (self.metrics['errors']['ws'] > 10 or
self.metrics['errors']['parse'] > 50):
logger.error("Excessive errors detected. Resetting connections.")
await self.cleanup()
await self.start()
await asyncio.sleep(30) # Check every 30 seconds
except Exception as e:
logger.error(f"Connection monitoring error: {e}")
await asyncio.sleep(5)
async def _monitor_performance(self):
"""
Periodic performance monitoring and garbage collection.
"""
while self.active:
try:
# Garbage collection
current_time = time.time()
if current_time - self.metrics['last_gc'] > 300: # Every 5 minutes
import gc
gc.collect()
self.metrics['last_gc'] = current_time
# Clear old opportunities
while len(self.recent_opportunities) > 1000:
self.recent_opportunities.popleft()
# Log performance metrics
logger.info("Performance Metrics", extra={
'active_scalps': len(self.active_scalps),
'validated_pools': len(self.validated_pools),
'message_rate': self.metrics['messages_processed'] / 300, # per 5 minutes
'trade_success_rate': (self.metrics['trades_executed'] /
max(1, self.metrics['trades_executed'] + self.metrics['failed_trades'])) * 100
})
await asyncio.sleep(300) # Every 5 minutes
except Exception as e:
logger.error(f"Performance monitoring error: {e}")
await asyncio.sleep(60)
# Optional: Add a method to reset metrics
def reset_metrics(self):
"""
Reset all tracked metrics to initial state.
"""
self.metrics = {
'messages_processed': 0,
'opportunities_found': 0,
'trades_executed': 0,
'failed_trades': 0,
'api_calls': {'helius': 0, 'quicknode': 0},
'errors': {'ws': 0, 'parse': 0, 'execution': 0},
'latency': [],
'last_gc': time.time(),
'scalp_trades': 0,
'scalp_profit': Decimal('0'),
'mev_profit': Decimal('0')
}
logger.info("Metrics have been reset")
# Additional method to check rate limits before critical actions
async def _check_rate_limits(self, trade: bool = False) -> bool:
"""
Check rate limits before executing actions.
Args:
trade (bool): Whether the action is a trade (more restrictive).
Returns:
bool: Whether action is allowed.
"""
try:
# Separate rate limiting for trades vs other actions
if trade:
if not self.rate_limiter.check_trade_limit():
logger.warning("Trade rate limit exceeded")
return False
else:
if not self.rate_limiter.check_action_limit():
logger.warning("Action rate limit exceeded")
return False
return True
except Exception as e:
logger.error(f"Rate limit check error: {e}")
return False
# Context manager support for easier resource management
async def __aenter__(self):
"""Support async context manager entry."""
await self.start()
return self
async def __aexit__(self, exc_type, exc, tb):
"""Support async context manager exit."""
await self.cleanup()
Example usage pattern
async def main():
"""Example of how to use the HeliusWbSocketClient."""
trading_core = TradingCore() # Assume this is defined
mempool_analyzer = EnhancedMempoolAnalyzer() # Assume this is defined
async with HeliusWbSocketClient(trading_core, mempool_analyzer) as client:
# The client will automatically start and cleanup
await asyncio.sleep(3600) # Run for an hour
if name == "main":
asyncio.run(main()) they are missing the bearer and the header with mozilla 5.0 or soemthing i forget but yeah its missing some shizznit