import time from collections import defaultdict from typing import Dict, List, Optional, Tuple class ClusterEngine: def __init__( self, cobuy_window: int = 300, min_wallets: int = 2, conviction_sol: float = 1.5, min_buy_sol: float = 1.0, conviction_bnb: float = 0.4, min_buy_bnb: float = 0.25, conviction_eth: float = 0.1, min_buy_eth: float = 0.05, rotator_window: int = 180, consecutive_buys_required: int = 3, only_consecutive_3_buys: bool = False, sssss_bundler_wallets: Optional[List[str]] = None ): self.cobuy_window = cobuy_window self.min_wallets = min_wallets self.conviction_sol = conviction_sol self.min_buy_sol = min_buy_sol self.conviction_bnb = conviction_bnb self.min_buy_bnb = min_buy_bnb self.conviction_eth = conviction_eth self.min_buy_eth = min_buy_eth self.rotator_window = rotator_window self.consecutive_buys_required = consecutive_buys_required self.only_consecutive_3_buys = only_consecutive_3_buys self.sssss_bundler_wallets = set(w.strip() for w in (sssss_bundler_wallets or [])) # mint -> list of buy dicts within rolling window: [{"wallet_name", "wallet_addr", "sol_amount", "amount", "currency", "chain", "time", "sig"}] self.recent_buys: Dict[str, List[dict]] = defaultdict(list) # mint -> wallet_name -> {"buys": [...], "sells": [...], "total_bought": float, "total_sold": float} # Tracks lifetime session positions to detect accumulation (3 buys in a row without selling) self.wallet_positions: Dict[str, Dict[str, dict]] = defaultdict( lambda: defaultdict(lambda: {"buys": [], "sells": [], "total_bought": 0.0, "total_sold": 0.0}) ) # mint -> set of alert types already triggered to avoid spam: {"CLUSTER", "CONVICTION", "ACCUMULATION", ...} self.triggered_alerts: Dict[str, set] = defaultdict(set) # wallet_name/wallet_addr -> list of recent buys across all tokens [(mint, time)]: tracks multi-token rotator spray self.wallet_activity: Dict[str, List[tuple]] = defaultdict(list) def is_rotator_spraying(self, wallet_key: str, current_time: Optional[float] = None) -> bool: """Check if a tracked wallet is currently spraying >=3 distinct tokens within rotator_window""" now = current_time or time.time() acts = self.wallet_activity.get(wallet_key, []) recent_tokens = set(m for m, t in acts if now - t <= self.rotator_window) return len(recent_tokens) >= 3 def clean_old_buys(self, current_time: Optional[float] = None): """Remove buys older than cobuy_window from cluster co-buy tracker""" now = current_time or time.time() for mint in list(self.recent_buys.keys()): self.recent_buys[mint] = [ b for b in self.recent_buys[mint] if now - b["time"] <= self.cobuy_window ] if not self.recent_buys[mint]: del self.recent_buys[mint] def record_sell(self, mint: str, wallet_name: str, wallet_addr: str, amount: float = 0.0, block_time: Optional[float] = None, sig: str = ""): """ Record a sell or token transfer out for a tracked wallet. Crucially resets active consecutive buy streaks on this token. """ b_time = block_time or time.time() sell_record = { "wallet_name": wallet_name, "wallet_addr": wallet_addr, "amount": amount, "time": b_time, "sig": sig } self.wallet_positions[mint][wallet_name]["sells"].append(sell_record) self.wallet_positions[mint][wallet_name]["total_sold"] += amount # Reset accumulation alert keys for this mint so that after a sell, a new 3-in-a-row wave can alert keys_to_remove = [k for k in self.triggered_alerts[mint] if k.startswith("ACCUM_") or k.startswith("CLUSTER_ACCUM_")] for k in keys_to_remove: self.triggered_alerts[mint].remove(k) def record_buy( self, mint: str, wallet_name: str, wallet_addr: str, sol_amount: float, block_time: float, sig: str, chain: Optional[str] = None, is_charity_buyback: bool = False, is_no_filter: bool = False ) -> Optional[dict]: """ Record a buy from a tracked wallet and evaluate if it triggers a signal: 1. CHARITY_BUYBACK: Immediately alerts once spotted, bypassing market cap filters. 2. BUNDLE_RADAR / NO_FILTER: Immediately alerts on ANY buy from tracked bundler / side wallets. 3. ACCUMULATION (Primary): Only signals calls where wallets buy 3 times in a row without selling, with each buy >= 1.0 SOL (or chain equivalent). 4. Optional/Legacy Conviction & Cluster: Evaluated when only_consecutive_3_buys is False. Supports Solana (SOL), BSC (BNB), and Robinhood Chain (ETH). """ is_evm = mint.startswith("0x") if chain: chain_clean = chain.lower() else: chain_clean = "bsc" if is_evm else "solana" is_robinhood = (chain_clean == "robinhood" or "rh" in chain_clean) is_bsc = (chain_clean == "bsc" or (is_evm and not is_robinhood)) if is_robinhood: currency = "ETH" chain_name = "robinhood" min_thresh = self.min_buy_eth conviction_thresh = self.conviction_eth rotator_conviction = 0.2 elif is_bsc: currency = "BNB" chain_name = "bsc" min_thresh = self.min_buy_bnb conviction_thresh = self.conviction_bnb rotator_conviction = 0.6 else: currency = "SOL" chain_name = "solana" min_thresh = self.min_buy_sol conviction_thresh = self.conviction_sol rotator_conviction = 2.0 # Filter out micro-buys below threshold (e.g. < 0.05 SOL) unless is_no_filter is active if not is_no_filter and sol_amount < min_thresh: return None self.clean_old_buys(block_time) # Check if this exact tx was already recorded in recent buys for b in self.recent_buys[mint]: if b["sig"] == sig: return None new_buy = { "wallet_name": wallet_name, "wallet_addr": wallet_addr, "sol_amount": round(sol_amount, 3), # preserved for backwards compatibility "amount": round(sol_amount, 3), "currency": currency, "chain": chain_name, "time": block_time, "sig": sig } self.recent_buys[mint].append(new_buy) # Also update lifetime position tracking for accumulation detection w_pos = self.wallet_positions[mint][wallet_name] if not any(b["sig"] == sig for b in w_pos["buys"]): w_pos["buys"].append(new_buy) w_pos["total_bought"] += sol_amount # Update wallet multi-token rotation activity for key in filter(None, [wallet_name, wallet_addr]): self.wallet_activity[key] = [ (m, t) for m, t in self.wallet_activity[key] if block_time - t <= self.rotator_window ] self.wallet_activity[key].append((mint, block_time)) is_rotator_spraying = self.is_rotator_spraying(wallet_name, block_time) or self.is_rotator_spraying(wallet_addr, block_time) # 1. Check Charity & Buyback Trigger (Instant Alert Once Spotted) if is_charity_buyback and "CHARITY_BUYBACK" not in self.triggered_alerts[mint]: self.triggered_alerts[mint].add("CHARITY_BUYBACK") return { "type": "CHARITY_BUYBACK", "mint": mint, "chain": chain_name, "currency": currency, "primary_wallet": wallet_name, "wallet_addr": wallet_addr, "sol_amount": sol_amount, "amount": sol_amount, "buys": [new_buy], "unique_wallets_count": 1, "total_sol": round(sol_amount, 3), "total_amount": round(sol_amount, 3), "time_span_seconds": 0, "is_charity_buyback": True } # 1b. Check No-Filter Trigger (Instant Alert on ANY buy) if is_no_filter and f"BUNDLE_{sig}" not in self.triggered_alerts[mint]: self.triggered_alerts[mint].add(f"BUNDLE_{sig}") return { "type": "BUNDLE_RADAR", "mint": mint, "chain": chain_name, "currency": currency, "primary_wallet": wallet_name, "wallet_addr": wallet_addr, "sol_amount": sol_amount, "amount": sol_amount, "buys": [new_buy], "unique_wallets_count": 1, "total_sol": round(sol_amount, 3), "total_amount": round(sol_amount, 3), "time_span_seconds": 0 } # 2. Check 3 Consecutive Buys In A Row Without Selling (ACCUMULATION Signal) wallet_sells = w_pos["sells"] last_sell_time = max([s["time"] for s in wallet_sells]) if wallet_sells else 0 active_w_buys = [b for b in w_pos["buys"] if b["time"] > last_sell_time and b["amount"] >= min_thresh] all_token_sells = [s for wp in self.wallet_positions[mint].values() for s in wp["sells"]] last_token_sell_time = max([s["time"] for s in all_token_sells]) if all_token_sells else 0 active_token_buys = [b for wp in self.wallet_positions[mint].values() for b in wp["buys"] if b["time"] > last_token_sell_time and b["amount"] >= min_thresh] active_token_buys.sort(key=lambda b: b["time"]) # Check per-wallet consecutive streak if len(active_w_buys) >= self.consecutive_buys_required: alert_key = f"ACCUM_{wallet_name}_{len(active_w_buys)}" if alert_key not in self.triggered_alerts[mint]: self.triggered_alerts[mint].add(alert_key) self.triggered_alerts[mint].add("ACCUMULATION") accum_times = [b["time"] for b in active_w_buys] accum_span = int(max(accum_times) - min(accum_times)) total_accum = sum(b["amount"] for b in active_w_buys) return { "type": "ACCUMULATION", "mint": mint, "chain": chain_name, "currency": currency, "primary_wallet": wallet_name, "wallet_addr": wallet_addr, "buy_count": len(active_w_buys), "total_amount": round(total_accum, 3), "total_sol": round(total_accum, 3), "amount": sol_amount, "sol_amount": sol_amount, "buys": active_w_buys[-3:], "unique_wallets_count": 1, "time_span_seconds": accum_span, "is_accumulation": True } # Check collective tracked wallet consecutive streak on this token if len(active_token_buys) >= self.consecutive_buys_required: alert_key = f"CLUSTER_ACCUM_{len(active_token_buys)}" if alert_key not in self.triggered_alerts[mint]: self.triggered_alerts[mint].add(alert_key) self.triggered_alerts[mint].add("ACCUMULATION") accum_times = [b["time"] for b in active_token_buys] accum_span = int(max(accum_times) - min(accum_times)) total_accum = sum(b["amount"] for b in active_token_buys) unique_w = len(set(b["wallet_name"] for b in active_token_buys)) return { "type": "ACCUMULATION", "mint": mint, "chain": chain_name, "currency": currency, "primary_wallet": wallet_name, "wallet_addr": wallet_addr, "buy_count": len(active_token_buys), "total_amount": round(total_accum, 3), "total_sol": round(total_accum, 3), "amount": sol_amount, "sol_amount": sol_amount, "buys": active_token_buys[-3:], "unique_wallets_count": unique_w, "time_span_seconds": accum_span, "is_accumulation": True } # If only_consecutive_3_buys is explicitly set to True, skip other signals if self.only_consecutive_3_buys: return None # 3. Check Wallets Buying The Same Memecoin (CLUSTER Signal) regular_buys = self.recent_buys[mint] unique_wallets = {b["wallet_name"]: b for b in regular_buys} total_amount = sum(b["sol_amount"] for b in regular_buys) times = [b["time"] for b in regular_buys] time_span_seconds = int(max(times) - min(times)) if times else 0 effective_conviction = rotator_conviction if is_rotator_spraying else conviction_thresh if len(unique_wallets) >= self.min_wallets and f"CLUSTER_{len(unique_wallets)}" not in self.triggered_alerts[mint]: self.triggered_alerts[mint].add(f"CLUSTER_{len(unique_wallets)}") self.triggered_alerts[mint].add("CLUSTER") return { "type": "CLUSTER", "mint": mint, "chain": chain_name, "currency": currency, "primary_wallet": wallet_name, "sol_amount": sol_amount, "amount": sol_amount, "buys": regular_buys, "unique_wallets_count": len(unique_wallets), "total_sol": round(total_amount, 3), "total_amount": round(total_amount, 3), "time_span_seconds": time_span_seconds, "is_cluster": True } # 4. Check High-Conviction Sizing Entry (CONVICTION Signal) if sol_amount >= effective_conviction and "CONVICTION" not in self.triggered_alerts[mint]: self.triggered_alerts[mint].add("CONVICTION") return { "type": "CONVICTION", "mint": mint, "chain": chain_name, "currency": currency, "primary_wallet": wallet_name, "sol_amount": sol_amount, "amount": sol_amount, "buys": regular_buys, "unique_wallets_count": len(unique_wallets), "total_sol": round(total_amount, 3), "total_amount": round(total_amount, 3), "time_span_seconds": time_span_seconds, "is_conviction": True } # 5. Base Tracked Smart Money Entry Call: # Every coin ticking filters (MC <= 20k/70k and description) gets called once per wallet per token # If wallet is rapid rotator spraying >=3 tokens in 180s, suppress base entry unless conviction/cluster if is_rotator_spraying: return None entry_key = f"ENTRY_{wallet_name}" if entry_key not in self.triggered_alerts[mint]: self.triggered_alerts[mint].add(entry_key) self.triggered_alerts[mint].add("ENTRY") return { "type": "ENTRY", "mint": mint, "chain": chain_name, "currency": currency, "primary_wallet": wallet_name, "wallet_addr": wallet_addr, "sol_amount": sol_amount, "amount": sol_amount, "buys": regular_buys, "unique_wallets_count": len(unique_wallets), "total_sol": round(total_amount, 3), "total_amount": round(total_amount, 3), "time_span_seconds": time_span_seconds } return None def get_cluster_stats(self, mint: str) -> dict: buys = self.recent_buys.get(mint, []) unique_wallets = {b["wallet_name"]: b for b in buys} total_amount = sum(b["sol_amount"] for b in buys) is_bsc = mint.startswith("0x") accum_wallets = [] for w_name, p in self.wallet_positions.get(mint, {}).items(): if len(p["buys"]) >= 3 and len(p["sells"]) == 0: accum_wallets.append(w_name) return { "buys_count": len(buys), "unique_wallets": list(unique_wallets.keys()), "total_sol": round(total_amount, 3), "total_amount": round(total_amount, 3), "currency": "BNB" if is_bsc else "SOL", "chain": "bsc" if is_bsc else "solana", "accumulating_wallets": accum_wallets }