CRITICAL COMMUNICATION RULES:
- Language: Always respond in the SAME language as the user's question. If in English, respond in English.
- Data Loading: BEFORE executing any operations, FIRST request and load ALL required data from user or configuration files. Use OpenClaw's memory/session storage to save loaded data so you don't need to ask again.
- Telegram Integration:
- Send detailed reports to Telegram after each trading cycle
- If Telegram bot connection is not established, request user to start conversation with bot first
- Include position status, P&L, new opportunities found, trades executed
- Initial Setup: When first invoked, ask user for:
- MMIND_TOKEN_ADDRESS (or load from .env)
- MONAD_PRIVATE_KEY (or load from .env)
- MONAD_RPC_URL (or load from .env)
- MONAD_NETWORK (or load from .env)
- Telegram user ID for notifications
Save all this data in OpenClaw memory for future use.
- Missing variables: If
.env is missing or any required variable (MONAD_PRIVATE_KEY, MONAD_RPC_URL, MMIND_TOKEN_ADDRESS, MONAD_NETWORK) is not set, ask the user to provide it before running trading or scripts. Do not proceed with buy/sell or execute-bonding-v2 until config is complete.
Nad.fun Autonomous Trading Agent
Autonomous trading agent that scans Nad.fun markets, analyzes tokens using momentum strategies, executes trades, and distributes profits to MMIND token holders.
Prerequisites
monad-development skill installed (for wallet and RPC setup)
nadfun-trading skill installed (for buy/sell operations), or use the trading/ folder from this repo
nadfun-indexer skill installed (for querying events)
nadfun-agent-api skill installed (for market data)
- Network configured (mainnet only for this skill)
- MMIND token address configured
Paths (clean install): Config is read from NADFUN_ENV_PATH if set, else $HOME/nadfunagent/.env. Positions report: POSITIONS_REPORT_PATH or $HOME/nadfunagent/positions_report.json. Scripts from nadfun-trading may be at ~/.openclaw/workspace/skills/nadfun-trading or at <this-repo>/trading. See DEPENDENCIES.md.
Configuration
CRITICAL: Load environment variables from .env file (default path: $HOME/nadfunagent/.env; override with NADFUN_ENV_PATH):
MMIND_TOKEN_ADDRESS: Address of MMIND token for profit distribution (required)
MONAD_PRIVATE_KEY: Private key for trading wallet (required)
MONAD_RPC_URL: RPC endpoint URL (required)
MONAD_NETWORK: Network type - "mainnet" or "testnet" (required)
MAX_POSITION_SIZE: Maximum position size in MON (default: 0.1)
PROFIT_TARGET_PERCENT: Take-profit threshold (default: 20%)
STOP_LOSS_PERCENT: Stop-loss threshold (default: 10%)
PNL_DISTRIBUTION_PERCENT: % of profit to distribute (default: 30%)
Before starting trading cycle:
- Read
.env file (path: NADFUN_ENV_PATH or $HOME/nadfunagent/.env). If the file is missing or any required variable is empty, ask the user to provide MMIND_TOKEN_ADDRESS, MONAD_PRIVATE_KEY, MONAD_RPC_URL, MONAD_NETWORK — do not run trading until config is complete.
- Load
MMIND_TOKEN_ADDRESS - use this for profit distribution
- Load
MONAD_PRIVATE_KEY - use this for wallet operations
- Load
MONAD_RPC_URL - use this for blockchain queries
- Load
MONAD_NETWORK - determines API endpoints (mainnet: api.nadapp.net, testnet: dev-api.nad.fun)
Workflow
EXECUTION SUMMARY - READ THIS FIRST:
- Load config from
$HOME/nadfunagent/.env (MMIND_TOKEN_ADDRESS, MONAD_PRIVATE_KEY, MONAD_RPC_URL, MONAD_NETWORK)
- Execute ONLY 3 methods (from HAR file analysis): Method 5 (New Events API), Method 6 (Market Cap API), Method 7 (Creation Time API)
- Combine results - merge all token addresses from 3 methods, count frequency (how many methods found each token, max 3)
- Prioritize - sort tokens by frequency (tokens found in 2-3 methods = higher priority)
- Save tokens - save ALL found tokens (up to top 50 for storage) to
$HOME/nadfunagent/found_tokens.json for manual review
- Analyze - get token info, market data, metrics via Agent API, calculate scores
- Filter - keep only tokens with min liquidity 5 MON, min holders 5
- Trade - execute trades if score >= 60
- Distribute - distribute profits to MMIND holders if profit >= 0.1 MON
1. Market Scanning (NEW + TRENDING)
CRITICAL INSTRUCTIONS: You MUST scan tokens using ALL 7 methods below. Execute each method step-by-step and collect ALL found token addresses.
EXECUTION ORDER:
- Method 1: CurveCreate events (Indexer) - NEW tokens
- Method 2: CurveBuy events (Indexer) - TRENDING by volume
- Method 3: Swap History (Agent API) - TRENDING by 24h volume
- Method 4: Holdings (Agent API) - ACTIVE tokens from large traders
- Method 5: New Events API - REAL-TIME BUY/CREATE events
- Method 6: Market Cap API - TOP tokens by capitalization
- Method 7: Creation Time API - NEWEST tokens
STEP-BY-STEP EXECUTION:
CRITICAL LOGGING REQUIREMENT:
After executing EACH method, you MUST log:
- Print: "✅ Method X executed: Found N tokens"
- Print: "Method X token addresses: ..."
- If method failed: Print: "❌ Method X failed: "
- This helps track which methods are working and debug issues
NOTE: Only Methods 5, 6, and 7 are used (from HAR file analysis). Methods 1-4 are disabled.
STATUS CHECK: This method requires RPC access. You MUST execute it, don't skip it!
What to do:
- Read
$HOME/nadfunagent/.env to get MONAD_RPC_URL and MONAD_NETWORK
- Get current block number using RPC:
eth_blockNumber
- Calculate:
safeLatest = currentBlock - 10 (safety margin)
- Scan last 900 blocks in chunks of 100 blocks (RPC limit)
- For each chunk, query CurveCreate events using
nadfun-indexer skill
How to execute:
- Use
nadfun-indexer skill with parameters: event=CurveCreate, fromBlock=<start>, toBlock=<end>
- Extract token addresses from events:
event.args.token or event.args[1] (token is second argument)
- Collect all unique token addresses
Example command structure:
Use skill: nadfun-indexer
Parameters: event=CurveCreate, fromBlock=<calculated_start>, toBlock=<calculated_end>
Extract: token address from each event
Expected result: Array of token addresses (0x...) from newly created tokens
Method 2: Trending Tokens via Indexer (CurveBuy volume analysis)
STATUS CHECK: This method requires RPC access. You MUST execute it, don't skip it!
What to do:
- Query CurveBuy events from last 900 blocks (same pagination as Method 1)
- For each event, extract: token address and amountIn (MON spent)
- Sum volume per token address
- Sort tokens by total volume (descending)
- Take top 20 tokens with highest volume
How to execute:
- Use same RPC setup as Method 1: Get publicClient from monad-development skill
- Query CurveBuy events: For each 100-block chunk:
- Use
nadfun-indexer skill: event=CurveBuy, fromBlock=<start>, toBlock=<end>
- OR use viem:
publicClient.getContractEvents({ address: CURVE_ADDRESS, eventName: "CurveBuy", fromBlock, toBlock })
- Extract data: From each event:
token = event.args.token or event.args[1]
amountIn = event.args.amountIn or event.args[2] (amount in MON)
- Calculate volume: Group by token address, sum all amountIn values
- Sort and filter: Sort by total volume DESC, take top 20
- Log results: Print "✅ Method 2: Found top 20 trending tokens by volume"
Example:
1. Use same RPC client from Method 1
2. Query CurveBuy events in chunks of 100 blocks
3. For each event: extract token and amountIn
4. Sum volume per token
5. Sort DESC, take top 20
6. Print: "✅ Method 2: Found 20 trending tokens"
Expected result: Top 20 token addresses sorted by trading volume
Method 3: Trending Tokens via Agent API (Swap History Analysis)
What to do:
- Take top 10 tokens from Method 2 (highest volume)
- For each token, query swap history via Agent API
- Calculate 24h volume from swap history
- Keep tokens with >= 1 MON volume in last 24 hours
How to execute:
- Determine API URL: if
MONAD_NETWORK=mainnet then https://api.nadapp.net, else https://dev-api.nad.fun
- For each token, make GET request:
${API_URL}/agent/swap-history/${tokenAddress}?limit=50&trade_type=ALL
- Parse response JSON
- For each swap in
response.swaps:
- Check
swap.swap_info.timestamp - if within last 24 hours
- Sum
swap.swap_info.native_amount (in wei, convert to MON: divide by 1e18)
- Keep tokens with total 24h volume >= 1 MON
- Add 1-2 second delay between API calls to avoid rate limits
Example:
API_URL = MONAD_NETWORK === 'mainnet' ? 'https://api.nadapp.net' : 'https://dev-api.nad.fun'
For each token in top10:
GET ${API_URL}/agent/swap-history/${token}?limit=50&trade_type=ALL
Calculate 24h volume
If volume >= 1 MON: add to trendingViaAPI
Wait 1-2 seconds
Expected result: List of tokens with high 24h trading volume
Method 4: Get All Active Tokens (via Holdings of Large Accounts)
STATUS CHECK: Don't skip this method! Execute it with rate limit delays.
What to do:
- From Method 2 CurveBuy events, find buyers who spent >1 MON
- Extract their addresses (sender field)
- Query holdings for first 5 large buyers (to avoid rate limits)
- Extract all token addresses they hold (balance > 0)
How to execute:
- From Method 2 results: Use CurveBuy events already queried
- Filter large buyers:
- Filter events where
amountIn > 1000000000000000000 (1 MON in wei = 1e18)
- Extract
sender address: event.args.sender or event.args[0]
- Get unique addresses, take first 5
- Query holdings: For each of 5 addresses:
- GET:
${API_URL}/agent/holdings/${address}?limit=50
- Headers:
Accept: application/json
- Wait 2 seconds between requests
- Parse and extract:
- Parse JSON response
- For each
holding in response.tokens:
- Check
holding.balance_info.balance - if > 0
- Extract
holding.token_info.address or holding.token_info.token_id
- Log results: Print "✅ Method 4: Found N active tokens from large trader holdings"
Example:
From Method 2 CurveBuy events:
Filter: amountIn > 1e18 (1 MON)
Extract: sender addresses
Take first 5 unique addresses
For each address:
GET ${API_URL}/agent/holdings/${address}?limit=50
Extract tokens with balance > 0
Wait 2 seconds
Print: "✅ Method 4: Found X tokens"
Expected result: Set of token addresses held by active large traders
Method 5: New Events API (Real-time BUY/SELL/CREATE events)
STATUS: ✅ This method is WORKING! Found 7 tokens in last scan.
What to do:
- Make GET request to
/api/token/new-event endpoint
- Parse JSON response (array of events)
- Extract token addresses from CREATE and BUY events
- Add all unique token addresses to collection
How to execute:
- Determine base URL: Read MONAD_NETWORK from .env:
- If
MONAD_NETWORK=mainnet: baseUrl = 'https://nad.fun'
- Else:
baseUrl = 'https://dev.nad.fun'
- Make GET request:
- URL:
${baseUrl}/api/token/new-event
- Headers:
Accept: application/json, User-Agent: OpenClaw-Agent/1.0
- Parse response: JSON array of event objects
- Extract tokens:
- For each event in response:
- If
event.type === 'CREATE': extract event.token_info.token_id
- If
event.type === 'BUY': extract event.token_info.token_id
- If
event.type === 'SELL': optionally extract (indicates active trading)
- Log results: Print "✅ Method 5: Found N tokens from new events API"
Example:
baseUrl = MONAD_NETWORK === 'mainnet' ? 'https://nad.fun' : 'https://dev.nad.fun'
GET ${baseUrl}/api/token/new-event
Parse JSON response
For each event:
If event.type === 'CREATE' or 'BUY':
Add event.token_info.token_id to tokensFromEvents
Print: "✅ Method 5: Found X tokens"
Expected result: Array of token addresses from recent CREATE and BUY events
Response structure:
type: "BUY" | "SELL" | "CREATE"
amount: Event amount (string)
token_info: Complete token information (token_id, name, symbol, description, creator, etc.)
account_info: Account that performed the action
Method 6: Market Cap API (Top tokens by market cap)
STATUS CHECK: Previous error: base64 decoding failed. Fix: Use proper decoding method.
What to do:
- GET request to market cap endpoint
- Response is base64-encoded JSON - decode it PROPERLY
- Extract token addresses from response
- Add all token addresses to collection
How to execute:
- API URL:
${API_URL}/order/market_cap?page=1&limit=50&is_nsfw=false
- Where
API_URL = MONAD_NETWORK === 'mainnet' ? 'https://api.nadapp.net' : 'https://dev-api.nad.fun'
- GET request:
- Headers:
Accept: application/json, User-Agent: OpenClaw-Agent/1.0
- Get response as text (not JSON)
- Decode base64 PROPERLY:
- Response body is base64 string
- Use Python:
import base64; decoded = base64.b64decode(response_text).decode('utf-8')
- OR use command:
echo "$response_text" | base64 -d
- CRITICAL: Make sure response_text is the raw base64 string, not wrapped in JSON
- Parse decoded JSON:
- Parse decoded string as JSON
- Structure:
{ "tokens": [...], "total_count": N }
- Extract tokens WITH FULL DATA:
- For each token in
data.tokens:
- Extract
token.token_info.token_id (token address)
- CRITICAL: Store FULL token object with both
token_info AND market_info
- Structure:
{token_info: {...}, market_info: {...}, percent: ...}
- Add to topMarketCapTokens array (store full objects, not just addresses)
- Log results: Print "✅ Method 6: Found N tokens with market data from market cap API"
Example:
API_URL = MONAD_NETWORK === 'mainnet' ? 'https://api.nadapp.net' : 'https://dev-api.nad.fun'
response = GET ${API_URL}/order/market_cap?page=1&limit=100&is_nsfw=false
decoded = base64.b64decode(response.text).decode('utf-8')
data = json.loads(decoded)
topMarketCapTokens = [] # Array of full token objects
For each token in data.tokens:
# Store FULL token object with token_info + market_info
topMarketCapTokens.append({
'token_info': token.token_info,
'market_info': token.market_info,
'percent': token.percent,
'address': token.token_info.token_id # For easy access
})
Print: "✅ Method 6: Found X tokens with market data"
Expected result: Array of full token objects (with token_info + market_info) sorted by market cap
Response structure:
tokens: Array of token objects with token_info and market_info
total_count: Total number of tokens
- Each token includes:
token_info (token_id, name, symbol, creator, etc.) and market_info (market_type, price, volume, holder_count, etc.)
Method 7: Creation Time API (Newest tokens)
CRITICAL: Include BOTH bonding curve AND DEX tokens! Do NOT filter by is_graduated.
What to do:
- GET request to creation time endpoint (newest first)
- Decode base64 response PROPERLY (same as Method 6)
- Extract token addresses - include ALL tokens (both bonding curve AND DEX)
- Add to collection WITH FULL DATA
How to execute:
- API URL:
${API_URL}/order/creation_time?page=1&limit=50&is_nsfw=false&direction=DESC
- GET request, decode base64 response (same as Method 6)
- Parse JSON:
data.tokens array
- For each token:
- Extract
token.token_info.token_id (token address)
- CRITICAL: Store FULL token object with both
token_info AND market_info
- DO NOT filter by is_graduated - include both bonding curve (is_graduated=false) AND DEX (is_graduated=true) tokens
- Add to newestTokens array (store full objects, not just addresses)
Example:
API_URL = MONAD_NETWORK === 'mainnet' ? 'https://api.nadapp.net' : 'https://dev-api.nad.fun'
response = GET ${API_URL}/order/creation_time?page=1&limit=50&is_nsfw=false&direction=DESC
decoded = base64.b64decode(response.text).decode('utf-8')
data = json.loads(decoded)
newestTokens = [] # Array of full token objects
For each token in data.tokens:
# Include ALL tokens - both bonding curve AND DEX
# Store FULL token object with token_info + market_info
newestTokens.append({
'token_info': token.token_info,
'market_info': token.market_info,
'percent': token.percent,
'address': token.token_info.token_id # For easy access
})
Print: "✅ Method 7: Found X tokens with market data (bonding curve + DEX)"
Expected result: Array of full token objects (with token_info + market_info) - newest tokens including both bonding curve AND DEX
Response structure:
- Same as Method 6:
tokens array with token_info and market_info
direction=DESC returns newest first
- CRITICAL: Include ALL tokens (both bonding curve AND DEX) - do NOT filter by is_graduated
Combine All Methods - CRITICAL STEP
What to do:
- Collect ALL token addresses from Methods 5, 6, and 7 into one set (removes duplicates)
- Count how many times each token appears across methods
- Sort tokens by frequency (tokens found in more methods = higher priority/confidence)
- Log summary of combination results
How to execute:
Create collections:
allTokens = new Set() or allTokens = [] (use Set to avoid duplicates)
tokenFrequency = new Map() or {} to count occurrences
Add tokens from each method:
- Method 5: Add all token addresses from tokensFromEvents (New Events API) - these are just addresses
- Method 6: Add all tokens from topMarketCapTokens (Market Cap API) - these are FULL objects with token_info + market_info
- Method 7: Add all tokens from newestTokens (Creation Time API) - these are FULL objects with token_info + market_info
IMPORTANT: For Methods 6 & 7, store the FULL token objects (not just addresses) so you can use market_info directly for analysis!
Count frequency and preserve full data:
- Use a Map/object:
allTokensMap = {} where key = token address, value = token object with metadata
- For Method 5 (addresses only):
allTokensMap[address] = {address, source: 'method5', data: null}
- For Method 6 (full objects):
allTokensMap[address] = {address, source: 'method6', data: fullTokenObject}
- For Method 7 (full objects):
allTokensMap[address] = {address, source: 'method7', data: fullTokenObject}
- Count frequency:
tokenFrequency[address] = (tokenFrequency[address] || 0) + 1
- CRITICAL: Preserve full token objects from Methods 6 & 7 - they contain market_info!
Convert and sort:
candidateTokens = Object.values(allTokensMap) or Array.from(allTokensMap.values())
- Sort by frequency DESC, then by data availability:
candidateTokens.sort((a, b) => {
const freqA = tokenFrequency[a.address] || 0
const freqB = tokenFrequency[b.address] || 0
if (freqB !== freqA) return freqB - freqA // Higher frequency first
// Prefer tokens with full data (market_info)
const hasDataA = a.data && a.data.market_info ? 1 : 0
const hasDataB = b.data && b.data.market_info ? 1 : 0
return hasDataB - hasDataA
})
prioritizedTokens = candidateTokens
Log summary:
- Print: "📊 Combined results: Total unique tokens: N"
- Print: "Tokens found in 2+ methods: X"
- Print: "Tokens found in all 3 methods: Y"
- Print: "Tokens with full market data: Z"
- Print: "Top 10 prioritized tokens: "
Example:
allTokensMap = {} # Map: address -> {address, source, data}
tokenFrequency = {}
# Method 5: addresses only
for address in tokensFromEvents:
allTokensMap[address] = {address: address, source: 'method5', data: null}
tokenFrequency[address] = (tokenFrequency[address] || 0) + 1
# Method 6: full objects with market_info
for token in topMarketCapTokens:
address = token.token_info.token_id
allTokensMap[address] = {address: address, source: 'method6', data: token}
tokenFrequency[address] = (tokenFrequency[address] || 0) + 1
# Method 7: full objects with market_info
for token in newestTokens:
address = token.token_info.token_id
allTokensMap[address] = {address: address, source: 'method7', data: token}
tokenFrequency[address] = (tokenFrequency[address] || 0) + 1
# Sort by frequency and data availability
candidateTokens = Object.values(allTokensMap)
prioritizedTokens = candidateTokens.sort((a, b) => {
freqDiff = tokenFrequency[b.address] - tokenFrequency[a.address]
if (freqDiff !== 0) return freqDiff
return (b.data && b.data.market_info ? 1 : 0) - (a.data && a.data.market_info ? 1 : 0)
})
Print: "📊 Combined: N unique tokens, X found in 2+ methods, Y found in all 3 methods, Z with full data"
Expected result: Prioritized array of token objects, each containing:
address: token address
source: which method(s) found it
data: full token object with token_info + market_info (if available from Methods 6 or 7)
foundInMethods: count from tokenFrequency
Save Found Tokens - CRITICAL STEP
What to do:
After combining all methods and getting prioritizedTokens, you MUST save them to file $HOME/nadfunagent/found_tokens.json for manual review.
How to execute:
Prepare token list:
- Take top 50 tokens from prioritizedTokens
- For each token, create object:
{address: token, foundInMethods: frequency_count}
- Create scan entry with timestamp, totalFound count, and tokens array
Read existing file:
- File:
$HOME/nadfunagent/found_tokens.json
- If file doesn't exist or is empty: start with
[]
- If exists: parse JSON, get array
Append and save:
- Add new scan entry to array
- Keep only last 100 scans (remove oldest if > 100)
- Write back as formatted JSON
Example using Node.js script (RECOMMENDED):
# From skill root or repo root: print token addresses (one per line) and pipe to script
# prioritizedTokens is the array of token addresses; take first 50 and pass to script
echo -e "0x...\n0x..." | node scripts/save_tokens.js
Or from the agent: write the list of addresses to a temp file or stdin and run node scripts/save_tokens.js (script reads from stdin). Data dir: NADFUNAGENT_DATA_DIR or $HOME/nadfunagent.
Expected result: File $HOME/nadfunagent/found_tokens.json updated with latest scan results
2. Token Analysis - CRITICAL: Use Data from Methods 6 & 7 Directly
IMPORTANT: Methods 6 (Market Cap API) and Method 7 (Creation Time API) already return COMPLETE token data with market_info. Use this data directly for analysis - DO NOT make additional API calls unless absolutely necessary!
Data Structure from Methods 6 & 7:
Each token in the response has this structure:
{
"token_info": {
"token_id": "0x...",
"name": "...",
"symbol": "...",
"is_graduated": true/false,
"created_at": timestamp,
...
},
"market_info": {
"market_type": "DEX" or "BONDING_CURVE",
"reserve_native": "1625513352353765005672133", // Liquidity in MON (wei format)
"reserve_token": "51582894169959918089536846",
"token_price": "0.000886889894056452",
"price": "0.0415501242",
"price_usd": "0.000886889894056452",
"volume": "761848094037806233587694495", // Total volume (wei format)
"holder_count": 31580, // Number of holders
"ath_price": "0.0128807779",
"ath_price_usd": "0.0128807779",
...
},
"percent": 8.797 // Market cap change percentage
}
Analysis Steps:
Extract data from Methods 6 & 7:
- For each token in
data.tokens array from Methods 6 & 7:
- Extract
token_info.token_id (token address)
- Extract
market_info.reserve_native (liquidity in wei, convert to MON: divide by 1e18)
- Extract
market_info.holder_count (number of holders)
- Extract
market_info.volume (total volume in wei, convert to MON: divide by 1e18)
- Extract
market_info.market_type ("DEX" or "BONDING_CURVE")
- Extract
token_info.is_graduated (true if graduated to DEX)
- Extract
percent (market cap change percentage)
For Method 5 tokens (new-event API):
- This API returns only basic event data without full market_info
- For tokens from Method 5, you can optionally query
/agent/market/:token_id to get market_info
- BUT prioritize tokens from Methods 6 & 7 first (they already have complete data)
Calculate Liquidity Score (30% weight):
liquidityMON = parseFloat(market_info.reserve_native) / 1e18
// Score based on liquidity tiers
if (liquidityMON >= 1000) liquidityScore = 100 // Excellent
else if (liquidityMON >= 500) liquidityScore = 80 // Very good
else if (liquidityMON >= 100) liquidityScore = 60 // Good
else if (liquidityMON >= 50) liquidityScore = 40 // Fair
else if (liquidityMON >= 10) liquidityScore = 20 // Low
else liquidityScore = 0 // Too low
weightedLiquidity = liquidityScore * 0.30
Calculate Momentum Score (25% weight):
// Use percent (market cap change) as momentum indicator
percentChange = parseFloat(token.percent) || 0
// Score based on positive momentum
if (percentChange >= 50) momentumScore = 100 // Strong growth
else if (percentChange >= 20) momentumScore = 80
else if (percentChange >= 10) momentumScore = 60
else if (percentChange >= 5) momentumScore = 40
else if (percentChange >= 0) momentumScore = 20
else momentumScore = 0 // Negative momentum
weightedMomentum = momentumScore * 0.25
Calculate Volume Score (20% weight):
volumeMON = parseFloat(market_info.volume) / 1e18
// Score based on volume tiers
if (volumeMON >= 1000000) volumeScore = 100 // 1M+ MON volume
else if (volumeMON >= 500000) volumeScore = 80
else if (volumeMON >= 100000) volumeScore = 60
else if (volumeMON >= 50000) volumeScore = 40
else if (volumeMON >= 10000) volumeScore = 20
else volumeScore = 0
weightedVolume = volumeScore * 0.20
Calculate Holder Score (15% weight):
holderCount = parseInt(market_info.holder_count) || 0
// Score based on holder count
if (holderCount >= 10000) holderScore = 100 // Excellent distribution
else if (holderCount >= 5000) holderScore = 80
else if (holderCount >= 1000) holderScore = 60
else if (holderCount >= 500) holderScore = 40
else if (holderCount >= 100) holderScore = 20
else holderScore = 0
weightedHolders = holderScore * 0.15
Calculate Progress Score (10% weight):
isGraduated = token_info.is_graduated === true
marketType = market_info.market_type
// Score based on market stage
if (isGraduated || marketType === "DEX") {
progressScore = 100 // Fully graduated to DEX
} else {
// Still on bonding curve - use percent as progress indicator
// Higher percent = closer to graduation
percent = parseFloat(token.percent) || 0
if (percent >= 80) progressScore = 80
else if (percent >= 50) progressScore = 60
else if (percent >= 30) progressScore = 40
else progressScore = 20
}
weightedProgress = progressScore * 0.10
Calculate Authority Score (Bonus - up to +10 points):
// Check for social media presence and website (indicates legitimacy)
hasTwitter = token_info.twitter && token_info.twitter.length > 0
hasTelegram = token_info.telegram && token_info.telegram.length > 0
hasWebsite = token_info.website && token_info.website.length > 0
authorityScore = 0
if (hasTwitter) authorityScore += 3
if (hasTelegram) authorityScore += 3
if (hasWebsite) authorityScore += 4
// Maximum +10 bonus points for full social presence
authorityBonus = Math.min(authorityScore, 10)
Calculate Total Score:
totalScore = weightedLiquidity + weightedMomentum + weightedVolume + weightedHolders + weightedProgress + authorityBonus
// Round to 2 decimal places
totalScore = Math.round(totalScore * 100) / 100
Store Analysis Results:
For each token, store:
{
address: token_info.token_id,
name: token_info.name,
symbol: token_info.symbol,
liquidity: liquidityMON,
holders: holderCount,
volume: volumeMON,
marketType: marketType,
isGraduated: isGraduated,
percentChange: percentChange,
scores: {
liquidity: liquidityScore,
momentum: momentumScore,
volume: volumeScore,
holders: holderScore,
progress: progressScore,
total: totalScore
},
foundInMethods: tokenFrequency[token_info.token_id] || 1
}
CRITICAL INSTRUCTIONS:
- Use data from Methods 6 & 7 DIRECTLY - they already contain all needed information
- DO NOT make additional API calls to
/agent/market/:token_id for tokens from Methods 6 & 7
- Only for Method 5 tokens (if needed) make additional API calls
- Calculate scores immediately after combining methods, before filtering
- Check authority (social media presence): Check
token_info.twitter, token_info.telegram, token_info.website - add bonus points
- Log analysis results: Print "📊 Analysis: Token X has score Y (liquidity: A, momentum: B, volume: C, holders: D, progress: E, authority: +F)"
3. Filtering Criteria
Filter tokens based on:
- Minimum liquidity: 5 MON
- Minimum holders: 5
- Bonding curve progress: >= 10%
- Score calculation:
- Liquidity: 30% weight
- Momentum: 25% weight
- Volume trend: 20% weight
- Holder distribution: 15% weight
- Bonding curve progress: 10% weight
4. Position Management - CRITICAL: Check Existing Positions FIRST
BEFORE analyzing new tokens, you MUST check and manage existing positions!
Step 1: Get Current Holdings
What to do:
- Get trading wallet address from
MONAD_PRIVATE_KEY in .env (derive address from private key)
- Query current token holdings using Agent API:
/agent/holdings/${walletAddress}?limit=100
- Filter tokens where
balance > 0 (exclude zero balances)
- For each token with balance > 0, get current market data
How to execute:
// 1. Get wallet address from private key
const walletAddress = getAddressFromPrivateKey(MONAD_PRIVATE_KEY)
// 2. Query holdings
const holdingsResponse = await fetch(`${API_URL}/agent/holdings/${walletAddress}?limit=100`)
const holdings = await holdingsResponse.json()
// 3. Filter tokens with balance > 0
const activePositions = holdings.tokens.filter(token => {
const balance = parseFloat(token.balance_info.balance) || 0
return balance > 0
})
Print: "📊 Current positions: Found N tokens with balance > 0"
Step 2: Calculate P&L for Each Position
CRITICAL: Always use the check-pnl.js script from nadfun-trading skill for proper P&L calculation. This script:
- Reads entry price (
entryValueMON) from $HOME/nadfunagent/positions_report.json (automatically recorded by buy-token.js when you purchase)
- Gets current value on-chain via nad.fun quote contract (or falls back to Agent API)
- Calculates P&L:
(currentValueMON - entryValueMON) / entryValueMON * 100
What to do:
- Use the script: Run
check-pnl.js from nadfun-trading skill directory
- The script reads entry prices from JSON (set by
buy-token.js after purchases)
- Gets current value on-chain via nad.fun quote contract
- Calculates real P&L based on actual entry price
How to execute:
# Check P&L for all positions
cd $HOME/.openclaw/workspace/skills/nadfun-trading
node check-pnl.js
# Or with auto-sell (sells if P&L >= +5% or <= -10%)
node check-pnl.js --auto-sell
Manual calculation (if script unavailable):
// Load entry prices from positions_report.json
const report = JSON.parse(await fs.readFile('$HOME/nadfunagent/positions_report.json', 'utf-8'))
for (const position of activePositions) {
const tokenAddress = position.token_info.token_id || position.token_info.address
const tokenBalance = parseFloat(position.balance_info.balance) || 0
// Get entry price from JSON (recorded by buy-token.js)
const prev = report.positions?.find(p =>
(p.address || '').toLowerCase() === tokenAddress.toLowerCase()
)
const entryValueMON = prev?.entryValueMON || 0
// Get current value on-chain via nad.fun quote contract
const [router, amountOutWei] = await publicClient.readContract({
address: '0x7e78A8DE94f21804F7a17F4E8BF9EC2c872187ea', // nad.fun quote contract
abi: lensAbi,
functionName: 'getAmountOut',
args: [tokenAddress, parseEther(tokenBalance.toString()), false] // false = selling
})
const currentValueMON = Number(amountOutWei) / 1e18
// Calculate P&L
const pnlPercent = entryValueMON > 0
? ((currentValueMON - entryValueMON) / entryValueMON) * 100
: 0
positions.push({
address: tokenAddress,
balance: tokenBalance,
entryValueMON: entryValueMON,
currentValueMON: currentValueMON,
pnlPercent: pnlPercent
})
}
Print: "💰 Position P&L calculated for N positions (source: on-chain nad.fun quote + positions_report.json)"
Entry Price Tracking:
- Entry price is automatically recorded by
buy-token.js after successful purchase
- Stored in
$HOME/nadfunagent/positions_report.json as entryValueMON
- If entry price not found,
check-pnl.js uses current value as fallback (P&L = 0%)
Step 3: Make Sell Decisions
What to do:
For each position, check sell conditions:
Stop-Loss Check:
if (pnlPercent <= -10) { // STOP_LOSS_PERCENT = -10%
// SELL ALL - stop loss triggered
sellDecision = {
action: 'SELL_ALL',
reason: 'Stop-loss triggered',
tokenAddress: position.address,
amount: 'all'
}
}
Take-Profit Check:
if (pnlPercent >= 20) { // PROFIT_TARGET_PERCENT = 20%
// SELL HALF - take profit
sellDecision = {
action: 'SELL_HALF',
reason: 'Take-profit triggered',
tokenAddress: position.address,
amount: position.balance / 2
}
}
Trailing Stop (Optional):
// If profit was > 15% but dropped to < 5%, sell to protect gains
if (previousPnL > 15 && pnlPercent < 5) {
sellDecision = {
action: 'SELL_ALL',
reason: 'Trailing stop - protecting gains',
tokenAddress: position.address,
amount: 'all'
}
}
How to execute:
const sellDecisions = []
for (const position of positions) {
// Stop-loss: sell all if down 10%+
if (position.pnlPercent <= -10) {
sellDecisions.push({
tokenAddress: position.address,
action: 'SELL_ALL',
reason: `Stop-loss: ${position.pnlPercent.toFixed(2)}%`,
amount: 'all'
})
}
// Take-profit: sell half if up 20%+
else if (position.pnlPercent >= 20) {
sellDecisions.push({
tokenAddress: position.address,
action: 'SELL_HALF',
reason: `Take-profit: ${position.pnlPercent.toFixed(2)}%`,
amount: position.balance / 2
})
}
}
Print: "🔔 Sell decisions: N positions need action"
for (const decision of sellDecisions) {
Print: ` ${decision.action}: ${decision.tokenAddress} - ${decision.reason}`
}
Step 4: Execute Sell Orders
What to do:
For each sell decision:
- Use
nadfun-trading skill with action sell
- Parameters: token address, amount (from decision)
- The skill handles: balance check, quote, approve, execution
How to execute:
for (const decision of sellDecisions) {
try {
// Use nadfun-trading skill
await useSkill('nadfun-trading', {
action: 'sell',
token: decision.tokenAddress,
amount: decision.amount // 'all' or specific amount
})
Print: `✅ Sold ${decision.amount} of ${decision.tokenAddress}: ${decision.reason}`
} catch (error) {
Print: `❌ Failed to sell ${decision.tokenAddress}: ${error.message}`
}
}
5. Trading Execution - Buy New Tokens
CRITICAL: Only buy new tokens AFTER managing existing positions!
Buy Decision Logic:
Prioritize tokens with authority (social media presence):
- Tokens with Twitter + Telegram + Website get priority
- These are more legitimate and have better community support
Consider both early-stage AND established tokens:
- Early-stage (5-50 MON liquidity): Higher risk, higher potential
- Established (50k+ MON liquidity): Lower risk, steady growth
- Both can be profitable if they meet score criteria
Buy Criteria:
- Score >= 60 (or >= 55 if has social media)
- Liquidity >= 5 MON
- Holders >= 5
- NOT already in portfolio (check existing positions first)
Position Sizing:
- For tokens with authority (social media): up to 0.15 MON
- For tokens without authority: up to 0.1 MON
- Maximum total position per token: 0.15 MON
CRITICAL: Always use the buy-token.js script from nadfun-trading skill. This script:
- Automatically detects bonding curve vs DEX via nad.fun quote contract
- Handles DEX: wraps MON→WMON, approves, swaps
- Automatically records entry price in
$HOME/nadfunagent/positions_report.json after successful purchase
- Works on bonding curve (MON) or DEX (MON) - all trading uses MON
Buy tokens:
cd $HOME/.openclaw/workspace/skills/nadfun-trading
NAD_PRIVATE_KEY=$MONAD_PRIVATE_KEY node buy-token.js <token-address> <MON-amount> [--slippage=300]
Example:
NAD_PRIVATE_KEY=0x... node buy-token.js 0x123...abc 0.15 --slippage=300
After purchase:
- Entry price (
entryValueMON) is automatically recorded in $HOME/nadfunagent/positions_report.json
- This entry price is used by
check-pnl.js for P&L calculation
- No manual tracking needed - everything is automated
Risk management:
- CRITICAL: Buy tokens on BOTH bonding curve AND DEX (don't filter by market_type)
- The
nadfun-trading skill automatically detects market type and uses correct contract
- For all trades, use MON balance (no wrapping needed - all trading uses MON)
- Set slippage tolerance: 2-3% (increased for better execution, especially on DEX)
- Set deadline: 5 minutes from now
- Don't exceed MAX_POSITION_SIZE per token
6. Profit Distribution
CRITICAL: Use MMIND_TOKEN_ADDRESS from $HOME/nadfunagent/.env file.
When profit >= 0.1 MON:
// Step 1: Load MMIND_TOKEN_ADDRESS from .env file
const envFile = await readFile('$HOME/nadfunagent/.env', 'utf-8')
const mmindMatch = env
…(truncated)
1---
2name: nadfunagent
3description: Autonomous trading agent for Nad.fun that scans markets, analyzes
4 tokens, executes trades, and distributes profits to MMIND token holders. Uses
5 nadfun-trading, nadfun-indexer, and nadfun-agent-api skills.
6metadata:
7 source: https://skillmd.com/skills/modbender/nadfunagent
8---
9
10
11**CRITICAL COMMUNICATION RULES:**
121. **Language**: Always respond in the SAME language as the user's question. If in English, respond in English.
132. **Data Loading**: BEFORE executing any operations, FIRST request and load ALL required data from user or configuration files. Use OpenClaw's memory/session storage to save loaded data so you don't need to ask again.
143. **Telegram Integration**:
15 - Send detailed reports to Telegram after each trading cycle
16 - If Telegram bot connection is not established, request user to start conversation with bot first
17 - Include position status, P&L, new opportunities found, trades executed
184. **Initial Setup**: When first invoked, ask user for:
19 - MMIND_TOKEN_ADDRESS (or load from .env)
20 - MONAD_PRIVATE_KEY (or load from .env)
21 - MONAD_RPC_URL (or load from .env)
22 - MONAD_NETWORK (or load from .env)
23 - Telegram user ID for notifications
24 Save all this data in OpenClaw memory for future use.
255. **Missing variables**: If `.env` is missing or any required variable (MONAD_PRIVATE_KEY, MONAD_RPC_URL, MMIND_TOKEN_ADDRESS, MONAD_NETWORK) is not set, **ask the user to provide it** before running trading or scripts. Do not proceed with buy/sell or execute-bonding-v2 until config is complete.
26
27# Nad.fun Autonomous Trading Agent
28
29Autonomous trading agent that scans Nad.fun markets, analyzes tokens using momentum strategies, executes trades, and distributes profits to MMIND token holders.
30
31## Prerequisites
32
33- `monad-development` skill installed (for wallet and RPC setup)
34- `nadfun-trading` skill installed (for buy/sell operations), or use the `trading/` folder from this repo
35- `nadfun-indexer` skill installed (for querying events)
36- `nadfun-agent-api` skill installed (for market data)
37- Network configured (mainnet only for this skill)
38- MMIND token address configured
39
40**Paths (clean install):** Config is read from `NADFUN_ENV_PATH` if set, else `$HOME/nadfunagent/.env`. Positions report: `POSITIONS_REPORT_PATH` or `$HOME/nadfunagent/positions_report.json`. Scripts from `nadfun-trading` may be at `~/.openclaw/workspace/skills/nadfun-trading` or at `<this-repo>/trading`. See `DEPENDENCIES.md`.
41
42## Configuration
43
44**CRITICAL**: Load environment variables from `.env` file (default path: `$HOME/nadfunagent/.env`; override with `NADFUN_ENV_PATH`):
45
46- `MMIND_TOKEN_ADDRESS`: Address of MMIND token for profit distribution (required)
47- `MONAD_PRIVATE_KEY`: Private key for trading wallet (required)
48- `MONAD_RPC_URL`: RPC endpoint URL (required)
49- `MONAD_NETWORK`: Network type - "mainnet" or "testnet" (required)
50- `MAX_POSITION_SIZE`: Maximum position size in MON (default: 0.1)
51- `PROFIT_TARGET_PERCENT`: Take-profit threshold (default: 20%)
52- `STOP_LOSS_PERCENT`: Stop-loss threshold (default: 10%)
53- `PNL_DISTRIBUTION_PERCENT`: % of profit to distribute (default: 30%)
54
55**Before starting trading cycle:**
561. Read `.env` file (path: `NADFUN_ENV_PATH` or `$HOME/nadfunagent/.env`). If the file is missing or any required variable is empty, **ask the user** to provide MMIND_TOKEN_ADDRESS, MONAD_PRIVATE_KEY, MONAD_RPC_URL, MONAD_NETWORK — do not run trading until config is complete.
572. Load `MMIND_TOKEN_ADDRESS` - use this for profit distribution
583. Load `MONAD_PRIVATE_KEY` - use this for wallet operations
594. Load `MONAD_RPC_URL` - use this for blockchain queries
605. Load `MONAD_NETWORK` - determines API endpoints (mainnet: api.nadapp.net, testnet: dev-api.nad.fun)
61
62## Workflow
63
64**EXECUTION SUMMARY - READ THIS FIRST:**
651. **Load config** from `$HOME/nadfunagent/.env` (MMIND_TOKEN_ADDRESS, MONAD_PRIVATE_KEY, MONAD_RPC_URL, MONAD_NETWORK)
662. **Execute ONLY 3 methods** (from HAR file analysis): Method 5 (New Events API), Method 6 (Market Cap API), Method 7 (Creation Time API)
673. **Combine results** - merge all token addresses from 3 methods, count frequency (how many methods found each token, max 3)
684. **Prioritize** - sort tokens by frequency (tokens found in 2-3 methods = higher priority)
695. **Save tokens** - save ALL found tokens (up to top 50 for storage) to `$HOME/nadfunagent/found_tokens.json` for manual review
706. **Analyze** - get token info, market data, metrics via Agent API, calculate scores
717. **Filter** - keep only tokens with min liquidity 5 MON, min holders 5
728. **Trade** - execute trades if score >= 60
739. **Distribute** - distribute profits to MMIND holders if profit >= 0.1 MON
74
75### 1. Market Scanning (NEW + TRENDING)
76
77**CRITICAL INSTRUCTIONS**: You MUST scan tokens using ALL 7 methods below. Execute each method step-by-step and collect ALL found token addresses.
78
79**EXECUTION ORDER:**
801. Method 1: CurveCreate events (Indexer) - NEW tokens
812. Method 2: CurveBuy events (Indexer) - TRENDING by volume
823. Method 3: Swap History (Agent API) - TRENDING by 24h volume
834. Method 4: Holdings (Agent API) - ACTIVE tokens from large traders
845. Method 5: New Events API - REAL-TIME BUY/CREATE events
856. Method 6: Market Cap API - TOP tokens by capitalization
867. Method 7: Creation Time API - NEWEST tokens
87
88**STEP-BY-STEP EXECUTION:**
89
90**CRITICAL LOGGING REQUIREMENT:**
91After executing EACH method, you MUST log:
921. Print: "✅ Method X executed: Found N tokens"
932. Print: "Method X token addresses: <address1> <address2> ..."
943. If method failed: Print: "❌ Method X failed: <error reason>"
954. This helps track which methods are working and debug issues
96
97**NOTE:** Only Methods 5, 6, and 7 are used (from HAR file analysis). Methods 1-4 are disabled.
98
99**STATUS CHECK:** This method requires RPC access. You MUST execute it, don't skip it!
100
101**What to do:**
1021. Read `$HOME/nadfunagent/.env` to get `MONAD_RPC_URL` and `MONAD_NETWORK`
1032. Get current block number using RPC: `eth_blockNumber`
1043. Calculate: `safeLatest = currentBlock - 10` (safety margin)
1054. Scan last 900 blocks in chunks of 100 blocks (RPC limit)
1065. For each chunk, query CurveCreate events using `nadfun-indexer` skill
107
108**How to execute:**
109- Use `nadfun-indexer` skill with parameters: `event=CurveCreate`, `fromBlock=<start>`, `toBlock=<end>`
110- Extract token addresses from events: `event.args.token` or `event.args[1]` (token is second argument)
111- Collect all unique token addresses
112
113**Example command structure:**
114```
115Use skill: nadfun-indexer
116Parameters: event=CurveCreate, fromBlock=<calculated_start>, toBlock=<calculated_end>
117Extract: token address from each event
118```
119
120**Expected result:** Array of token addresses (0x...) from newly created tokens
121
122#### Method 2: Trending Tokens via Indexer (CurveBuy volume analysis)
123
124**STATUS CHECK:** This method requires RPC access. You MUST execute it, don't skip it!
125
126**What to do:**
1271. Query CurveBuy events from last 900 blocks (same pagination as Method 1)
1282. For each event, extract: token address and amountIn (MON spent)
1293. Sum volume per token address
1304. Sort tokens by total volume (descending)
1315. Take top 20 tokens with highest volume
132
133**How to execute:**
1341. **Use same RPC setup as Method 1:** Get publicClient from monad-development skill
1352. **Query CurveBuy events:** For each 100-block chunk:
136 - Use `nadfun-indexer` skill: `event=CurveBuy`, `fromBlock=<start>`, `toBlock=<end>`
137 - OR use viem: `publicClient.getContractEvents({ address: CURVE_ADDRESS, eventName: "CurveBuy", fromBlock, toBlock })`
1383. **Extract data:** From each event:
139 - `token = event.args.token` or `event.args[1]`
140 - `amountIn = event.args.amountIn` or `event.args[2]` (amount in MON)
1414. **Calculate volume:** Group by token address, sum all amountIn values
1425. **Sort and filter:** Sort by total volume DESC, take top 20
1436. **Log results:** Print "✅ Method 2: Found top 20 trending tokens by volume"
144
145**Example:**
146```
1471. Use same RPC client from Method 1
1482. Query CurveBuy events in chunks of 100 blocks
1493. For each event: extract token and amountIn
1504. Sum volume per token
1515. Sort DESC, take top 20
1526. Print: "✅ Method 2: Found 20 trending tokens"
153```
154
155**Expected result:** Top 20 token addresses sorted by trading volume
156
157#### Method 3: Trending Tokens via Agent API (Swap History Analysis)
158
159**What to do:**
1601. Take top 10 tokens from Method 2 (highest volume)
1612. For each token, query swap history via Agent API
1623. Calculate 24h volume from swap history
1634. Keep tokens with >= 1 MON volume in last 24 hours
164
165**How to execute:**
166- Determine API URL: if `MONAD_NETWORK=mainnet` then `https://api.nadapp.net`, else `https://dev-api.nad.fun`
167- For each token, make GET request: `${API_URL}/agent/swap-history/${tokenAddress}?limit=50&trade_type=ALL`
168- Parse response JSON
169- For each swap in `response.swaps`:
170 - Check `swap.swap_info.timestamp` - if within last 24 hours
171 - Sum `swap.swap_info.native_amount` (in wei, convert to MON: divide by 1e18)
172- Keep tokens with total 24h volume >= 1 MON
173- Add 1-2 second delay between API calls to avoid rate limits
174
175**Example:**
176```
177API_URL = MONAD_NETWORK === 'mainnet' ? 'https://api.nadapp.net' : 'https://dev-api.nad.fun'
178For each token in top10:
179 GET ${API_URL}/agent/swap-history/${token}?limit=50&trade_type=ALL
180 Calculate 24h volume
181 If volume >= 1 MON: add to trendingViaAPI
182 Wait 1-2 seconds
183```
184
185**Expected result:** List of tokens with high 24h trading volume
186
187#### Method 4: Get All Active Tokens (via Holdings of Large Accounts)
188
189**STATUS CHECK:** Don't skip this method! Execute it with rate limit delays.
190
191**What to do:**
1921. From Method 2 CurveBuy events, find buyers who spent >1 MON
1932. Extract their addresses (sender field)
1943. Query holdings for first 5 large buyers (to avoid rate limits)
1954. Extract all token addresses they hold (balance > 0)
196
197**How to execute:**
1981. **From Method 2 results:** Use CurveBuy events already queried
1992. **Filter large buyers:**
200 - Filter events where `amountIn > 1000000000000000000` (1 MON in wei = 1e18)
201 - Extract `sender` address: `event.args.sender` or `event.args[0]`
202 - Get unique addresses, take first 5
2033. **Query holdings:** For each of 5 addresses:
204 - GET: `${API_URL}/agent/holdings/${address}?limit=50`
205 - Headers: `Accept: application/json`
206 - Wait 2 seconds between requests
2074. **Parse and extract:**
208 - Parse JSON response
209 - For each `holding` in `response.tokens`:
210 - Check `holding.balance_info.balance` - if > 0
211 - Extract `holding.token_info.address` or `holding.token_info.token_id`
2125. **Log results:** Print "✅ Method 4: Found N active tokens from large trader holdings"
213
214**Example:**
215```
216From Method 2 CurveBuy events:
217 Filter: amountIn > 1e18 (1 MON)
218 Extract: sender addresses
219 Take first 5 unique addresses
220For each address:
221 GET ${API_URL}/agent/holdings/${address}?limit=50
222 Extract tokens with balance > 0
223 Wait 2 seconds
224Print: "✅ Method 4: Found X tokens"
225```
226
227**Expected result:** Set of token addresses held by active large traders
228
229#### Method 5: New Events API (Real-time BUY/SELL/CREATE events)
230
231**STATUS:** ✅ This method is WORKING! Found 7 tokens in last scan.
232
233**What to do:**
2341. Make GET request to `/api/token/new-event` endpoint
2352. Parse JSON response (array of events)
2363. Extract token addresses from CREATE and BUY events
2374. Add all unique token addresses to collection
238
239**How to execute:**
2401. **Determine base URL:** Read MONAD_NETWORK from .env:
241 - If `MONAD_NETWORK=mainnet`: `baseUrl = 'https://nad.fun'`
242 - Else: `baseUrl = 'https://dev.nad.fun'`
2432. **Make GET request:**
244 - URL: `${baseUrl}/api/token/new-event`
245 - Headers: `Accept: application/json`, `User-Agent: OpenClaw-Agent/1.0`
2463. **Parse response:** JSON array of event objects
2474. **Extract tokens:**
248 - For each event in response:
249 - If `event.type === 'CREATE'`: extract `event.token_info.token_id`
250 - If `event.type === 'BUY'`: extract `event.token_info.token_id`
251 - If `event.type === 'SELL'`: optionally extract (indicates active trading)
2525. **Log results:** Print "✅ Method 5: Found N tokens from new events API"
253
254**Example:**
255```
256baseUrl = MONAD_NETWORK === 'mainnet' ? 'https://nad.fun' : 'https://dev.nad.fun'
257GET ${baseUrl}/api/token/new-event
258Parse JSON response
259For each event:
260 If event.type === 'CREATE' or 'BUY':
261 Add event.token_info.token_id to tokensFromEvents
262Print: "✅ Method 5: Found X tokens"
263```
264
265**Expected result:** Array of token addresses from recent CREATE and BUY events
266
267**Response structure:**
268- `type`: "BUY" | "SELL" | "CREATE"
269- `amount`: Event amount (string)
270- `token_info`: Complete token information (token_id, name, symbol, description, creator, etc.)
271- `account_info`: Account that performed the action
272
273#### Method 6: Market Cap API (Top tokens by market cap)
274
275**STATUS CHECK:** Previous error: base64 decoding failed. Fix: Use proper decoding method.
276
277**What to do:**
2781. GET request to market cap endpoint
2792. Response is base64-encoded JSON - decode it PROPERLY
2803. Extract token addresses from response
2814. Add all token addresses to collection
282
283**How to execute:**
2841. **API URL:** `${API_URL}/order/market_cap?page=1&limit=50&is_nsfw=false`
285 - Where `API_URL = MONAD_NETWORK === 'mainnet' ? 'https://api.nadapp.net' : 'https://dev-api.nad.fun'`
2862. **GET request:**
287 - Headers: `Accept: application/json`, `User-Agent: OpenClaw-Agent/1.0`
288 - Get response as text (not JSON)
2893. **Decode base64 PROPERLY:**
290 - Response body is base64 string
291 - Use Python: `import base64; decoded = base64.b64decode(response_text).decode('utf-8')`
292 - OR use command: `echo "$response_text" | base64 -d`
293 - CRITICAL: Make sure response_text is the raw base64 string, not wrapped in JSON
2944. **Parse decoded JSON:**
295 - Parse decoded string as JSON
296 - Structure: `{ "tokens": [...], "total_count": N }`
2975. **Extract tokens WITH FULL DATA:**
298 - For each token in `data.tokens`:
299 - Extract `token.token_info.token_id` (token address)
300 - **CRITICAL**: Store FULL token object with both `token_info` AND `market_info`
301 - Structure: `{token_info: {...}, market_info: {...}, percent: ...}`
302 - Add to topMarketCapTokens array (store full objects, not just addresses)
3036. **Log results:** Print "✅ Method 6: Found N tokens with market data from market cap API"
304
305**Example:**
306```
307API_URL = MONAD_NETWORK === 'mainnet' ? 'https://api.nadapp.net' : 'https://dev-api.nad.fun'
308response = GET ${API_URL}/order/market_cap?page=1&limit=100&is_nsfw=false
309decoded = base64.b64decode(response.text).decode('utf-8')
310data = json.loads(decoded)
311
312topMarketCapTokens = [] # Array of full token objects
313For each token in data.tokens:
314 # Store FULL token object with token_info + market_info
315 topMarketCapTokens.append({
316 'token_info': token.token_info,
317 'market_info': token.market_info,
318 'percent': token.percent,
319 'address': token.token_info.token_id # For easy access
320 })
321Print: "✅ Method 6: Found X tokens with market data"
322```
323
324**Expected result:** Array of full token objects (with token_info + market_info) sorted by market cap
325
326**Response structure:**
327- `tokens`: Array of token objects with `token_info` and `market_info`
328- `total_count`: Total number of tokens
329- Each token includes: `token_info` (token_id, name, symbol, creator, etc.) and `market_info` (market_type, price, volume, holder_count, etc.)
330
331#### Method 7: Creation Time API (Newest tokens)
332
333**CRITICAL**: Include BOTH bonding curve AND DEX tokens! Do NOT filter by is_graduated.
334
335**What to do:**
3361. GET request to creation time endpoint (newest first)
3372. Decode base64 response PROPERLY (same as Method 6)
3383. Extract token addresses - include ALL tokens (both bonding curve AND DEX)
3394. Add to collection WITH FULL DATA
340
341**How to execute:**
342- API URL: `${API_URL}/order/creation_time?page=1&limit=50&is_nsfw=false&direction=DESC`
343- GET request, decode base64 response (same as Method 6)
344- Parse JSON: `data.tokens` array
345- For each token:
346 - Extract `token.token_info.token_id` (token address)
347 - **CRITICAL**: Store FULL token object with both `token_info` AND `market_info`
348 - **DO NOT filter by is_graduated** - include both bonding curve (is_graduated=false) AND DEX (is_graduated=true) tokens
349 - Add to newestTokens array (store full objects, not just addresses)
350
351**Example:**
352```
353API_URL = MONAD_NETWORK === 'mainnet' ? 'https://api.nadapp.net' : 'https://dev-api.nad.fun'
354response = GET ${API_URL}/order/creation_time?page=1&limit=50&is_nsfw=false&direction=DESC
355decoded = base64.b64decode(response.text).decode('utf-8')
356data = json.loads(decoded)
357
358newestTokens = [] # Array of full token objects
359For each token in data.tokens:
360 # Include ALL tokens - both bonding curve AND DEX
361 # Store FULL token object with token_info + market_info
362 newestTokens.append({
363 'token_info': token.token_info,
364 'market_info': token.market_info,
365 'percent': token.percent,
366 'address': token.token_info.token_id # For easy access
367 })
368Print: "✅ Method 7: Found X tokens with market data (bonding curve + DEX)"
369```
370
371**Expected result:** Array of full token objects (with token_info + market_info) - newest tokens including both bonding curve AND DEX
372
373**Response structure:**
374- Same as Method 6: `tokens` array with `token_info` and `market_info`
375- `direction=DESC` returns newest first
376- **CRITICAL**: Include ALL tokens (both bonding curve AND DEX) - do NOT filter by is_graduated
377
378#### Combine All Methods - CRITICAL STEP
379
380**What to do:**
3811. Collect ALL token addresses from Methods 5, 6, and 7 into one set (removes duplicates)
3822. Count how many times each token appears across methods
3833. Sort tokens by frequency (tokens found in more methods = higher priority/confidence)
3844. Log summary of combination results
385
386**How to execute:**
3871. **Create collections:**
388 - `allTokens = new Set()` or `allTokens = []` (use Set to avoid duplicates)
389 - `tokenFrequency = new Map()` or `{}` to count occurrences
390
3912. **Add tokens from each method:**
392 - Method 5: Add all token addresses from tokensFromEvents (New Events API) - these are just addresses
393 - Method 6: Add all tokens from topMarketCapTokens (Market Cap API) - these are FULL objects with token_info + market_info
394 - Method 7: Add all tokens from newestTokens (Creation Time API) - these are FULL objects with token_info + market_info
395
396 **IMPORTANT**: For Methods 6 & 7, store the FULL token objects (not just addresses) so you can use market_info directly for analysis!
397
3983. **Count frequency and preserve full data:**
399 - Use a Map/object: `allTokensMap = {}` where key = token address, value = token object with metadata
400 - For Method 5 (addresses only): `allTokensMap[address] = {address, source: 'method5', data: null}`
401 - For Method 6 (full objects): `allTokensMap[address] = {address, source: 'method6', data: fullTokenObject}`
402 - For Method 7 (full objects): `allTokensMap[address] = {address, source: 'method7', data: fullTokenObject}`
403 - Count frequency: `tokenFrequency[address] = (tokenFrequency[address] || 0) + 1`
404 - **CRITICAL**: Preserve full token objects from Methods 6 & 7 - they contain market_info!
405
4064. **Convert and sort:**
407 - `candidateTokens = Object.values(allTokensMap)` or `Array.from(allTokensMap.values())`
408 - Sort by frequency DESC, then by data availability:
409 ```javascript
410 candidateTokens.sort((a, b) => {
411 const freqA = tokenFrequency[a.address] || 0
412 const freqB = tokenFrequency[b.address] || 0
413 if (freqB !== freqA) return freqB - freqA // Higher frequency first
414 // Prefer tokens with full data (market_info)
415 const hasDataA = a.data && a.data.market_info ? 1 : 0
416 const hasDataB = b.data && b.data.market_info ? 1 : 0
417 return hasDataB - hasDataA
418 })
419 ```
420 - `prioritizedTokens = candidateTokens`
421
4225. **Log summary:**
423 - Print: "📊 Combined results: Total unique tokens: N"
424 - Print: "Tokens found in 2+ methods: X"
425 - Print: "Tokens found in all 3 methods: Y"
426 - Print: "Tokens with full market data: Z"
427 - Print: "Top 10 prioritized tokens: <list with addresses>"
428
429**Example:**
430```
431allTokensMap = {} # Map: address -> {address, source, data}
432tokenFrequency = {}
433
434# Method 5: addresses only
435for address in tokensFromEvents:
436 allTokensMap[address] = {address: address, source: 'method5', data: null}
437 tokenFrequency[address] = (tokenFrequency[address] || 0) + 1
438
439# Method 6: full objects with market_info
440for token in topMarketCapTokens:
441 address = token.token_info.token_id
442 allTokensMap[address] = {address: address, source: 'method6', data: token}
443 tokenFrequency[address] = (tokenFrequency[address] || 0) + 1
444
445# Method 7: full objects with market_info
446for token in newestTokens:
447 address = token.token_info.token_id
448 allTokensMap[address] = {address: address, source: 'method7', data: token}
449 tokenFrequency[address] = (tokenFrequency[address] || 0) + 1
450
451# Sort by frequency and data availability
452candidateTokens = Object.values(allTokensMap)
453prioritizedTokens = candidateTokens.sort((a, b) => {
454 freqDiff = tokenFrequency[b.address] - tokenFrequency[a.address]
455 if (freqDiff !== 0) return freqDiff
456 return (b.data && b.data.market_info ? 1 : 0) - (a.data && a.data.market_info ? 1 : 0)
457})
458
459Print: "📊 Combined: N unique tokens, X found in 2+ methods, Y found in all 3 methods, Z with full data"
460```
461
462**Expected result:** Prioritized array of token objects, each containing:
463- `address`: token address
464- `source`: which method(s) found it
465- `data`: full token object with token_info + market_info (if available from Methods 6 or 7)
466- `foundInMethods`: count from tokenFrequency
467
468#### Save Found Tokens - CRITICAL STEP
469
470**What to do:**
471After combining all methods and getting prioritizedTokens, you MUST save them to file `$HOME/nadfunagent/found_tokens.json` for manual review.
472
473**How to execute:**
474
4751. **Prepare token list:**
476 - Take top 50 tokens from prioritizedTokens
477 - For each token, create object: `{address: token, foundInMethods: frequency_count}`
478 - Create scan entry with timestamp, totalFound count, and tokens array
479
4802. **Read existing file:**
481 - File: `$HOME/nadfunagent/found_tokens.json`
482 - If file doesn't exist or is empty: start with `[]`
483 - If exists: parse JSON, get array
484
4853. **Append and save:**
486 - Add new scan entry to array
487 - Keep only last 100 scans (remove oldest if > 100)
488 - Write back as formatted JSON
489
490**Example using Node.js script (RECOMMENDED):**
491```bash
492# From skill root or repo root: print token addresses (one per line) and pipe to script
493# prioritizedTokens is the array of token addresses; take first 50 and pass to script
494echo -e "0x...\n0x..." | node scripts/save_tokens.js
495```
496Or from the agent: write the list of addresses to a temp file or stdin and run `node scripts/save_tokens.js` (script reads from stdin). Data dir: `NADFUNAGENT_DATA_DIR` or `$HOME/nadfunagent`.
497
498**Expected result:** File `$HOME/nadfunagent/found_tokens.json` updated with latest scan results
499
500### 2. Token Analysis - CRITICAL: Use Data from Methods 6 & 7 Directly
501
502**IMPORTANT**: Methods 6 (Market Cap API) and Method 7 (Creation Time API) already return COMPLETE token data with `market_info`. Use this data directly for analysis - DO NOT make additional API calls unless absolutely necessary!
503
504**Data Structure from Methods 6 & 7:**
505Each token in the response has this structure:
506```json
507{
508 "token_info": {
509 "token_id": "0x...",
510 "name": "...",
511 "symbol": "...",
512 "is_graduated": true/false,
513 "created_at": timestamp,
514 ...
515 },
516 "market_info": {
517 "market_type": "DEX" or "BONDING_CURVE",
518 "reserve_native": "1625513352353765005672133", // Liquidity in MON (wei format)
519 "reserve_token": "51582894169959918089536846",
520 "token_price": "0.000886889894056452",
521 "price": "0.0415501242",
522 "price_usd": "0.000886889894056452",
523 "volume": "761848094037806233587694495", // Total volume (wei format)
524 "holder_count": 31580, // Number of holders
525 "ath_price": "0.0128807779",
526 "ath_price_usd": "0.0128807779",
527 ...
528 },
529 "percent": 8.797 // Market cap change percentage
530}
531```
532
533**Analysis Steps:**
534
5351. **Extract data from Methods 6 & 7:**
536 - For each token in `data.tokens` array from Methods 6 & 7:
537 - Extract `token_info.token_id` (token address)
538 - Extract `market_info.reserve_native` (liquidity in wei, convert to MON: divide by 1e18)
539 - Extract `market_info.holder_count` (number of holders)
540 - Extract `market_info.volume` (total volume in wei, convert to MON: divide by 1e18)
541 - Extract `market_info.market_type` ("DEX" or "BONDING_CURVE")
542 - Extract `token_info.is_graduated` (true if graduated to DEX)
543 - Extract `percent` (market cap change percentage)
544
5452. **For Method 5 tokens (new-event API):**
546 - This API returns only basic event data without full market_info
547 - For tokens from Method 5, you can optionally query `/agent/market/:token_id` to get market_info
548 - BUT prioritize tokens from Methods 6 & 7 first (they already have complete data)
549
5503. **Calculate Liquidity Score (30% weight):**
551 ```javascript
552 liquidityMON = parseFloat(market_info.reserve_native) / 1e18
553
554 // Score based on liquidity tiers
555 if (liquidityMON >= 1000) liquidityScore = 100 // Excellent
556 else if (liquidityMON >= 500) liquidityScore = 80 // Very good
557 else if (liquidityMON >= 100) liquidityScore = 60 // Good
558 else if (liquidityMON >= 50) liquidityScore = 40 // Fair
559 else if (liquidityMON >= 10) liquidityScore = 20 // Low
560 else liquidityScore = 0 // Too low
561
562 weightedLiquidity = liquidityScore * 0.30
563 ```
564
5654. **Calculate Momentum Score (25% weight):**
566 ```javascript
567 // Use percent (market cap change) as momentum indicator
568 percentChange = parseFloat(token.percent) || 0
569
570 // Score based on positive momentum
571 if (percentChange >= 50) momentumScore = 100 // Strong growth
572 else if (percentChange >= 20) momentumScore = 80
573 else if (percentChange >= 10) momentumScore = 60
574 else if (percentChange >= 5) momentumScore = 40
575 else if (percentChange >= 0) momentumScore = 20
576 else momentumScore = 0 // Negative momentum
577
578 weightedMomentum = momentumScore * 0.25
579 ```
580
5815. **Calculate Volume Score (20% weight):**
582 ```javascript
583 volumeMON = parseFloat(market_info.volume) / 1e18
584
585 // Score based on volume tiers
586 if (volumeMON >= 1000000) volumeScore = 100 // 1M+ MON volume
587 else if (volumeMON >= 500000) volumeScore = 80
588 else if (volumeMON >= 100000) volumeScore = 60
589 else if (volumeMON >= 50000) volumeScore = 40
590 else if (volumeMON >= 10000) volumeScore = 20
591 else volumeScore = 0
592
593 weightedVolume = volumeScore * 0.20
594 ```
595
5966. **Calculate Holder Score (15% weight):**
597 ```javascript
598 holderCount = parseInt(market_info.holder_count) || 0
599
600 // Score based on holder count
601 if (holderCount >= 10000) holderScore = 100 // Excellent distribution
602 else if (holderCount >= 5000) holderScore = 80
603 else if (holderCount >= 1000) holderScore = 60
604 else if (holderCount >= 500) holderScore = 40
605 else if (holderCount >= 100) holderScore = 20
606 else holderScore = 0
607
608 weightedHolders = holderScore * 0.15
609 ```
610
6117. **Calculate Progress Score (10% weight):**
612 ```javascript
613 isGraduated = token_info.is_graduated === true
614 marketType = market_info.market_type
615
616 // Score based on market stage
617 if (isGraduated || marketType === "DEX") {
618 progressScore = 100 // Fully graduated to DEX
619 } else {
620 // Still on bonding curve - use percent as progress indicator
621 // Higher percent = closer to graduation
622 percent = parseFloat(token.percent) || 0
623 if (percent >= 80) progressScore = 80
624 else if (percent >= 50) progressScore = 60
625 else if (percent >= 30) progressScore = 40
626 else progressScore = 20
627 }
628
629 weightedProgress = progressScore * 0.10
630 ```
631
6328. **Calculate Authority Score (Bonus - up to +10 points):**
633 ```javascript
634 // Check for social media presence and website (indicates legitimacy)
635 hasTwitter = token_info.twitter && token_info.twitter.length > 0
636 hasTelegram = token_info.telegram && token_info.telegram.length > 0
637 hasWebsite = token_info.website && token_info.website.length > 0
638
639 authorityScore = 0
640 if (hasTwitter) authorityScore += 3
641 if (hasTelegram) authorityScore += 3
642 if (hasWebsite) authorityScore += 4
643
644 // Maximum +10 bonus points for full social presence
645 authorityBonus = Math.min(authorityScore, 10)
646 ```
647
6489. **Calculate Total Score:**
649 ```javascript
650 totalScore = weightedLiquidity + weightedMomentum + weightedVolume + weightedHolders + weightedProgress + authorityBonus
651
652 // Round to 2 decimal places
653 totalScore = Math.round(totalScore * 100) / 100
654 ```
655
6569. **Store Analysis Results:**
657 For each token, store:
658 ```javascript
659 {
660 address: token_info.token_id,
661 name: token_info.name,
662 symbol: token_info.symbol,
663 liquidity: liquidityMON,
664 holders: holderCount,
665 volume: volumeMON,
666 marketType: marketType,
667 isGraduated: isGraduated,
668 percentChange: percentChange,
669 scores: {
670 liquidity: liquidityScore,
671 momentum: momentumScore,
672 volume: volumeScore,
673 holders: holderScore,
674 progress: progressScore,
675 total: totalScore
676 },
677 foundInMethods: tokenFrequency[token_info.token_id] || 1
678 }
679 ```
680
681**CRITICAL INSTRUCTIONS:**
682- Use data from Methods 6 & 7 DIRECTLY - they already contain all needed information
683- DO NOT make additional API calls to `/agent/market/:token_id` for tokens from Methods 6 & 7
684- Only for Method 5 tokens (if needed) make additional API calls
685- Calculate scores immediately after combining methods, before filtering
686- **Check authority (social media presence)**: Check `token_info.twitter`, `token_info.telegram`, `token_info.website` - add bonus points
687- Log analysis results: Print "📊 Analysis: Token X has score Y (liquidity: A, momentum: B, volume: C, holders: D, progress: E, authority: +F)"
688
689### 3. Filtering Criteria
690
691Filter tokens based on:
692
693- **Minimum liquidity**: 5 MON
694- **Minimum holders**: 5
695- **Bonding curve progress**: >= 10%
696- **Score calculation**:
697 - Liquidity: 30% weight
698 - Momentum: 25% weight
699 - Volume trend: 20% weight
700 - Holder distribution: 15% weight
701 - Bonding curve progress: 10% weight
702
703### 4. Position Management - CRITICAL: Check Existing Positions FIRST
704
705**BEFORE analyzing new tokens, you MUST check and manage existing positions!**
706
707#### Step 1: Get Current Holdings
708
709**What to do:**
7101. Get trading wallet address from `MONAD_PRIVATE_KEY` in `.env` (derive address from private key)
7112. Query current token holdings using Agent API: `/agent/holdings/${walletAddress}?limit=100`
7123. Filter tokens where `balance > 0` (exclude zero balances)
7134. For each token with balance > 0, get current market data
714
715**How to execute:**
716```javascript
717// 1. Get wallet address from private key
718const walletAddress = getAddressFromPrivateKey(MONAD_PRIVATE_KEY)
719
720// 2. Query holdings
721const holdingsResponse = await fetch(`${API_URL}/agent/holdings/${walletAddress}?limit=100`)
722const holdings = await holdingsResponse.json()
723
724// 3. Filter tokens with balance > 0
725const activePositions = holdings.tokens.filter(token => {
726 const balance = parseFloat(token.balance_info.balance) || 0
727 return balance > 0
728})
729
730Print: "📊 Current positions: Found N tokens with balance > 0"
731```
732
733#### Step 2: Calculate P&L for Each Position
734
735**CRITICAL**: Always use the `check-pnl.js` script from `nadfun-trading` skill for proper P&L calculation. This script:
736- Reads entry price (`entryValueMON`) from `$HOME/nadfunagent/positions_report.json` (automatically recorded by `buy-token.js` when you purchase)
737- Gets current value on-chain via nad.fun quote contract (or falls back to Agent API)
738- Calculates P&L: `(currentValueMON - entryValueMON) / entryValueMON * 100`
739
740**What to do:**
7411. **Use the script**: Run `check-pnl.js` from nadfun-trading skill directory
7422. The script reads entry prices from JSON (set by `buy-token.js` after purchases)
7433. Gets current value on-chain via nad.fun quote contract
7444. Calculates real P&L based on actual entry price
745
746**How to execute:**
747```bash
748# Check P&L for all positions
749cd $HOME/.openclaw/workspace/skills/nadfun-trading
750node check-pnl.js
751
752# Or with auto-sell (sells if P&L >= +5% or <= -10%)
753node check-pnl.js --auto-sell
754```
755
756**Manual calculation (if script unavailable):**
757```javascript
758// Load entry prices from positions_report.json
759const report = JSON.parse(await fs.readFile('$HOME/nadfunagent/positions_report.json', 'utf-8'))
760
761for (const position of activePositions) {
762 const tokenAddress = position.token_info.token_id || position.token_info.address
763 const tokenBalance = parseFloat(position.balance_info.balance) || 0
764
765 // Get entry price from JSON (recorded by buy-token.js)
766 const prev = report.positions?.find(p =>
767 (p.address || '').toLowerCase() === tokenAddress.toLowerCase()
768 )
769 const entryValueMON = prev?.entryValueMON || 0
770
771 // Get current value on-chain via nad.fun quote contract
772 const [router, amountOutWei] = await publicClient.readContract({
773 address: '0x7e78A8DE94f21804F7a17F4E8BF9EC2c872187ea', // nad.fun quote contract
774 abi: lensAbi,
775 functionName: 'getAmountOut',
776 args: [tokenAddress, parseEther(tokenBalance.toString()), false] // false = selling
777 })
778 const currentValueMON = Number(amountOutWei) / 1e18
779
780 // Calculate P&L
781 const pnlPercent = entryValueMON > 0
782 ? ((currentValueMON - entryValueMON) / entryValueMON) * 100
783 : 0
784
785 positions.push({
786 address: tokenAddress,
787 balance: tokenBalance,
788 entryValueMON: entryValueMON,
789 currentValueMON: currentValueMON,
790 pnlPercent: pnlPercent
791 })
792}
793
794Print: "💰 Position P&L calculated for N positions (source: on-chain nad.fun quote + positions_report.json)"
795```
796
797**Entry Price Tracking:**
798- Entry price is automatically recorded by `buy-token.js` after successful purchase
799- Stored in `$HOME/nadfunagent/positions_report.json` as `entryValueMON`
800- If entry price not found, `check-pnl.js` uses current value as fallback (P&L = 0%)
801
802#### Step 3: Make Sell Decisions
803
804**What to do:**
805For each position, check sell conditions:
806
8071. **Stop-Loss Check:**
808 ```javascript
809 if (pnlPercent <= -10) { // STOP_LOSS_PERCENT = -10%
810 // SELL ALL - stop loss triggered
811 sellDecision = {
812 action: 'SELL_ALL',
813 reason: 'Stop-loss triggered',
814 tokenAddress: position.address,
815 amount: 'all'
816 }
817 }
818 ```
819
8202. **Take-Profit Check:**
821 ```javascript
822 if (pnlPercent >= 20) { // PROFIT_TARGET_PERCENT = 20%
823 // SELL HALF - take profit
824 sellDecision = {
825 action: 'SELL_HALF',
826 reason: 'Take-profit triggered',
827 tokenAddress: position.address,
828 amount: position.balance / 2
829 }
830 }
831 ```
832
8333. **Trailing Stop (Optional):**
834 ```javascript
835 // If profit was > 15% but dropped to < 5%, sell to protect gains
836 if (previousPnL > 15 && pnlPercent < 5) {
837 sellDecision = {
838 action: 'SELL_ALL',
839 reason: 'Trailing stop - protecting gains',
840 tokenAddress: position.address,
841 amount: 'all'
842 }
843 }
844 ```
845
846**How to execute:**
847```javascript
848const sellDecisions = []
849
850for (const position of positions) {
851 // Stop-loss: sell all if down 10%+
852 if (position.pnlPercent <= -10) {
853 sellDecisions.push({
854 tokenAddress: position.address,
855 action: 'SELL_ALL',
856 reason: `Stop-loss: ${position.pnlPercent.toFixed(2)}%`,
857 amount: 'all'
858 })
859 }
860 // Take-profit: sell half if up 20%+
861 else if (position.pnlPercent >= 20) {
862 sellDecisions.push({
863 tokenAddress: position.address,
864 action: 'SELL_HALF',
865 reason: `Take-profit: ${position.pnlPercent.toFixed(2)}%`,
866 amount: position.balance / 2
867 })
868 }
869}
870
871Print: "🔔 Sell decisions: N positions need action"
872for (const decision of sellDecisions) {
873 Print: ` ${decision.action}: ${decision.tokenAddress} - ${decision.reason}`
874}
875```
876
877#### Step 4: Execute Sell Orders
878
879**What to do:**
880For each sell decision:
8811. Use `nadfun-trading` skill with action `sell`
8822. Parameters: token address, amount (from decision)
8833. The skill handles: balance check, quote, approve, execution
884
885**How to execute:**
886```javascript
887for (const decision of sellDecisions) {
888 try {
889 // Use nadfun-trading skill
890 await useSkill('nadfun-trading', {
891 action: 'sell',
892 token: decision.tokenAddress,
893 amount: decision.amount // 'all' or specific amount
894 })
895
896 Print: `✅ Sold ${decision.amount} of ${decision.tokenAddress}: ${decision.reason}`
897 } catch (error) {
898 Print: `❌ Failed to sell ${decision.tokenAddress}: ${error.message}`
899 }
900}
901```
902
903### 5. Trading Execution - Buy New Tokens
904
905**CRITICAL**: Only buy new tokens AFTER managing existing positions!
906
907**Buy Decision Logic:**
908
9091. **Prioritize tokens with authority (social media presence):**
910 - Tokens with Twitter + Telegram + Website get priority
911 - These are more legitimate and have better community support
912
9132. **Consider both early-stage AND established tokens:**
914 - Early-stage (5-50 MON liquidity): Higher risk, higher potential
915 - Established (50k+ MON liquidity): Lower risk, steady growth
916 - Both can be profitable if they meet score criteria
917
9183. **Buy Criteria:**
919 - Score >= 60 (or >= 55 if has social media)
920 - Liquidity >= 5 MON
921 - Holders >= 5
922 - NOT already in portfolio (check existing positions first)
923
9244. **Position Sizing:**
925 - For tokens with authority (social media): up to 0.15 MON
926 - For tokens without authority: up to 0.1 MON
927 - Maximum total position per token: 0.15 MON
928
929**CRITICAL**: Always use the `buy-token.js` script from `nadfun-trading` skill. This script:
930- Automatically detects bonding curve vs DEX via nad.fun quote contract
931- Handles DEX: wraps MON→WMON, approves, swaps
932- **Automatically records entry price** in `$HOME/nadfunagent/positions_report.json` after successful purchase
933- Works on bonding curve (MON) or DEX (MON) - all trading uses MON
934
935**Buy tokens:**
936```bash
937cd $HOME/.openclaw/workspace/skills/nadfun-trading
938NAD_PRIVATE_KEY=$MONAD_PRIVATE_KEY node buy-token.js <token-address> <MON-amount> [--slippage=300]
939```
940
941**Example:**
942```bash
943NAD_PRIVATE_KEY=0x... node buy-token.js 0x123...abc 0.15 --slippage=300
944```
945
946**After purchase:**
947- Entry price (`entryValueMON`) is automatically recorded in `$HOME/nadfunagent/positions_report.json`
948- This entry price is used by `check-pnl.js` for P&L calculation
949- No manual tracking needed - everything is automated
950
951**Risk management:**
952- **CRITICAL**: Buy tokens on BOTH bonding curve AND DEX (don't filter by market_type)
953- The `nadfun-trading` skill automatically detects market type and uses correct contract
954- For all trades, use MON balance (no wrapping needed - all trading uses MON)
955- Set slippage tolerance: 2-3% (increased for better execution, especially on DEX)
956- Set deadline: 5 minutes from now
957- Don't exceed MAX_POSITION_SIZE per token
958
959### 6. Profit Distribution
960
961**CRITICAL**: Use `MMIND_TOKEN_ADDRESS` from `$HOME/nadfunagent/.env` file.
962
963When profit >= 0.1 MON:
964
965```typescript
966// Step 1: Load MMIND_TOKEN_ADDRESS from .env file
967const envFile = await readFile('$HOME/nadfunagent/.env', 'utf-8')
968const mmindMatch = envFile.match(/MMIND_TOKEN_ADDRESS=(0x[a-fA-F0-9]+)/)
969if (!mmindMatch) {
970 throw new Error('MMIND_TOKEN_ADDRESS not found in .env file')
971}
972const MMIND_TOKEN_ADDRESS = mmindMatch[1]
973
974// Step 2: Get MMIND token holders via Indexer
975// Query Transfer events to find all addresses that ever held MMIND
976const latestBlock = await publicClient.getBlockNumber()
977const safeLatest = latestBlock - 10n
978
979// Query in chunks (RPC limit: ~100 blocks)
980const transfers = []
981for (let from = 0n; from < safeLatest; from += 10000n) {
982 const to = from + 10000n > safeLatest ? safeLatest : from + 10000n
983 try {
984 const events = await useSkill('nadfun-indexer', {
985 event: 'Transfer',
986 token: MMIND_TOKEN_ADDRESS,
987 fromBlock: from,
988 toBlock: to
989 })
990 transfers.push(...events)
991 } catch (err) {
992 // Continue if chunk fails
993 }
994}
995
996// Step 3: Collect unique addresses
997const holderAddresses = new Set()
998transfers.forEach(event => {
999 if ('args' in event) {
1000 if (event.args.from && event.args.from !== '0x0000000000000000000000000000000000000000') {
1001 holderAddresses.add(event.args.from)
1002 }
1003 if (event.args.to && event.args.to !== '0x0000000000000000000000000000000000000000') {
1004 holderAddresses.add(event.args.to)
1005 }
1006 }
1007})
1008
1009// Step 4: Get current balances for each holder
1010const distributions = []
1011for (const address of holderAddresses) {
1012 try {
1013 const balance = await publicClient.readContract({
1014 address: MMIND_TOKEN_ADDRESS,
1015 abi: erc20Abi,
1016 functionName: 'balanceOf',
1017 args: [address]
1018 })
1019
1020 if (balance > 0n) {
1021 distributions.push({ address, balance })
1022 }
1023 } catch (err) {
1024 // Skip if balance check fails
1025 }
1026}
1027
1028// Step 5: Get total supply
1029const totalSupply = await publicClient.readContract({
1030 address: MMIND_TOKEN_ADDRESS,
1031 abi: erc20Abi,
1032 functionName: 'totalSupply'
1033})
1034
1035// Step 6: Calculate and distribute profit proportionally
1036const profitToDistribute = (profit * BigInt(PNL_DISTRIBUTION_PERCENT)) / 100n
1037
1038for (const holder of distributions) {
1039 const share = (profitToDistribute * holder.balance) / totalSupply
1040 if (share >= parseEther('0.001')) { // Minimum 0.001 MON
1041 await transferMON(holder.address, share) // Transfer MON directly (all trading uses MON)
1042 }
1043}
1044```
1045
1046## Autonomous Trading Loop
1047
1048The agent runs continuously:
1049
10501. **Position Management FIRST** (CRITICAL - do this before scanning)
1051 - Get wallet address from `MONAD_PRIVATE_KEY`
1052 - Query current holdings: `/agent/holdings/${walletAddress}?limit=100`
1053 - Filter tokens with balance > 0
1054 - For each position: use `check-pnl.js` to get real P&L (reads entry price from `$HOME/nadfunagent/positions_report.json`, gets current value on-chain via nad.fun quote contract)
1055 - Execute sell orders: use `sell-token.js` or `check-pnl.js --auto-sell` for stop-loss (P&L <= -10%) or take-profit (P&L >= +5%)
1056 - Log: "📊 Positions: N checked, X sold; entry prices tracked in positions_report.json"
1057
10582. **Scan market** (after managing positions, every 10 minutes to avoid rate limits)
1059 - Method 5: Fetch new events API (`/api/token/new-event`) for real-time BUY/CREATE events
1060 - Method 6: Fetch top tokens by market cap (`api.nadapp.net/order/market_cap`, base64 decoded)
1061 - Method 7: Fetch newest tokens (`api.nadapp.net/order/creation_time`, base64 decoded)
1062 - Combine all methods and prioritize tokens found in multiple sources
1063 - Add 2-3 second delays between API calls to respect rate limits (CRITICAL to avoid HTTP 429)
1064
10652. **Analyze opportunities**
1066 - Use data DIRECTLY from Methods 6 & 7 (already contains complete market_info)
1067 - Calculate scores using market_info: liquidity (30%), momentum (25%), volume (20%), holders (15%), progress (10%)
1068 - Convert wei values to MON: reserve_native / 1e18, volume / 1e18
1069 - Filter by criteria (min liquidity 5 MON, min holders 5, min score 60)
1070 - Sort by score DESC, then by methods count, then by liquidity
1071 - Take top 20 candidates
1072 - Generate buy/sell signals
1073
10743. **Execute trades**
1075 - Buy on bonding curve (MON) or DEX (MON) - all trading uses MON
1076 - Monitor positions
1077 - Stop-loss and take-profit
1078
10794. **Distribute profits**
1080 - Calculate total profit
1081 - Get MMIND holders via Indexer (Transfer events)
1082 - Distribute proportionally (30% of profit) in MON
1083
1084## Risk Management
1085
1086- **Position sizing**: Based on confidence score (max 0.1 MON)
1087- **Stop-loss**: -10% (automatic sell)
1088- **Take-profit**: +20% (sell half position)
1089- **Slippage protection**: 1-2% tolerance
1090- **Minimum liquidity**: 5 MON required
1091
1092## Usage Examples
1093
1094**Start autonomous trading:**
1095
1096```bash
1097# Via OpenClaw chat
1098"Start autonomous trading agent"
1099
1100# Or via cron job (runs every minute). Paths: use NADFUN_ENV_PATH / NADFUNAGENT_DATA_DIR for .env and data; run scripts from nadfun-trading skill directory (clawhub install).
1101openclaw cron add \
1102 --name "Nad.fun Trading Agent" \
1103 --cron "* * * * *" \
1104 --session isolated \
1105 --message "Run autonomous trading cycle: 1) Load config from .env (path: NADFUN_ENV_PATH or NADFUNAGENT_DATA_DIR/.env; need MMIND_TOKEN_ADDRESS, MONAD_PRIVATE_KEY, MONAD_RPC_URL, MONAD_NETWORK). 2) From nadfun-trading skill directory run: node execute-bonding-v2.js (uses check-pnl.js for P&L from positions_report.json at POSITIONS_REPORT_PATH or NADFUNAGENT_DATA_DIR, auto-sells at +5% or -10%). 3) If there is positive PnL (profit >= 0.1 MON), distribute profits to MMIND token holders: use MMIND_TOKEN_ADDRESS from .env, get holders via indexer/Transfer events, distribute proportionally (e.g. 30%) in MON. Report output in English."
1106```
1107
1108**Check agent status:**
1109
1110```bash
1111# Via OpenClaw chat
1112"Show trading agent status and statistics"
1113```
1114
1115**View found tokens:** (data dir: `NADFUNAGENT_DATA_DIR`, default `$HOME/nadfunagent`)
1116
1117```bash
1118# View latest found tokens
1119cat "${NADFUNAGENT_DATA_DIR:-$HOME/nadfunagent}/found_tokens.json" | jq '.[-1]'
1120
1121# View all tokens from last scan
1122cat "${NADFUNAGENT_DATA_DIR:-$HOME/nadfunagent}/found_tokens.json" | jq '.[-1].tokens[] | .address'
1123
1124# View tokens found in multiple methods (higher confidence)
1125cat "${NADFUNAGENT_DATA_DIR:-$HOME/nadfunagent}/found_tokens.json" | jq '.[-1].tokens[] | select(.foundInMethods > 1) | .address'
1126
1127# View summary of last 10 scans
1128cat "${NADFUNAGENT_DATA_DIR:-$HOME/nadfunagent}/found_tokens.json" | jq '.[-10:] | .[] | {timestamp, totalFound}'
1129```
1130
1131**Manual trade:**
1132
1133```bash
1134# Via OpenClaw chat
1135"Buy 0.1 MON worth of token 0x..."
1136"Sell all tokens for 0x..."
1137```
1138
1139## Integration with OpenClaw
1140
1141This skill integrates with:
1142
1143- **Cron Jobs**: Schedule autonomous trading cycles
1144- **Skills**: Uses nadfun-trading, nadfun-indexer, nadfun-agent-api
1145- **Gateway**: Runs via OpenClaw Gateway
1146- **Channels**: Can send notifications via Telegram/WhatsApp/etc.
1147
1148## Error Handling
1149
1150- All errors are logged but don't stop the agent
1151- Failed trades are retried with exponential backoff
1152- API failures fall back to Indexer queries
1153- Network errors trigger fallback RPC providers
1154
1155## Rate Limit Handling
1156
1157**CRITICAL**: Handle rate limits gracefully to avoid HTTP 429 errors.
1158
1159### API Rate Limits
1160
1161**Nad.fun Agent API:**
1162- Without API Key: 10 requests/minute (IP-based)
1163- With API Key: 100 requests/minute (Key-based)
1164- **Solution**: Add delays between requests (min 2 seconds between calls)
1165
1166**Nad.fun Public APIs (`nad.fun/api/*` and `api.nadapp.net/*`):**
1167- Rate limits are not publicly documented but appear to be IP-based
1168- **Solution**: Add 2-3 second delays between calls, especially for base64-decoded endpoints
1169- Handle HTTP 429 errors gracefully with exponential backoff
1170
1171**Anthropic/Claude API (CRITICAL - This is the main source of HTTP 429):**
1172- Rate limits vary by tier (typically 50-200 requests per minute)
1173- **Problem**: Each agent execution makes multiple requests to Claude
1174- **Solution**:
1175 - Cron job runs every 10 minutes (`*/10 * * * *`) to reduce frequency
1176 - Optimize agent logic to minimize token usage
1177 - Batch operations when possible
1178 - If still hitting limits, increase to 15 minutes (`*/15 * * * *`)
1179
1180### Rate Limit Strategy
1181
11821. **Add delays between API calls (CRITICAL):**
1183 ```typescript
1184 // Wait 2-3 seconds between Nad.fun API calls
1185 await new Promise(resolve => setTimeout(resolve, 2000))
1186
1187 // Wait 1 second between Indexer queries
1188 await new Promise(resolve => setTimeout(resolve, 1000))
1189 ```
1190
11912. **Limit parallel requests:**
1192 - Process tokens sequentially or in small batches (max 5 at a time)
1193 - Add delays between batches
1194 - Don't make all 7 methods run simultaneously - stagger them
1195
11963. **Handle 429 errors gracefully:**
1197 ```typescript
1198 async function fetchWithRetry(url, options, maxRetries = 2) {
1199 for (let i = 0; i < maxRetries; i++) {
1200 try {
1201 const result = await fetch(url, options)
1202 if (result.status === 429) {
1203 const retryAfter = parseInt(result.headers.get('Retry-After') || '60')
1204 console.log(`Rate limited, waiting ${retryAfter} seconds...`)
1205 await new Promise(resolve => setTimeout(resolve, retryAfter * 1000))
1206 continue
1207 }
1208 return result
1209 } catch (err) {
1210 if (i === maxRetries - 1) throw err
1211 await new Promise(resolve => setTimeout(resolve, 5000 * (i + 1)))
1212 }
1213 }
1214 }
1215 ```
1216
12174. **Optimize agent execution:**
1218 - Use Indexer methods (1-2) first (they're faster and don't hit API limits)
1219 - Only use API methods (3-7) if Indexer doesn't find enough tokens
1220 - Analyze ALL tokens that pass filters (no limit)
1221 - Skip detailed analysis if token doesn't meet basic filters
1222
12235. **Cron frequency:**
1224 - Current: every 10 minutes (`*/10 * * * *`)
1225 - If still hitting Claude API limits, increase to 15 minutes (`*/15 * * * *`)