mirror of
https://github.com/laoxong/nofx.git
synced 2026-06-04 01:48:22 +08:00
f4ece051e7
* 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 ---------
371 lines
10 KiB
Go
371 lines
10 KiB
Go
package trader
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"nofx/logger"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/elliottech/lighter-go/types"
|
|
)
|
|
|
|
// SetStopLoss 設置止損單(實現 Trader 接口)
|
|
func (t *LighterTraderV2) SetStopLoss(symbol string, positionSide string, quantity, stopPrice float64) error {
|
|
if t.txClient == nil {
|
|
return fmt.Errorf("TxClient 未初始化")
|
|
}
|
|
|
|
logger.Infof("🛑 LIGHTER 設置止損: %s %s qty=%.4f, stop=%.2f", symbol, positionSide, quantity, stopPrice)
|
|
|
|
// 確定訂單方向(做空止損用買單,做多止損用賣單)
|
|
isAsk := (positionSide == "LONG" || positionSide == "long")
|
|
|
|
// 創建限價止損單
|
|
_, err := t.CreateOrder(symbol, isAsk, quantity, stopPrice, "limit")
|
|
if err != nil {
|
|
return fmt.Errorf("設置止損失敗: %w", err)
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER 止損已設置: %.2f", stopPrice)
|
|
return nil
|
|
}
|
|
|
|
// SetTakeProfit 設置止盈單(實現 Trader 接口)
|
|
func (t *LighterTraderV2) SetTakeProfit(symbol string, positionSide string, quantity, takeProfitPrice float64) error {
|
|
if t.txClient == nil {
|
|
return fmt.Errorf("TxClient 未初始化")
|
|
}
|
|
|
|
logger.Infof("🎯 LIGHTER 設置止盈: %s %s qty=%.4f, tp=%.2f", symbol, positionSide, quantity, takeProfitPrice)
|
|
|
|
// 確定訂單方向(做空止盈用買單,做多止盈用賣單)
|
|
isAsk := (positionSide == "LONG" || positionSide == "long")
|
|
|
|
// 創建限價止盈單
|
|
_, err := t.CreateOrder(symbol, isAsk, quantity, takeProfitPrice, "limit")
|
|
if err != nil {
|
|
return fmt.Errorf("設置止盈失敗: %w", err)
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER 止盈已設置: %.2f", takeProfitPrice)
|
|
return nil
|
|
}
|
|
|
|
// CancelAllOrders 取消所有訂單(實現 Trader 接口)
|
|
func (t *LighterTraderV2) CancelAllOrders(symbol string) error {
|
|
if t.txClient == nil {
|
|
return fmt.Errorf("TxClient 未初始化")
|
|
}
|
|
|
|
if err := t.ensureAuthToken(); err != nil {
|
|
return fmt.Errorf("認證令牌無效: %w", err)
|
|
}
|
|
|
|
// 獲取所有活躍訂單
|
|
orders, err := t.GetActiveOrders(symbol)
|
|
if err != nil {
|
|
return fmt.Errorf("獲取活躍訂單失敗: %w", err)
|
|
}
|
|
|
|
if len(orders) == 0 {
|
|
logger.Infof("✓ LIGHTER - 無需取消訂單(無活躍訂單)")
|
|
return nil
|
|
}
|
|
|
|
// 批量取消
|
|
canceledCount := 0
|
|
for _, order := range orders {
|
|
if err := t.CancelOrder(symbol, order.OrderID); err != nil {
|
|
logger.Infof("⚠️ 取消訂單失敗 (ID: %s): %v", order.OrderID, err)
|
|
} else {
|
|
canceledCount++
|
|
}
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER - 已取消 %d 個訂單", canceledCount)
|
|
return nil
|
|
}
|
|
|
|
// GetOrderStatus 獲取訂單狀態(實現 Trader 接口)
|
|
func (t *LighterTraderV2) GetOrderStatus(symbol string, orderID string) (map[string]interface{}, error) {
|
|
// LIGHTER 使用市價單通常立即成交
|
|
// 嘗試查詢訂單狀態
|
|
if err := t.ensureAuthToken(); err != nil {
|
|
return nil, fmt.Errorf("認證令牌無效: %w", err)
|
|
}
|
|
|
|
// 構建請求 URL
|
|
endpoint := fmt.Sprintf("%s/api/v1/order/%s", t.baseURL, orderID)
|
|
|
|
req, err := http.NewRequest("GET", endpoint, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req.Header.Set("Authorization", t.authToken)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := t.client.Do(req)
|
|
if err != nil {
|
|
// 如果查詢失敗,假設訂單已完成
|
|
return map[string]interface{}{
|
|
"orderId": orderID,
|
|
"status": "FILLED",
|
|
"avgPrice": 0.0,
|
|
"executedQty": 0.0,
|
|
"commission": 0.0,
|
|
}, nil
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return map[string]interface{}{
|
|
"orderId": orderID,
|
|
"status": "FILLED",
|
|
"avgPrice": 0.0,
|
|
"executedQty": 0.0,
|
|
"commission": 0.0,
|
|
}, nil
|
|
}
|
|
|
|
var order OrderResponse
|
|
if err := json.Unmarshal(body, &order); err != nil {
|
|
return map[string]interface{}{
|
|
"orderId": orderID,
|
|
"status": "FILLED",
|
|
"avgPrice": 0.0,
|
|
"executedQty": 0.0,
|
|
"commission": 0.0,
|
|
}, nil
|
|
}
|
|
|
|
// 轉換狀態為統一格式
|
|
unifiedStatus := order.Status
|
|
switch order.Status {
|
|
case "filled":
|
|
unifiedStatus = "FILLED"
|
|
case "open":
|
|
unifiedStatus = "NEW"
|
|
case "cancelled":
|
|
unifiedStatus = "CANCELED"
|
|
}
|
|
|
|
return map[string]interface{}{
|
|
"orderId": order.OrderID,
|
|
"status": unifiedStatus,
|
|
"avgPrice": order.Price,
|
|
"executedQty": order.FilledQty,
|
|
"commission": 0.0,
|
|
}, nil
|
|
}
|
|
|
|
// CancelStopLossOrders 僅取消止損單(實現 Trader 接口)
|
|
func (t *LighterTraderV2) CancelStopLossOrders(symbol string) error {
|
|
// LIGHTER 暫時無法區分止損和止盈單,取消所有止盈止損單
|
|
logger.Infof("⚠️ LIGHTER 無法區分止損/止盈單,將取消所有止盈止損單")
|
|
return t.CancelStopOrders(symbol)
|
|
}
|
|
|
|
// CancelTakeProfitOrders 僅取消止盈單(實現 Trader 接口)
|
|
func (t *LighterTraderV2) CancelTakeProfitOrders(symbol string) error {
|
|
// LIGHTER 暫時無法區分止損和止盈單,取消所有止盈止損單
|
|
logger.Infof("⚠️ LIGHTER 無法區分止損/止盈單,將取消所有止盈止損單")
|
|
return t.CancelStopOrders(symbol)
|
|
}
|
|
|
|
// CancelStopOrders 取消該幣種的止盈/止損單(實現 Trader 接口)
|
|
func (t *LighterTraderV2) CancelStopOrders(symbol string) error {
|
|
if t.txClient == nil {
|
|
return fmt.Errorf("TxClient 未初始化")
|
|
}
|
|
|
|
if err := t.ensureAuthToken(); err != nil {
|
|
return fmt.Errorf("認證令牌無效: %w", err)
|
|
}
|
|
|
|
// 獲取活躍訂單
|
|
orders, err := t.GetActiveOrders(symbol)
|
|
if err != nil {
|
|
return fmt.Errorf("獲取活躍訂單失敗: %w", err)
|
|
}
|
|
|
|
canceledCount := 0
|
|
for _, order := range orders {
|
|
// TODO: 檢查訂單類型,只取消止盈止損單
|
|
// 暫時取消所有訂單
|
|
if err := t.CancelOrder(symbol, order.OrderID); err != nil {
|
|
logger.Infof("⚠️ 取消訂單失敗 (ID: %s): %v", order.OrderID, err)
|
|
} else {
|
|
canceledCount++
|
|
}
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER - 已取消 %d 個止盈止損單", canceledCount)
|
|
return nil
|
|
}
|
|
|
|
// GetActiveOrders 獲取活躍訂單
|
|
func (t *LighterTraderV2) GetActiveOrders(symbol string) ([]OrderResponse, error) {
|
|
if err := t.ensureAuthToken(); err != nil {
|
|
return nil, fmt.Errorf("認證令牌無效: %w", err)
|
|
}
|
|
|
|
// 獲取市場索引
|
|
marketIndex, err := t.getMarketIndex(symbol)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("獲取市場索引失敗: %w", err)
|
|
}
|
|
|
|
// 構建請求 URL
|
|
endpoint := fmt.Sprintf("%s/api/v1/accountActiveOrders?account_index=%d&market_id=%d",
|
|
t.baseURL, t.accountIndex, marketIndex)
|
|
|
|
// 發送 GET 請求
|
|
req, err := http.NewRequest("GET", endpoint, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("創建請求失敗: %w", err)
|
|
}
|
|
|
|
// 添加認證頭
|
|
req.Header.Set("Authorization", t.authToken)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := t.client.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("請求失敗: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("讀取響應失敗: %w", err)
|
|
}
|
|
|
|
// 解析響應
|
|
var apiResp struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data []OrderResponse `json:"data"`
|
|
}
|
|
|
|
if err := json.Unmarshal(body, &apiResp); err != nil {
|
|
return nil, fmt.Errorf("解析響應失敗: %w, body: %s", err, string(body))
|
|
}
|
|
|
|
if apiResp.Code != 200 {
|
|
return nil, fmt.Errorf("獲取活躍訂單失敗 (code %d): %s", apiResp.Code, apiResp.Message)
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER - 獲取到 %d 個活躍訂單", len(apiResp.Data))
|
|
return apiResp.Data, nil
|
|
}
|
|
|
|
// CancelOrder 取消單個訂單
|
|
func (t *LighterTraderV2) CancelOrder(symbol, orderID string) error {
|
|
if t.txClient == nil {
|
|
return fmt.Errorf("TxClient 未初始化")
|
|
}
|
|
|
|
// 獲取市場索引
|
|
marketIndex, err := t.getMarketIndex(symbol)
|
|
if err != nil {
|
|
return fmt.Errorf("獲取市場索引失敗: %w", err)
|
|
}
|
|
|
|
// 將 orderID 轉換為 int64
|
|
orderIndex, err := strconv.ParseInt(orderID, 10, 64)
|
|
if err != nil {
|
|
return fmt.Errorf("無效的訂單ID: %w", err)
|
|
}
|
|
|
|
// 構建取消訂單請求
|
|
txReq := &types.CancelOrderTxReq{
|
|
MarketIndex: marketIndex,
|
|
Index: orderIndex,
|
|
}
|
|
|
|
// 使用 SDK 簽名交易
|
|
nonce := int64(-1) // -1 表示自動獲取
|
|
tx, err := t.txClient.GetCancelOrderTransaction(txReq, &types.TransactOpts{
|
|
Nonce: &nonce,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("簽名取消訂單失敗: %w", err)
|
|
}
|
|
|
|
// 序列化交易
|
|
txBytes, err := json.Marshal(tx)
|
|
if err != nil {
|
|
return fmt.Errorf("序列化交易失敗: %w", err)
|
|
}
|
|
|
|
// 提交取消訂單到 LIGHTER API
|
|
_, err = t.submitCancelOrder(txBytes)
|
|
if err != nil {
|
|
return fmt.Errorf("提交取消訂單失敗: %w", err)
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER訂單已取消 - ID: %s", orderID)
|
|
return nil
|
|
}
|
|
|
|
// submitCancelOrder 提交已簽名的取消訂單到 LIGHTER API
|
|
func (t *LighterTraderV2) submitCancelOrder(signedTx []byte) (map[string]interface{}, error) {
|
|
const TX_TYPE_CANCEL_ORDER = 15
|
|
|
|
// 構建請求
|
|
req := SendTxRequest{
|
|
TxType: TX_TYPE_CANCEL_ORDER,
|
|
TxInfo: string(signedTx),
|
|
PriceProtection: false, // 取消訂單不需要價格保護
|
|
}
|
|
|
|
reqBody, err := json.Marshal(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("序列化請求失敗: %w", err)
|
|
}
|
|
|
|
// 發送 POST 請求到 /api/v1/sendTx
|
|
endpoint := fmt.Sprintf("%s/api/v1/sendTx", t.baseURL)
|
|
httpReq, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(reqBody))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
httpReq.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := t.client.Do(httpReq)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 解析響應
|
|
var sendResp SendTxResponse
|
|
if err := json.Unmarshal(body, &sendResp); err != nil {
|
|
return nil, fmt.Errorf("解析響應失敗: %w, body: %s", err, string(body))
|
|
}
|
|
|
|
// 檢查響應碼
|
|
if sendResp.Code != 200 {
|
|
return nil, fmt.Errorf("提交取消訂單失敗 (code %d): %s", sendResp.Code, sendResp.Message)
|
|
}
|
|
|
|
result := map[string]interface{}{
|
|
"tx_hash": sendResp.Data["tx_hash"],
|
|
"status": "cancelled",
|
|
}
|
|
|
|
logger.Infof("✓ 取消訂單已提交到 LIGHTER - tx_hash: %v", sendResp.Data["tx_hash"])
|
|
return result, nil
|
|
}
|