- trader/alpaca/: Full Trader interface implementation for Alpaca
- Paper/Live trading support (market orders, stop/limit)
- GetBalance, GetPositions, GetMarketPrice via Alpaca API
- Fractional share support (4 decimal places)
- Commission-free trading
- Agent trade routing: stock symbols (AAPL, TSLA) → Alpaca
- isStockSymbol() heuristic to distinguish crypto vs stock
- execute_trade tool updated for stock buy/sell semantics
- get_market_price works for both crypto and stocks
- TraderManager + API: Alpaca registered as exchange type
- Factory case in auto_trader.go
- Config mapping in trader_manager.go
- Temp trader creation in handler_trader.go for balance query
- Frontend: PositionsPanel distinguishes stock vs crypto
- US flag emoji for stock positions
- Dollar prefix for stock PnL/prices
- 'Shares' label instead of 'Qty' for stocks
- System prompts updated for stock trading capabilities
- Guard GridCount-1 division by zero in grid spacing calculation (both grid.go and grid_levels.go)
- Rate-limit /wallet/validate and /wallet/generate endpoints (prevent DoS on key generation)
- Wrap JSON.parse(localStorage) in try-catch in AuthContext (corrupted data → graceful re-login)
- Wrap handleJSONResponse JSON.parse in try-catch with descriptive error
- Add HTTP status code checks for Lighter GetActiveOrders and sendTx
- Replace deprecated strings.Title with cases.Title (golang.org/x/text)
- Reuse HTTP client in checkClaw402Health (was creating new client per call)
- Propagate request context through MCP client (Request.Ctx field)
— Client disconnects now cancel in-flight LLM API calls (both streaming and non-streaming)
— Prevents wasted LLM tokens when user navigates away mid-response
- proxyBinance: use http.NewRequestWithContext for context-aware upstream calls
— Client disconnects cancel Binance proxy requests
— Distinguishes client cancellation from upstream failures
- Fix SSE parse bug in AgentChatPage: catch block was swallowing error events
— throw new Error(data) for 'error' events was caught by the same try/catch
— Now parse JSON separately, then handle events outside try/catch
- Add io.LimitReader to Hyperliquid coins.go JSON decoder (4MB limit)
- Use safe.ReadAllLimited in batch ticker handler for consistency
- Sanitize URL validation error in handler_ai_model.go (was leaking raw error)
- Cache agent tool definitions (built once, reused per message)
- Sort trade history by exit time for consistent ordering
- 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
- 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
- Replace all raw pos["key"].(type) assertions with posFloat64/posString/posInt64 helpers
across auto_trader_decision, auto_trader_grid, auto_trader_grid_orders,
auto_trader_grid_regime, auto_trader_loop, auto_trader_orders, auto_trader_risk
- Add posInt64 helper for int64 extraction (createdTime etc)
- Fix emergencyExit: log CloseLong/CloseShort errors instead of silently dropping
- Fix emergencyExit: log GetPositions error on failure
- Upgrade closeAllPositions log level from Infof to Warnf for close failures
- Zero raw type assertions remaining in auto_trader_* files
- 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
- CancelStopOrders: only cancel orders with non-empty TriggerPrice (was canceling ALL orders including regular limit orders — safety bug)
- proxyBinance: return 502 when upstream returns non-200 instead of silently proxying error pages
- Remove redundant CORS headers in agent/web.go (already handled by gin middleware)
- market/api_client.go: check StatusCode for exchangeInfo, klines, price
endpoints + add truncateBody helper for safe error messages
- market/data.go: check StatusCode for openInterest and premiumIndex
- provider/coinank: check StatusCode for GET and POST requests
- provider/twelvedata: check StatusCode for time series and quote APIs
- Prevents confusing JSON unmarshal errors when APIs return 429/500/etc
Previously each direct API call (orders, sync, account) created a new
http.Client, preventing TCP/TLS connection reuse. Now all calls share
a single client on the HyperliquidTrader struct (30s timeout).
Applied safe.GoNamed to:
- 9 exchange order_sync goroutines (OKX, Hyperliquid, Aster, Bybit, KuCoin, Gate, Bitget, Lighter, Binance×2)
- Drawdown monitor (auto_trader_risk.go)
- Brain news scanner + market briefs (agent/brain.go)
- Sentinel scanner (agent/sentinel.go)
- Agent scheduler (agent/scheduler.go)
- x402 idle watchdog (mcp/payment/x402.go)
- MCP stream idle watchdog (mcp/client.go)
- Rate limiter cleanup (api/rate_limiter.go)
- 3 telemetry fire-and-forget sends (telemetry/experience.go)
- CoinAnk WS handler (provider/coinank/coinank_api/kline_ws.go)
- API server goroutine (main.go)
Added manual defer/recover with error reporting to:
- Telegram AI agent handler (sends error msg to user on panic)
- Trader data fetch (returns error result on panic to prevent deadlock)
Before: a panic in ANY of these 27 goroutines would crash the entire
trading process with zero diagnostics. Now all panics are caught, logged
with stack traces, and the process continues running.
Security:
- Remove /api/crypto/decrypt from public routes. The endpoint allowed
anyone to decrypt ciphertext without authentication. Internal callers
(exchange/model handlers) use the service directly and are behind auth.
Reliability:
- Add safe.Go / safe.GoNamed panic recovery wrapper (safe/go.go).
Previously 31 goroutines had zero recover() calls — a single panic
in any trader goroutine would crash the entire process.
- Apply safe.GoNamed to all trader launch paths:
- StartAll, RestoreRunning, LoadSingleTrader auto-start
- API handler start/restart endpoints
- Panics are now logged with full stack traces instead of crashing.
- handler_klines.go: pass c.Request.Context() to all external API calls
instead of context.Background(). Client disconnects now cancel upstream
requests to CoinAnk, Alpaca, TwelveData, Hyperliquid.
- Extract renderMessageContent + renderInline into
components/agent/MessageRenderer.tsx (187 lines).
AgentChatPage.tsx reduced from 1009 → 825 lines.
Previously when the seen map exceeded 1000 entries, ALL entries were
deleted, losing dedup state and causing re-notifications. Now evicts
~half the entries, preserving recent URLs for dedup continuity.
- 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
- 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
- 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
- / now defaults to AgentChatPage (NOFXi's main interface)
- Agent page accessible without login
- LandingPage only shown at /landing or for non-agent pages when not logged in
All functionality has been migrated to the top-level agent/ package.
The old nofxi/ code was fully self-contained with no external references.
Integration plan doc preserved in docs/nofx-integration-plan.md.
Removed 35 files, ~4400 lines of dead code.
- 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