2026-01-03 14:25:40 +08:00
|
|
|
package kernel
|
2025-10-29 06:14:57 +08:00
|
|
|
|
|
|
|
|
import (
|
2026-02-22 04:03:05 -05:00
|
|
|
"context"
|
2025-10-29 06:14:57 +08:00
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
2025-12-10 14:40:08 +08:00
|
|
|
"io"
|
|
|
|
|
"net/http"
|
2026-03-25 09:58:24 +08:00
|
|
|
"os"
|
Refactor/trading actions (#1169)
* refactor: 简化交易动作,移除 update_stop_loss/update_take_profit/partial_close
- 移除 Decision 结构体中的 NewStopLoss, NewTakeProfit, ClosePercentage 字段
- 删除 executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord 函数
- 简化 logger 中的 partial_close 聚合逻辑
- 更新 AI prompt 和验证逻辑,只保留 6 个核心动作
- 清理相关测试代码
保留的交易动作: open_long, open_short, close_long, close_short, hold, wait
* refactor: 移除 AI学习与反思 模块
- 删除前端 AILearning.tsx 组件和相关引用
- 删除后端 /performance API 接口
- 删除 logger 中 AnalyzePerformance、calculateSharpeRatio 等函数
- 删除 PerformanceAnalysis、TradeOutcome、SymbolPerformance 等结构体
- 删除 Context 中的 Performance 字段
- 移除 AI prompt 中夏普比率自我进化相关内容
- 清理 i18n 翻译文件中的相关条目
该模块基于磁盘存储计算,经常出错,做减法移除
* refactor: 将数据库操作统一迁移到 store 包
- 新增 store/ 包,统一管理所有数据库操作
- store.go: 主 Store 结构,懒加载各子模块
- user.go, ai_model.go, exchange.go, trader.go 等子模块
- 支持加密/解密函数注入 (SetCryptoFuncs)
- 更新 main.go 使用 store.New() 替代 config.NewDatabase()
- 更新 api/server.go 使用 *store.Store 替代 *config.Database
- 更新 manager/trader_manager.go:
- 新增 LoadTradersFromStore, LoadUserTradersFromStore 方法
- 删除旧版 LoadUserTraders, LoadTraderByID, loadSingleTrader 等方法
- 移除 nofx/config 依赖
- 删除 config/database.go 和 config/database_test.go
- 更新 api/server_test.go 使用 store.Trader 类型
- 清理 logger/ 包中未使用的 telegram 相关代码
* refactor: unify encryption key management via .env
- Remove redundant EncryptionManager and SecureStorage
- Simplify CryptoService to load keys from environment variables only
- RSA_PRIVATE_KEY: RSA private key for client-server encryption
- DATA_ENCRYPTION_KEY: AES-256 key for database encryption
- JWT_SECRET: JWT signing key for authentication
- Update start.sh to auto-generate missing keys on first run
- Remove secrets/ directory and file-based key storage
- Delete obsolete encryption setup scripts
- Update .env.example with all required keys
* refactor: unify logger usage across mcp package
- Add MCPLogger adapter in logger package to implement mcp.Logger interface
- Update mcp/config.go to use global logger by default
- Remove redundant defaultLogger from mcp/logger.go
- Keep noopLogger for testing purposes
* chore: remove leftover test RSA key file
* chore: remove unused bootstrap package
* refactor: unify logging to use logger package instead of fmt/log
- Replace all fmt.Print/log.Print calls with logger package
- Add auto-initialization in logger package init() for test compatibility
- Update main.go to initialize logger at startup
- Migrate all packages: api, backtest, config, decision, manager, market, store, trader
* refactor: rename database file from config.db to data.db
- Update main.go, start.sh, docker-compose.yml
- Update migration script and documentation
- Update .gitignore and translations
* fix: add RSA_PRIVATE_KEY to docker-compose environment
* fix: add registration_enabled to /api/config response
* fix: Fix navigation between login and register pages
Use window.location.href instead of react-router's navigate() to fix
the issue where URL changes but the page doesn't reload due to App.tsx
using custom route state management.
* fix: Switch SQLite from WAL to DELETE mode for Docker compatibility
WAL mode causes data sync issues with Docker bind mounts on macOS due
to incompatible file locking mechanisms between the container and host.
DELETE mode (traditional journaling) ensures data is written directly
to the main database file.
* refactor: Remove default user from database initialization
The default user was a legacy placeholder that is no longer needed now
that proper user registration is in place.
* feat: Add order tracking system with centralized status sync
- Add trader_orders table for tracking all order lifecycle
- Implement GetOrderStatus interface for all exchanges (Binance, Bybit, Hyperliquid, Aster, Lighter)
- Create OrderSyncManager for centralized order status polling
- Add trading statistics (Sharpe ratio, win rate, profit factor) to AI context
- Include recent completed orders in AI decision input
- Remove per-order goroutine polling in favor of global sync manager
* feat: Add TradingView K-line chart to dashboard
- Create TradingViewChart component with exchange/symbol selectors
- Support Binance, Bybit, OKX, Coinbase, Kraken, KuCoin exchanges
- Add popular symbols quick selection
- Support multiple timeframes (1m to 1W)
- Add fullscreen mode
- Integrate with Dashboard page below equity chart
- Add i18n translations for zh/en
* refactor: Replace separate charts with tabbed ChartTabs component
- Create ChartTabs component with tab switching between equity curve and K-line
- Add embedded mode support for EquityChart and TradingViewChart
- User can now switch between account equity and market chart in same area
* fix: Use ChartTabs in App.tsx and fix embedded mode in EquityChart
- Replace EquityChart with ChartTabs in App.tsx (the actual dashboard renderer)
- Fix EquityChart embedded mode for error and empty data states
- Rename interval state to timeInterval to avoid shadowing window.setInterval
- Add debug logging to ChartTabs component
* feat: Add position tracking system for accurate trade history
- Add trader_positions table to track complete open/close trades
- Add PositionSyncManager to detect manual closes via polling
- Record position on open, update on close with PnL calculation
- Use positions table for trading stats and recent trades (replacing orders table)
- Fix TradingView chart symbol format (add .P suffix for futures)
- Fix DecisionCard wait/hold action color (gray instead of red)
- Auto-append USDT suffix for custom symbol input
* update
---------
2025-12-06 01:04:26 +08:00
|
|
|
"nofx/logger"
|
2025-10-29 06:14:57 +08:00
|
|
|
"nofx/market"
|
2026-02-22 04:03:05 -05:00
|
|
|
"nofx/provider/hyperliquid"
|
2026-01-04 00:59:07 +08:00
|
|
|
"nofx/provider/nofxos"
|
fix: add SSRF protection for user-controlled URLs
- Add security/url_validator.go with ValidateURL, SafeHTTPClient, SafeGet
- Block private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16)
- Block cloud metadata endpoints (169.254.169.254, metadata.google.internal)
- Validate DNS resolution to prevent DNS rebinding attacks
- Check redirect destinations for SSRF
- Fix FetchQuantData, FetchOIRanking, fetchAI500, fetchOITop, fetchSingleExternalSource
2025-12-14 12:01:23 +08:00
|
|
|
"nofx/security"
|
2025-12-10 14:40:08 +08:00
|
|
|
"nofx/store"
|
2025-10-29 06:14:57 +08:00
|
|
|
"strings"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
// ============================================================================
|
|
|
|
|
// Type Definitions
|
|
|
|
|
// ============================================================================
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// PositionInfo position information
|
2025-10-29 06:14:57 +08:00
|
|
|
type PositionInfo struct {
|
|
|
|
|
Symbol string `json:"symbol"`
|
|
|
|
|
Side string `json:"side"` // "long" or "short"
|
|
|
|
|
EntryPrice float64 `json:"entry_price"`
|
|
|
|
|
MarkPrice float64 `json:"mark_price"`
|
|
|
|
|
Quantity float64 `json:"quantity"`
|
|
|
|
|
Leverage int `json:"leverage"`
|
|
|
|
|
UnrealizedPnL float64 `json:"unrealized_pnl"`
|
|
|
|
|
UnrealizedPnLPct float64 `json:"unrealized_pnl_pct"`
|
2025-12-08 01:40:48 +08:00
|
|
|
PeakPnLPct float64 `json:"peak_pnl_pct"` // Historical peak profit percentage
|
2025-10-29 06:14:57 +08:00
|
|
|
LiquidationPrice float64 `json:"liquidation_price"`
|
|
|
|
|
MarginUsed float64 `json:"margin_used"`
|
2025-12-08 01:40:48 +08:00
|
|
|
UpdateTime int64 `json:"update_time"` // Position update timestamp (milliseconds)
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// AccountInfo account information
|
2025-10-29 06:14:57 +08:00
|
|
|
type AccountInfo struct {
|
2025-12-08 01:40:48 +08:00
|
|
|
TotalEquity float64 `json:"total_equity"` // Account equity
|
|
|
|
|
AvailableBalance float64 `json:"available_balance"` // Available balance
|
|
|
|
|
UnrealizedPnL float64 `json:"unrealized_pnl"` // Unrealized profit/loss
|
|
|
|
|
TotalPnL float64 `json:"total_pnl"` // Total profit/loss
|
|
|
|
|
TotalPnLPct float64 `json:"total_pnl_pct"` // Total profit/loss percentage
|
|
|
|
|
MarginUsed float64 `json:"margin_used"` // Used margin
|
|
|
|
|
MarginUsedPct float64 `json:"margin_used_pct"` // Margin usage rate
|
|
|
|
|
PositionCount int `json:"position_count"` // Number of positions
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// CandidateCoin candidate coin (from coin pool)
|
2025-10-29 06:14:57 +08:00
|
|
|
type CandidateCoin struct {
|
|
|
|
|
Symbol string `json:"symbol"`
|
2025-12-08 01:40:48 +08:00
|
|
|
Sources []string `json:"sources"` // Sources: "ai500" and/or "oi_top"
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// OITopData open interest growth top data (for AI decision reference)
|
2025-10-29 06:14:57 +08:00
|
|
|
type OITopData struct {
|
2025-12-08 01:40:48 +08:00
|
|
|
Rank int // OI Top ranking
|
|
|
|
|
OIDeltaPercent float64 // Open interest change percentage (1 hour)
|
|
|
|
|
OIDeltaValue float64 // Open interest change value
|
|
|
|
|
PriceDeltaPercent float64 // Price change percentage
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// TradingStats trading statistics (for AI input)
|
Refactor/trading actions (#1169)
* refactor: 简化交易动作,移除 update_stop_loss/update_take_profit/partial_close
- 移除 Decision 结构体中的 NewStopLoss, NewTakeProfit, ClosePercentage 字段
- 删除 executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord 函数
- 简化 logger 中的 partial_close 聚合逻辑
- 更新 AI prompt 和验证逻辑,只保留 6 个核心动作
- 清理相关测试代码
保留的交易动作: open_long, open_short, close_long, close_short, hold, wait
* refactor: 移除 AI学习与反思 模块
- 删除前端 AILearning.tsx 组件和相关引用
- 删除后端 /performance API 接口
- 删除 logger 中 AnalyzePerformance、calculateSharpeRatio 等函数
- 删除 PerformanceAnalysis、TradeOutcome、SymbolPerformance 等结构体
- 删除 Context 中的 Performance 字段
- 移除 AI prompt 中夏普比率自我进化相关内容
- 清理 i18n 翻译文件中的相关条目
该模块基于磁盘存储计算,经常出错,做减法移除
* refactor: 将数据库操作统一迁移到 store 包
- 新增 store/ 包,统一管理所有数据库操作
- store.go: 主 Store 结构,懒加载各子模块
- user.go, ai_model.go, exchange.go, trader.go 等子模块
- 支持加密/解密函数注入 (SetCryptoFuncs)
- 更新 main.go 使用 store.New() 替代 config.NewDatabase()
- 更新 api/server.go 使用 *store.Store 替代 *config.Database
- 更新 manager/trader_manager.go:
- 新增 LoadTradersFromStore, LoadUserTradersFromStore 方法
- 删除旧版 LoadUserTraders, LoadTraderByID, loadSingleTrader 等方法
- 移除 nofx/config 依赖
- 删除 config/database.go 和 config/database_test.go
- 更新 api/server_test.go 使用 store.Trader 类型
- 清理 logger/ 包中未使用的 telegram 相关代码
* refactor: unify encryption key management via .env
- Remove redundant EncryptionManager and SecureStorage
- Simplify CryptoService to load keys from environment variables only
- RSA_PRIVATE_KEY: RSA private key for client-server encryption
- DATA_ENCRYPTION_KEY: AES-256 key for database encryption
- JWT_SECRET: JWT signing key for authentication
- Update start.sh to auto-generate missing keys on first run
- Remove secrets/ directory and file-based key storage
- Delete obsolete encryption setup scripts
- Update .env.example with all required keys
* refactor: unify logger usage across mcp package
- Add MCPLogger adapter in logger package to implement mcp.Logger interface
- Update mcp/config.go to use global logger by default
- Remove redundant defaultLogger from mcp/logger.go
- Keep noopLogger for testing purposes
* chore: remove leftover test RSA key file
* chore: remove unused bootstrap package
* refactor: unify logging to use logger package instead of fmt/log
- Replace all fmt.Print/log.Print calls with logger package
- Add auto-initialization in logger package init() for test compatibility
- Update main.go to initialize logger at startup
- Migrate all packages: api, backtest, config, decision, manager, market, store, trader
* refactor: rename database file from config.db to data.db
- Update main.go, start.sh, docker-compose.yml
- Update migration script and documentation
- Update .gitignore and translations
* fix: add RSA_PRIVATE_KEY to docker-compose environment
* fix: add registration_enabled to /api/config response
* fix: Fix navigation between login and register pages
Use window.location.href instead of react-router's navigate() to fix
the issue where URL changes but the page doesn't reload due to App.tsx
using custom route state management.
* fix: Switch SQLite from WAL to DELETE mode for Docker compatibility
WAL mode causes data sync issues with Docker bind mounts on macOS due
to incompatible file locking mechanisms between the container and host.
DELETE mode (traditional journaling) ensures data is written directly
to the main database file.
* refactor: Remove default user from database initialization
The default user was a legacy placeholder that is no longer needed now
that proper user registration is in place.
* feat: Add order tracking system with centralized status sync
- Add trader_orders table for tracking all order lifecycle
- Implement GetOrderStatus interface for all exchanges (Binance, Bybit, Hyperliquid, Aster, Lighter)
- Create OrderSyncManager for centralized order status polling
- Add trading statistics (Sharpe ratio, win rate, profit factor) to AI context
- Include recent completed orders in AI decision input
- Remove per-order goroutine polling in favor of global sync manager
* feat: Add TradingView K-line chart to dashboard
- Create TradingViewChart component with exchange/symbol selectors
- Support Binance, Bybit, OKX, Coinbase, Kraken, KuCoin exchanges
- Add popular symbols quick selection
- Support multiple timeframes (1m to 1W)
- Add fullscreen mode
- Integrate with Dashboard page below equity chart
- Add i18n translations for zh/en
* refactor: Replace separate charts with tabbed ChartTabs component
- Create ChartTabs component with tab switching between equity curve and K-line
- Add embedded mode support for EquityChart and TradingViewChart
- User can now switch between account equity and market chart in same area
* fix: Use ChartTabs in App.tsx and fix embedded mode in EquityChart
- Replace EquityChart with ChartTabs in App.tsx (the actual dashboard renderer)
- Fix EquityChart embedded mode for error and empty data states
- Rename interval state to timeInterval to avoid shadowing window.setInterval
- Add debug logging to ChartTabs component
* feat: Add position tracking system for accurate trade history
- Add trader_positions table to track complete open/close trades
- Add PositionSyncManager to detect manual closes via polling
- Record position on open, update on close with PnL calculation
- Use positions table for trading stats and recent trades (replacing orders table)
- Fix TradingView chart symbol format (add .P suffix for futures)
- Fix DecisionCard wait/hold action color (gray instead of red)
- Auto-append USDT suffix for custom symbol input
* update
---------
2025-12-06 01:04:26 +08:00
|
|
|
type TradingStats struct {
|
2025-12-08 01:40:48 +08:00
|
|
|
TotalTrades int `json:"total_trades"` // Total number of trades (closed)
|
|
|
|
|
WinRate float64 `json:"win_rate"` // Win rate (%)
|
|
|
|
|
ProfitFactor float64 `json:"profit_factor"` // Profit factor
|
|
|
|
|
SharpeRatio float64 `json:"sharpe_ratio"` // Sharpe ratio
|
|
|
|
|
TotalPnL float64 `json:"total_pnl"` // Total profit/loss
|
|
|
|
|
AvgWin float64 `json:"avg_win"` // Average win
|
|
|
|
|
AvgLoss float64 `json:"avg_loss"` // Average loss
|
|
|
|
|
MaxDrawdownPct float64 `json:"max_drawdown_pct"` // Maximum drawdown (%)
|
Refactor/trading actions (#1169)
* refactor: 简化交易动作,移除 update_stop_loss/update_take_profit/partial_close
- 移除 Decision 结构体中的 NewStopLoss, NewTakeProfit, ClosePercentage 字段
- 删除 executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord 函数
- 简化 logger 中的 partial_close 聚合逻辑
- 更新 AI prompt 和验证逻辑,只保留 6 个核心动作
- 清理相关测试代码
保留的交易动作: open_long, open_short, close_long, close_short, hold, wait
* refactor: 移除 AI学习与反思 模块
- 删除前端 AILearning.tsx 组件和相关引用
- 删除后端 /performance API 接口
- 删除 logger 中 AnalyzePerformance、calculateSharpeRatio 等函数
- 删除 PerformanceAnalysis、TradeOutcome、SymbolPerformance 等结构体
- 删除 Context 中的 Performance 字段
- 移除 AI prompt 中夏普比率自我进化相关内容
- 清理 i18n 翻译文件中的相关条目
该模块基于磁盘存储计算,经常出错,做减法移除
* refactor: 将数据库操作统一迁移到 store 包
- 新增 store/ 包,统一管理所有数据库操作
- store.go: 主 Store 结构,懒加载各子模块
- user.go, ai_model.go, exchange.go, trader.go 等子模块
- 支持加密/解密函数注入 (SetCryptoFuncs)
- 更新 main.go 使用 store.New() 替代 config.NewDatabase()
- 更新 api/server.go 使用 *store.Store 替代 *config.Database
- 更新 manager/trader_manager.go:
- 新增 LoadTradersFromStore, LoadUserTradersFromStore 方法
- 删除旧版 LoadUserTraders, LoadTraderByID, loadSingleTrader 等方法
- 移除 nofx/config 依赖
- 删除 config/database.go 和 config/database_test.go
- 更新 api/server_test.go 使用 store.Trader 类型
- 清理 logger/ 包中未使用的 telegram 相关代码
* refactor: unify encryption key management via .env
- Remove redundant EncryptionManager and SecureStorage
- Simplify CryptoService to load keys from environment variables only
- RSA_PRIVATE_KEY: RSA private key for client-server encryption
- DATA_ENCRYPTION_KEY: AES-256 key for database encryption
- JWT_SECRET: JWT signing key for authentication
- Update start.sh to auto-generate missing keys on first run
- Remove secrets/ directory and file-based key storage
- Delete obsolete encryption setup scripts
- Update .env.example with all required keys
* refactor: unify logger usage across mcp package
- Add MCPLogger adapter in logger package to implement mcp.Logger interface
- Update mcp/config.go to use global logger by default
- Remove redundant defaultLogger from mcp/logger.go
- Keep noopLogger for testing purposes
* chore: remove leftover test RSA key file
* chore: remove unused bootstrap package
* refactor: unify logging to use logger package instead of fmt/log
- Replace all fmt.Print/log.Print calls with logger package
- Add auto-initialization in logger package init() for test compatibility
- Update main.go to initialize logger at startup
- Migrate all packages: api, backtest, config, decision, manager, market, store, trader
* refactor: rename database file from config.db to data.db
- Update main.go, start.sh, docker-compose.yml
- Update migration script and documentation
- Update .gitignore and translations
* fix: add RSA_PRIVATE_KEY to docker-compose environment
* fix: add registration_enabled to /api/config response
* fix: Fix navigation between login and register pages
Use window.location.href instead of react-router's navigate() to fix
the issue where URL changes but the page doesn't reload due to App.tsx
using custom route state management.
* fix: Switch SQLite from WAL to DELETE mode for Docker compatibility
WAL mode causes data sync issues with Docker bind mounts on macOS due
to incompatible file locking mechanisms between the container and host.
DELETE mode (traditional journaling) ensures data is written directly
to the main database file.
* refactor: Remove default user from database initialization
The default user was a legacy placeholder that is no longer needed now
that proper user registration is in place.
* feat: Add order tracking system with centralized status sync
- Add trader_orders table for tracking all order lifecycle
- Implement GetOrderStatus interface for all exchanges (Binance, Bybit, Hyperliquid, Aster, Lighter)
- Create OrderSyncManager for centralized order status polling
- Add trading statistics (Sharpe ratio, win rate, profit factor) to AI context
- Include recent completed orders in AI decision input
- Remove per-order goroutine polling in favor of global sync manager
* feat: Add TradingView K-line chart to dashboard
- Create TradingViewChart component with exchange/symbol selectors
- Support Binance, Bybit, OKX, Coinbase, Kraken, KuCoin exchanges
- Add popular symbols quick selection
- Support multiple timeframes (1m to 1W)
- Add fullscreen mode
- Integrate with Dashboard page below equity chart
- Add i18n translations for zh/en
* refactor: Replace separate charts with tabbed ChartTabs component
- Create ChartTabs component with tab switching between equity curve and K-line
- Add embedded mode support for EquityChart and TradingViewChart
- User can now switch between account equity and market chart in same area
* fix: Use ChartTabs in App.tsx and fix embedded mode in EquityChart
- Replace EquityChart with ChartTabs in App.tsx (the actual dashboard renderer)
- Fix EquityChart embedded mode for error and empty data states
- Rename interval state to timeInterval to avoid shadowing window.setInterval
- Add debug logging to ChartTabs component
* feat: Add position tracking system for accurate trade history
- Add trader_positions table to track complete open/close trades
- Add PositionSyncManager to detect manual closes via polling
- Record position on open, update on close with PnL calculation
- Use positions table for trading stats and recent trades (replacing orders table)
- Fix TradingView chart symbol format (add .P suffix for futures)
- Fix DecisionCard wait/hold action color (gray instead of red)
- Auto-append USDT suffix for custom symbol input
* update
---------
2025-12-06 01:04:26 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// RecentOrder recently completed order (for AI input)
|
Refactor/trading actions (#1169)
* refactor: 简化交易动作,移除 update_stop_loss/update_take_profit/partial_close
- 移除 Decision 结构体中的 NewStopLoss, NewTakeProfit, ClosePercentage 字段
- 删除 executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord 函数
- 简化 logger 中的 partial_close 聚合逻辑
- 更新 AI prompt 和验证逻辑,只保留 6 个核心动作
- 清理相关测试代码
保留的交易动作: open_long, open_short, close_long, close_short, hold, wait
* refactor: 移除 AI学习与反思 模块
- 删除前端 AILearning.tsx 组件和相关引用
- 删除后端 /performance API 接口
- 删除 logger 中 AnalyzePerformance、calculateSharpeRatio 等函数
- 删除 PerformanceAnalysis、TradeOutcome、SymbolPerformance 等结构体
- 删除 Context 中的 Performance 字段
- 移除 AI prompt 中夏普比率自我进化相关内容
- 清理 i18n 翻译文件中的相关条目
该模块基于磁盘存储计算,经常出错,做减法移除
* refactor: 将数据库操作统一迁移到 store 包
- 新增 store/ 包,统一管理所有数据库操作
- store.go: 主 Store 结构,懒加载各子模块
- user.go, ai_model.go, exchange.go, trader.go 等子模块
- 支持加密/解密函数注入 (SetCryptoFuncs)
- 更新 main.go 使用 store.New() 替代 config.NewDatabase()
- 更新 api/server.go 使用 *store.Store 替代 *config.Database
- 更新 manager/trader_manager.go:
- 新增 LoadTradersFromStore, LoadUserTradersFromStore 方法
- 删除旧版 LoadUserTraders, LoadTraderByID, loadSingleTrader 等方法
- 移除 nofx/config 依赖
- 删除 config/database.go 和 config/database_test.go
- 更新 api/server_test.go 使用 store.Trader 类型
- 清理 logger/ 包中未使用的 telegram 相关代码
* refactor: unify encryption key management via .env
- Remove redundant EncryptionManager and SecureStorage
- Simplify CryptoService to load keys from environment variables only
- RSA_PRIVATE_KEY: RSA private key for client-server encryption
- DATA_ENCRYPTION_KEY: AES-256 key for database encryption
- JWT_SECRET: JWT signing key for authentication
- Update start.sh to auto-generate missing keys on first run
- Remove secrets/ directory and file-based key storage
- Delete obsolete encryption setup scripts
- Update .env.example with all required keys
* refactor: unify logger usage across mcp package
- Add MCPLogger adapter in logger package to implement mcp.Logger interface
- Update mcp/config.go to use global logger by default
- Remove redundant defaultLogger from mcp/logger.go
- Keep noopLogger for testing purposes
* chore: remove leftover test RSA key file
* chore: remove unused bootstrap package
* refactor: unify logging to use logger package instead of fmt/log
- Replace all fmt.Print/log.Print calls with logger package
- Add auto-initialization in logger package init() for test compatibility
- Update main.go to initialize logger at startup
- Migrate all packages: api, backtest, config, decision, manager, market, store, trader
* refactor: rename database file from config.db to data.db
- Update main.go, start.sh, docker-compose.yml
- Update migration script and documentation
- Update .gitignore and translations
* fix: add RSA_PRIVATE_KEY to docker-compose environment
* fix: add registration_enabled to /api/config response
* fix: Fix navigation between login and register pages
Use window.location.href instead of react-router's navigate() to fix
the issue where URL changes but the page doesn't reload due to App.tsx
using custom route state management.
* fix: Switch SQLite from WAL to DELETE mode for Docker compatibility
WAL mode causes data sync issues with Docker bind mounts on macOS due
to incompatible file locking mechanisms between the container and host.
DELETE mode (traditional journaling) ensures data is written directly
to the main database file.
* refactor: Remove default user from database initialization
The default user was a legacy placeholder that is no longer needed now
that proper user registration is in place.
* feat: Add order tracking system with centralized status sync
- Add trader_orders table for tracking all order lifecycle
- Implement GetOrderStatus interface for all exchanges (Binance, Bybit, Hyperliquid, Aster, Lighter)
- Create OrderSyncManager for centralized order status polling
- Add trading statistics (Sharpe ratio, win rate, profit factor) to AI context
- Include recent completed orders in AI decision input
- Remove per-order goroutine polling in favor of global sync manager
* feat: Add TradingView K-line chart to dashboard
- Create TradingViewChart component with exchange/symbol selectors
- Support Binance, Bybit, OKX, Coinbase, Kraken, KuCoin exchanges
- Add popular symbols quick selection
- Support multiple timeframes (1m to 1W)
- Add fullscreen mode
- Integrate with Dashboard page below equity chart
- Add i18n translations for zh/en
* refactor: Replace separate charts with tabbed ChartTabs component
- Create ChartTabs component with tab switching between equity curve and K-line
- Add embedded mode support for EquityChart and TradingViewChart
- User can now switch between account equity and market chart in same area
* fix: Use ChartTabs in App.tsx and fix embedded mode in EquityChart
- Replace EquityChart with ChartTabs in App.tsx (the actual dashboard renderer)
- Fix EquityChart embedded mode for error and empty data states
- Rename interval state to timeInterval to avoid shadowing window.setInterval
- Add debug logging to ChartTabs component
* feat: Add position tracking system for accurate trade history
- Add trader_positions table to track complete open/close trades
- Add PositionSyncManager to detect manual closes via polling
- Record position on open, update on close with PnL calculation
- Use positions table for trading stats and recent trades (replacing orders table)
- Fix TradingView chart symbol format (add .P suffix for futures)
- Fix DecisionCard wait/hold action color (gray instead of red)
- Auto-append USDT suffix for custom symbol input
* update
---------
2025-12-06 01:04:26 +08:00
|
|
|
type RecentOrder struct {
|
2025-12-10 14:40:08 +08:00
|
|
|
Symbol string `json:"symbol"` // Trading pair
|
|
|
|
|
Side string `json:"side"` // long/short
|
|
|
|
|
EntryPrice float64 `json:"entry_price"` // Entry price
|
|
|
|
|
ExitPrice float64 `json:"exit_price"` // Exit price
|
|
|
|
|
RealizedPnL float64 `json:"realized_pnl"` // Realized profit/loss
|
|
|
|
|
PnLPct float64 `json:"pnl_pct"` // Profit/loss percentage
|
|
|
|
|
EntryTime string `json:"entry_time"` // Entry time
|
|
|
|
|
ExitTime string `json:"exit_time"` // Exit time
|
|
|
|
|
HoldDuration string `json:"hold_duration"` // Hold duration, e.g. "2h30m"
|
Refactor/trading actions (#1169)
* refactor: 简化交易动作,移除 update_stop_loss/update_take_profit/partial_close
- 移除 Decision 结构体中的 NewStopLoss, NewTakeProfit, ClosePercentage 字段
- 删除 executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord 函数
- 简化 logger 中的 partial_close 聚合逻辑
- 更新 AI prompt 和验证逻辑,只保留 6 个核心动作
- 清理相关测试代码
保留的交易动作: open_long, open_short, close_long, close_short, hold, wait
* refactor: 移除 AI学习与反思 模块
- 删除前端 AILearning.tsx 组件和相关引用
- 删除后端 /performance API 接口
- 删除 logger 中 AnalyzePerformance、calculateSharpeRatio 等函数
- 删除 PerformanceAnalysis、TradeOutcome、SymbolPerformance 等结构体
- 删除 Context 中的 Performance 字段
- 移除 AI prompt 中夏普比率自我进化相关内容
- 清理 i18n 翻译文件中的相关条目
该模块基于磁盘存储计算,经常出错,做减法移除
* refactor: 将数据库操作统一迁移到 store 包
- 新增 store/ 包,统一管理所有数据库操作
- store.go: 主 Store 结构,懒加载各子模块
- user.go, ai_model.go, exchange.go, trader.go 等子模块
- 支持加密/解密函数注入 (SetCryptoFuncs)
- 更新 main.go 使用 store.New() 替代 config.NewDatabase()
- 更新 api/server.go 使用 *store.Store 替代 *config.Database
- 更新 manager/trader_manager.go:
- 新增 LoadTradersFromStore, LoadUserTradersFromStore 方法
- 删除旧版 LoadUserTraders, LoadTraderByID, loadSingleTrader 等方法
- 移除 nofx/config 依赖
- 删除 config/database.go 和 config/database_test.go
- 更新 api/server_test.go 使用 store.Trader 类型
- 清理 logger/ 包中未使用的 telegram 相关代码
* refactor: unify encryption key management via .env
- Remove redundant EncryptionManager and SecureStorage
- Simplify CryptoService to load keys from environment variables only
- RSA_PRIVATE_KEY: RSA private key for client-server encryption
- DATA_ENCRYPTION_KEY: AES-256 key for database encryption
- JWT_SECRET: JWT signing key for authentication
- Update start.sh to auto-generate missing keys on first run
- Remove secrets/ directory and file-based key storage
- Delete obsolete encryption setup scripts
- Update .env.example with all required keys
* refactor: unify logger usage across mcp package
- Add MCPLogger adapter in logger package to implement mcp.Logger interface
- Update mcp/config.go to use global logger by default
- Remove redundant defaultLogger from mcp/logger.go
- Keep noopLogger for testing purposes
* chore: remove leftover test RSA key file
* chore: remove unused bootstrap package
* refactor: unify logging to use logger package instead of fmt/log
- Replace all fmt.Print/log.Print calls with logger package
- Add auto-initialization in logger package init() for test compatibility
- Update main.go to initialize logger at startup
- Migrate all packages: api, backtest, config, decision, manager, market, store, trader
* refactor: rename database file from config.db to data.db
- Update main.go, start.sh, docker-compose.yml
- Update migration script and documentation
- Update .gitignore and translations
* fix: add RSA_PRIVATE_KEY to docker-compose environment
* fix: add registration_enabled to /api/config response
* fix: Fix navigation between login and register pages
Use window.location.href instead of react-router's navigate() to fix
the issue where URL changes but the page doesn't reload due to App.tsx
using custom route state management.
* fix: Switch SQLite from WAL to DELETE mode for Docker compatibility
WAL mode causes data sync issues with Docker bind mounts on macOS due
to incompatible file locking mechanisms between the container and host.
DELETE mode (traditional journaling) ensures data is written directly
to the main database file.
* refactor: Remove default user from database initialization
The default user was a legacy placeholder that is no longer needed now
that proper user registration is in place.
* feat: Add order tracking system with centralized status sync
- Add trader_orders table for tracking all order lifecycle
- Implement GetOrderStatus interface for all exchanges (Binance, Bybit, Hyperliquid, Aster, Lighter)
- Create OrderSyncManager for centralized order status polling
- Add trading statistics (Sharpe ratio, win rate, profit factor) to AI context
- Include recent completed orders in AI decision input
- Remove per-order goroutine polling in favor of global sync manager
* feat: Add TradingView K-line chart to dashboard
- Create TradingViewChart component with exchange/symbol selectors
- Support Binance, Bybit, OKX, Coinbase, Kraken, KuCoin exchanges
- Add popular symbols quick selection
- Support multiple timeframes (1m to 1W)
- Add fullscreen mode
- Integrate with Dashboard page below equity chart
- Add i18n translations for zh/en
* refactor: Replace separate charts with tabbed ChartTabs component
- Create ChartTabs component with tab switching between equity curve and K-line
- Add embedded mode support for EquityChart and TradingViewChart
- User can now switch between account equity and market chart in same area
* fix: Use ChartTabs in App.tsx and fix embedded mode in EquityChart
- Replace EquityChart with ChartTabs in App.tsx (the actual dashboard renderer)
- Fix EquityChart embedded mode for error and empty data states
- Rename interval state to timeInterval to avoid shadowing window.setInterval
- Add debug logging to ChartTabs component
* feat: Add position tracking system for accurate trade history
- Add trader_positions table to track complete open/close trades
- Add PositionSyncManager to detect manual closes via polling
- Record position on open, update on close with PnL calculation
- Use positions table for trading stats and recent trades (replacing orders table)
- Fix TradingView chart symbol format (add .P suffix for futures)
- Fix DecisionCard wait/hold action color (gray instead of red)
- Auto-append USDT suffix for custom symbol input
* update
---------
2025-12-06 01:04:26 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// Context trading context (complete information passed to AI)
|
2025-10-29 06:14:57 +08:00
|
|
|
type Context struct {
|
refactor: split large files and clean up project structure
- Rename experience/ to telemetry/ for clarity
- Split 15+ large Go files (800-2200 lines) into focused modules:
kernel/engine.go, backtest/runner.go, market/data.go, store/position.go,
api/handler_trader.go, trader/auto_trader_grid.go, and 9 exchange traders
- Split frontend monoliths: types.ts, api.ts, AITradersPage.tsx, BacktestPage.tsx
into domain-specific modules with barrel re-exports
- Remove stale files: screenshots, .yml.old, pyproject.toml
- Remove unused scripts/ and cmd/ directories
- Remove broken/outdated test files (network-dependent, stale expectations)
2026-03-12 12:53:57 +08:00
|
|
|
CurrentTime string `json:"current_time"`
|
|
|
|
|
RuntimeMinutes int `json:"runtime_minutes"`
|
|
|
|
|
CallCount int `json:"call_count"`
|
|
|
|
|
Account AccountInfo `json:"account"`
|
|
|
|
|
Positions []PositionInfo `json:"positions"`
|
|
|
|
|
CandidateCoins []CandidateCoin `json:"candidate_coins"`
|
|
|
|
|
PromptVariant string `json:"prompt_variant,omitempty"`
|
|
|
|
|
TradingStats *TradingStats `json:"trading_stats,omitempty"`
|
|
|
|
|
RecentOrders []RecentOrder `json:"recent_orders,omitempty"`
|
|
|
|
|
MarketDataMap map[string]*market.Data `json:"-"`
|
|
|
|
|
MultiTFMarket map[string]map[string]*market.Data `json:"-"`
|
|
|
|
|
OITopDataMap map[string]*OITopData `json:"-"`
|
|
|
|
|
QuantDataMap map[string]*QuantData `json:"-"`
|
|
|
|
|
OIRankingData *nofxos.OIRankingData `json:"-"` // Market-wide OI ranking data
|
|
|
|
|
NetFlowRankingData *nofxos.NetFlowRankingData `json:"-"` // Market-wide fund flow ranking data
|
|
|
|
|
PriceRankingData *nofxos.PriceRankingData `json:"-"` // Market-wide price gainers/losers
|
|
|
|
|
BTCETHLeverage int `json:"-"`
|
|
|
|
|
AltcoinLeverage int `json:"-"`
|
|
|
|
|
Timeframes []string `json:"-"`
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// Decision AI trading decision
|
2025-10-29 06:14:57 +08:00
|
|
|
type Decision struct {
|
2025-11-07 13:38:39 +08:00
|
|
|
Symbol string `json:"symbol"`
|
Ai grid (#1344)
* feat: add AI grid trading and market regime classification
- Add GridTrader interface with PlaceLimitOrder, CancelOrder, GetOrderBook
- Implement GridTrader for all exchanges (Binance, Bybit, OKX, Bitget, Hyperliquid, Aster, Lighter)
- Add grid engine with ATR-based boundary calculation and fund distribution
- Add market regime classification documents (Chinese/English)
- Add GridConfigEditor component for frontend configuration
* fix: implement GetOpenOrders for Lighter exchange
* debug: add logging for Lighter GetActiveOrders API call
* fix: correct Lighter API response parsing for GetOpenOrders
- Changed response field from 'data' to 'orders' to match Lighter API
- Updated OrderResponse struct to match Lighter's actual field names
- Fixed field types: price/quantity as strings, is_ask for side
* feat: implement GetOpenOrders for Aster, OKX, Bitget exchanges
- Aster: uses /fapi/v3/openOrders endpoint
- OKX: uses /api/v5/trade/orders-pending and orders-algo-pending
- Bitget: uses /api/v2/mix/order/orders-pending and orders-plan-pending
* fix: address code review issues for GetOpenOrders
- Add error logging for OKX/Bitget API failures (was silently swallowed)
- Fix Lighter position side logic to handle reduce-only orders
- Change verbose debug logs from Infof to Debugf level
* fix: provide FromAccountIndex and ApiKeyIndex for Lighter nonce auto-fetch
Root cause: SDK requires these fields to fetch nonce from API, otherwise nonce gets cached/stuck
* fix: use auth query parameter instead of Authorization header for Lighter API
* test: add Lighter API authentication tests and diagnostic tools
* fix(grid): add leverage setting before order placement
CRITICAL BUG FIX:
- Call SetLeverage() in GridTraderAdapter.PlaceLimitOrder()
- Set leverage during grid initialization
- Log leverage setting results
* fix(grid): prevent CancelOrder from canceling all orders
CRITICAL BUG FIX:
- CancelOrder no longer calls CancelAllOrders
- Try exchange-specific CancelOrder if available
- Return error if individual cancellation not supported
* fix(grid): add total position value limit check
CRITICAL: Prevent excessive position accumulation
- New checkTotalPositionLimit() function
- Checks current + pending + new order value
- Rejects orders that would exceed TotalInvestment x Leverage
- Logs clear error messages when limit exceeded
* feat(grid): implement stop loss execution
CRITICAL: Add code-level stop loss protection
- New checkAndExecuteStopLoss() function
- Checks each filled level against StopLossPct
- Automatically closes positions exceeding stop loss
- Called during every grid state sync
* feat(grid): add breakout detection and auto-pause
CRITICAL: Detect price breakout from grid range
- New checkBreakout() function to detect upper/lower breakouts
- Auto-pause grid on significant breakout (>2%)
- Cancel all orders when breakout detected
- Prevent continued losses in trending market
- Minor breakouts (1-2%) logged for AI consideration
* feat(grid): enforce max drawdown limit with emergency exit
CRITICAL: Add drawdown protection
- New checkMaxDrawdown() function tracks peak equity
- emergencyExit() closes all positions and cancels orders
- Auto-pause grid when MaxDrawdownPct exceeded
- Protect capital from excessive losses
* feat(grid): enforce daily loss limit
- Add checkDailyLossLimit() function to check if daily loss exceeds limit
- Track daily PnL with auto-reset at midnight
- Pause grid when DailyLossLimitPct exceeded
- Add updateDailyPnL() helper for realized PnL tracking
- Prevent excessive single-day losses
* fix(grid): update daily PnL when stop loss is executed
The updateDailyPnL() function was added but never called, leaving
DailyPnL always at 0 and preventing daily loss limit checks from
triggering.
This fix updates DailyPnL and TotalProfit directly in checkAndExecuteStopLoss()
when a stop loss is executed. We update directly rather than calling
updateDailyPnL() because the mutex is already held in that function.
* feat(grid): add automatic grid adjustment
- New checkGridSkew() detects imbalanced grid
- autoAdjustGrid() reinitializes around current price
- Prevents grid from becoming ineffective after drift
- Triggers when one side is 3x more filled than other
* fix(grid): recalculate bounds in autoAdjustGrid before reinitializing levels
Critical fix for grid auto-adjustment:
- Recalculate grid bounds (UpperPrice, LowerPrice, GridSpacing) centered
on current price before reinitializing grid levels
- Preserve filled positions during adjustment by saving and restoring
them to the closest new level after reinitialization
- Hold mutex lock for the entire adjustment operation to ensure atomicity
- Add locked variants of calculateDefaultBounds, calculateATRBounds, and
initializeGridLevels to use during adjustment
Without this fix, autoAdjustGrid was using old boundaries when creating
new grid levels, defeating the purpose of auto-adjustment when price
moved significantly.
* fix(grid): improve order state sync logic
- Don't assume missing orders are filled
- Compare position size to determine fill vs cancel
- Properly reset cancelled orders to empty state
- More accurate grid state tracking
* fix(grid): use actual PositionSize sum instead of count in syncGridState heuristic
The position-based heuristic was using `float64(previousFilledCount) * level.OrderQuantity`
which incorrectly assumed uniform order quantities. Since the grid uses weighted distribution
(gaussian, pyramid, uniform) where orders have different quantities, this could lead to
incorrect fill detection.
Now sums the actual PositionSize from filled levels for accurate comparison.
Also adds warning log when GetPositions() fails.
* docs: add grid market regime detection design
Design for enhanced market state recognition with:
- Multi-dimensional indicators (ATR, Bollinger, EMA, MACD, RSI)
- Multi-period box indicators (72/240/500 1h candles)
- 4-level ranging classification
- Breakout detection and handling
- Frontend risk control panel
* docs: add grid market regime implementation plan
20 tasks covering:
- Donchian channel calculation
- Box data types and API
- Regime classification (4 levels)
- Breakout detection and handling
- False breakout recovery
- Frontend risk panel
- AI prompt updates
* feat(market): add Donchian channel calculation
Add calculateDonchian function to compute highest high and lowest low
over a specified period. This is the foundation for box (range) detection
in the multi-period box indicator system for grid trading.
* fix(market): handle invalid period in calculateDonchian
* feat(market): add BoxData and RegimeLevel types
* feat(market): add GetBoxData for multi-period box calculation
Adds calculateBoxData internal function and GetBoxData public API that
fetches 1h klines and computes three Donchian box levels (short/mid/long).
This will be used by the grid trading system to detect market regime.
* feat(store): add box and regime fields to grid models
* feat(trader): add regime classification and breakout detection
Implements Tasks 6-9 for grid market regime awareness:
- Task 6: classifyRegimeLevel with Bollinger/ATR thresholds
- Task 7: detectBoxBreakout for multi-period box breakouts
- Task 8: confirmBreakout with 3-candle confirmation logic
- Task 9: getBreakoutAction mapping breakout levels to actions
* feat(trader): integrate box breakout detection into grid cycle
- Task 10: Add checkBoxBreakout with 3-candle confirmation
- Task 11: Add checkFalseBreakoutRecovery for 50% position recovery
- Task 12: Add box/breakout/regime fields to GridState
* feat: add grid risk panel with API endpoint
- Task 13: Add GridRiskInfo type to frontend
- Task 14: Add /traders/:id/grid-risk API endpoint
- Task 15: Add GetGridRiskInfo method to AutoTrader
- Task 16: Create GridRiskPanel component with i18n
* feat(kernel): add box indicators to AI prompt
- Add BoxData field to GridContext
- Add box indicator table to both zh/en prompts
- Show breakout/warning alerts based on price position
* feat(web): integrate GridRiskPanel into TraderDashboardPage
* feat(lighter): improve API key validation and market caching
- Add API key validation status tracking
- Add market list caching to reduce API calls
- Improve logging (debug vs info levels)
- Add comprehensive integration tests
- Update trader manager and store for lighter support
* fix: remove hardcoded test wallet address
* fix(grid): improve GridRiskPanel layout and fix liquidation data
- Make panel collapsible with summary badges when collapsed
- Use compact 2-column grid layout for detailed info
- Fix auth token key (token -> auth_token)
- Only calculate liquidation distance when position exists
* fix(grid): add isRunning checks to prevent trades after Stop() is called
2026-01-19 12:07:14 +08:00
|
|
|
Action string `json:"action"` // Standard: "open_long", "open_short", "close_long", "close_short", "hold", "wait"
|
|
|
|
|
// Grid actions: "place_buy_limit", "place_sell_limit", "cancel_order", "cancel_all_orders", "pause_grid", "resume_grid", "adjust_grid"
|
2025-11-02 05:32:23 +08:00
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// Opening position parameters
|
2025-10-29 06:14:57 +08:00
|
|
|
Leverage int `json:"leverage,omitempty"`
|
|
|
|
|
PositionSizeUSD float64 `json:"position_size_usd,omitempty"`
|
|
|
|
|
StopLoss float64 `json:"stop_loss,omitempty"`
|
|
|
|
|
TakeProfit float64 `json:"take_profit,omitempty"`
|
2025-11-02 05:32:23 +08:00
|
|
|
|
Ai grid (#1344)
* feat: add AI grid trading and market regime classification
- Add GridTrader interface with PlaceLimitOrder, CancelOrder, GetOrderBook
- Implement GridTrader for all exchanges (Binance, Bybit, OKX, Bitget, Hyperliquid, Aster, Lighter)
- Add grid engine with ATR-based boundary calculation and fund distribution
- Add market regime classification documents (Chinese/English)
- Add GridConfigEditor component for frontend configuration
* fix: implement GetOpenOrders for Lighter exchange
* debug: add logging for Lighter GetActiveOrders API call
* fix: correct Lighter API response parsing for GetOpenOrders
- Changed response field from 'data' to 'orders' to match Lighter API
- Updated OrderResponse struct to match Lighter's actual field names
- Fixed field types: price/quantity as strings, is_ask for side
* feat: implement GetOpenOrders for Aster, OKX, Bitget exchanges
- Aster: uses /fapi/v3/openOrders endpoint
- OKX: uses /api/v5/trade/orders-pending and orders-algo-pending
- Bitget: uses /api/v2/mix/order/orders-pending and orders-plan-pending
* fix: address code review issues for GetOpenOrders
- Add error logging for OKX/Bitget API failures (was silently swallowed)
- Fix Lighter position side logic to handle reduce-only orders
- Change verbose debug logs from Infof to Debugf level
* fix: provide FromAccountIndex and ApiKeyIndex for Lighter nonce auto-fetch
Root cause: SDK requires these fields to fetch nonce from API, otherwise nonce gets cached/stuck
* fix: use auth query parameter instead of Authorization header for Lighter API
* test: add Lighter API authentication tests and diagnostic tools
* fix(grid): add leverage setting before order placement
CRITICAL BUG FIX:
- Call SetLeverage() in GridTraderAdapter.PlaceLimitOrder()
- Set leverage during grid initialization
- Log leverage setting results
* fix(grid): prevent CancelOrder from canceling all orders
CRITICAL BUG FIX:
- CancelOrder no longer calls CancelAllOrders
- Try exchange-specific CancelOrder if available
- Return error if individual cancellation not supported
* fix(grid): add total position value limit check
CRITICAL: Prevent excessive position accumulation
- New checkTotalPositionLimit() function
- Checks current + pending + new order value
- Rejects orders that would exceed TotalInvestment x Leverage
- Logs clear error messages when limit exceeded
* feat(grid): implement stop loss execution
CRITICAL: Add code-level stop loss protection
- New checkAndExecuteStopLoss() function
- Checks each filled level against StopLossPct
- Automatically closes positions exceeding stop loss
- Called during every grid state sync
* feat(grid): add breakout detection and auto-pause
CRITICAL: Detect price breakout from grid range
- New checkBreakout() function to detect upper/lower breakouts
- Auto-pause grid on significant breakout (>2%)
- Cancel all orders when breakout detected
- Prevent continued losses in trending market
- Minor breakouts (1-2%) logged for AI consideration
* feat(grid): enforce max drawdown limit with emergency exit
CRITICAL: Add drawdown protection
- New checkMaxDrawdown() function tracks peak equity
- emergencyExit() closes all positions and cancels orders
- Auto-pause grid when MaxDrawdownPct exceeded
- Protect capital from excessive losses
* feat(grid): enforce daily loss limit
- Add checkDailyLossLimit() function to check if daily loss exceeds limit
- Track daily PnL with auto-reset at midnight
- Pause grid when DailyLossLimitPct exceeded
- Add updateDailyPnL() helper for realized PnL tracking
- Prevent excessive single-day losses
* fix(grid): update daily PnL when stop loss is executed
The updateDailyPnL() function was added but never called, leaving
DailyPnL always at 0 and preventing daily loss limit checks from
triggering.
This fix updates DailyPnL and TotalProfit directly in checkAndExecuteStopLoss()
when a stop loss is executed. We update directly rather than calling
updateDailyPnL() because the mutex is already held in that function.
* feat(grid): add automatic grid adjustment
- New checkGridSkew() detects imbalanced grid
- autoAdjustGrid() reinitializes around current price
- Prevents grid from becoming ineffective after drift
- Triggers when one side is 3x more filled than other
* fix(grid): recalculate bounds in autoAdjustGrid before reinitializing levels
Critical fix for grid auto-adjustment:
- Recalculate grid bounds (UpperPrice, LowerPrice, GridSpacing) centered
on current price before reinitializing grid levels
- Preserve filled positions during adjustment by saving and restoring
them to the closest new level after reinitialization
- Hold mutex lock for the entire adjustment operation to ensure atomicity
- Add locked variants of calculateDefaultBounds, calculateATRBounds, and
initializeGridLevels to use during adjustment
Without this fix, autoAdjustGrid was using old boundaries when creating
new grid levels, defeating the purpose of auto-adjustment when price
moved significantly.
* fix(grid): improve order state sync logic
- Don't assume missing orders are filled
- Compare position size to determine fill vs cancel
- Properly reset cancelled orders to empty state
- More accurate grid state tracking
* fix(grid): use actual PositionSize sum instead of count in syncGridState heuristic
The position-based heuristic was using `float64(previousFilledCount) * level.OrderQuantity`
which incorrectly assumed uniform order quantities. Since the grid uses weighted distribution
(gaussian, pyramid, uniform) where orders have different quantities, this could lead to
incorrect fill detection.
Now sums the actual PositionSize from filled levels for accurate comparison.
Also adds warning log when GetPositions() fails.
* docs: add grid market regime detection design
Design for enhanced market state recognition with:
- Multi-dimensional indicators (ATR, Bollinger, EMA, MACD, RSI)
- Multi-period box indicators (72/240/500 1h candles)
- 4-level ranging classification
- Breakout detection and handling
- Frontend risk control panel
* docs: add grid market regime implementation plan
20 tasks covering:
- Donchian channel calculation
- Box data types and API
- Regime classification (4 levels)
- Breakout detection and handling
- False breakout recovery
- Frontend risk panel
- AI prompt updates
* feat(market): add Donchian channel calculation
Add calculateDonchian function to compute highest high and lowest low
over a specified period. This is the foundation for box (range) detection
in the multi-period box indicator system for grid trading.
* fix(market): handle invalid period in calculateDonchian
* feat(market): add BoxData and RegimeLevel types
* feat(market): add GetBoxData for multi-period box calculation
Adds calculateBoxData internal function and GetBoxData public API that
fetches 1h klines and computes three Donchian box levels (short/mid/long).
This will be used by the grid trading system to detect market regime.
* feat(store): add box and regime fields to grid models
* feat(trader): add regime classification and breakout detection
Implements Tasks 6-9 for grid market regime awareness:
- Task 6: classifyRegimeLevel with Bollinger/ATR thresholds
- Task 7: detectBoxBreakout for multi-period box breakouts
- Task 8: confirmBreakout with 3-candle confirmation logic
- Task 9: getBreakoutAction mapping breakout levels to actions
* feat(trader): integrate box breakout detection into grid cycle
- Task 10: Add checkBoxBreakout with 3-candle confirmation
- Task 11: Add checkFalseBreakoutRecovery for 50% position recovery
- Task 12: Add box/breakout/regime fields to GridState
* feat: add grid risk panel with API endpoint
- Task 13: Add GridRiskInfo type to frontend
- Task 14: Add /traders/:id/grid-risk API endpoint
- Task 15: Add GetGridRiskInfo method to AutoTrader
- Task 16: Create GridRiskPanel component with i18n
* feat(kernel): add box indicators to AI prompt
- Add BoxData field to GridContext
- Add box indicator table to both zh/en prompts
- Show breakout/warning alerts based on price position
* feat(web): integrate GridRiskPanel into TraderDashboardPage
* feat(lighter): improve API key validation and market caching
- Add API key validation status tracking
- Add market list caching to reduce API calls
- Improve logging (debug vs info levels)
- Add comprehensive integration tests
- Update trader manager and store for lighter support
* fix: remove hardcoded test wallet address
* fix(grid): improve GridRiskPanel layout and fix liquidation data
- Make panel collapsible with summary badges when collapsed
- Use compact 2-column grid layout for detailed info
- Fix auth token key (token -> auth_token)
- Only calculate liquidation distance when position exists
* fix(grid): add isRunning checks to prevent trades after Stop() is called
2026-01-19 12:07:14 +08:00
|
|
|
// Grid trading parameters
|
|
|
|
|
Price float64 `json:"price,omitempty"` // Limit order price (for grid)
|
|
|
|
|
Quantity float64 `json:"quantity,omitempty"` // Order quantity (for grid)
|
|
|
|
|
LevelIndex int `json:"level_index,omitempty"` // Grid level index
|
|
|
|
|
OrderID string `json:"order_id,omitempty"` // Order ID (for cancel)
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// Common parameters
|
|
|
|
|
Confidence int `json:"confidence,omitempty"` // Confidence level (0-100)
|
|
|
|
|
RiskUSD float64 `json:"risk_usd,omitempty"` // Maximum USD risk
|
2025-11-07 13:38:39 +08:00
|
|
|
Reasoning string `json:"reasoning"`
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-08 01:40:48 +08:00
|
|
|
// FullDecision AI's complete decision (including chain of thought)
|
2025-10-29 06:14:57 +08:00
|
|
|
type FullDecision struct {
|
2025-12-10 14:40:08 +08:00
|
|
|
SystemPrompt string `json:"system_prompt"`
|
|
|
|
|
UserPrompt string `json:"user_prompt"`
|
|
|
|
|
CoTTrace string `json:"cot_trace"`
|
|
|
|
|
Decisions []Decision `json:"decisions"`
|
|
|
|
|
RawResponse string `json:"raw_response"`
|
|
|
|
|
Timestamp time.Time `json:"timestamp"`
|
|
|
|
|
AIRequestDurationMs int64 `json:"ai_request_duration_ms,omitempty"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// QuantData quantitative data structure (fund flow, position changes, price changes)
|
|
|
|
|
type QuantData struct {
|
|
|
|
|
Symbol string `json:"symbol"`
|
|
|
|
|
Price float64 `json:"price"`
|
|
|
|
|
Netflow *NetflowData `json:"netflow,omitempty"`
|
|
|
|
|
OI map[string]*OIData `json:"oi,omitempty"`
|
|
|
|
|
PriceChange map[string]float64 `json:"price_change,omitempty"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type NetflowData struct {
|
|
|
|
|
Institution *FlowTypeData `json:"institution,omitempty"`
|
|
|
|
|
Personal *FlowTypeData `json:"personal,omitempty"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type FlowTypeData struct {
|
|
|
|
|
Future map[string]float64 `json:"future,omitempty"`
|
|
|
|
|
Spot map[string]float64 `json:"spot,omitempty"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type OIData struct {
|
|
|
|
|
CurrentOI float64 `json:"current_oi"`
|
|
|
|
|
Delta map[string]*OIDeltaData `json:"delta,omitempty"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type OIDeltaData struct {
|
|
|
|
|
OIDelta float64 `json:"oi_delta"`
|
|
|
|
|
OIDeltaValue float64 `json:"oi_delta_value"`
|
|
|
|
|
OIDeltaPercent float64 `json:"oi_delta_percent"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ============================================================================
|
|
|
|
|
// StrategyEngine - Core Strategy Execution Engine
|
|
|
|
|
// ============================================================================
|
|
|
|
|
|
|
|
|
|
// StrategyEngine strategy execution engine
|
|
|
|
|
type StrategyEngine struct {
|
2026-01-04 00:59:07 +08:00
|
|
|
config *store.StrategyConfig
|
|
|
|
|
nofxosClient *nofxos.Client
|
2025-12-10 14:40:08 +08:00
|
|
|
}
|
|
|
|
|
|
2026-03-25 10:08:55 +08:00
|
|
|
// NewStrategyEngine creates strategy execution engine.
|
|
|
|
|
// claw402WalletKey is optional — if provided, nofxos data requests are routed through claw402.
|
|
|
|
|
func NewStrategyEngine(config *store.StrategyConfig, claw402WalletKey ...string) *StrategyEngine {
|
2026-01-04 00:59:07 +08:00
|
|
|
// Create NofxOS client with API key from config
|
|
|
|
|
apiKey := config.Indicators.NofxOSAPIKey
|
|
|
|
|
if apiKey == "" {
|
|
|
|
|
apiKey = nofxos.DefaultAuthKey
|
|
|
|
|
}
|
|
|
|
|
client := nofxos.NewClient(nofxos.DefaultBaseURL, apiKey)
|
|
|
|
|
|
2026-03-25 10:08:55 +08:00
|
|
|
// If claw402 wallet key is provided (from trader's AI config), route through claw402
|
|
|
|
|
walletKey := ""
|
|
|
|
|
if len(claw402WalletKey) > 0 {
|
|
|
|
|
walletKey = claw402WalletKey[0]
|
|
|
|
|
}
|
|
|
|
|
if walletKey == "" {
|
|
|
|
|
walletKey = os.Getenv("CLAW402_WALLET_KEY")
|
|
|
|
|
}
|
|
|
|
|
if walletKey != "" {
|
2026-03-25 09:58:24 +08:00
|
|
|
claw402URL := os.Getenv("CLAW402_URL")
|
|
|
|
|
if claw402URL == "" {
|
|
|
|
|
claw402URL = "https://claw402.ai"
|
|
|
|
|
}
|
2026-03-27 00:26:40 +08:00
|
|
|
claw402Client, err := nofxos.NewClaw402DataClient(claw402URL, walletKey, &logger.MCPLogger{})
|
2026-03-25 09:58:24 +08:00
|
|
|
if err == nil {
|
|
|
|
|
client.SetClaw402(claw402Client)
|
|
|
|
|
logger.Infof("🔗 NofxOS data routed through claw402 (%s)", claw402URL)
|
|
|
|
|
} else {
|
|
|
|
|
logger.Warnf("⚠️ Failed to init claw402 data client: %v (using direct nofxos.ai)", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
return &StrategyEngine{
|
|
|
|
|
config: config,
|
|
|
|
|
nofxosClient: client,
|
|
|
|
|
}
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
// GetRiskControlConfig gets risk control configuration
|
|
|
|
|
func (e *StrategyEngine) GetRiskControlConfig() store.RiskControlConfig {
|
|
|
|
|
return e.config.RiskControl
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
// GetLanguage returns the language from config or falls back to auto-detection
|
|
|
|
|
func (e *StrategyEngine) GetLanguage() Language {
|
|
|
|
|
switch e.config.Language {
|
|
|
|
|
case "zh":
|
|
|
|
|
return LangChinese
|
|
|
|
|
case "en":
|
|
|
|
|
return LangEnglish
|
|
|
|
|
default:
|
|
|
|
|
// Fall back to auto-detection from prompt content for backward compatibility
|
|
|
|
|
return detectLanguage(e.config.PromptSections.RoleDefinition)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
// GetConfig gets complete strategy configuration
|
|
|
|
|
func (e *StrategyEngine) GetConfig() *store.StrategyConfig {
|
|
|
|
|
return e.config
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ============================================================================
|
|
|
|
|
// Candidate Coins
|
|
|
|
|
// ============================================================================
|
|
|
|
|
|
|
|
|
|
// GetCandidateCoins gets candidate coins based on strategy configuration
|
|
|
|
|
func (e *StrategyEngine) GetCandidateCoins() ([]CandidateCoin, error) {
|
|
|
|
|
var candidates []CandidateCoin
|
|
|
|
|
symbolSources := make(map[string][]string)
|
|
|
|
|
|
|
|
|
|
coinSource := e.config.CoinSource
|
|
|
|
|
|
|
|
|
|
switch coinSource.SourceType {
|
|
|
|
|
case "static":
|
|
|
|
|
for _, symbol := range coinSource.StaticCoins {
|
|
|
|
|
symbol = market.Normalize(symbol)
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"static"},
|
|
|
|
|
})
|
2025-11-28 21:34:27 +08:00
|
|
|
}
|
2026-01-03 01:21:17 +08:00
|
|
|
|
|
|
|
|
return e.filterExcludedCoins(candidates), nil
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
case "ai500":
|
2026-03-12 16:12:08 +08:00
|
|
|
// Check use_ai500 flag; if false, fall back to static coins
|
2026-01-04 00:59:07 +08:00
|
|
|
if !coinSource.UseAI500 {
|
|
|
|
|
logger.Infof("⚠️ source_type is 'ai500' but use_ai500 is false, falling back to static coins")
|
2025-12-26 00:58:12 +08:00
|
|
|
for _, symbol := range coinSource.StaticCoins {
|
|
|
|
|
symbol = market.Normalize(symbol)
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"static"},
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-01-03 01:21:17 +08:00
|
|
|
return e.filterExcludedCoins(candidates), nil
|
|
|
|
|
}
|
2026-01-04 00:59:07 +08:00
|
|
|
coins, err := e.getAI500Coins(coinSource.AI500Limit)
|
2026-01-03 01:21:17 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2025-12-26 00:58:12 +08:00
|
|
|
}
|
2026-03-12 16:12:08 +08:00
|
|
|
// Empty list is a normal condition, return directly
|
2026-01-03 01:21:17 +08:00
|
|
|
return e.filterExcludedCoins(coins), nil
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
case "oi_top":
|
2026-03-12 16:12:08 +08:00
|
|
|
// Check use_oi_top flag; if false, fall back to static coins
|
2025-12-26 00:58:12 +08:00
|
|
|
if !coinSource.UseOITop {
|
|
|
|
|
logger.Infof("⚠️ source_type is 'oi_top' but use_oi_top is false, falling back to static coins")
|
|
|
|
|
for _, symbol := range coinSource.StaticCoins {
|
|
|
|
|
symbol = market.Normalize(symbol)
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"static"},
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-01-03 01:21:17 +08:00
|
|
|
return e.filterExcludedCoins(candidates), nil
|
|
|
|
|
}
|
|
|
|
|
coins, err := e.getOITopCoins(coinSource.OITopLimit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2025-12-26 00:58:12 +08:00
|
|
|
}
|
2026-03-12 16:12:08 +08:00
|
|
|
// Empty list is a normal condition, return directly
|
2026-01-03 01:21:17 +08:00
|
|
|
return e.filterExcludedCoins(coins), nil
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2026-01-23 20:16:30 +08:00
|
|
|
case "oi_low":
|
2026-03-12 16:12:08 +08:00
|
|
|
// OI decrease ranking, suitable for short positions
|
2026-01-23 20:16:30 +08:00
|
|
|
if !coinSource.UseOILow {
|
|
|
|
|
logger.Infof("⚠️ source_type is 'oi_low' but use_oi_low is false, falling back to static coins")
|
|
|
|
|
for _, symbol := range coinSource.StaticCoins {
|
|
|
|
|
symbol = market.Normalize(symbol)
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"static"},
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
return e.filterExcludedCoins(candidates), nil
|
|
|
|
|
}
|
|
|
|
|
coins, err := e.getOILowCoins(coinSource.OILowLimit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-03-12 16:12:08 +08:00
|
|
|
// Empty list is a normal condition, return directly
|
2026-01-23 20:16:30 +08:00
|
|
|
return e.filterExcludedCoins(coins), nil
|
|
|
|
|
|
2026-02-22 04:03:05 -05:00
|
|
|
case "hyper_all":
|
|
|
|
|
// All Hyperliquid perp coins
|
|
|
|
|
if !coinSource.UseHyperAll {
|
|
|
|
|
logger.Infof("⚠️ source_type is 'hyper_all' but use_hyper_all is false, falling back to static coins")
|
|
|
|
|
for _, symbol := range coinSource.StaticCoins {
|
|
|
|
|
symbol = market.Normalize(symbol)
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"static"},
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
return e.filterExcludedCoins(candidates), nil
|
|
|
|
|
}
|
|
|
|
|
coins, err := e.getHyperAllCoins()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return e.filterExcludedCoins(coins), nil
|
|
|
|
|
|
|
|
|
|
case "hyper_main":
|
|
|
|
|
// Top N Hyperliquid coins by 24h volume
|
|
|
|
|
if !coinSource.UseHyperMain {
|
|
|
|
|
logger.Infof("⚠️ source_type is 'hyper_main' but use_hyper_main is false, falling back to static coins")
|
|
|
|
|
for _, symbol := range coinSource.StaticCoins {
|
|
|
|
|
symbol = market.Normalize(symbol)
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"static"},
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
return e.filterExcludedCoins(candidates), nil
|
|
|
|
|
}
|
|
|
|
|
coins, err := e.getHyperMainCoins(coinSource.HyperMainLimit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return e.filterExcludedCoins(coins), nil
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
case "mixed":
|
2026-01-04 00:59:07 +08:00
|
|
|
if coinSource.UseAI500 {
|
|
|
|
|
poolCoins, err := e.getAI500Coins(coinSource.AI500Limit)
|
2025-12-10 14:40:08 +08:00
|
|
|
if err != nil {
|
2026-01-04 00:59:07 +08:00
|
|
|
logger.Infof("⚠️ Failed to get AI500 coins: %v", err)
|
2025-12-10 14:40:08 +08:00
|
|
|
} else {
|
|
|
|
|
for _, coin := range poolCoins {
|
|
|
|
|
symbolSources[coin.Symbol] = append(symbolSources[coin.Symbol], "ai500")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-11-11 09:18:39 +08:00
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
if coinSource.UseOITop {
|
|
|
|
|
oiCoins, err := e.getOITopCoins(coinSource.OITopLimit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Infof("⚠️ Failed to get OI Top: %v", err)
|
|
|
|
|
} else {
|
|
|
|
|
for _, coin := range oiCoins {
|
|
|
|
|
symbolSources[coin.Symbol] = append(symbolSources[coin.Symbol], "oi_top")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-23 20:16:30 +08:00
|
|
|
if coinSource.UseOILow {
|
|
|
|
|
oiLowCoins, err := e.getOILowCoins(coinSource.OILowLimit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Infof("⚠️ Failed to get OI Low: %v", err)
|
|
|
|
|
} else {
|
|
|
|
|
for _, coin := range oiLowCoins {
|
|
|
|
|
symbolSources[coin.Symbol] = append(symbolSources[coin.Symbol], "oi_low")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-22 04:03:05 -05:00
|
|
|
if coinSource.UseHyperAll {
|
|
|
|
|
hyperCoins, err := e.getHyperAllCoins()
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Infof("⚠️ Failed to get Hyperliquid All coins: %v", err)
|
|
|
|
|
} else {
|
|
|
|
|
for _, coin := range hyperCoins {
|
|
|
|
|
symbolSources[coin.Symbol] = append(symbolSources[coin.Symbol], "hyper_all")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if coinSource.UseHyperMain {
|
|
|
|
|
hyperMainCoins, err := e.getHyperMainCoins(coinSource.HyperMainLimit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Infof("⚠️ Failed to get Hyperliquid Main coins: %v", err)
|
|
|
|
|
} else {
|
|
|
|
|
for _, coin := range hyperMainCoins {
|
|
|
|
|
symbolSources[coin.Symbol] = append(symbolSources[coin.Symbol], "hyper_main")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
for _, symbol := range coinSource.StaticCoins {
|
|
|
|
|
symbol = market.Normalize(symbol)
|
|
|
|
|
if _, exists := symbolSources[symbol]; !exists {
|
|
|
|
|
symbolSources[symbol] = []string{"static"}
|
|
|
|
|
} else {
|
|
|
|
|
symbolSources[symbol] = append(symbolSources[symbol], "static")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for symbol, sources := range symbolSources {
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: sources,
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-01-03 01:21:17 +08:00
|
|
|
return e.filterExcludedCoins(candidates), nil
|
2025-12-10 14:40:08 +08:00
|
|
|
|
|
|
|
|
default:
|
|
|
|
|
return nil, fmt.Errorf("unknown coin source type: %s", coinSource.SourceType)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-03 01:21:17 +08:00
|
|
|
// filterExcludedCoins removes excluded coins from the candidates list
|
|
|
|
|
func (e *StrategyEngine) filterExcludedCoins(candidates []CandidateCoin) []CandidateCoin {
|
|
|
|
|
if len(e.config.CoinSource.ExcludedCoins) == 0 {
|
|
|
|
|
return candidates
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Build excluded set for O(1) lookup
|
|
|
|
|
excluded := make(map[string]bool)
|
|
|
|
|
for _, coin := range e.config.CoinSource.ExcludedCoins {
|
|
|
|
|
normalized := market.Normalize(coin)
|
|
|
|
|
excluded[normalized] = true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Filter out excluded coins
|
|
|
|
|
filtered := make([]CandidateCoin, 0, len(candidates))
|
|
|
|
|
for _, c := range candidates {
|
|
|
|
|
if !excluded[c.Symbol] {
|
|
|
|
|
filtered = append(filtered, c)
|
|
|
|
|
} else {
|
|
|
|
|
logger.Infof("🚫 Excluded coin: %s", c.Symbol)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return filtered
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
func (e *StrategyEngine) getAI500Coins(limit int) ([]CandidateCoin, error) {
|
2025-12-10 14:40:08 +08:00
|
|
|
if limit <= 0 {
|
|
|
|
|
limit = 30
|
2025-11-11 09:18:39 +08:00
|
|
|
}
|
|
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
symbols, err := e.nofxosClient.GetTopRatedCoins(limit)
|
2025-10-29 06:14:57 +08:00
|
|
|
if err != nil {
|
2025-12-10 14:40:08 +08:00
|
|
|
return nil, err
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
var candidates []CandidateCoin
|
|
|
|
|
for _, symbol := range symbols {
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"ai500"},
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
return candidates, nil
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
func (e *StrategyEngine) getOITopCoins(limit int) ([]CandidateCoin, error) {
|
|
|
|
|
if limit <= 0 {
|
2026-01-23 20:50:23 +08:00
|
|
|
limit = 10
|
2025-12-10 14:40:08 +08:00
|
|
|
}
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
positions, err := e.nofxosClient.GetOITopPositions()
|
2025-12-10 14:40:08 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
var candidates []CandidateCoin
|
|
|
|
|
for i, pos := range positions {
|
|
|
|
|
if i >= limit {
|
2025-10-29 06:14:57 +08:00
|
|
|
break
|
|
|
|
|
}
|
2025-12-10 14:40:08 +08:00
|
|
|
symbol := market.Normalize(pos.Symbol)
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"oi_top"},
|
|
|
|
|
})
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
2025-12-10 14:40:08 +08:00
|
|
|
return candidates, nil
|
|
|
|
|
}
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2026-01-23 20:16:30 +08:00
|
|
|
func (e *StrategyEngine) getOILowCoins(limit int) ([]CandidateCoin, error) {
|
|
|
|
|
if limit <= 0 {
|
2026-01-23 20:50:23 +08:00
|
|
|
limit = 10
|
2026-01-23 20:16:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
positions, err := e.nofxosClient.GetOILowPositions()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var candidates []CandidateCoin
|
|
|
|
|
for i, pos := range positions {
|
|
|
|
|
if i >= limit {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
symbol := market.Normalize(pos.Symbol)
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: symbol,
|
|
|
|
|
Sources: []string{"oi_low"},
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
return candidates, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-22 04:03:05 -05:00
|
|
|
// getHyperAllCoins returns all available Hyperliquid perpetual coins
|
|
|
|
|
func (e *StrategyEngine) getHyperAllCoins() ([]CandidateCoin, error) {
|
|
|
|
|
ctx := context.Background()
|
|
|
|
|
symbols, err := hyperliquid.GetAllCoinSymbols(ctx)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to get Hyperliquid coins: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var candidates []CandidateCoin
|
|
|
|
|
for _, symbol := range symbols {
|
|
|
|
|
// Add USDT suffix for compatibility
|
|
|
|
|
normalizedSymbol := market.Normalize(symbol + "USDT")
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: normalizedSymbol,
|
|
|
|
|
Sources: []string{"hyper_all"},
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
logger.Infof("✅ Loaded %d Hyperliquid coins (hyper_all)", len(candidates))
|
|
|
|
|
return candidates, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// getHyperMainCoins returns top N Hyperliquid coins by 24h volume
|
|
|
|
|
func (e *StrategyEngine) getHyperMainCoins(limit int) ([]CandidateCoin, error) {
|
|
|
|
|
if limit <= 0 {
|
|
|
|
|
limit = 20
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ctx := context.Background()
|
|
|
|
|
symbols, err := hyperliquid.GetMainCoinSymbols(ctx, limit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to get Hyperliquid main coins: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var candidates []CandidateCoin
|
|
|
|
|
for _, symbol := range symbols {
|
|
|
|
|
// Add USDT suffix for compatibility
|
|
|
|
|
normalizedSymbol := market.Normalize(symbol + "USDT")
|
|
|
|
|
candidates = append(candidates, CandidateCoin{
|
|
|
|
|
Symbol: normalizedSymbol,
|
|
|
|
|
Sources: []string{"hyper_main"},
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
logger.Infof("✅ Loaded %d Hyperliquid main coins (hyper_main) by 24h volume", len(candidates))
|
|
|
|
|
return candidates, nil
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
// ============================================================================
|
|
|
|
|
// External & Quant Data
|
|
|
|
|
// ============================================================================
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
// FetchMarketData fetches market data based on strategy configuration
|
|
|
|
|
func (e *StrategyEngine) FetchMarketData(symbol string) (*market.Data, error) {
|
|
|
|
|
return market.Get(symbol)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// FetchExternalData fetches external data sources
|
|
|
|
|
func (e *StrategyEngine) FetchExternalData() (map[string]interface{}, error) {
|
|
|
|
|
externalData := make(map[string]interface{})
|
|
|
|
|
|
|
|
|
|
for _, source := range e.config.Indicators.ExternalDataSources {
|
|
|
|
|
data, err := e.fetchSingleExternalSource(source)
|
2025-10-29 06:14:57 +08:00
|
|
|
if err != nil {
|
2025-12-10 14:40:08 +08:00
|
|
|
logger.Infof("⚠️ Failed to fetch external data source [%s]: %v", source.Name, err)
|
2025-10-29 06:14:57 +08:00
|
|
|
continue
|
|
|
|
|
}
|
2025-12-10 14:40:08 +08:00
|
|
|
externalData[source.Name] = data
|
|
|
|
|
}
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
return externalData, nil
|
|
|
|
|
}
|
2025-11-04 10:55:11 +08:00
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
func (e *StrategyEngine) fetchSingleExternalSource(source store.ExternalDataSource) (interface{}, error) {
|
fix: add SSRF protection for user-controlled URLs
- Add security/url_validator.go with ValidateURL, SafeHTTPClient, SafeGet
- Block private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16)
- Block cloud metadata endpoints (169.254.169.254, metadata.google.internal)
- Validate DNS resolution to prevent DNS rebinding attacks
- Check redirect destinations for SSRF
- Fix FetchQuantData, FetchOIRanking, fetchAI500, fetchOITop, fetchSingleExternalSource
2025-12-14 12:01:23 +08:00
|
|
|
// SSRF Protection: Validate URL before making request
|
|
|
|
|
if err := security.ValidateURL(source.URL); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("external source URL validation failed: %w", err)
|
2025-12-10 14:40:08 +08:00
|
|
|
}
|
fix: add SSRF protection for user-controlled URLs
- Add security/url_validator.go with ValidateURL, SafeHTTPClient, SafeGet
- Block private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16)
- Block cloud metadata endpoints (169.254.169.254, metadata.google.internal)
- Validate DNS resolution to prevent DNS rebinding attacks
- Check redirect destinations for SSRF
- Fix FetchQuantData, FetchOIRanking, fetchAI500, fetchOITop, fetchSingleExternalSource
2025-12-14 12:01:23 +08:00
|
|
|
|
|
|
|
|
timeout := time.Duration(source.RefreshSecs) * time.Second
|
|
|
|
|
if timeout == 0 {
|
|
|
|
|
timeout = 30 * time.Second
|
2025-12-10 14:40:08 +08:00
|
|
|
}
|
2025-10-29 06:14:57 +08:00
|
|
|
|
fix: add SSRF protection for user-controlled URLs
- Add security/url_validator.go with ValidateURL, SafeHTTPClient, SafeGet
- Block private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16)
- Block cloud metadata endpoints (169.254.169.254, metadata.google.internal)
- Validate DNS resolution to prevent DNS rebinding attacks
- Check redirect destinations for SSRF
- Fix FetchQuantData, FetchOIRanking, fetchAI500, fetchOITop, fetchSingleExternalSource
2025-12-14 12:01:23 +08:00
|
|
|
// Use SSRF-safe HTTP client
|
|
|
|
|
client := security.SafeHTTPClient(timeout)
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
req, err := http.NewRequest(source.Method, source.URL, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for k, v := range source.Headers {
|
|
|
|
|
req.Header.Set(k, v)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var result interface{}
|
|
|
|
|
if err := json.Unmarshal(body, &result); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if source.DataPath != "" {
|
|
|
|
|
result = extractJSONPath(result, source.DataPath)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func extractJSONPath(data interface{}, path string) interface{} {
|
|
|
|
|
parts := strings.Split(path, ".")
|
|
|
|
|
current := data
|
|
|
|
|
|
|
|
|
|
for _, part := range parts {
|
|
|
|
|
if m, ok := current.(map[string]interface{}); ok {
|
|
|
|
|
current = m[part]
|
|
|
|
|
} else {
|
|
|
|
|
return nil
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
return current
|
2025-10-29 06:14:57 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
// FetchQuantData fetches quantitative data for a single coin
|
|
|
|
|
func (e *StrategyEngine) FetchQuantData(symbol string) (*QuantData, error) {
|
2026-01-04 00:59:07 +08:00
|
|
|
if !e.config.Indicators.EnableQuantData {
|
2025-12-10 14:40:08 +08:00
|
|
|
return nil, nil
|
|
|
|
|
}
|
2025-11-05 00:27:47 +08:00
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
// Use nofxos client with unified API key
|
|
|
|
|
include := "oi,price"
|
|
|
|
|
if e.config.Indicators.EnableQuantNetflow {
|
|
|
|
|
include = "netflow,oi,price"
|
2025-11-05 00:27:47 +08:00
|
|
|
}
|
|
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
nofxosData, err := e.nofxosClient.GetCoinData(symbol, include)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to fetch quant data: %w", err)
|
2025-12-10 14:40:08 +08:00
|
|
|
}
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
if nofxosData == nil {
|
|
|
|
|
return nil, nil
|
2025-11-05 19:05:09 +08:00
|
|
|
}
|
|
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
// Convert nofxos.QuantData to kernel.QuantData
|
|
|
|
|
quantData := &QuantData{
|
|
|
|
|
Symbol: nofxosData.Symbol,
|
|
|
|
|
Price: nofxosData.Price,
|
|
|
|
|
PriceChange: nofxosData.PriceChange,
|
2025-12-10 14:40:08 +08:00
|
|
|
}
|
2025-11-05 19:05:09 +08:00
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
// Convert OI data
|
|
|
|
|
if nofxosData.OI != nil {
|
|
|
|
|
quantData.OI = make(map[string]*OIData)
|
|
|
|
|
for exchange, oiData := range nofxosData.OI {
|
|
|
|
|
if oiData != nil {
|
|
|
|
|
kData := &OIData{
|
|
|
|
|
CurrentOI: oiData.CurrentOI,
|
|
|
|
|
}
|
|
|
|
|
if oiData.Delta != nil {
|
|
|
|
|
kData.Delta = make(map[string]*OIDeltaData)
|
|
|
|
|
for dur, delta := range oiData.Delta {
|
|
|
|
|
if delta != nil {
|
|
|
|
|
kData.Delta[dur] = &OIDeltaData{
|
|
|
|
|
OIDelta: delta.OIDelta,
|
|
|
|
|
OIDeltaValue: delta.OIDeltaValue,
|
|
|
|
|
OIDeltaPercent: delta.OIDeltaPercent,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
quantData.OI[exchange] = kData
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-10-31 03:42:01 +08:00
|
|
|
}
|
2025-11-01 19:45:54 +08:00
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
// Convert Netflow data
|
|
|
|
|
if nofxosData.Netflow != nil {
|
|
|
|
|
quantData.Netflow = &NetflowData{}
|
|
|
|
|
if nofxosData.Netflow.Institution != nil {
|
|
|
|
|
quantData.Netflow.Institution = &FlowTypeData{
|
|
|
|
|
Future: nofxosData.Netflow.Institution.Future,
|
|
|
|
|
Spot: nofxosData.Netflow.Institution.Spot,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if nofxosData.Netflow.Personal != nil {
|
|
|
|
|
quantData.Netflow.Personal = &FlowTypeData{
|
|
|
|
|
Future: nofxosData.Netflow.Personal.Future,
|
|
|
|
|
Spot: nofxosData.Netflow.Personal.Spot,
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-12-10 14:40:08 +08:00
|
|
|
}
|
2025-11-01 19:45:54 +08:00
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
return quantData, nil
|
2025-10-31 03:42:01 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
// FetchQuantDataBatch batch fetches quantitative data
|
|
|
|
|
func (e *StrategyEngine) FetchQuantDataBatch(symbols []string) map[string]*QuantData {
|
|
|
|
|
result := make(map[string]*QuantData)
|
2025-10-29 06:14:57 +08:00
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
if !e.config.Indicators.EnableQuantData {
|
2025-12-10 14:40:08 +08:00
|
|
|
return result
|
2025-11-01 19:45:54 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:40:08 +08:00
|
|
|
for _, symbol := range symbols {
|
|
|
|
|
data, err := e.FetchQuantData(symbol)
|
2025-11-01 19:45:54 +08:00
|
|
|
if err != nil {
|
2025-12-10 14:40:08 +08:00
|
|
|
logger.Infof("⚠️ Failed to fetch quantitative data for %s: %v", symbol, err)
|
|
|
|
|
continue
|
2025-11-01 19:45:54 +08:00
|
|
|
}
|
2025-12-10 14:40:08 +08:00
|
|
|
if data != nil {
|
|
|
|
|
result[symbol] = data
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-12 16:08:21 +08:00
|
|
|
// FetchOIRankingData fetches market-wide OI ranking data
|
2026-01-04 00:59:07 +08:00
|
|
|
func (e *StrategyEngine) FetchOIRankingData() *nofxos.OIRankingData {
|
2025-12-12 16:08:21 +08:00
|
|
|
indicators := e.config.Indicators
|
|
|
|
|
if !indicators.EnableOIRanking {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
duration := indicators.OIRankingDuration
|
|
|
|
|
if duration == "" {
|
|
|
|
|
duration = "1h"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
limit := indicators.OIRankingLimit
|
|
|
|
|
if limit <= 0 {
|
|
|
|
|
limit = 10
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof("📊 Fetching OI ranking data (duration: %s, limit: %d)", duration, limit)
|
|
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
data, err := e.nofxosClient.GetOIRanking(duration, limit)
|
2025-12-12 16:08:21 +08:00
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf("⚠️ Failed to fetch OI ranking data: %v", err)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof("✓ OI ranking data ready: %d top, %d low positions",
|
|
|
|
|
len(data.TopPositions), len(data.LowPositions))
|
|
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-04 00:59:07 +08:00
|
|
|
// FetchNetFlowRankingData fetches market-wide NetFlow ranking data
|
|
|
|
|
func (e *StrategyEngine) FetchNetFlowRankingData() *nofxos.NetFlowRankingData {
|
|
|
|
|
indicators := e.config.Indicators
|
|
|
|
|
if !indicators.EnableNetFlowRanking {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
duration := indicators.NetFlowRankingDuration
|
|
|
|
|
if duration == "" {
|
|
|
|
|
duration = "1h"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
limit := indicators.NetFlowRankingLimit
|
|
|
|
|
if limit <= 0 {
|
|
|
|
|
limit = 10
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof("💰 Fetching NetFlow ranking data (duration: %s, limit: %d)", duration, limit)
|
|
|
|
|
|
|
|
|
|
data, err := e.nofxosClient.GetNetFlowRanking(duration, limit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf("⚠️ Failed to fetch NetFlow ranking data: %v", err)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof("✓ NetFlow ranking data ready: inst_in=%d, inst_out=%d, retail_in=%d, retail_out=%d",
|
|
|
|
|
len(data.InstitutionFutureTop), len(data.InstitutionFutureLow),
|
|
|
|
|
len(data.PersonalFutureTop), len(data.PersonalFutureLow))
|
|
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// FetchPriceRankingData fetches market-wide price ranking data (gainers/losers)
|
|
|
|
|
func (e *StrategyEngine) FetchPriceRankingData() *nofxos.PriceRankingData {
|
|
|
|
|
indicators := e.config.Indicators
|
|
|
|
|
if !indicators.EnablePriceRanking {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
durations := indicators.PriceRankingDuration
|
|
|
|
|
if durations == "" {
|
|
|
|
|
durations = "1h"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
limit := indicators.PriceRankingLimit
|
|
|
|
|
if limit <= 0 {
|
|
|
|
|
limit = 10
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof("📈 Fetching Price ranking data (durations: %s, limit: %d)", durations, limit)
|
|
|
|
|
|
|
|
|
|
data, err := e.nofxosClient.GetPriceRanking(durations, limit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf("⚠️ Failed to fetch Price ranking data: %v", err)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof("✓ Price ranking data ready for %d durations", len(data.Durations))
|
|
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-26 00:58:12 +08:00
|
|
|
// ============================================================================
|
|
|
|
|
// Helper Functions
|
|
|
|
|
// ============================================================================
|
|
|
|
|
|
|
|
|
|
// detectLanguage detects language from text content
|
|
|
|
|
// Returns LangChinese if text contains Chinese characters, otherwise LangEnglish
|
|
|
|
|
func detectLanguage(text string) Language {
|
|
|
|
|
for _, r := range text {
|
|
|
|
|
if r >= 0x4E00 && r <= 0x9FFF {
|
|
|
|
|
return LangChinese
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return LangEnglish
|
|
|
|
|
}
|