Commit Graph

20 Commits

Author SHA1 Message Date
shinchan-zhai
d6dafd830e fix: SSE streaming for no-tool path, batch ticker API, security & cleanup
- Fix thinkAndActStream: emit delta event for non-tool responses (was silent)
- Add fallback to streaming on first LLM call failure
- Add batch ticker endpoint /api/agent/tickers (3 API calls → 1)
- Update MarketTicker to use batch endpoint, remove unused state
- Warn loudly when JWT_SECRET uses default value
- Fix 华为 mapping (was incorrectly mapped to Tencent)
- Replace ioutil.ReadAll with safe.ReadAllLimited in nofxos client
- Remove unused variable in hyperliquid trader_account
- Wrap CoinAnk WS readers with safe.GoNamed for panic recovery
- Use 100dvh for mobile viewport in AgentChatPage
- console.log → console.warn for auth events
2026-03-25 01:05:54 +08:00
shinchan-zhai
9bb1ab8da3 feat: real SSE streaming for agent chat + data cleanup on startup
SSE Streaming:
- Add POST /api/agent/chat/stream endpoint with real SSE streaming
- Agent.HandleMessageStream() streams final LLM response via onEvent callback
- Tool-calling rounds use non-streaming; tool status sent as 'tool' events
- Frontend uses ReadableStream API instead of fake word-by-word setTimeout
- SSE events: tool (tool execution), delta (text chunk), done (complete), error

Data Maintenance:
- Add cleanupOldData() on server startup (decisions >90d, equity >180d)
- Add CleanOldRecords to DecisionStore and EquityStore
- Add store-level logger for cleanup operations

Exchange Traders:
- Add GetAccountInfo() to Bitget, Bybit, Indodax, KuCoin, Lighter, OKX traders
- Remove unused imports in Aster/Lighter traders
2026-03-25 01:05:54 +08:00
shinchan-zhai
8a7ac8719a feat: dynamic crypto detection, trade history tool, fix 9 ticker leaks
- Agent gatherContext: expand from 10 hardcoded symbols to 38+ known symbols
  plus dynamic XXXUSDT pattern extraction (caps at 5 to avoid slow context)
- Add get_trade_history tool: LLM can now query closed trades with PnL summary
  (win rate, total PnL, recent N trades across all traders)
- Fix ticker.Stop() leak in ALL 9 exchange order_sync goroutines:
  OKX, Hyperliquid, Aster, Bybit, KuCoin, Gate, Bitget, Lighter, Binance
  — tickers were never stopped when traders were stopped, leaking goroutines
2026-03-25 01:05:54 +08:00
shinchan-zhai
ed9230d38b fix: toFloat handles json.Number, CORS credentials+wildcard bug, strategy config error handling
- agent/agent.go: toFloat() now handles json.Number and int32 types to prevent silent data loss
- api/server.go: CORS fix — echo specific origin instead of '*' when credentials are enabled (browsers reject Allow-Credentials with wildcard)
- api/strategy.go: all 4 json.Unmarshal calls now check errors and return 'config_error' field instead of silently serving zero-value configs
- store/decision.go: explicitly mark best-effort unmarshal with _ = assignment for clarity
2026-03-25 01:05:54 +08:00
shinchan-zhai
0f67747b0c fix: enforce tool-based data only — Agent can no longer fabricate prices
- System prompt now has absolute rule: no tool result = no price
- Pre-market overview must call search_stock for each major stock
- Index futures explicitly marked as unsupported
- Training data prices explicitly declared outdated and forbidden
- Applied to both CN and EN prompts
2026-03-25 01:05:54 +08:00
shinchan-zhai
b1500f9e9a fix: prevent Agent from fabricating position/balance data
- Add strict data truthfulness rules to system prompt (CN + EN)
- Positions MUST come from get_positions tool only
- Balance MUST come from get_balance tool only
- Looking up a stock price != user owns it
- Fix unused variable warnings in hyperliquid trader
2026-03-25 01:05:54 +08:00
shinchan-zhai
e2de4e8d0b feat: US stock pre-market/after-hours data support
- Parse extended hours fields from Sina Finance API (field 21-24)
- Display pre-market/after-hours price, change%, and time in stock quotes
- Update system prompt: stocks have real-time data via search_stock tool
- Remove incorrect 'no real-time stock data' disclaimer
2026-03-25 01:05:54 +08:00
shinchan-zhai
5676ba2e5c feat: dynamic stock search via Sina suggest API
- 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
2026-03-25 01:05:54 +08:00
shinchan-zhai
0fa8c48b84 feat(agent): LLM tool-calling for auto trade execution
- New agent/tools.go: defines LLM tools (execute_trade, get_positions,
  get_balance, get_market_price)
- thinkAndAct now uses CallWithRequestFull with tool-calling loop
  (max 5 rounds) — LLM autonomously decides when to call tools
- Trade safety: execute_trade creates pending orders requiring user
  confirmation ('确认 trade_xxx' / 'confirm trade_xxx')
- Pending trades expire after 5 minutes
- System prompt updated with tool usage instructions and safety rules
- Both paths work: regex shortcut ('做多 BTC 0.01') and natural
  language ('帮我开一个BTC多单') via LLM tool calling
- Fallback: if tool-calling fails, degrades to plain LLM call
2026-03-25 01:05:54 +08:00
shinchan-zhai
c55800ab68 feat: add multi-turn conversation memory to Agent
- 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)
2026-03-25 01:05:54 +08:00
shinchan-zhai
53db1c72ac feat: real-time A-share stock data via Sina Finance API
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
2026-03-25 01:05:54 +08:00
shinchan-zhai
3ad71b025d fix: AI no longer fabricates prices for assets without real-time data
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.
2026-03-25 01:05:54 +08:00
shinchan-zhai
ebd8a9c8f5 fix: bypass SSRF DNS resolver for AI API calls
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
2026-03-25 01:05:54 +08:00
shinchan-zhai
75f271ad65 refactor: delete router.go — LLM is the brain, not regex
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.
2026-03-25 01:05:54 +08:00
shinchan-zhai
d69dad5c1a fix: smart routing + auto AI client from store
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
2026-03-25 01:05:54 +08:00
shinchan-zhai
58ea77be6b feat: AI-powered analysis for ANY asset (stocks, forex, crypto)
- 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
2026-03-25 01:05:54 +08:00
shinchan-zhai
6ab410e50b fix: Agent answers questions first, setup only when asked
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.
2026-03-25 01:05:54 +08:00
shinchan-zhai
0f086e5ebc feat: conversational onboarding — setup exchange & AI via chat
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
2026-03-25 01:05:54 +08:00
shinchan-zhai
fb456a3537 fix: NOFXi Agent real AI integration + quality improvements
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.
2026-03-25 01:05:54 +08:00
shinchan-zhai
f095b6655b feat: NOFXi Agent integrated into NOFX core
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
2026-03-25 01:05:54 +08:00