Spaces:
Sleeping
Sleeping
File size: 17,671 Bytes
fa81f47 7a9b5d0 fa81f47 7a9b5d0 fa81f47 7a9b5d0 9f62f02 fa81f47 7a9b5d0 9f62f02 fa81f47 7a9b5d0 fa81f47 7a9b5d0 fa81f47 7a9b5d0 fa81f47 7a9b5d0 0d5a318 fa81f47 7a9b5d0 0d5a318 7a9b5d0 0d5a318 fa81f47 e40d27f fa81f47 7a9b5d0 fa81f47 7a9b5d0 0d5a318 e40d27f 0d5a318 e40d27f 0d5a318 7a9b5d0 e40d27f 7a9b5d0 e40d27f 7a9b5d0 e40d27f 7a9b5d0 e40d27f 7a9b5d0 e40d27f 7a9b5d0 045f9cf 7a9b5d0 045f9cf e40d27f 9f62f02 7a9b5d0 fa81f47 045f9cf fa81f47 045f9cf fa81f47 7a9b5d0 fa81f47 9f62f02 fa81f47 7a9b5d0 fa81f47 e40d27f fa81f47 045f9cf fa81f47 045f9cf fa81f47 7a9b5d0 fa81f47 9f62f02 fa81f47 7a9b5d0 fa81f47 e40d27f fa81f47 7a9b5d0 fa81f47 | 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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | 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
}
|