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 ---------
324 lines
8.6 KiB
Go
324 lines
8.6 KiB
Go
package trader
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"nofx/logger"
|
|
"net/http"
|
|
)
|
|
|
|
// CreateOrderRequest 创建订单请求
|
|
type CreateOrderRequest struct {
|
|
Symbol string `json:"symbol"` // 交易对,如 "BTC-PERP"
|
|
Side string `json:"side"` // "buy" 或 "sell"
|
|
OrderType string `json:"order_type"` // "market" 或 "limit"
|
|
Quantity float64 `json:"quantity"` // 数量
|
|
Price float64 `json:"price"` // 价格(限价单必填)
|
|
ReduceOnly bool `json:"reduce_only"` // 是否只减仓
|
|
TimeInForce string `json:"time_in_force"` // "GTC", "IOC", "FOK"
|
|
PostOnly bool `json:"post_only"` // 是否只做Maker
|
|
}
|
|
|
|
// OrderResponse 订单响应
|
|
type OrderResponse struct {
|
|
OrderID string `json:"order_id"`
|
|
Symbol string `json:"symbol"`
|
|
Side string `json:"side"`
|
|
OrderType string `json:"order_type"`
|
|
Quantity float64 `json:"quantity"`
|
|
Price float64 `json:"price"`
|
|
Status string `json:"status"` // "open", "filled", "cancelled"
|
|
FilledQty float64 `json:"filled_qty"`
|
|
RemainingQty float64 `json:"remaining_qty"`
|
|
CreateTime int64 `json:"create_time"`
|
|
}
|
|
|
|
// CreateOrder 创建订单(市价或限价)
|
|
func (t *LighterTrader) CreateOrder(symbol, side string, quantity, price float64, orderType string) (string, error) {
|
|
if err := t.ensureAuthToken(); err != nil {
|
|
return "", fmt.Errorf("认证令牌无效: %w", err)
|
|
}
|
|
|
|
// 构建订单请求
|
|
req := CreateOrderRequest{
|
|
Symbol: symbol,
|
|
Side: side,
|
|
OrderType: orderType,
|
|
Quantity: quantity,
|
|
ReduceOnly: false,
|
|
TimeInForce: "GTC",
|
|
PostOnly: false,
|
|
}
|
|
|
|
if orderType == "limit" {
|
|
req.Price = price
|
|
}
|
|
|
|
// 发送订单
|
|
orderResp, err := t.sendOrder(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER订单已创建 - ID: %s, Symbol: %s, Side: %s, Qty: %.4f",
|
|
orderResp.OrderID, symbol, side, quantity)
|
|
|
|
return orderResp.OrderID, nil
|
|
}
|
|
|
|
// sendOrder 发送订单到LIGHTER API
|
|
func (t *LighterTrader) sendOrder(orderReq CreateOrderRequest) (*OrderResponse, error) {
|
|
endpoint := fmt.Sprintf("%s/api/v1/order", t.baseURL)
|
|
|
|
// 序列化请求
|
|
jsonData, err := json.Marshal(orderReq)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 创建HTTP请求
|
|
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonData))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 添加请求头
|
|
req.Header.Set("Content-Type", "application/json")
|
|
t.accountMutex.RLock()
|
|
req.Header.Set("Authorization", t.authToken)
|
|
t.accountMutex.RUnlock()
|
|
|
|
// 发送请求
|
|
resp, err := t.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
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("创建订单失败 (status %d): %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
var orderResp OrderResponse
|
|
if err := json.Unmarshal(body, &orderResp); err != nil {
|
|
return nil, fmt.Errorf("解析订单响应失败: %w", err)
|
|
}
|
|
|
|
return &orderResp, nil
|
|
}
|
|
|
|
// CancelOrder 取消订单
|
|
func (t *LighterTrader) CancelOrder(symbol, orderID string) error {
|
|
if err := t.ensureAuthToken(); err != nil {
|
|
return fmt.Errorf("认证令牌无效: %w", err)
|
|
}
|
|
|
|
endpoint := fmt.Sprintf("%s/api/v1/order/%s", t.baseURL, orderID)
|
|
|
|
req, err := http.NewRequest("DELETE", endpoint, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 添加认证头
|
|
t.accountMutex.RLock()
|
|
req.Header.Set("Authorization", t.authToken)
|
|
t.accountMutex.RUnlock()
|
|
|
|
resp, err := t.client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
return fmt.Errorf("取消订单失败 (status %d): %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER订单已取消 - ID: %s", orderID)
|
|
return nil
|
|
}
|
|
|
|
// CancelAllOrders 取消所有订单
|
|
func (t *LighterTrader) CancelAllOrders(symbol string) error {
|
|
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
|
|
}
|
|
|
|
// 批量取消
|
|
for _, order := range orders {
|
|
if err := t.CancelOrder(symbol, order.OrderID); err != nil {
|
|
logger.Infof("⚠️ 取消订单失败 (ID: %s): %v", order.OrderID, err)
|
|
}
|
|
}
|
|
|
|
logger.Infof("✓ LIGHTER - 已取消 %d 个订单", len(orders))
|
|
return nil
|
|
}
|
|
|
|
// GetActiveOrders 获取活跃订单
|
|
func (t *LighterTrader) GetActiveOrders(symbol string) ([]OrderResponse, error) {
|
|
if err := t.ensureAuthToken(); err != nil {
|
|
return nil, fmt.Errorf("认证令牌无效: %w", err)
|
|
}
|
|
|
|
t.accountMutex.RLock()
|
|
accountIndex := t.accountIndex
|
|
t.accountMutex.RUnlock()
|
|
|
|
endpoint := fmt.Sprintf("%s/api/v1/order/active?account_index=%d", t.baseURL, accountIndex)
|
|
if symbol != "" {
|
|
endpoint += fmt.Sprintf("&symbol=%s", symbol)
|
|
}
|
|
|
|
req, err := http.NewRequest("GET", endpoint, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 添加认证头
|
|
t.accountMutex.RLock()
|
|
req.Header.Set("Authorization", t.authToken)
|
|
t.accountMutex.RUnlock()
|
|
|
|
resp, err := t.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
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("获取活跃订单失败 (status %d): %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
var orders []OrderResponse
|
|
if err := json.Unmarshal(body, &orders); err != nil {
|
|
return nil, fmt.Errorf("解析订单列表失败: %w", err)
|
|
}
|
|
|
|
return orders, nil
|
|
}
|
|
|
|
// GetOrderStatus 获取订单状态(实现 Trader 接口)
|
|
func (t *LighterTrader) GetOrderStatus(symbol string, orderID string) (map[string]interface{}, error) {
|
|
if err := t.ensureAuthToken(); err != nil {
|
|
return nil, fmt.Errorf("认证令牌无效: %w", err)
|
|
}
|
|
|
|
endpoint := fmt.Sprintf("%s/api/v1/order/%s", t.baseURL, orderID)
|
|
|
|
req, err := http.NewRequest("GET", endpoint, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 添加认证头
|
|
t.accountMutex.RLock()
|
|
req.Header.Set("Authorization", t.authToken)
|
|
t.accountMutex.RUnlock()
|
|
|
|
resp, err := t.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
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("获取订单状态失败 (status %d): %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
var order OrderResponse
|
|
if err := json.Unmarshal(body, &order); err != nil {
|
|
return nil, fmt.Errorf("解析订单响应失败: %w", err)
|
|
}
|
|
|
|
// 转换状态为统一格式
|
|
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 仅取消止损单(LIGHTER 暂无法区分,取消所有止盈止损单)
|
|
func (t *LighterTrader) CancelStopLossOrders(symbol string) error {
|
|
// LIGHTER 暂时无法区分止损和止盈单,取消所有止盈止损单
|
|
logger.Infof(" ⚠️ LIGHTER 无法区分止损/止盈单,将取消所有止盈止损单")
|
|
return t.CancelStopOrders(symbol)
|
|
}
|
|
|
|
// CancelTakeProfitOrders 仅取消止盈单(LIGHTER 暂无法区分,取消所有止盈止损单)
|
|
func (t *LighterTrader) CancelTakeProfitOrders(symbol string) error {
|
|
// LIGHTER 暂时无法区分止损和止盈单,取消所有止盈止损单
|
|
logger.Infof(" ⚠️ LIGHTER 无法区分止损/止盈单,将取消所有止盈止损单")
|
|
return t.CancelStopOrders(symbol)
|
|
}
|
|
|
|
// CancelStopOrders 取消该币种的止盈/止损单
|
|
func (t *LighterTrader) CancelStopOrders(symbol string) error {
|
|
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
|
|
}
|