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
---------
This commit is contained in:
tinkle-community
2025-12-06 01:04:26 +08:00
parent 010676c591
commit f4ece051e7
87 changed files with 6870 additions and 10584 deletions
+48 -48
View File
@@ -12,71 +12,71 @@ import (
)
func main() {
log.Println("🔄 開始遷移數據庫到加密格式...")
log.Println("🔄 开始迁移数据库到加密格式...")
// 1. 檢查數據庫檔案
dbPath := "config.db"
// 1. 检查数据库文件
dbPath := "data.db"
if len(os.Args) > 1 {
dbPath = os.Args[1]
}
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
log.Fatalf("❌ 數據庫檔案不存在: %s", dbPath)
log.Fatalf("❌ 数据库文件不存在: %s", dbPath)
}
// 2. 備份數據庫
// 2. 备份数据库
backupPath := fmt.Sprintf("%s.pre_encryption_backup", dbPath)
log.Printf("📦 備份數據庫到: %s", backupPath)
log.Printf("📦 备份数据库到: %s", backupPath)
input, err := os.ReadFile(dbPath)
if err != nil {
log.Fatalf("❌ 讀取數據庫失敗: %v", err)
log.Fatalf("❌ 读取数据库失败: %v", err)
}
if err := os.WriteFile(backupPath, input, 0600); err != nil {
log.Fatalf("❌ 份失: %v", err)
log.Fatalf("❌ 份失: %v", err)
}
// 3. 打開數據庫
// 3. 打开数据库
db, err := sql.Open("sqlite", dbPath)
if err != nil {
log.Fatalf("❌ 打開數據庫失敗: %v", err)
log.Fatalf("❌ 打开数据库失败: %v", err)
}
defer db.Close()
// 4. 初始化加密管理器
em, err := crypto.GetEncryptionManager()
// 4. 初始化 CryptoService(从环境变量加载密钥)
cs, err := crypto.NewCryptoService()
if err != nil {
log.Fatalf("❌ 初始化加密管理器失敗: %v", err)
log.Fatalf("❌ 初始化加密服务失败: %v", err)
}
// 5. 移交易所配置
if err := migrateExchanges(db, em); err != nil {
log.Fatalf("❌ 移交易所配置失: %v", err)
// 5. 移交易所配置
if err := migrateExchanges(db, cs); err != nil {
log.Fatalf("❌ 移交易所配置失: %v", err)
}
// 6. 移 AI 模型配置
if err := migrateAIModels(db, em); err != nil {
log.Fatalf("❌ 移 AI 模型配置失: %v", err)
// 6. 移 AI 模型配置
if err := migrateAIModels(db, cs); err != nil {
log.Fatalf("❌ 移 AI 模型配置失: %v", err)
}
log.Println("✅ 數據遷移完成!")
log.Printf("📝 原始數據備份位: %s", backupPath)
log.Println("⚠️ 請驗證系統功能正常,手動刪除備份檔案")
log.Println("✅ 数据迁移完成!")
log.Printf("📝 原始数据备份位: %s", backupPath)
log.Println("⚠️ 请验证系统功能正常,手动删除备份文件")
}
// migrateExchanges 移交易所配置
func migrateExchanges(db *sql.DB, em *crypto.EncryptionManager) error {
log.Println("🔄 移交易所配置...")
// migrateExchanges 移交易所配置
func migrateExchanges(db *sql.DB, cs *crypto.CryptoService) error {
log.Println("🔄 移交易所配置...")
// 查所有未加密的記錄(假設加密數據都包含 '==' Base64 特徵
// 查所有未加密的记录(加密数据以 ENC:v1: 开头
rows, err := db.Query(`
SELECT user_id, id, api_key, secret_key,
COALESCE(hyperliquid_private_key, ''),
COALESCE(aster_private_key, '')
FROM exchanges
WHERE (api_key != '' AND api_key NOT LIKE '%==%')
OR (secret_key != '' AND secret_key NOT LIKE '%==%')
WHERE (api_key != '' AND api_key NOT LIKE 'ENC:v1:%')
OR (secret_key != '' AND secret_key NOT LIKE 'ENC:v1:%')
`)
if err != nil {
return err
@@ -96,34 +96,34 @@ func migrateExchanges(db *sql.DB, em *crypto.EncryptionManager) error {
return err
}
// 加密每字段
encAPIKey, err := em.EncryptForDatabase(apiKey)
// 加密每字段
encAPIKey, err := cs.EncryptForStorage(apiKey)
if err != nil {
return fmt.Errorf("加密 API Key 失: %w", err)
return fmt.Errorf("加密 API Key 失: %w", err)
}
encSecretKey, err := em.EncryptForDatabase(secretKey)
encSecretKey, err := cs.EncryptForStorage(secretKey)
if err != nil {
return fmt.Errorf("加密 Secret Key 失: %w", err)
return fmt.Errorf("加密 Secret Key 失: %w", err)
}
encHLPrivateKey := ""
if hlPrivateKey != "" {
encHLPrivateKey, err = em.EncryptForDatabase(hlPrivateKey)
encHLPrivateKey, err = cs.EncryptForStorage(hlPrivateKey)
if err != nil {
return fmt.Errorf("加密 Hyperliquid Private Key 失: %w", err)
return fmt.Errorf("加密 Hyperliquid Private Key 失: %w", err)
}
}
encAsterPrivateKey := ""
if asterPrivateKey != "" {
encAsterPrivateKey, err = em.EncryptForDatabase(asterPrivateKey)
encAsterPrivateKey, err = cs.EncryptForStorage(asterPrivateKey)
if err != nil {
return fmt.Errorf("加密 Aster Private Key 失: %w", err)
return fmt.Errorf("加密 Aster Private Key 失: %w", err)
}
}
// 更新數據庫
// 更新数据库
_, err = tx.Exec(`
UPDATE exchanges
SET api_key = ?, secret_key = ?,
@@ -132,7 +132,7 @@ func migrateExchanges(db *sql.DB, em *crypto.EncryptionManager) error {
`, encAPIKey, encSecretKey, encHLPrivateKey, encAsterPrivateKey, userID, exchangeID)
if err != nil {
return fmt.Errorf("更新數據庫失敗: %w", err)
return fmt.Errorf("更新数据库失败: %w", err)
}
log.Printf(" ✓ 已加密: [%s] %s", userID, exchangeID)
@@ -143,18 +143,18 @@ func migrateExchanges(db *sql.DB, em *crypto.EncryptionManager) error {
return err
}
log.Printf("✅ 已移 %d 交易所配置", count)
log.Printf("✅ 已移 %d 交易所配置", count)
return nil
}
// migrateAIModels 移 AI 模型配置
func migrateAIModels(db *sql.DB, em *crypto.EncryptionManager) error {
log.Println("🔄 移 AI 模型配置...")
// migrateAIModels 移 AI 模型配置
func migrateAIModels(db *sql.DB, cs *crypto.CryptoService) error {
log.Println("🔄 移 AI 模型配置...")
rows, err := db.Query(`
SELECT user_id, id, api_key
FROM ai_models
WHERE api_key != '' AND api_key NOT LIKE '%==%'
WHERE api_key != '' AND api_key NOT LIKE 'ENC:v1:%'
`)
if err != nil {
return err
@@ -174,9 +174,9 @@ func migrateAIModels(db *sql.DB, em *crypto.EncryptionManager) error {
return err
}
encAPIKey, err := em.EncryptForDatabase(apiKey)
encAPIKey, err := cs.EncryptForStorage(apiKey)
if err != nil {
return fmt.Errorf("加密 API Key 失: %w", err)
return fmt.Errorf("加密 API Key 失: %w", err)
}
_, err = tx.Exec(`
@@ -184,7 +184,7 @@ func migrateAIModels(db *sql.DB, em *crypto.EncryptionManager) error {
`, encAPIKey, userID, modelID)
if err != nil {
return fmt.Errorf("更新數據庫失敗: %w", err)
return fmt.Errorf("更新数据库失败: %w", err)
}
log.Printf(" ✓ 已加密: [%s] %s", userID, modelID)
@@ -195,6 +195,6 @@ func migrateAIModels(db *sql.DB, em *crypto.EncryptionManager) error {
return err
}
log.Printf("✅ 已移 %d AI 模型配置", count)
log.Printf("✅ 已移 %d AI 模型配置", count)
return nil
}