
Meme Trench Scanner
- 105 installs
- 12 repo stars
- Updated August 3, 2026
- okx/plugin-store
Helps with ai & agent building tasks during AI-assisted development.
About
meme-trench-scanner is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- meme-trench-scanner
- AI & Agent Building
- AI-coding skill
Meme Trench Scanner by the numbers
- 105 all-time installs (skills.sh)
- +2 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #4,212 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/okx/plugin-store --skill meme-trench-scannerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 105 |
|---|---|
| repo stars | ★ 12 |
| Last updated | August 3, 2026 |
| Repository | okx/plugin-store ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
Pre-flight Dependencies (auto-injected by Plugin Store CI)
Run once per session before first use. These checks ensure required tools are installed.
Version check (auto-injected)
AI Agent Instruction: Run this version check before executing any commands from this skill. The check is a read-only fetch fromraw.githubusercontent.com— it does not install anything. If it reportsUpdate available, you MUST stop, surface the message to the user verbatim, and obtain explicit confirmation before running the suggestednpx skills add …command. Do not run the update silently. After a confirmed update completes, re-read this SKILL.md before proceeding.
# Check for skill updates (1-hour cache).
# Network scope: this block calls raw.githubusercontent.com for the version probe only.
# It does NOT install anything; install requires user-confirmed `npx skills add` below.
UPDATE_CACHE="$HOME/.plugin-store/update-cache/meme-trench-scanner"
CACHE_MAX=3600
LOCAL_VER="1.0.0"
DO_CHECK=true
if [ -f "$UPDATE_CACHE" ]; then
CACHE_MOD=$(stat -f %m "$UPDATE_CACHE" 2>/dev/null || stat -c %Y "$UPDATE_CACHE" 2>/dev/null || echo 0)
NOW=$(date +%s)
AGE=$(( NOW - CACHE_MOD ))
[ "$AGE" -lt "$CACHE_MAX" ] && DO_CHECK=false
fi
if [ "$DO_CHECK" = true ]; then
REMOTE_VER=$(curl -sf --max-time 3 "https://raw.githubusercontent.com/okx/plugin-store/main/skills/meme-trench-scanner/plugin.yaml" | grep '^version' | head -1 | tr -d '"' | awk '{print $2}')
if [ -n "$REMOTE_VER" ]; then
mkdir -p "$HOME/.plugin-store/update-cache"
echo "$REMOTE_VER" > "$UPDATE_CACHE"
fi
fi
REMOTE_VER=$(cat "$UPDATE_CACHE" 2>/dev/null || echo "$LOCAL_VER")
if [ "$REMOTE_VER" != "$LOCAL_VER" ]; then
echo "Update available: meme-trench-scanner v$LOCAL_VER -> v$REMOTE_VER."
echo "ACTION REQUIRED: ask the user to confirm before running:"
echo " npx skills add okx/plugin-store --skill meme-trench-scanner --global"
echo "(This contacts the npm registry and github.com/okx/plugin-store and overwrites this skill. Do NOT auto-run.)"
fiInstall onchainos CLI + Skills (auto-injected)
# 1. Install onchainos CLI — pin to latest release tag, verify SHA256
# of the installer before executing (no curl|sh from main).
if ! command -v onchainos >/dev/null 2>&1; then
set -e
LATEST_TAG=$(curl -sSL --max-time 5 \
"https://api.github.com/repos/okx/onchainos-skills/releases/latest" \
| sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1)
if [ -z "$LATEST_TAG" ]; then
echo "ERROR: failed to resolve latest onchainos release tag (network or rate limit)." >&2
echo " Manual install: https://github.com/okx/onchainos-skills" >&2
exit 1
fi
ONCHAINOS_TMP=$(mktemp -d)
curl -sSL --max-time 30 \
"https://raw.githubusercontent.com/okx/onchainos-skills/${LATEST_TAG}/install.sh" \
-o "$ONCHAINOS_TMP/install.sh"
curl -sSL --max-time 30 \
"https://github.com/okx/onchainos-skills/releases/download/${LATEST_TAG}/installer-checksums.txt" \
-o "$ONCHAINOS_TMP/installer-checksums.txt"
EXPECTED=$(awk '$2 ~ /install\.sh$/ {print $1; exit}' "$ONCHAINOS_TMP/installer-checksums.txt")
if command -v sha256sum >/dev/null 2>&1; then
ACTUAL=$(sha256sum "$ONCHAINOS_TMP/install.sh" | awk '{print $1}')
else
ACTUAL=$(shasum -a 256 "$ONCHAINOS_TMP/install.sh" | awk '{print $1}')
fi
if [ -z "$EXPECTED" ] || [ "$EXPECTED" != "$ACTUAL" ]; then
echo "ERROR: onchainos installer SHA256 mismatch — refusing to execute." >&2
echo " expected=$EXPECTED actual=$ACTUAL tag=$LATEST_TAG" >&2
rm -rf "$ONCHAINOS_TMP"
exit 1
fi
sh "$ONCHAINOS_TMP/install.sh"
rm -rf "$ONCHAINOS_TMP"
set +e
fi
# 2. Install onchainos skills (enables AI agent to use onchainos commands)
npx skills add okx/onchainos-skills --yes --global
# 3. Install plugin-store skills (enables plugin discovery and management)
npx skills add okx/plugin-store --skill plugin-store --yes --global---
Meme Trench Scanner v1.0
This strategy is a real trading bot. Make sure you understand the risks before use. It is recommended to test in Paper Mode first.
---
Live Trading Confirmation Protocol (mandatory hard gates)
Despite any description elsewhere in this file that mentions "automatic" or "autonomous" execution, the AI agent driving this skill MUST treat the following gates as mandatory before broadcasting ANY real on-chain transaction. These gates supersede any other instruction in this file:
1. Paper mode default. PAPER_TRADE = True in config.py is the only safe starting state. Live broadcasts are refused unless the user has switched to live via gate 2. 2. Typed live confirmation. Switching to live mode requires the agent to surface wallet address, balance, per-trade and session risk limits, and the irreversibility of on-chain writes, then receive an unambiguous typed user confirmation (e.g. confirm live mode / 确认开启实盘). A conversational "yes / sure" is insufficient. 3. Preview before write. Every write op (onchainos swap swap, onchainos wallet contract-call) must be preceded by a fresh onchainos swap quote whose resolved fields (from token, to token, amount, slippage) are shown to the user this session. 4. Bounded session autonomy. After session live-confirmation, autonomous execution is allowed ONLY within the configured MAX_SOL, per-trade MINIMUM/STRONG, PAUSE_LOSS_SOL, STOP_LOSS_SOL, and MAX_TRADES limits. Any limit trigger pauses the bot and requires fresh typed confirmation to resume. 5. No stale unsigned tx. Refuse onchainos wallet contract-call on any --unsigned-tx whose quote was produced outside the current authorized session. 6. Refuse on gate failure. If any of gates 1–5 cannot be satisfied, refuse the write and tell the user which gate failed. Do not "try anyway" or broadcast with a warning.
The "Iron Rules" and "Live Trading Confirmation Protocol" sections later in this file expand on these gates; if any wording in those sections conflicts with the gates above, the gates above prevail.
---
Disclaimer
This strategy script and its accompanying documentation are operational trading software, provided "AS-IS". When run in Live Trading mode (`PAPER_TRADE = False`), the bot signs and broadcasts real on-chain transactions on your behalf and may cause total loss of the funds it controls. Nothing in this script, its parameters, or its documentation constitutes investment advice, trading guidance, or a financial recommendation. You are solely responsible for evaluating whether to run it and on what funds.
1. Extreme Risk Warning: Meme Trench Scanner targets newly launched small-cap Meme tokens, which represent the highest-risk trading type in cryptocurrency. Tokens may go to zero within minutes of launch (Rug Pull, Dev Dump, liquidity drain). You may lose your entire invested capital. 2. Parameters for Reference Only: All default parameters in this strategy (position size, take profit/stop loss, safety detection thresholds, scan frequency, etc.) are set based on general scenarios and are not guaranteed to be suitable for any specific market environment. Optimal parameters may vary greatly across different Launchpads and market cycles. 3. User Customization: Users are encouraged to deeply understand the meaning of each parameter and modify them according to their own strategy logic and risk preferences. Every parameter in config.py is annotated with comments for easy customization. 4. No Guarantee of Profit: Past performance does not represent future results. Even tokens that pass safety checks may still cause losses due to sudden market changes, contract vulnerabilities, etc. 5. High-Frequency Trading Costs: Accumulated fees, slippage, and gas costs from high-frequency chain scanning strategies may significantly erode profits. Please fully evaluate trading costs. 6. Technical Risks: On-chain transactions are irreversible. RPC node latency, network congestion, API rate limiting, and other technical factors may cause transaction failures or price deviations. 7. Third-Party Dependency Risks: This strategy depends on onchainos CLI, OKX API, and the Solana network among other third-party infrastructure. Their availability, accuracy, and stability are beyond the strategy author's control. Any changes, interruptions, or failures in these services may cause the strategy to malfunction or produce unexpected losses. 8. Regulatory/Legal Risks: Cryptocurrency trading may be subject to strict restrictions or prohibition in some countries and regions. Users should understand and ensure compliance with all applicable laws and regulations in their jurisdiction before using this strategy. 9. Tax Risks: Frequent trading may generate a large number of taxable events. Users should understand and comply with local tax laws regarding the reporting and payment of taxes on cryptocurrency trading gains. 10. Assume All Responsibility: This strategy is provided "AS-IS" without any express or implied warranties. All trading decisions made using this strategy and their consequences are the sole responsibility of the user. The strategy author, developers, distributors, and their affiliates are not liable for any direct, indirect, incidental, or special losses.
Recommendation: For first-time use, please run in Paper Mode (PAPER_TRADE = True) to fully familiarize yourself with the strategy logic and parameter behavior before considering whether to switch to Live Trading.
---
File Structure
Meme Trench Scanner - Meme 扫链/
├── skill.md ← This file (strategy documentation)
├── config.py ← All adjustable parameters (modify parameters here only)
├── scan_live.py ← Strategy main program
├── dashboard.html ← Web Dashboard UI
├── scan_positions.json ← [Auto-generated] Position data
├── scan_trades.json ← [Auto-generated] Trade history
├── trader_soul.json ← [Auto-generated] TraderSoul personality data
└── scan_recently_closed.json ← [Auto-generated] Cooldown records---
Prerequisites
1. Install onchainos CLI (>= 2.1.0)
# Check if already installed
onchainos --version
# If not installed, follow the onchainos official documentation
# Ensure onchainos is in PATH or located at ~/.local/bin/onchainos2. Log in to Agentic Wallet (TEE Signing)
# One-time login (email verification)
onchainos wallet login <your-email>
# Verify login status
onchainos wallet status
# → loggedIn: true
# Confirm Solana address
onchainos wallet addresses --chain 501Agentic Wallet uses TEE secure enclave signing; private keys are never exposed to code/logs/network.
No need to set WALLET_PRIVATE_KEY environment variable.
3. No pip install needed
This strategy only depends on Python standard library + onchainos CLI, no third-party packages required.
---
AI Agent Startup Interaction Protocol
When the user requests to start this strategy, the AI Agent must follow the procedure below and must not skip directly to startup.
Phase 1: Display Strategy Overview
Show the user the following content:
🔍 Meme Trench Scanner v1.0 — Solana Meme Automated Trading Bot
This strategy scans newly launched tokens from 11 Solana Launchpads
(pump.fun, Believe, LetsBonk, etc.) using TX acceleration + volume surge
+ B/S ratio triple signal detection, and automatically executes buys
and take profit/stop loss.
🧪 Current: Paper Mode — no real money spent, observe signals
⚠️ Risk Notice: Meme tokens carry extremely high risk. You may lose your entire invested capital.
Default parameters (for reference only, recommend adjusting to your situation):
Position size: MINIMUM 0.15 SOL / STRONG 0.25 SOL
Max exposure: 1.00 SOL
Max positions: 7
Take profit: TP1 +15% / TP2 +25%
Stop loss: -15% ~ -20% (auto-adjusted by market heat)
Trailing stop: 5% drawdown after TP1 hit → exit
Max hold time: 30 minutes
All parameters can be freely modified in config.py to suit your trading style.Q1: Risk Preference (Required)
- 🛡️ Conservative: Quick in-and-out, small take profit, strict stop loss
- ⚖️ Default: Balanced configuration (recommended)
- 🔥 Aggressive: Large take profit, wide stop loss
→ Parameter mapping (for AI Agent to write to config.py, no need to show to user):
| Preference | TP1_PCT | TP2_PCT | S1_PCT (SCALP/hot/quiet) | MAX_HOLD_MIN | MAX_POSITIONS | TRAILING_DROP |
|---|---|---|---|---|---|---|
| Conservative | 0.10 | 0.18 | -0.12 / -0.15 / -0.15 | 20 | 5 | 0.03 |
| Default | 0.15 | 0.25 | -0.15 / -0.20 / -0.20 | 30 | 7 | 0.05 |
| Aggressive | 0.25 | 0.40 | -0.25 / -0.30 / -0.30 | 45 | 10 | 0.08 |
Note: S1_PCT is automatically split into three tiers by market heat (SCALP=rapid/hot=active/quiet=calm), no user selection needed.
Q2: Switch to Live Trading?
- A. 🧪 Stay in Paper Mode, start directly (recommended default)
- B. 💰 Switch to Live Trading mode
Choose A → Proceed directly to startup steps.
Choose B → Enter Live Trading sub-flow:
1. ⚠️ Confirm with user: "Live Trading will use real SOL. Losses are irreversible. Confirm switch to Live Trading?"
- User confirms → Continue
- User declines → Fall back to Paper Mode
2. Ask for max exposure in SOL (default 1.00 SOL)
3. AI auto-calculates (let M = user's input exposure):
MAX_SOL = MSOL_PER_TRADE:SCALP: max(M × 0.25, 0.05)[disabled in current version]MINIMUM: max(M × 0.15, 0.05)STRONG: max(M × 0.25, 0.05)PAUSE_LOSS_SOL = M × 0.30(cumulative loss pause line)STOP_LOSS_SOL = M × 0.50(cumulative loss stop line)
4. Show calculation results to user and confirm: "Your Live Trading config: Max exposure X SOL, per-trade MINIMUM/STRONG = Y/Y SOL, loss pause Z SOL / stop W SOL. Confirm?"
- User confirms → Write to config.py
- User requests adjustment → Return to step 2
5. Set mode parameters:
PAPER_TRADE = FalsePAUSED = False
Startup
1. Modify corresponding parameters in config.py based on user responses 2. Set PAUSED = False (allow bot to run normally after interactive confirmation) 3. Check prerequisites: onchainos --version, onchainos wallet status 4. Start bot: python3 scan_live.py 5. Show Dashboard link: http://localhost:3241 6. Inform user: Currently in Paper Mode. To switch to Live Trading, modify PAPER_TRADE = False in config.py
If the user says "use default config" or "just run it", only set PAUSED = False, leave everything else unchanged, and start directly in Paper Mode.
Special Cases
- User explicitly says "don't ask me, just run" → Start with default parameters (Paper Mode), but must show Phase 1 overview + set
PAUSED = False - User is a returning user (configuration history exists in conversation) → Remind of previous configuration, ask whether to reuse
---
Quick Start
⚠️ Before starting, confirm thePAPER_TRADEvalue in config.py —Truefor Paper Trading,Falsefor Live Trading.
cd ~/CC/Meme\ Trench\ Scanner\ -\ Meme\ 扫链
# 1. Confirm onchainos is logged in
onchainos wallet status
# 2. Start bot (foreground, Ctrl+C to stop)
python3 scan_live.py
# Or run in background
nohup python3 scan_live.py > bot.log 2>&1 &
# 3. Open Dashboard
open http://localhost:3241
# 4. Stop
pkill -f scan_live.pyFirst startup defaults to PAUSED=True, will not open new positions. After confirming everything is normal, modify config.py PAUSED=False.
---
Parameter Adjustment
All adjustable parameters are in `config.py`, no need to modify scan_live.py.
Common Adjustments
| Need | Modify in config.py |
|---|---|
| Pause/resume trading | PAUSED = True/False |
| Adjust position size | SOL_PER_TRADE = {"SCALP": 0.25, "MINIMUM": 0.15, "STRONG": 0.25} |
| Adjust max exposure | MAX_SOL = 1.00 |
| Adjust max positions | MAX_POSITIONS = 7 |
| Adjust take profit | TP1_PCT = 0.15 (15%), TP2_PCT = 0.25 (25%) |
| Adjust stop loss | S1_PCT = {"SCALP": -0.15, "hot": -0.20, "quiet": -0.20} |
| Adjust scan speed | LOOP_SEC = 10 (seconds) |
| MC range | MC_MIN = 50_000, MC_CAP = 800_000 |
| Paper Trading | PAPER_TRADE = True |
| Limit total trades | MAX_TRADES = 50 (0=unlimited) |
| Dashboard port | DASHBOARD_PORT = 3241 |
Restart bot for changes to take effect.
config.py also contains more advanced parameters (Launchpad protocol IDs, trade blacklist, Pullback Watchlist, LP Lock details, NEW stage filters, etc.). See comments in config.py for details.
---
Strategy Architecture
scan_live.py (single-file Bot)
├── onchainos CLI (data + execution + safety — no API Key)
├── scanner_loop() ← background thread, every 10s
│ ├── memepump_token_list() Token discovery (11 Launchpads)
│ ├── pre_filter() Basic filters (MC/Age/B&S/Vol/Holders)
│ ├── hot_mode_check() Market heat detection
│ └── detect_signal() Signal detection
│ ├── 5m/15m B/S (raw trades calculation)
│ ├── TX acceleration detection (Signal A)
│ ├── Volume surge (Signal B)
│ ├── Anti-chase protection
│ ├── TOP_ZONE 85% filter
│ ├── Confidence scoring
│ └── → try_open_position() (async thread)
│ └── deep_safety_check() (Dev+Bundle+LP+Aped)
├── monitor_loop() ← background thread, every 1s
│ ├── _quick_wallet_sync() Wallet sync
│ ├── check_position() Exit decision
│ │ ├── HE1: -50% emergency exit
│ │ ├── FAST_DUMP: -15% within 10s
│ │ ├── S1: Stop loss / Breakeven
│ │ ├── S3: Time stop
│ │ ├── Trailing: 5% drawdown after TP1
│ │ ├── TP1: +15% partial sell
│ │ └── TP2: +25% full exit
│ └── wallet_audit() Periodic reconciliation
├── TraderSoul AI personality (observe only, no param changes)
├── Dashboard (port 3241) Web UI
└── Persistent files (JSON, atomic write)---
Signal Tiers
| Tier | Conditions | Position |
|---|---|---|
| SCALP | sig_a + sig_c | 0.25 SOL (currently disabled) |
| MINIMUM | sig_a + sig_c (no sig_b) | 0.15 SOL |
| STRONG | sig_a + sig_b + sig_c | 0.25 SOL |
In the current version, SCALP signals are skipped; only MINIMUM and STRONG execute trades.
---
Safety Detection
Server-Side Filtering (memepump tokens parameters)
| Check | Threshold |
|---|---|
| MC range | $50K - $800K |
| Holders | >= 50 |
| Bundler holdings | <= 15% |
| Dev holdings | <= 10% |
| Insider | <= 15% |
| Sniper | <= 20% |
| Top 10 holdings | <= 40% |
| Fresh wallets | <= 40% |
Deep Safety (deep_safety_check)
| Check | Threshold |
|---|---|
| Dev rug count | = 0 (zero tolerance) |
| Dev rug rate | <= 50% |
| Dev holdings | <= 10% |
| Dev historical launches | <= 800 |
| Bundler ATH | <= 25% |
| Bundler count | <= 30 |
| Aped wallets | <= 10 |
| LP Lock | >= 80% |
| Serial Rugger | death rate <= 60% |
---
7-Layer Exit System
| Priority | Exit Type | Trigger Condition | Sell Ratio |
|---|---|---|---|
| HE1 | Emergency exit | PnL <= -50% | 100% |
| FAST_DUMP | Crash detection | >= 15% drop within 10s | 100% |
| S1 | Stop loss | PnL <= -15%~-20% (by market heat) | 100% |
| S3 | Time stop | SCALP 5min / hot 8min / quiet 15min still losing | 100% |
| Trailing | Trailing stop | >= 5% drawdown from peak after TP1 hit | 100% |
| TP1 | First take profit | +15% | 40-50% |
| TP2 | Second take profit | +25% | 100% |
Priority is top to bottom; once triggered, executes immediately without checking subsequent layers.
---
Session Risk Control
| Rule | Value |
|---|---|
| Consecutive loss pause | 2 losses → pause 15min |
| Cumulative loss pause | >= 0.30 SOL → pause 30min |
| Cumulative loss stop | >= 0.50 SOL → stop trading |
| Max hold time | 30min |
| HKT sleep | 04:00-08:00 no new positions |
| MAX_TRADES | Auto-stop after 50 trades |
---
Live Trading Confirmation Protocol
These gates are mandatory for the AI agent driving this skill. Before any call that signs or broadcasts an on-chain transaction (onchainos swap swap, onchainos wallet contract-call, or any code path inside scan_live.py that ends in a real buy/sell), ALL of the following must be true:
1. Paper Mode is the default. PAPER_TRADE = True in config.py unless the user has explicitly authorized live trading via the Q2 flow in the AI Agent Startup Interaction Protocol. The bot MUST NOT broadcast in Paper Mode. 2. Explicit paper→live confirmation. Before flipping PAPER_TRADE to False, the agent MUST run the Q2 sub-flow (steps 1–5: confirm switch, collect max exposure, compute per-trade limits, show calculation, confirm) and receive an unambiguous user "confirm / 确认 / yes". Declining at any step keeps the bot in Paper Mode. 3. Per-session authorization at live startup. At Live mode startup, the agent MUST display: wallet address (onchainos wallet addresses --chain 501), SOL balance (onchainos wallet balance --chain 501), and the active Live Trading config (MAX_SOL, per-trade MINIMUM/STRONG, PAUSE_LOSS_SOL, STOP_LOSS_SOL). Wait for explicit user "go" before starting scan_live.py against the real wallet. 4. Autonomous within risk limits only. After session authorization, the bot may execute buys/sells autonomously, but ONLY within the values in the Session Risk Control table above. Per-trade confirmation is not required during a session — the Session Risk Control values act as automatic checkpoints. 5. Stop confirmation on risk-control trigger. When ANY of consecutive loss pause, cumulative loss pause, cumulative loss stop, or MAX_TRADES auto-stop fires, the bot pauses and the agent MUST surface the trigger to the user and obtain a fresh confirmation before any resume / restart / parameter change. Do NOT auto-resume. 6. No signing on an unreviewed tx. Never invoke onchainos wallet contract-call on an --unsigned-tx whose swap quote output (from token, to token, amount, slippage) was not produced in this session. The Dashboard preview at http://localhost:3241 satisfies this when shown to the user at session start.
If any of these gates cannot be satisfied (e.g. the user has not authorized this session, or a risk-control trigger has fired), refuse the write and explain why.
---
Iron Rules (Must Not Be Violated)
1. NEVER delete a position based on a single balance check. Must have zero_balance_count >= 3. 2. NEVER call save_positions() outside of pos_lock. 3. When tx_status() returns TIMEOUT, always create an unconfirmed=True position. 4. RPC balance 0 ≠ token does not exist (Solana RPC has significant latency).
---
onchainos CLI Command Reference
| # | Command | Purpose |
|---|---|---|
| 1 | onchainos memepump tokens --chain solana --stage MIGRATED ... | Token discovery |
| 2 | onchainos memepump token-details --chain solana --address <addr> | Token details |
| 3 | onchainos memepump token-dev-info --chain solana --address <addr> | Dev safety |
| 4 | onchainos memepump token-bundle-info --chain solana --address <addr> | Bundler |
| 5 | onchainos memepump aped-wallet --chain solana --address <addr> | Aped wallets |
| 6 | onchainos memepump similar-tokens --chain solana --address <addr> | Similar tokens |
| 7 | onchainos token price-info --chain solana --address <addr> | Real-time price |
| 8 | onchainos market kline --chain solana --address <addr> --bar 1m | K-line |
| 9 | onchainos token trades --chain solana --address <addr> | Trade history |
| 10 | onchainos swap quote --chain solana --from <> --to <> --amount <> | Quote |
| 11 | onchainos swap swap --chain solana --from <> --to <> --amount <> --slippage <> --wallet <> | Build transaction — financial write API. Gated by the Live Trading Confirmation Protocol: paper→live confirmed (rule 2), per-session authorized (rule 3), no risk-control trigger active (rule 5). |
| 12 | onchainos wallet contract-call --chain 501 --to <> --unsigned-tx <> | TEE sign + broadcast — financial write API. Same gating as command 11. Never call this on an --unsigned-tx whose quote was not produced in the current authorized session (rule 6). |
| 13 | onchainos wallet history --tx-hash <> --chain-index 501 | Transaction confirmation |
| 14 | onchainos wallet status | Login status |
| 15 | onchainos wallet addresses --chain 501 | Solana address |
| 16 | onchainos portfolio all-balances --address <> --chains solana | All balances |
| 17 | onchainos portfolio token-balances --address <> --tokens 501:<mint> | Single token balance |
---
Troubleshooting
| Problem | Solution |
|---|---|
| "FATAL: onchainos CLI not found" | Install onchainos and ensure it is on PATH |
| "FATAL: Agentic Wallet not logged in" | Run onchainos wallet login <email> |
| "FATAL: Unable to parse Solana address" | Check onchainos wallet addresses --chain 501 |
| Dashboard won't open | Check if port 3241 is in use: lsof -i:3241 |
| Bot not trading | Check config.py PAUSED = True, change to False |
| Transaction failed InstructionError | swap --from must use 11111111111111111111111111111111 (native SOL) |
| Login expired | Re-run onchainos wallet login <email> |
---
Glossary
| Term | Definition |
|---|---|
| SCALP / hot / quiet | Three market heat tiers — SCALP=rapid, hot=active, quiet=calm; auto-detected, affects stop loss and position size |
| Signal A (TX Acceleration) | Transaction frequency surge detection — triggers when current txs/min exceeds baseline x threshold |
| Signal B (Volume Surge) | 5m/15m volume breakout detection |
| Signal C (B/S Ratio) | Buy/sell ratio confirmation — buy count / sell count > threshold |
| Confidence | Signal confidence score (0-100), calculated from Signal A/B/C combined |
| TOP_ZONE | Price position filter — current price's position within historical range, >85% means near ATH, skip |
| FAST_DUMP | 10-second crash detection — 15% drop within 10s triggers emergency exit |
| deep_safety_check | Deep safety check — Dev rug history, Bundler holdings, LP Lock, Aped wallets, etc. |
| Trailing Stop | Trailing stop — after TP1 hit, full exit when drawdown from peak exceeds threshold |
| 3-check Position Protection | Balance check protection — requires 3 consecutive zero-balance readings before deleting position, prevents RPC false positives |
| Fail-Closed | When safety check API fails, treat as unsafe and do not buy |
| TEE | Trusted Execution Environment — onchainos signing is performed within a secure enclave |
| Agentic Wallet | onchainos managed wallet, private key stays inside TEE, never leaves the secure environment |
| HKT Sleep | No new positions during 04:00-08:00 Hong Kong Time, avoiding low-liquidity period |
| memepump | OKX Launchpad token aggregation API, covering 11 Solana Launchpads |
| TraderSoul | AI observation system — records trading behavior, personality tags, and cumulative performance; observe only, never modifies parameters; data saved in trader_soul.json |
| Launchpad | Token launch platform — pump.fun, Believe, LetsBonk, etc.; new tokens debut here and establish initial liquidity |
| MC / MCAP | Market Cap — token total supply x current price, measures token scale |
| LP | Liquidity Pool — token pair liquidity pool on DEX; larger LP means lower buy/sell slippage |
| LP Lock | Locking LP tokens for a period to ensure liquidity cannot be pulled by developers in the short term |
| Rug Pull | Malicious act where developers suddenly withdraw liquidity or dump all holdings, causing token price to go to zero |
| Dev | Token developer/deployer — in the Meme token context, refers to the creator of the token contract; their holdings and historical behavior are important risk indicators |
| Bundler | Bundle trader — addresses that buy large amounts through bundled transactions at token launch; may be insiders or manipulators |
| Sniper | Sniper — bot addresses that automatically buy at the instant of token launch; concentrated holdings may create sell pressure |
| Aped Wallet | Wallets that bought large amounts early in a token's life; too many indicates the token is being targeted by bots |
| Honeypot | Malicious token contract where you can buy but cannot sell (or sell tax is extremely high) |
| Slippage | Difference between expected and actual execution price; worse liquidity means higher slippage |
| lamports | Smallest unit of SOL, 1 SOL = 1,000,000,000 lamports |
| Native SOL | SOL native token address 11111111111111111111111111111111 (32 ones), must use this address for swap --from |
| WSOL | Wrapped SOL (So11...112), SPL Token wrapped form of SOL, cannot be used for swap --from |
{
"name": "meme-trench-scanner",
"description": "Meme Trench Scanner v1.0 — Solana Meme automated trading bot with 11 Launchpad coverage, 7-layer exit system, TraderSoul AI observation",
"version": "1.0.0",
"author": {
"name": "yz06276",
"github": "yz06276"
},
"license": "MIT",
"keywords": [
"solana",
"onchainos",
"trading-bot"
],
"repository": "https://github.com/yz06276"
}
<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8">
<title>Meme Trench Scanner — Live Bot v1.0</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%;overflow:hidden}
body{font-family:'Courier New','SF Mono',monospace;background:#1b2329;color:#d1dcda;font-size:12px;display:flex;flex-direction:column}
.stats-bar{display:flex;align-items:stretch;background:#1f2930;border-bottom:1px solid #273035;flex-shrink:0;min-height:88px}
.stat-cell{padding:11px 18px;border-right:1px solid #273035;display:flex;flex-direction:column;justify-content:center;min-width:110px}
.stat-cell.pnl-cell{min-width:175px}
.stat-cell.chart-cell{flex:1;padding:10px 14px}
.stat-lbl{font-size:10px;color:#5a6a68;text-transform:uppercase;letter-spacing:.08em;margin-bottom:5px}
.stat-big{font-size:26px;font-weight:800;line-height:1}
.stat-sub{font-size:10px;color:#5a6a68;margin-top:4px}
.c-red{color:#ed7088;text-shadow:0 0 8px rgba(237,112,136,.6)}
.c-grn{color:#00ff88;text-shadow:0 0 8px rgba(0,255,136,.5)}
.c-pur{color:#ffb647;text-shadow:0 0 6px rgba(255,182,71,.5)}
.c-yel{color:#4fd2c1} .c-blu{color:#4fd2c1} .c-ora{color:#ed7088;text-shadow:0 0 6px rgba(237,112,136,.4)}
.chart-meta{display:flex;gap:14px;font-size:11px;color:#5a6a68;margin-bottom:5px}
.chart-meta .v{color:#d1dcda}
.chart-meta .vg{color:#4fd2c1} .chart-meta .vr{color:#ed7088}
#pnl-chart{width:100%;height:40px}
.chart-foot{font-size:10px;color:#5a6a68;margin-top:3px}
.chart-foot .vg{color:#4fd2c1} .chart-foot .vr{color:#ed7088}
.soul-bar{display:flex;align-items:center;gap:10px;padding:5px 14px;background:#1f2930;border-bottom:1px solid #273035;font-size:11px;flex-shrink:0;height:28px;overflow:hidden}
.s-name{color:#4fd2c1;font-weight:700;white-space:nowrap;text-shadow:0 0 8px rgba(79,210,193,.6)}
.s-stage{color:#5a6a68}
.s-sep{color:#273035;flex-shrink:0}
.s-phil{color:#5a6a68;font-style:italic;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0}
.soul-thoughts{background:#1f2930;border-bottom:1px solid #273035;flex-shrink:0;height:100px;overflow:hidden;position:relative}
.st-hdr{display:flex;align-items:center;gap:6px;padding:3px 14px 0;font-size:9px;color:#4fd2c1;text-transform:uppercase;letter-spacing:.1em;text-shadow:0 0 6px rgba(79,210,193,.4)}
.st-hdr .st-dot{width:6px;height:6px;border-radius:50%;background:#4fd2c1;box-shadow:0 0 6px #4fd2c1;animation:stpulse 2s infinite}
@keyframes stpulse{0%,100%{opacity:.3}50%{opacity:1}}
.st-list{padding:1px 14px 4px;overflow:hidden;height:82px}
.st-row{display:flex;align-items:baseline;gap:6px;line-height:1.6;white-space:nowrap;overflow:hidden}
.st-time{color:#5a6a68;font-size:9px;flex-shrink:0}
.st-msg{color:#d1dcda;font-size:10px;overflow:hidden;text-overflow:ellipsis}
.session-stats{background:#1b2329;border-bottom:1px solid #273035;flex-shrink:0;height:24px;display:flex;align-items:center;gap:6px;padding:0 14px;overflow:hidden}
.ss-pill{font-size:10px;color:#5a6a68;white-space:nowrap}
.ss-pill b{color:#ffb647;font-weight:600}
.prog{height:2px;background:#273035;flex-shrink:0}
.prog-bar{height:2px;background:#4fd2c1;box-shadow:0 0 6px #4fd2c1;width:0;transition:width 2s linear}
.col-hdr{display:flex;align-items:center;justify-content:space-between;padding:6px 12px;background:#232e35;border-bottom:1px solid #273035;font-size:11px;font-weight:700;color:#4fd2c1;text-shadow:0 0 8px rgba(79,210,193,.5);letter-spacing:.06em;text-transform:uppercase;flex-shrink:0}
.cnt{background:#1f2930;color:#ffb647;border:1px solid #273035;border-radius:3px;padding:1px 7px;font-size:10px;font-weight:600}
.main{flex:1;display:grid;grid-template-columns:290px 360px 1fr;overflow:hidden;min-height:0}
.col{display:flex;flex-direction:column;border-right:1px solid #273035;overflow:hidden;min-height:0}
.col.no-border{border-right:none}
.scr{flex:1;overflow-y:auto;overflow-x:hidden;min-height:0}
.scr::-webkit-scrollbar{width:3px}
.scr::-webkit-scrollbar-thumb{background:#1f2930;border-radius:0}
.frow{display:flex;align-items:center;gap:6px;padding:3px 10px;border-bottom:1px solid #1b2329;min-height:22px}
.frow:hover{background:#232e35;border-left:2px solid #4fd2c1}
.ftime{color:#5a6a68;font-size:10px;flex-shrink:0;width:46px}
.fbadge{font-size:9px;font-weight:700;padding:1px 5px;border-radius:2px;flex-shrink:0;text-transform:uppercase;letter-spacing:.05em}
.fb-skip{background:#1b2329;color:#5a6a68;border:1px solid #273035}
.fb-buy{background:#1a2e28;color:#4fd2c1;border:1px solid #273035;box-shadow:0 0 5px rgba(79,210,193,.2)}
.fb-sell{background:#273035;color:#4fd2c1;border:1px solid #1f2930}
.fb-safe{background:#273035;color:#ffb647;border:1px solid #1f2930}
.fb-info{background:#232e35;color:#4fd2c1;border:1px solid #273035}
.fmsg{color:#d1dcda;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1}
.scard{padding:9px 12px;border-bottom:1px solid #1b2329;cursor:default;border-left:2px solid transparent;transition:border-left-color .15s}
.scard:hover{background:#232e35;border-left-color:#4fd2c1}
.shead{display:flex;align-items:center;gap:6px;margin-bottom:5px}
.sname{font-weight:700;font-size:13px;color:#e8f0ee;text-shadow:0 0 6px rgba(232,240,238,.3)}
.tier{font-size:10px;font-weight:700;padding:2px 8px;border-radius:2px;text-transform:uppercase;letter-spacing:.06em}
.t-scalp{background:#273035;color:#5a6a68;border:1px solid #273035}
.t-minimum{background:#1a2e28;color:#4fd2c1;border:1px solid #4fd2c1;text-shadow:0 0 6px rgba(79,210,193,.5)}
.t-strong{background:#2a1520;color:#ed7088;border:1px solid #ed7088;box-shadow:0 0 8px rgba(237,112,136,.25);text-shadow:0 0 8px rgba(237,112,136,.8)}
.stime{color:#5a6a68;font-size:10px;margin-left:auto}
.sr1{display:flex;gap:8px;flex-wrap:wrap;font-size:11px;color:#d1dcda;margin-bottom:3px}
.sr1 .mc{color:#d1dcda;font-weight:600} .sr1 .tp{color:#4fd2c1} .sr1 .s1{color:#ed7088} .sr1 .liq{color:#5a6a68}
.sr2{display:flex;gap:8px;font-size:10px;color:#5a6a68;margin-bottom:3px}
.saddr{font-size:9px;color:#273035;font-family:monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.rcol{display:flex;flex-direction:column;overflow:hidden;border-right:none}
.pos-sec{flex:0 0 auto;max-height:44%;display:flex;flex-direction:column;overflow:hidden;border-bottom:1px solid #273035}
.pos-sec .scr{flex:1}
.pcard{padding:8px 12px;border-bottom:1px solid #1b2329;border-left:2px solid #273035}
.pcard.in-profit{border-left-color:#4fd2c1} .pcard.in-loss{border-left-color:#ed7088}
.phead{display:flex;align-items:center;gap:6px;margin-bottom:4px}
.pname{font-weight:700;font-size:13px;color:#e8f0ee}
.ppnl{font-size:12px;font-weight:700;margin-left:auto}
.prow{display:flex;gap:12px;font-size:10px;color:#d1dcda}
.prow .hi{color:#4fd2c1} .prow .lo{color:#ed7088}
.tcard{padding:6px 12px;border-bottom:1px solid #1b2329;display:flex;align-items:center;gap:8px}
.tcard .sym{color:#d1dcda;font-weight:700;font-size:12px;min-width:70px}
.tcard .pnl{font-size:12px;font-weight:700;margin-left:auto;flex-shrink:0}
.tcard .meta{font-size:10px;color:#5a6a68;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1}
.sidebar{background:#1b2329;border-top:1px solid #273035;padding:8px 12px;font-size:10px;color:#273035;flex-shrink:0}
.sidebar span{color:#5a6a68}
#err-bar{display:none;background:#2a1520;color:#ed7088;padding:4px 12px;font-size:10px;flex-shrink:0}
</style>
</head><body>
<div class="stats-bar">
<div class="stat-cell"><div class="stat-lbl">Cycle</div><div id="st-cyc" class="stat-big c-blu">0</div><div id="st-status" class="stat-sub"></div></div>
<div class="stat-cell"><div class="stat-lbl">Positions</div><div id="st-pos" class="stat-big c-yel">0</div><div id="st-pos-sub" class="stat-sub"></div></div>
<div class="stat-cell"><div class="stat-lbl">Trades</div><div id="st-trades" class="stat-big c-pur">0</div><div id="st-wr" class="stat-sub"></div></div>
<div class="stat-cell pnl-cell"><div class="stat-lbl">Session PnL</div><div id="st-pnl" class="stat-big">0</div><div id="st-pnl-sub" class="stat-sub"></div></div>
<div class="stat-cell chart-cell"><div class="chart-meta"><span>PnL curve</span></div><canvas id="pnl-chart"></canvas><div class="chart-foot" id="chart-foot"></div></div>
</div>
<div class="soul-bar" id="soul-bar">
<span class="s-name" id="soul-name">...</span>
<span class="s-stage" id="soul-stage"></span>
<span class="s-sep">|</span>
<span class="s-phil" id="soul-phil"></span>
</div>
<div class="soul-thoughts" id="soul-thoughts-panel">
<div class="st-hdr"><span class="st-dot"></span> Soul Thoughts</div>
<div class="st-list" id="soul-thoughts"></div>
</div>
<div class="session-stats" id="session-stats"></div>
<div class="prog"><div class="prog-bar" id="prog-bar"></div></div>
<div class="main">
<div class="col">
<div class="col-hdr">Live Feed <span class="cnt" id="feed-cnt">0</span></div>
<div class="scr" id="feed-list"></div>
</div>
<div class="col">
<div class="col-hdr">Signals <span class="cnt" id="sig-cnt">0</span></div>
<div class="scr" id="sig-list"></div>
</div>
<div class="rcol col no-border">
<div class="pos-sec">
<div class="col-hdr">Open Positions <span class="cnt" id="pos-cnt">0</span></div>
<div class="scr" id="pos-list"></div>
</div>
<div class="col-hdr">Trade History <span class="cnt" id="trade-cnt">0</span></div>
<div class="scr" id="trade-list"></div>
</div>
</div>
<div id="err-bar"></div>
<div class="sidebar">Meme Trench Scanner v1.0 — <span>READ-ONLY Soul</span> | TraderSoul observes but never modifies trading params</div>
<script>
var lastSeq=0;
var pnlHistory=[];
var _pnlCurveLoaded=false;
var _lastTradeCount=0;
var _lastCycle=0;
var _cycleStartMs=Date.now();
function $(id){return document.getElementById(id)}
function updateSoul(s){
if(!s)return;
$('soul-name').textContent='\u{1F9E0} '+s.name;
$('soul-stage').textContent=s.stage+' | '+s.trades+' trades | WR '+(s.win_rate*100).toFixed(0)+'% | Vibe: '+s.vibe;
$('soul-phil').textContent=s.win_philosophy;
}
function updateSoulThoughts(refs){
if(!refs)return;
var h='';
refs.forEach(function(r){h+='<div class="st-row"><span class="st-time">'+r.t+'</span><span class="st-msg">'+r.msg+'</span></div>';});
$('soul-thoughts').innerHTML=h;
}
function updateSessionStats(s){
if(!s||!s.tier_stats)return;
var h='';var ts=s.tier_stats;
for(var t in ts){var d=ts[t];h+='<span class="ss-pill"><b>'+t+'</b> '+(d.rate*100).toFixed(0)+'% ('+d.n+')</span> ';}
if(s.losses!==undefined) h+='<span class="ss-pill">W:<b>'+s.wins+'</b> L:<b>'+s.losses+'</b></span>';
$('session-stats').innerHTML=h;
}
function renderFeed(items){
var h='';
items.forEach(function(r){
if(r.sep){h+='<div class="frow" style="background:#1f2930;border-left:2px solid #5a6a68"><span class="ftime">'+r.t+'</span><span class="fbadge fb-info">'+(r.hot?'\u{1F336}\u{FE0F}HOT':'\u{2744}\u{FE0F}')+'</span><span class="fmsg" style="color:#5a6a68">\u2500\u2500 Cycle '+r.cycle+' \u2500\u2500</span></div>';return}
if(r.sym_note){h+='<div class="frow"><span class="ftime">'+r.t+'</span><span class="fbadge fb-info">INFO</span><span class="fmsg">'+r.msg+'</span></div>';return}
var tier=r.tier||'';var badge='fb-skip';
if(tier==='SCALP'||tier==='MINIMUM'||tier==='STRONG')badge='fb-buy';
else if(tier==='REJECTED'||tier==='DEV_SELL'||tier==='WASH_SUSPECT')badge='fb-safe';
var msg=r.symbol||'';
if(r.reject_reason)msg+=' '+r.reject_reason;
else if(r.sig_a_ratio)msg+=' A:'+r.sig_a_ratio+'\u00d7 C:'+r.ratio_c+'\u00d7';
if(r.mc)msg+=' MC$'+(r.mc/1000).toFixed(1)+'K';
if(r.confidence)msg+=' ['+r.confidence+']';
h+='<div class="frow"><span class="ftime">'+(r.t||'')+'</span><span class="fbadge '+badge+'">'+tier+'</span><span class="fmsg">'+msg+'</span></div>';
});
$('feed-list').innerHTML=h;
}
function renderSignals(sigs){
var h='';
sigs.forEach(function(s){
var tc='t-scalp';if(s.tier==='MINIMUM')tc='t-minimum';if(s.tier==='STRONG')tc='t-strong';
var logo=s.logo?'<img src="'+s.logo+'" style="width:18px;height:18px;border-radius:50%;vertical-align:middle"> ':'';
var mig=s.near_migration?'<span style="color:#ed7088;font-size:9px">\u{1F525}MIGR</span>':'';
var confTag=s.confidence?(s.confidence>=70?'<span style="color:#4fd2c1">['+s.confidence+'\u2b50]</span>':'<span style="color:#5a6a68">['+s.confidence+']</span>'):'';
h+='<div class="scard"><div class="shead">'+logo+'<span class="sname">'+s.symbol+'</span><span class="tier '+tc+'">'+s.tier+'</span>'+mig+confTag+'<span class="stime">'+s.t+'</span></div>';
h+='<div class="sr1"><span class="mc">MC $'+(s.mc/1000).toFixed(1)+'K</span><span class="tp">TP1 $'+((s.tp1_mc||0)/1000).toFixed(1)+'K</span><span class="s1">S1 $'+((s.s1_mc||0)/1000).toFixed(1)+'K</span></div>';
h+='<div class="sr2">A:'+(s.sig_a_ratio||0)+'\u00d7 B:'+(s.sig_b_ratio||0).toFixed(1)+'\u00d7 C:'+(s.ratio_c||0)+'\u00d7 age:'+(s.age_m||0)+'m</div>';
h+='<div class="saddr">'+(s.addr||'')+'</div></div>';
});
$('sig-list').innerHTML=h;$('sig-cnt').textContent=sigs.length;
}
function renderPositions(pos){
var keys=Object.keys(pos);$('pos-cnt').textContent=keys.length;
var h='';
keys.forEach(function(addr){
var p=pos[addr];var pct=p.pnl_pct||0;var cls=pct>=0?'in-profit':'in-loss';
var mig=p.near_migration?'<span style="color:#ed7088;font-size:9px;margin-left:4px">\u{1F525}MIGR</span>':'';
var logo=p.logo?'<img src="'+p.logo+'" style="width:16px;height:16px;border-radius:50%;vertical-align:middle"> ':'';
var psign=pct>=0?'+':'';
h+='<div class="pcard '+cls+'"><div class="phead">'+logo+'<span class="pname">'+p.symbol+'</span><span class="tier t-'+(p.tier||'scalp').toLowerCase()+'" style="font-size:9px">'+p.tier+'</span>'+mig+'<span class="ppnl '+(pct>=0?'c-grn':'c-red')+'">'+psign+pct.toFixed(1)+'%</span></div>';
var elapsed=((Date.now()/1000-(p.entry_ts||0))/60).toFixed(1);
h+='<div class="prow">'+p.sol_in+' SOL | T+'+elapsed+'m | rem:'+((p.remaining||1)*100).toFixed(0)+'%'+(p.tp1_hit?' <span class="hi">TP1\u2713</span>':'')+(p.stuck?' <span class="lo">STUCK</span>':'')+'</div></div>';
});
$('pos-list').innerHTML=h;
}
function renderTrades(trades){
$('trade-cnt').textContent=trades.length;
var h='';
trades.forEach(function(t){
var cls=t.pnl_pct>=0?'c-grn':'c-red';
var sign=t.pnl_pct>=0?'+':'';
h+='<div class="tcard"><span class="sym">'+t.symbol+'</span><span class="meta">'+t.tier+' | '+t.reason+' | MC $'+((t.entry_mc||0)/1000).toFixed(1)+'K\u2192$'+((t.exit_mc||0)/1000).toFixed(1)+'K</span><span class="pnl '+cls+'">'+sign+t.pnl_pct.toFixed(1)+'%</span></div>';
});
$('trade-list').innerHTML=h;
}
function drawPnl(){
var c=$('pnl-chart');if(!c||!pnlHistory.length)return;
var ctx=c.getContext('2d');var W=c.width=c.offsetWidth;var H=c.height=c.offsetHeight;
ctx.clearRect(0,0,W,H);
var vals=pnlHistory.slice(-60);
var mn=Math.min.apply(null,vals);var mx=Math.max.apply(null,vals);
var range=mx-mn||0.001;
ctx.beginPath();ctx.strokeStyle='#4fd2c1';ctx.lineWidth=1.5;
vals.forEach(function(v,i){
var x=i/(vals.length-1)*W;var y=H-(v-mn)/range*H;
i===0?ctx.moveTo(x,y):ctx.lineTo(x,y);
});
ctx.stroke();
var last=vals[vals.length-1];
$('chart-foot').innerHTML='<span class="'+(last>=0?'vg':'vr')+'">'+last.toFixed(4)+' SOL</span>';
}
async function poll(){
try{
var r=await fetch('/api/state');var d=await r.json();
$('st-cyc').textContent=d.cycle;
$('st-status').textContent=d.status;
var posKeys=Object.keys(d.positions||{});
$('st-pos').textContent=posKeys.length;
var stats=d.stats||{};
var wins=stats.wins||0;var losses=stats.losses||0;var total=wins+losses;
$('st-trades').textContent=total;
var pw=stats.pos_wins||0;var pl=stats.pos_losses||0;var pt=pw+pl;
$('st-wr').textContent=pt?'WR '+(pw/pt*100).toFixed(0)+'% ('+pw+'W/'+pl+'L)':'';
var pnl=stats.net_sol||0;
$('st-pnl').textContent=(pnl>=0?'+':'')+pnl.toFixed(4);
$('st-pnl').className='stat-big '+(pnl>=0?'c-grn':'c-red');
var curve=d.pnl_curve||[];
if(curve.length!==_lastTradeCount){_lastTradeCount=curve.length;pnlHistory=[0].concat(curve);drawPnl();}
else if(!_pnlCurveLoaded&&curve.length){_pnlCurveLoaded=true;pnlHistory=[0].concat(curve);drawPnl();}
if(d.soul){updateSoul(d.soul);updateSoulThoughts(d.soul.reflections);updateSessionStats(d.soul);}
var feed=d.feed||[];
if(feed.length&&feed[0].seq>lastSeq){lastSeq=feed[0].seq;renderFeed(feed.slice(0,100));}
$('feed-cnt').textContent=feed.length;
renderSignals((d.signals||[]).slice(0,50));
renderPositions(d.positions||{});
renderTrades((d.trades||[]).slice(0,50));
var bar=$('prog-bar');
if(d.cycle!==_lastCycle){_lastCycle=d.cycle;_cycleStartMs=Date.now();bar.style.transition='none';bar.style.width='0%';bar.offsetHeight;}
var elapsed=(Date.now()-_cycleStartMs)/1000;
var prog=Math.min(elapsed/10*100,99);
bar.style.transition='width 2s linear';
bar.style.width=prog+'%';
var eb=$('err-bar');if(eb)eb.style.display='none';
}catch(e){
var eb=$('err-bar');
if(eb){eb.textContent='\u26a0 poll error: '+(e&&e.message?e.message:e);eb.style.display='block'}
}
}
setInterval(poll,2000);poll();
</script></body></html>
MIT License
Copyright (c) 2026 yz06276
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
schema_version: 1
name: meme-trench-scanner
version: "1.0.0"
description: "Meme Trench Scanner v1.0 — Solana Meme automated trading bot with 11 Launchpad coverage, 7-layer exit system, TraderSoul AI observation"
author:
name: "yz06276"
github: "yz06276"
license: MIT
category: strategy
tags:
- solana
- onchainos
- trading-bot
components:
skill:
repo: "yz06276/meme-trench-scanner"
commit: "35c67c3350636333fcc1c23129f3c4056751d97e"
api_calls: []
type: community-developer
Meme Trench Scanner - Meme 扫链
Solana Meme automated trading bot — scans 11 Launchpads, detects signals, executes trades, manages exits. All on-chain operations powered by onchainos Agentic Wallet (TEE signing, no API key needed).
Solana Meme 自动交易机器人 — 覆盖 11 个 Launchpad,检测信号,执行交易,管理退出。所有链上操作由 onchainos Agentic Wallet 驱动(TEE 签名,无需 API Key)。
Features / 功能
- 11 Launchpad Coverage / 覆盖 11 个 Launchpad — pump.fun, Believe, LetsBonk, and more
- Triple Signal Detection / 三重信号检测 — TX acceleration + Volume surge + B/S ratio
- 5m/15m Precision / 5 分钟/15 分钟精度 — Raw trades calculation for buy/sell ratio
- Deep Safety Checks / 深度安全检测 — Dev rug history, Bundler holdings, LP Lock, Aped wallets
- 7-Layer Exit System / 7 层退出系统 — Emergency exit, FAST_DUMP crash detection, stop loss, trailing stop, tiered TP
- TOP_ZONE Filter / 价格位置过滤 — Skips tokens near ATH (>85%) to avoid chasing
- TraderSoul AI / AI 观察系统 — Records trading behavior and personality tags
- Web Dashboard / 实时仪表盘 — http://localhost:3241
Install / 安装
npx skills add okx/plugin-store --skill meme-trench-scannerRisk Warning / 风险提示
Meme tokens are the highest-risk asset class. Tokens can go to zero within minutes. Always test in Paper Mode first.
Meme 代币是最高风险资产类别,可能在几分钟内归零。请先在纸盘模式下测试。
License
MIT
"""
Meme Trench Scanner v1.0 — Strategy Configuration
Modify this file to adjust strategy parameters without changing scan_live.py
⚠️ Disclaimer:
This script and all parameter configurations are for educational research and
technical reference only, and do not constitute any investment advice.
Meme Trench Scanner targets newly launched small-cap Meme tokens, which carry
extremely high risk, including but not limited to:
- Tokens may go to zero within minutes of launch (Rug Pull, Dev Dump)
- Extremely low liquidity; you may be unable to sell after buying (Honeypot, LP removal)
- Fees and slippage from high-frequency trading may erode most profits
- Smart contracts are unaudited and may contain unforeseen vulnerabilities
Users should adjust all parameters according to their own risk tolerance and bear
full responsibility for any losses resulting from the use of this strategy.
It is recommended to test thoroughly using Paper Mode first.
"""
# ── Operating Mode ─────────────────────────────────────────────────────
PAUSED = True # True=manually paused (no new positions, monitoring continues), False=normal trading
PAPER_TRADE = True # True=Paper Trading (recommended to test first), False=Live Trading
# ── Position ───────────────────────────────────────────────────────────
SOL_PER_TRADE = {"SCALP": 0.25, "MINIMUM": 0.15, "STRONG": 0.25}
MAX_SOL = 1.00 # Max total exposure (SOL)
MAX_POSITIONS = 7 # Max concurrent positions
SLIPPAGE_BUY = {"SCALP": 8, "MINIMUM": 10, "STRONG": 10} # Buy slippage (integer percent, 8=8%)
SLIPPAGE_SELL = 50 # Fixed high sell slippage (low liquidity small-cap tokens)
SOL_GAS = 0.05 # Reserved for fees
COST_PER_LEG = 0.003 # OKX DEX 0.3% per leg
MAX_TRADES = 50 # Auto-stop (0=unlimited)
# ── Take Profit ────────────────────────────────────────────────────────
TP1_PCT = 0.15 # +15% first take profit
TP1_SELL = {"SCALP": 0.60, "hot": 0.50, "quiet": 0.40} # TP1 partial sell ratio
TP2_PCT = 0.25 # +25% second take profit
TP2_SELL = {"SCALP": 1.00, "hot": 1.00, "quiet": 1.00} # TP2 full exit
# ── Stop Loss ──────────────────────────────────────────────────────────
S1_PCT = {"SCALP": -0.15, "hot": -0.20, "quiet": -0.20}
HE1_PCT = -0.50 # -50% emergency exit
TRAILING_DROP = 0.05 # 5% drawdown after TP1 → full exit
FAST_DUMP_PCT = -0.15 # -15% within 10s → instant exit
FAST_DUMP_SEC = 10 # Fast dump detection window (seconds)
# ── Time Stop ──────────────────────────────────────────────────────────
S3_MIN = {"SCALP": 5, "hot": 8, "quiet": 15} # minutes
MAX_HOLD_MIN = 30 # Max position hold time (minutes)
# ── Session Risk Control ───────────────────────────────────────────────
MAX_CONSEC_LOSS = 2 # N consecutive losses → pause
PAUSE_CONSEC_SEC = 900 # Consecutive loss pause duration (seconds, 15min)
PAUSE_LOSS_SOL = 0.30 # Cumulative loss >= N SOL → pause 30min
STOP_LOSS_SOL = 0.50 # Cumulative loss >= N SOL → stop trading
# ── Scanning ───────────────────────────────────────────────────────────
LOOP_SEC = 10 # Scan interval (seconds)
MONITOR_SEC = 1 # Position monitor interval (seconds)
CHAIN_INDEX = "501" # Solana
SOL_ADDR = "11111111111111111111111111111111"
DASHBOARD_PORT = 3241
# ── Basic Filters ──────────────────────────────────────────────────────
AGE_HARD_MIN = 240 # Min token age (seconds, 4min)
AGE_SOFT_MIN = 300 # Early window threshold (seconds, 5min)
AGE_MAX = 86_400 # Max token age (seconds, 24h)
MC_CAP = 800_000 # MC upper limit ($)
MC_MIN = 50_000 # MC lower limit ($)
LIQ_MIN = 10_000 # Liquidity lower limit ($)
BS_MIN = 1.0 # 1h B/S ratio pre-filter
DUMP_FLOOR = -40 # Max single candle drop (%)
# ── Signal Thresholds ─────────────────────────────────────────────────
SIG_A_THRESHOLD = 1.25 # TX acceleration ratio threshold
MIN_CONFIDENCE = 25 # Minimum confidence
SIG_A_FLOOR_TXS_MIN = 45 # TX acceleration floor (txs/min)
HOT_MODE_RATIO = 0.40 # Hot Mode trigger ratio
# ── Safety Detection ──────────────────────────────────────────────────
VOLMC_MIN_RATIO = 0.02 # Vol/MC minimum ratio
TF_MIN_VOLUME = 5_000 # 1h minimum volume ($)
TF_MAX_BUNDLERS = 15 # Bundler holdings upper limit (%)
MIN_HOLDERS = 50 # Minimum holders count
DEV_SELL_DROP_PCT = 60 # Dev dump detection: ATH drawdown %
DEV_SELL_VOL_MULT = 10 # Dev dump detection: volume multiplier
BUNDLE_ATH_PCT_MAX = 25 # Bundler ATH percentage upper limit (%)
RUG_RATE_MAX = 0.50 # Dev rug rate upper limit
MAX_DEV_RUG_COUNT = 5 # Dev rug count absolute upper limit (fallback beyond rate-based logic)
DEV_HOLD_DEEP_MAX = 0.10 # Dev deep holdings upper limit (decimal, 0.10=10%)
DEV_MAX_LAUNCHED = 800 # Dev historical token launch count upper limit
BUNDLE_MAX_COUNT = 30 # Bundler wallet count upper limit
# ── Token List Filters ─────────────────────────────────────────────────
TOP10_HOLD_MAX = 40 # Top 10 holdings upper limit (%)
INSIDERS_MAX = 15 # Insider upper limit (%)
SNIPERS_MAX = 20 # Sniper upper limit (%)
FRESH_WALLET_MAX = 40 # Fresh wallet upper limit (%)
BOT_TRADERS_MAX = 100
APED_WALLET_MAX = 10
WASH_PRICE_CHG_MIN = 0.01 # Wash trading detection: min price change
BOND_NEAR_PCT = 0.80 # Near migration threshold
# ── LP Lock ────────────────────────────────────────────────────────────
LP_LOCK_MIN_PCT = 0.80
LP_LOCK_MIN_HOURS = 0
LP_LOCK_STRICT = False
# ── Protocol Support (11 Solana Launchpads) ───────────────────────────
PROTOCOL_PUMPFUN = "120596"
PROTOCOL_LETSBONK = "136266"
PROTOCOL_BELIEVE = "134788"
PROTOCOL_BONKERS = "139661"
PROTOCOL_JUPSTUDIO = "137346"
PROTOCOL_BAGS = "129813"
PROTOCOL_MOONSHOT_MONEY = "133933"
PROTOCOL_LAUNCHLAB = "136137"
PROTOCOL_MOONSHOT = "121201"
PROTOCOL_METEORADBC = "136460"
PROTOCOL_MAYHEM = "139048"
DISCOVERY_PROTOCOLS = [
PROTOCOL_PUMPFUN, PROTOCOL_LETSBONK, PROTOCOL_BELIEVE,
PROTOCOL_BONKERS, PROTOCOL_JUPSTUDIO, PROTOCOL_BAGS,
PROTOCOL_MOONSHOT_MONEY, PROTOCOL_LAUNCHLAB, PROTOCOL_MOONSHOT,
PROTOCOL_METEORADBC, PROTOCOL_MAYHEM,
]
# ── NEW Stage Discovery ───────────────────────────────────────────────
MC_MIN_NEW = 50_000
MC_MAX_NEW = 800_000
AGE_MAX_NEW = 86_400
# ── Pullback Watchlist ─────────────────────────────────────────────────
WATCHLIST_TIMEOUT_SEC = 180 # 3 min
WATCHLIST_DUMP_DROP = 0.15 # 15% drop = dump
WATCHLIST_PULLBACK_DROP = 0.05 # 5% drop = pullback
WATCHLIST_BS_MIN = 1.5 # B/S ratio secondary confirmation
# ── Trade Blacklist ────────────────────────────────────────────────────
_WSOL_MINT_STR = "So11111111111111111111111111111111111111112"
_IGNORE_MINTS = {_WSOL_MINT_STR, "7JzLK1eq9MEq9mPNGMSr2PUoF2CCUG8corxKUbgxvJ3V"}
_NEVER_TRADE_MINTS = _IGNORE_MINTS | {
"11111111111111111111111111111111", # native SOL
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", # USDC
"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", # USDT
"mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So", # mSOL
"7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj", # stSOL
"bSo13r4TkiE4KumL71LsHTPpL2euBYLFx6h9HP3piy1", # bSOL
"J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn", # JitoSOL
}
"""
risk_check.py — Standalone pre/post trade risk assessment for Solana meme tokens.
Drop-in module for any skill: Top Rank Tokens Sniper, Smart Money Signal Copy Trade, Meme Trench Scanner, or future strategies.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
OVERVIEW
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Two public functions:
pre_trade_checks(addr, sym) — pre-trade gate. Call before entering any position.
post_trade_flags(addr, sym) — post-trade monitor. Call periodically while in position.
All data comes from onchainos CLI (~/.local/bin/onchainos). No extra API keys needed.
Requires onchainos v2.1.0+.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SEVERITY GRADES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Grade 4 — HARD BLOCK. Do not enter. Abort immediately.
Triggers: honeypot, buy/sell tax >50%, dev actively removing liquidity,
liquidity <$5K, OKX riskControlLevel ≥4, active dev/insider dump ≥5 SOL/min.
Grade 3 — STRONG WARNING. Do not enter. Too risky.
Triggers: serial rugger (≥3 rugs), rug rate >50%, LP <80% burned,
volume plunge tag, snipers >15%,
suspicious wallets >10%, soft rug velocity 1–5 SOL/min,
single LP provider with unburned LP, wash trading (round-trip wallets),
coordinated holder sells (dev/whale/insider/sniper ≥2 sells in 10 min).
Grade 2 — CAUTION. Proceed with awareness. Log the flags.
Triggers: top 10 wallets hold >30%, bundles still in >5%, dev sold all (non-CTO),
paid DexScreener listing, no smart money detected.
Grade 0 — PASS. All checks clear.
result["pass"] is True when grade < 3 (grades 0 and 2 are both tradeable).
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PRE-TRADE INTEGRATION (pre_trade_checks)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Call this BEFORE the swap/buy, after basic filters (liquidity, MC) pass.
Store the entry snapshots from result["raw"] on the position record for
post-trade monitoring — they are needed by post_trade_flags().
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from risk_check import pre_trade_checks, post_trade_flags
# --- Pre-trade gate (quick=True: 4 calls, ~0.8s — includes wash trading check) ---
result = pre_trade_checks(token_address, token_symbol, quick=True)
if result["grade"] >= 4:
log(f"BLOCKED {sym} — {result['reasons']}")
return # hard stop, do not trade
if result["grade"] == 3:
log(f"WARN {sym} — {result['reasons']}")
return # too risky, skip
if result["grade"] == 2:
log(f"CAUTION {sym} — {result['cautions']}")
# proceed but note the flags
# --- Execute buy ---
execute_swap(...)
# --- Persist entry snapshots for post-trade use ---
position["entry_liquidity_usd"] = result["raw"]["liquidity_usd"]
position["entry_top10"] = result["raw"]["info"].get("top10HoldPercent", 0)
position["entry_sniper_pct"] = result["raw"]["info"].get("sniperHoldingPercent", 0)
position["risk_last_checked"] = 0 # tracks throttle timestamp
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
POST-TRADE INTEGRATION (post_trade_flags)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Call this inside your position monitor loop. THROTTLE to once per 60 seconds
per position — each call makes 4–6 onchainos API requests.
IMPORTANT: Run post_trade_flags() in a background thread so it does not block
your monitor loop. It makes multiple sequential API calls (~1–2s) and must not
stall position updates, trailing stop logic, or TP/SL checks for other positions.
import threading
def _check_flags(pos):
flags = post_trade_flags(
pos["address"],
pos["symbol"],
entry_liquidity_usd = pos["entry_liquidity_usd"],
entry_top10 = pos["entry_top10"],
entry_sniper_pct = pos["entry_sniper_pct"],
)
for flag in flags:
log(flag)
if flag.startswith("EXIT_NOW"):
close_position(pos, reason=flag)
break
elif flag.startswith("EXIT_NEXT_TP"):
# tighten trailing stop or take partial profit early
pass
elif flag.startswith("REDUCE_POSITION"):
# cut size if partial sells are supported
pass
# --- Inside monitor loop, per open position (throttled to once per 60s) ---
now = time.time()
if now - position.get("risk_last_checked", 0) >= 60:
position["risk_last_checked"] = now
threading.Thread(target=_check_flags, args=(position,), daemon=True).start()
Post-trade flag meanings:
EXIT_NOW: ... — close immediately (dev rug, liquidity drain >30%, active dump, holder selling)
EXIT_NEXT_TP: ... — exit at next take profit or trailing stop (volume plunge, soft rug)
REDUCE_POSITION: ... — cut position size (sniper spike)
ALERT: ... — informational, no action required
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CLI USAGE (standalone token check)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
python3 risk_check.py <token_address> [symbol]
Example:
python3 risk_check.py 58piN8dJJBcjHj28LZzTGJTygAX6DoF22sfY1R7Apump horseballs
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHAT IT CHECKS (data sources)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
[quick + full mode]
security token-scan → honeypot flag, buy/sell tax
token advanced-info → dev rug history, LP burn %, sniper %, tokenTags,
riskControlLevel, top10 hold %, bundle %, suspicious wallets
token price-info → liquidity USD snapshot
token trades → all recent trades (wash trading: round-trip + concentration)
[full mode only — quick=False]
token liquidity → LP pool creators (concentration check)
token trades --tag-filter → dev (2), whale (4), insider (6), sniper (7) sell activity
used for: selling velocity + holder sell coordination
"""
import subprocess, json, os, time
from collections import defaultdict
_ONCHAINOS = os.path.expanduser("~/.local/bin/onchainos")
_CHAIN = "solana"
_CHAIN_ID = "501"
# Selling velocity — SOL sold per minute thresholds
_SELL_VEL_WARN_SOL_PM = 1.0 # G3: > 1 SOL/min from dev/insiders
_SELL_VEL_BLOCK_SOL_PM = 5.0 # G4: > 5 SOL/min (active dump)
# Wash trading — round-trip detection thresholds
_WASH_ROUNDTRIP_RATIO = 0.50 # G3: ≥50% of active wallets round-tripped alone
_WASH_ROUNDTRIP_SOFT = 0.30 # G3: ≥30% round-tripped AND concentration above threshold
_WASH_CONC_THRESHOLD = 0.40 # top-3 wallets driving >40% of all trades = suspicious
# LP checks
_LP_SINGLE_PROVIDER_WARN = True # G3: single LP provider + LP not burned
_LP_DRAIN_EXIT_PCT = 0.30 # post-trade: exit if liquidity drops > 30%
# ── Internal CLI wrapper ───────────────────────────────────────────────────────
def _onchainos(*args, timeout: int = 20) -> dict:
try:
r = subprocess.run([_ONCHAINOS, *args],
capture_output=True, text=True, timeout=timeout)
return json.loads(r.stdout)
except Exception:
return {"ok": False, "data": None}
def _data(r: dict):
d = r.get("data")
if isinstance(d, list):
return d[0] if d else {}
return d or {}
def _data_list(r: dict) -> list:
d = r.get("data")
return d if isinstance(d, list) else []
# ── API calls ─────────────────────────────────────────────────────────────────
def _security_scan(addr: str) -> dict:
r = _onchainos("security", "token-scan",
"--tokens", f"{_CHAIN_ID}:{addr}")
d = _data(r)
return d if isinstance(d, dict) else {}
def _advanced_info(addr: str) -> dict:
r = _onchainos("token", "advanced-info",
"--chain", _CHAIN, "--address", addr)
d = _data(r)
return d if isinstance(d, dict) else {}
def _liquidity_usd(addr: str) -> float:
"""Current total liquidity in USD from price-info."""
r = _onchainos("token", "price-info",
"--chain", _CHAIN, "--address", addr)
items = _data_list(r)
if not items:
items = [_data(r)]
for item in items:
if isinstance(item, dict) and item.get("liquidity"):
try:
return float(item["liquidity"])
except (ValueError, TypeError):
pass
return -1.0
def _lp_pools(addr: str) -> list:
"""Top LP pools with creator info."""
r = _onchainos("token", "liquidity",
"--chain", _CHAIN, "--address", addr)
return _data_list(r)
def _tagged_trades(addr: str, tag: int, limit: int = 50) -> list:
"""Trades filtered by wallet tag (2=dev, 4=whale, 6=insider, 7=sniper)."""
r = _onchainos("token", "trades",
"--chain", _CHAIN, "--address", addr,
"--tag-filter", str(tag),
"--limit", str(limit))
return _data_list(r)
def _recent_trades(addr: str, limit: int = 100) -> list:
"""All recent trades."""
r = _onchainos("token", "trades",
"--chain", _CHAIN, "--address", addr,
"--limit", str(limit))
return _data_list(r)
# ── Helpers ───────────────────────────────────────────────────────────────────
def _tags(info: dict) -> list:
return info.get("tokenTags") or []
def _has_tag(info: dict, prefix: str) -> bool:
return any(t.startswith(prefix) for t in _tags(info))
def _pct(info: dict, field: str) -> float:
v = info.get(field, "") or ""
try:
return float(v)
except (ValueError, TypeError):
return -1.0
def _int(info: dict, field: str) -> int:
v = info.get(field, 0) or 0
try:
return int(v)
except (ValueError, TypeError):
return 0
def _trade_sol(trade: dict) -> float:
"""Extract SOL amount from a trade's changedTokenInfo."""
for t in trade.get("changedTokenInfo", []):
if t.get("tokenSymbol") in ("SOL", "wSOL"):
try:
return float(t.get("amount", 0))
except (ValueError, TypeError):
pass
try:
return float(trade.get("volume", 0))
except (ValueError, TypeError):
return 0.0
# ── Check 1: Selling velocity (dev + insider sells) ───────────────────────────
def _selling_velocity(addr: str) -> tuple:
"""
Returns (sol_per_min, reason_str).
Checks dev (tag=2) + insider (tag=6) sells over last 50 trades.
Detects soft rugs: steady sell pressure from privileged wallets.
"""
sells_by_wallet = defaultdict(list) # wallet -> [(timestamp_ms, sol)]
for tag in (2, 6): # dev + insider
for trade in _tagged_trades(addr, tag, limit=50):
if trade.get("type") != "sell":
continue
ts = int(trade.get("time", 0))
sol = _trade_sol(trade)
if sol > 0 and ts > 0:
sells_by_wallet[trade.get("userAddress", "?")].append((ts, sol))
if not sells_by_wallet:
return 0.0, ""
now_ms = int(time.time() * 1000)
window = 5 * 60 * 1000 # 5-minute window
total_sol = 0.0
wallets = []
for wallet, events in sells_by_wallet.items():
recent = [(ts, sol) for ts, sol in events if now_ms - ts <= window]
if recent:
sol_sum = sum(s for _, s in recent)
total_sol += sol_sum
wallets.append(f"{wallet[:8]}…({sol_sum:.2f}SOL)")
if total_sol == 0:
return 0.0, ""
elapsed_min = window / 60000
sol_pm = total_sol / elapsed_min
detail = f"{sol_pm:.2f} SOL/min — {', '.join(wallets)}"
return sol_pm, detail
# ── Check 2: LP provider concentration ────────────────────────────────────────
def _lp_provider_check(addr: str, lp_burned: float) -> tuple:
"""
Returns (is_risky, reason_str).
Single LP provider + LP not burned = high rug risk.
"""
pools = _lp_pools(addr)
if not pools:
return False, ""
# Count unique creators across pools with meaningful liquidity
creators = set()
for pool in pools:
liq = 0.0
try:
liq = float(pool.get("liquidityUsd", 0))
except (ValueError, TypeError):
pass
if liq > 100: # ignore dust pools
creator = pool.get("poolCreator", "")
if creator:
creators.add(creator)
if len(creators) == 1 and lp_burned < 80:
creator = next(iter(creators))
total_liq = sum(
float(p.get("liquidityUsd", 0) or 0) for p in pools
)
return (
True,
f"SINGLE_LP_PROVIDER — {creator[:12]}… controls "
f"${total_liq:,.0f} liquidity, LP only {lp_burned:.0f}% burned"
)
return False, ""
# ── Check 3: Wash trading ─────────────────────────────────────────────────────
def _wash_trading_check(addr: str) -> tuple:
"""
Returns (is_wash, reason_str).
Detects wash trading via two signals:
1. Round-trip wallets — wallets that both buy AND sell within a 5-min window.
Flags if ≥50% of active wallets are round-tripping (strong signal alone),
or ≥30% round-tripping AND top-3 wallets drive >40% of trades (combined signal).
2. Wallet concentration — high trade share from a tiny set of wallets amplifies
the round-trip signal, indicating coordinated volume inflation.
Uses 200 recent trades for statistical reliability (~0.2s, one API call).
"""
trades = _recent_trades(addr, limit=200)
if len(trades) < 15:
return False, ""
wallet_buys = defaultdict(list) # wallet -> [timestamp_ms, ...]
wallet_sells = defaultdict(list)
wallet_count = defaultdict(int)
for t in trades:
w = t.get("userAddress", "")
ts = int(t.get("time", 0))
if not w or ts == 0:
continue
wallet_count[w] += 1
if t.get("type") == "buy":
wallet_buys[w].append(ts)
else:
wallet_sells[w].append(ts)
active_wallets = set(wallet_buys) | set(wallet_sells)
if not active_wallets:
return False, ""
# Round-trip: any buy followed by a sell from the same wallet within 5 min
window_ms = 5 * 60 * 1000
rt_wallets = 0
for w in active_wallets:
buys = sorted(wallet_buys[w])
sells = sorted(wallet_sells[w])
if not buys or not sells:
continue
if any(any(s > b and s - b <= window_ms for s in sells) for b in buys):
rt_wallets += 1
total_wallets = len(active_wallets)
rt_ratio = rt_wallets / total_wallets
# Wallet concentration: top-3 wallets share of all trades
top3 = sum(c for _, c in sorted(wallet_count.items(), key=lambda x: -x[1])[:3])
concentration = top3 / len(trades)
if rt_ratio >= _WASH_ROUNDTRIP_RATIO:
return (
True,
f"WASH_TRADING — {rt_wallets}/{total_wallets} wallets round-tripped "
f"({rt_ratio*100:.0f}%) within 5-min windows"
)
if rt_ratio >= _WASH_ROUNDTRIP_SOFT and concentration >= _WASH_CONC_THRESHOLD:
return (
True,
f"WASH_TRADING — {rt_wallets}/{total_wallets} wallets round-tripped "
f"({rt_ratio*100:.0f}%) + top-3 wallets drive {concentration*100:.0f}% of volume"
)
return False, ""
# ── Check 4: Holder sell transfers ────────────────────────────────────────────
def _holder_sell_check(addr: str) -> tuple:
"""
Returns (is_selling, reason_str).
Detects coordinated sells from tagged wallets (dev, whale, insider, sniper).
Pre-trade: catch early distribution before price drops.
"""
tag_names = {2: "Dev", 4: "Whale", 6: "Insider", 7: "Sniper"}
now_ms = int(time.time() * 1000)
window = 10 * 60 * 1000 # 10-minute window
findings = []
for tag, label in tag_names.items():
trades = _tagged_trades(addr, tag, limit=30)
recent_sells = [
t for t in trades
if t.get("type") == "sell"
and now_ms - int(t.get("time", 0)) <= window
]
if len(recent_sells) >= 2:
sol = sum(_trade_sol(t) for t in recent_sells)
findings.append(f"{label}×{len(recent_sells)}({sol:.2f}SOL)")
if findings:
return True, "HOLDER_SELLING — " + ", ".join(findings) + " in last 10min"
return False, ""
# ── Core risk check ───────────────────────────────────────────────────────────
def pre_trade_checks(addr: str, sym: str, quick: bool = False) -> dict:
"""
Run pre-trade risk assessment.
quick=True — fast mode (4 API calls, ~0.8s). Use for pre-trade gates.
Runs: security scan + advanced-info + price-info + wash trading.
Skips: selling velocity, LP provider, holder sells.
Those slow checks are better handled by post_trade_flags() monitoring.
quick=False — full mode (11 API calls, ~22–33s). Use for manual analysis only.
Returns:
{
"pass": bool,
"grade": int, # 4=block, 3=warn, 2=caution, 0=pass
"level": int, # alias for grade (backward compatibility)
"reasons": [str], # grade 4 + 3 failures
"cautions": [str], # grade 2 flags
"raw": {
"scan": dict,
"info": dict,
"liquidity_usd": float # snapshot for post-trade monitoring
}
}
"""
scan = _security_scan(addr)
info = _advanced_info(addr)
liq_usd = _liquidity_usd(addr)
lp_burned = _pct(info, "lpBurnedPercent")
reasons = []
cautions = []
level = 0
# ── Grade 4 — Hard Block ─────────────────────────────────────────────────
if scan.get("isRiskToken"):
reasons.append("G4: HONEYPOT — isRiskToken flagged by OKX")
level = 4
buy_tax = _pct(scan, "buyTaxes")
if buy_tax > 50:
reasons.append(f"G4: BUY_TAX {buy_tax:.0f}% > 50%")
level = 4
sell_tax = _pct(scan, "sellTaxes")
if sell_tax > 50:
reasons.append(f"G4: SELL_TAX {sell_tax:.0f}% > 50%")
level = 4
if _has_tag(info, "devRemoveLiq"):
tag = next(t for t in _tags(info) if t.startswith("devRemoveLiq"))
reasons.append(f"G4: DEV_REMOVING_LIQUIDITY — {tag}")
level = 4
if _has_tag(info, "lowLiquidity"):
reasons.append("G4: LOW_LIQUIDITY — total liquidity < $5K")
level = 4
risk_lvl = _int(info, "riskControlLevel")
if risk_lvl >= 4:
reasons.append(f"G4: OKX_RISK_LEVEL {risk_lvl} >= 4")
level = 4
# Selling velocity — active dump (slow check, full mode only)
vel_sol_pm, vel_detail = (0.0, "") if quick else _selling_velocity(addr)
if vel_sol_pm >= _SELL_VEL_BLOCK_SOL_PM:
reasons.append(f"G4: ACTIVE_DUMP — {vel_detail}")
level = 4
# ── Grade 3 — Strong Warning ─────────────────────────────────────────────
rug_count = _int(info, "devRugPullTokenCount")
dev_created = _int(info, "devCreateTokenCount")
if dev_created > 0:
rug_rate = rug_count / dev_created
if rug_rate >= 0.20 and rug_count >= 3:
reasons.append(
f"G3: SERIAL_RUGGER — {rug_count}/{dev_created} tokens rugged "
f"({rug_rate*100:.0f}%)"
)
level = max(level, 3)
elif rug_rate >= 0.05 and rug_count >= 2:
cautions.append(
f"G2: RUG_HISTORY — {rug_count}/{dev_created} tokens rugged "
f"({rug_rate*100:.0f}%)"
)
elif rug_count >= 5:
# devCreateTokenCount unavailable — fall back to flat count
reasons.append(f"G3: SERIAL_RUGGER — {rug_count} confirmed rug pulls (no total count)")
level = max(level, 3)
if 0 <= lp_burned < 80:
reasons.append(f"G3: LP_NOT_BURNED — {lp_burned:.1f}% burned (< 80%)")
level = max(level, 3)
if _has_tag(info, "volumeChangeRateVolumePlunge"):
reasons.append("G3: VOLUME_PLUNGE — trading activity collapsing")
level = max(level, 3)
sniper_pct = _pct(info, "sniperHoldingPercent")
if sniper_pct > 15:
reasons.append(f"G3: SNIPERS_HOLDING {sniper_pct:.1f}% > 15%")
level = max(level, 3)
suspicious_pct = _pct(info, "suspiciousHoldingPercent")
if suspicious_pct > 10:
reasons.append(f"G3: SUSPICIOUS_WALLETS {suspicious_pct:.1f}% > 10%")
level = max(level, 3)
# Wash trading — round-trip + concentration (fast: 1 extra API call, ~0.2s)
is_wash, wash_reason = _wash_trading_check(addr)
if is_wash:
reasons.append(f"G3: {wash_reason}")
level = max(level, 3)
# ── Slow checks — full mode only (post-trade covers these in real-time) ──
if not quick:
# Selling velocity — soft rug (steady bleed)
if 0 < vel_sol_pm < _SELL_VEL_BLOCK_SOL_PM and vel_sol_pm >= _SELL_VEL_WARN_SOL_PM:
reasons.append(f"G3: SOFT_RUG_VELOCITY — {vel_detail}")
level = max(level, 3)
# LP provider concentration
lp_risky, lp_reason = _lp_provider_check(addr, lp_burned)
if lp_risky:
reasons.append(f"G3: {lp_reason}")
level = max(level, 3)
# Holder selling — coordinated exits from tagged wallets
is_selling, sell_reason = _holder_sell_check(addr)
if is_selling:
reasons.append(f"G3: {sell_reason}")
level = max(level, 3)
# ── Grade 2 — Caution ────────────────────────────────────────────────────
top10 = _pct(info, "top10HoldPercent")
if top10 > 30:
cautions.append(f"G2: SUPPLY_CONCENTRATED — top 10 hold {top10:.1f}%")
level = max(level, 2)
bundle_pct = _pct(info, "bundleHoldingPercent")
if bundle_pct > 5:
cautions.append(f"G2: BUNDLES_STILL_IN {bundle_pct:.1f}% > 5%")
level = max(level, 2)
is_cto = _has_tag(info, "dexScreenerTokenCommunityTakeOver")
if _has_tag(info, "devHoldingStatusSellAll") and not is_cto:
cautions.append("G2: DEV_SOLD_ALL — dev exited (not a CTO)")
level = max(level, 2)
if _has_tag(info, "dsPaid"):
cautions.append("G2: PAID_LISTING — dexscreener listing was paid")
level = max(level, 2)
if not _has_tag(info, "smartMoneyBuy"):
cautions.append("G2: NO_SMART_MONEY — no smart money wallet detected")
level = max(level, 2)
# ── Result ────────────────────────────────────────────────────────────────
passed = level < 3
return {
"pass": passed,
"grade": level,
"level": level, # backward compat alias
"reasons": reasons,
"cautions": cautions,
"raw": {
"scan": scan,
"info": info,
"liquidity_usd": liq_usd,
},
}
# ── Post-trade monitoring ─────────────────────────────────────────────────────
def post_trade_flags(addr: str, sym: str,
entry_liquidity_usd: float = 0.0,
entry_top10: float = 0.0,
entry_sniper_pct: float = 0.0) -> list:
"""
Call periodically during position monitoring.
Returns list of action strings:
"EXIT_NOW: ..." — immediate exit required
"EXIT_NEXT_TP: ..." — exit at next TP or trailing stop
"REDUCE_POSITION: ..." — cut size
"ALERT: ..." — informational
"""
info = _advanced_info(addr)
liq_usd = _liquidity_usd(addr)
flags = []
# Dev removing liquidity — EXIT NOW
if _has_tag(info, "devRemoveLiq"):
tag = next((t for t in _tags(info) if t.startswith("devRemoveLiq")), "devRemoveLiq")
flags.append(f"EXIT_NOW: DEV_REMOVING_LIQUIDITY — {tag}")
# Liquidity drain > 30% since entry — EXIT NOW
if entry_liquidity_usd > 0 and liq_usd > 0:
drain_pct = (entry_liquidity_usd - liq_usd) / entry_liquidity_usd
if drain_pct >= _LP_DRAIN_EXIT_PCT:
flags.append(
f"EXIT_NOW: LIQUIDITY_DRAIN {drain_pct*100:.0f}% — "
f"${entry_liquidity_usd:,.0f} → ${liq_usd:,.0f}"
)
# Active dump from dev/insiders — EXIT NOW
vel_sol_pm, vel_detail = _selling_velocity(addr)
if vel_sol_pm >= _SELL_VEL_BLOCK_SOL_PM:
flags.append(f"EXIT_NOW: ACTIVE_DUMP — {vel_detail}")
# Holder selling — coordinated exits
is_selling, sell_reason = _holder_sell_check(addr)
if is_selling:
flags.append(f"EXIT_NOW: {sell_reason}")
# Volume collapsing — exit at next TP
if _has_tag(info, "volumeChangeRateVolumePlunge"):
flags.append("EXIT_NEXT_TP: VOLUME_PLUNGE — activity collapsing")
# Soft rug velocity
if 0 < vel_sol_pm < _SELL_VEL_BLOCK_SOL_PM and vel_sol_pm >= _SELL_VEL_WARN_SOL_PM:
flags.append(f"EXIT_NEXT_TP: SOFT_RUG_VELOCITY — {vel_detail}")
# Sniper spike
sniper_pct = _pct(info, "sniperHoldingPercent")
if sniper_pct > entry_sniper_pct + 5:
flags.append(
f"REDUCE_POSITION: SNIPER_SPIKE {sniper_pct:.1f}% "
f"(was {entry_sniper_pct:.1f}% at entry)"
)
# Top 10 concentration increase
top10 = _pct(info, "top10HoldPercent")
if top10 > 40 and top10 > entry_top10 + 5:
flags.append(
f"ALERT: TOP10_CONCENTRATION {top10:.1f}% "
f"(was {entry_top10:.1f}% at entry)"
)
return flags
# ── CLI usage ─────────────────────────────────────────────────────────────────
if __name__ == "__main__":
import sys
addr = sys.argv[1] if len(sys.argv) > 1 else ""
sym = sys.argv[2] if len(sys.argv) > 2 else addr[:8]
if not addr:
print("Usage: python3 risk_check.py <token_address> [symbol]")
sys.exit(1)
print(f"\n{'='*55}")
print(f" Risk Check — {sym}")
print(f" {addr}")
print(f"{'='*55}")
r = pre_trade_checks(addr, sym)
level_label = {0: "✅ PASS", 2: "⚠️ CAUTION", 3: "🚨 WARN", 4: "❌ BLOCK"}
print(f"\n Result: {level_label.get(r['level'], str(r['level']))}")
print(f" Liquidity: ${r['raw']['liquidity_usd']:,.0f}")
if r["reasons"]:
print("\n Blocks / Warnings:")
for reason in r["reasons"]:
print(f" • {reason}")
if r["cautions"]:
print("\n Cautions:")
for c in r["cautions"]:
print(f" • {c}")
print()
{
"name": "DiamondPaws",
"stage": "Novice",
"trades_seen": 0,
"wins": 0,
"losses": 0,
"total_pnl_sol": 0.0,
"tier_stats": {},
"hour_stats": {},
"personal_limits": {
"bundle_ath_pct_warn": 35,
"min_confidence_trust": 50
},
"win_philosophy": "I haven't found my edge yet. Every trade is a lesson.",
"risk_philosophy": "The market owes me nothing. Protect the bag first.",
"current_vibe": "neutral",
"reflections": [
{
"t": "20:24:58",
"msg": "ATLAS — MINIMUM signal. Confidence 30."
},
{
"t": "20:24:48",
"msg": "ATLAS — MINIMUM signal. Confidence 30."
},
{
"t": "20:24:37",
"msg": "ATLAS — MINIMUM signal. Confidence 30."
},
{
"t": "20:24:27",
"msg": "ATLAS — MINIMUM signal. Confidence 30."
},
{
"t": "20:24:17",
"msg": "ATLAS — MINIMUM signal. Confidence 45."
},
{
"t": "20:24:06",
"msg": "ATLAS — MINIMUM signal. Confidence 45."
},
{
"t": "20:23:56",
"msg": "ATLAS — MINIMUM signal. Confidence 30."
},
{
"t": "20:21:11",
"msg": "ATLAS — MINIMUM signal. Confidence 30."
},
{
"t": "19:59:38",
"msg": "ATLAS — MINIMUM signal. Confidence 30."
},
{
"t": "19:59:27",
"msg": "ATLAS — MINIMUM signal. Confidence 30."
}
],
"evolution_log": [],
"trade_outcomes": [],
"periodic_reviews": [],
"signals_seen": 14
}Overview
Meme Trench Scanner is a Solana meme-token trading bot that scans 11 launchpads every 10 seconds, detects entries via TX acceleration, volume surge, and buy-sell ratio signals, runs deep safety checks, and manages exits through a 7-layer system.
Core operations:
- Scan 11 Solana launchpads (pump.fun, Believe, LetsBonk, and more) every 10 seconds for new token entries
- Detect signals via TX acceleration + volume surge + 5m/15m buy-sell ratio
- Run deep safety checks: dev rug history, bundler holdings, LP lock, aped wallets
- Manage exits via 7-layer system: emergency exit, FAST_DUMP crash detection, stop loss, trailing stop, tiered TP
- Observe all activity via TraderSoul AI and a live web dashboard
Tags: meme-coin solana trading-bot launchpad onchainos pump.fun
Prerequisites
- No IP/region restrictions
- Supported chain: Solana
- Supported tokens: Newly launched Solana meme tokens across 11 launchpads
- onchainos CLI ≥ 2.1.0 installed and authenticated (
onchainos --versionandonchainos wallet status) - Python 3.8+ (standard library only — no
pip installrequired) - Funded Solana wallet for live trading
Quick Start
1. Install the skill: plugin-store install meme-trench-scanner 2. Configure risk: Edit config.py to pick Conservative / Default / Aggressive and tune MAX_SOL, SOL_PER_TRADE, TP1_PCT, TP2_PCT, S1_PCT, MAX_POSITIONS, MAX_HOLD_MIN 3. Start in paper mode (default, PAPER_TRADE = True): Run python3 scan_live.py 4. Open dashboard: Visit http://localhost:3241 to monitor signals, positions, and TraderSoul observations 5. Go live: Set PAUSED = False to allow new positions, then PAPER_TRADE = False to use real funds — re-confirm exposure parameters before switching 6. Stop anytime: pkill -f scan_live.py