- Add searchStock() using Sina's suggest API (type=11,31,41)
- Supports A-share, HK, and US markets dynamically
- No longer limited to hardcoded knownStocks map
- resolveStockCodeDynamic: tries static map first, then API fallback
- extractStockKeyword: smart keyword extraction from natural language
- New LLM tool 'search_stock': agent can proactively search stocks
- Top 3 search results auto-enriched with real-time quotes
- System prompts updated for both zh/en
- Add NOFXiAgent interface and SetNOFXiAgent() in telegram/bot.go
- Telegram messages now route through the unified agent.Agent
instead of the legacy telegram/agent package
- Language hint injected from Telegram config for proper i18n
- Legacy telegram/agent path preserved as fallback
- Agent created before Telegram bot starts in main.go
- Build verified, API tested
- Add chatHistory store (in-memory, per user, last 20 messages)
- Agent now passes full conversation context to LLM via CallWithRequest
- Records both user messages and assistant responses
- Add /clear command to reset conversation history
- Add 'Clear' quick action button in frontend
- Supports natural multi-turn conversations (follow-up questions, context)
- Rewrite AgentChatPage as primary interface with Perplexity-style layout
- Add right sidebar with Market Ticker, Positions, and Trader Status panels
- Sidebar is collapsible and responsive (auto-hides on mobile)
- Each sidebar section independently collapsible
- Chat area: centered 720px max-width with smooth streaming effect
- Simple markdown rendering (bold, code blocks, inline code)
- Quick action chips redesigned as pill buttons with hover effects
- Input upgraded to auto-resizing textarea
- New components: MarketTicker, PositionsPanel, TraderStatusPanel
- Dark theme consistent with NOFXi brand colors
- Real-time data via SWR for positions and trader status
NOFXi can now fetch REAL stock prices for A-shares.
Data source: Sina Finance hq.sinajs.cn (free, no API key)
- Name, price, open, prev close, high, low, volume, turnover
- Change % calculated from prev close
- GBK → UTF-8 encoding handled
Stock resolution:
- Known stocks: 拓维信息→sz002261, 贵州茅台→sh600519, etc.
- Auto-detect 6-digit codes in user text
- Prefix detection: 6xx→sh, 0xx/3xx→sz
Context injection:
- Stock data auto-appended to LLM context when user mentions a stock
- AI sees REAL price, volume, change % — cannot fabricate
Tested: '拓维信息这只股,10万元,1个月交易计划'
→ Returns ¥35.57 (real price), -6.71% (real change), 53.94亿成交额
→ Strategy based on actual price levels, not hallucinated
System prompt now explicitly:
- Lists which assets have real-time data (crypto) and which don't (stocks/forex)
- FORBIDS fabricating specific prices
- Requires disclosure: 'based on historical knowledge, not live data'
- Allows strategy frameworks but not fake price levels
Tested: 拓维信息 → now says '我没有A股实时数据' upfront, gives
strategy framework without fake prices. Honesty > confidence.
SSRF protection was blocking AI API calls because Go's custom resolver
couldn't resolve external domains (DNS timeout). curl worked because it
uses the system resolver.
Fix: Agent creates MCP client with standard http.Client (no SSRF filter)
since we control the API URLs.
Tested: '帮我看看拓维信息这只股,我有10万元,帮我制定1个月交易计划'
→ Returns professional A-share analysis with entry/exit strategy in 5.8s
DELETED: agent/router.go (regex-based intent routing)
The fundamental architecture was wrong. A real AI Agent doesn't use
pattern matching to understand users. It uses AI.
New flow:
1. User says anything
2. /help and /status → instant response (no AI needed)
3. Setup keywords → onboard flow
4. EVERYTHING else → LLM with full context
The LLM receives:
- System prompt with NOFXi's capabilities and behavior rules
- Real-time market data (auto-detected from mentioned symbols)
- Live trader positions and status
- User's message
The LLM decides what to do. Not regex. Not if-else. The AI.
This is what makes it an Agent, not a chatbot.
1. Complex natural language → AI chat (not regex analyze)
'拓维信息这个股怎么样帮我写策略' now goes to AI, not broken regex
2. Agent auto-loads AI client from store on startup
- Scans AIModel configs, creates MCP client from first available
- No manual injection needed
3. Added start.sh for one-command startup (backend + frontend)
Routing logic:
- /analyze BTC (simple, ≤3 words) → structured analyze
- Complex sentences → AI chat with full context
- This is the key insight: regex can't parse natural language, AI can
- Crypto: real-time data (market.Get) + AI analysis
- Stocks/Forex: AI answers with its own knowledge (A股/港股/美股/外汇)
- No more 'coming soon' — if AI is configured, it can analyze anything
- Graceful fallback: no AI → guide user to configure
- AI prompt asks for: asset type, fundamentals, trend, key levels, risks
Core behavior change:
- Agent NO LONGER auto-prompts setup on first message
- Setup only triggers on explicit: '开始配置' / 'setup' / '绑定交易所'
- Normal questions answered normally, even without trader configured
- AI analysis works without AI model (shows raw data + guidance)
- Stock analysis shows 'coming soon' instead of error
Intent routing improved:
- '你能分析拓维信息吗' → correctly routes to analyze
- Chinese suffixes cleaned (吗/呢/这只股票)
- More natural language patterns matched
Philosophy: Agent should be helpful from minute one.
Configuration is optional, not a gate.
- Detects when user sends Chinese text, short text, or text with spaces
during key-input steps → auto-pauses setup and answers the question
- API key masking fixed (no more garbled display)
- User can resume setup with '开始配置' anytime
Key changes:
- Agent API routes (/api/agent/*) registered directly on NOFX's :8080 server
- No more separate :8900 port — everything on :8080
- AgentChatPage.tsx added to React frontend
- Agent tab (🤖 Agent) added to navigation bar, set as DEFAULT page
- Branding: NOFX → NOFXi everywhere (title, header, branding.ts, i18n)
- Default landing page is now Agent chat, not competition
This is THE change: there is no more 'NOFX' vs 'NOFXi'.
Users open localhost:8080, they see NOFXi.
Agent chat is the first thing they see.
All other pages (Traders, Dashboard, Strategy, Data) are still there.
One binary. One port. One product. NOFXi.
Users no longer need Web UI to configure NOFXi. The agent guides them
through setup via natural language:
1. First message → agent detects no traders → shows welcome
2. User says '开始配置' or 'setup'
3. Agent asks: which exchange? (1-7, name, or Chinese name)
4. Agent asks: API Key → API Secret → Passphrase (if needed)
5. Agent asks: which AI model? (DeepSeek/Qwen/GPT/Claude/Skip)
6. Agent asks: AI API Key
7. Agent creates Exchange + AIModel + Trader in NOFX store
8. Done. User can immediately start using /analyze, /positions, etc.
Features:
- Full Chinese/English bilingual flow
- Cancel anytime with '取消' or 'cancel'
- State persisted in SystemConfig (survives restarts)
- Supports all 7 exchanges + 4 AI providers
- OKX/Bitget/KuCoin auto-asks for Passphrase
- API keys stored encrypted via NOFX crypto service
Critical fixes:
1. Agent now uses NOFX's MCP client for AI calls (real models, not placeholder)
- Gets AI client from first configured trader's MCP config
- Added AutoTrader.GetMCPClient() export
2. /analyze uses REAL market data (market.Get → EMA/MACD/RSI/BB/OI/funding)
then sends to AI — no more hallucinated prices
3. AI chat enriches prompts with live market data when user mentions a coin
4. Fallback: if AI unavailable, shows raw formatted market data (still useful)
Router improvements:
- Better natural language detection for Chinese
- '该不该买' '走势' '趋势' '行情' → analyze intent
- '多少钱' '赚了' '亏了' → query intent
- Fewer messages falling through to generic chat
Web UI:
- Endpoints updated to /api/agent/* namespace
- nofxi.html served at agent root (localhost:8900)
Result: AI analysis now shows real BTC price, real RSI, real EMA — not fiction.
This is the key architectural change: NOFXi is no longer a separate
sub-project in nofxi/, but a first-class module in agent/ that sits
on top of NOFX's existing engine.
agent/ package:
- agent.go: Core orchestrator, directly uses NOFX's TraderManager,
Store, and Market packages. No wrapper/bridge needed.
- brain.go: Proactive intelligence (news scan, market briefs, signal handling)
- sentinel.go: Market anomaly detection (price breakout, volume spike, funding rate)
- scheduler.go: Daily reports, position risk checks
- router.go: Intent routing for natural language (中/英 bilingual)
- i18n.go: Full Chinese/English message catalog
- web.go: Agent REST API on :8900 (chat, klines, ticker)
main.go changes:
- Banner: NOFX → NOFXi
- Agent auto-starts with NOFX (sentinel + brain + scheduler + web)
- Zero breaking changes to existing NOFX functionality
Key difference from old nofxi/:
- Agent reads LIVE data from TraderManager (positions, balances, status)
- Uses market.Get() for full technical indicators (EMA/MACD/RSI/BB)
- No duplicate code — kernel, trader, store all used directly
- Old nofxi/ sub-project will be removed once migration is verified
Architecture:
NOFX (engine) → kernel + trader + market + store + mcp + telegram
NOFXi (brain) → agent/ package → uses all of the above
Full audit of NOFX's capabilities vs NOFXi's current integration status.
Priority roadmap: P0 (kernel+trader+market+mcp) → P1 (store+risk) → P2 (grid+web)
Agent i18n:
- All command responses bilingual (help, status, positions, balance, trades, analysis, settings, errors)
- Language auto-detected from web UI lang toggle
- Stored per-user in SQLite preferences
- AI chat system prompt switches to Chinese/English based on user lang
- Trade confirmation prompts bilingual
Web UI:
- Sends lang parameter with every API request
- Agent extracts [lang:xx] prefix and persists preference
i18n message catalog: nofxi/internal/agent/i18n.go
- Track consecutive AI failures
- After 3 failures: activate safe mode (no new positions, close/hold only)
- Auto-deactivate when AI recovers
- Keep loop running in safe mode (retry each cycle)
- Log clearly: 🛡️ SAFE MODE ACTIVATED/DEACTIVATED
sonner's toast.promise() returns a toast ID (not a Promise), so
await resolves immediately and subsequent data refresh fetches stale
data. Users had to manually reload to see changes.
Fixed across AITradersPage, SettingsPage, and TraderConfigModal.
* feat: add X-Client-ID header for claw402 monitoring
* feat(mcp): add context length guard to prevent oversized requests
- Add MaxContext field to Config (default 0 = no limit)
- Add WithMaxContext() option for setting model context limits
- Add context_guard.go: token estimation + message truncation
- Integrate guard into both BuildMCPRequestBody and BuildRequestBodyFromRequest
- Support both map[string]string and map[string]any message formats
- Truncates oldest non-system messages when estimated tokens exceed limit
- Always preserves system messages and keeps at least 1 non-system message
- Logs warning when truncation occurs for debugging
Usage: mcp.NewDeepSeekClient(mcp.WithMaxContext(131072))
- Extract ParseSSEStream as shared function from CallWithRequestStream
- Add DoX402RequestStream and X402CallStream for streaming x402 payments
- Switch Claw402Client.Call to use streaming (X402CallStream)
- TeeReader fallback: SSE parsing with JSON fallback for non-SSE responses
- Idle timeout watchdog (90s) protects against stalled streams
CoinSourceEditor constructs keys as `${value}Desc` where value='oi_top',
expecting 'oi_topDesc' but the translation key was 'oiTopDesc' (camelCase).
This caused ts(undefined, lang) → "Cannot read properties of undefined".
- Add missing configResponse.ok check in handleCreateStrategy to prevent
rendering with invalid config data when API fails
- Remove deleted benefit3 translation key reference from LoginRequiredOverlay
The outer retry loop in client.go re-initiates the entire x402 payment
flow on each attempt, causing duplicate USDC charges. The inner x402
retry loop (5 attempts with re-signing) already handles all retryable
scenarios. Set MaxRetries=1 for Claw402, BlockRunBase, and BlockRunSol
to ensure only one payment per AI decision.
AI inference (especially DeepSeek) often exceeds the default 120s HTTP
timeout, causing the client to disconnect while the server completes
successfully — resulting in repeated payments on each retry.
Changes:
- Set X402Timeout = 5min for all x402 providers (Claw402, BlockRunBase, BlockRunSol)
- Handle 402 during payment retry by re-extracting Payment-Required
header and re-signing instead of failing immediately
- Increase payment retry attempts from 3 to 5 for unstable gateways