Files
nofx/trader/lighter_trader.go
T
tinkle-community f4ece051e7 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

216 lines
5.6 KiB
Go

package trader
import (
"context"
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"nofx/logger"
"net/http"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/crypto"
)
// LighterTrader LIGHTER DEX交易器
// LIGHTER是基于Ethereum L2的永续合约DEX,使用zk-rollup技术
type LighterTrader struct {
ctx context.Context
privateKey *ecdsa.PrivateKey
walletAddr string // Ethereum钱包地址
client *http.Client
baseURL string
testnet bool
// 账户信息缓存
accountIndex int // LIGHTER账户索引
apiKey string // API密钥(从私钥派生)
authToken string // 认证令牌(8小时有效期)
tokenExpiry time.Time
accountMutex sync.RWMutex
// 市场信息缓存
symbolPrecision map[string]SymbolPrecision
precisionMutex sync.RWMutex
}
// LighterConfig LIGHTER配置
type LighterConfig struct {
PrivateKeyHex string
WalletAddr string
Testnet bool
}
// NewLighterTrader 创建LIGHTER交易器
func NewLighterTrader(privateKeyHex string, walletAddr string, testnet bool) (*LighterTrader, error) {
// 去掉私钥的 0x 前缀(如果有)
privateKeyHex = strings.TrimPrefix(strings.ToLower(privateKeyHex), "0x")
// 解析私钥
privateKey, err := crypto.HexToECDSA(privateKeyHex)
if err != nil {
return nil, fmt.Errorf("解析私钥失败: %w", err)
}
// 从私钥派生钱包地址(如果未提供)
if walletAddr == "" {
walletAddr = crypto.PubkeyToAddress(*privateKey.Public().(*ecdsa.PublicKey)).Hex()
logger.Infof("✓ 从私钥派生钱包地址: %s", walletAddr)
}
// 选择API URL
baseURL := "https://mainnet.zklighter.elliot.ai"
if testnet {
baseURL = "https://testnet.zklighter.elliot.ai" // TODO: 确认testnet URL
}
trader := &LighterTrader{
ctx: context.Background(),
privateKey: privateKey,
walletAddr: walletAddr,
client: &http.Client{Timeout: 30 * time.Second},
baseURL: baseURL,
testnet: testnet,
symbolPrecision: make(map[string]SymbolPrecision),
}
logger.Infof("✓ LIGHTER交易器初始化成功 (testnet=%v, wallet=%s)", testnet, walletAddr)
// 初始化账户信息(获取账户索引和API密钥)
if err := trader.initializeAccount(); err != nil {
return nil, fmt.Errorf("初始化账户失败: %w", err)
}
return trader, nil
}
// initializeAccount 初始化账户信息
func (t *LighterTrader) initializeAccount() error {
// 1. 获取账户信息(通过L1地址)
accountInfo, err := t.getAccountByL1Address()
if err != nil {
return fmt.Errorf("获取账户信息失败: %w", err)
}
t.accountMutex.Lock()
t.accountIndex = accountInfo["index"].(int)
t.accountMutex.Unlock()
logger.Infof("✓ LIGHTER账户索引: %d", t.accountIndex)
// 2. 生成认证令牌(有效期8小时)
if err := t.refreshAuthToken(); err != nil {
return fmt.Errorf("生成认证令牌失败: %w", err)
}
return nil
}
// getAccountByL1Address 通过Ethereum地址获取LIGHTER账户信息
func (t *LighterTrader) getAccountByL1Address() (map[string]interface{}, error) {
endpoint := fmt.Sprintf("%s/api/v1/account/by/l1/%s", t.baseURL, t.walletAddr)
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return nil, err
}
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("API错误 (status %d): %s", resp.StatusCode, string(body))
}
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("解析响应失败: %w", err)
}
return result, nil
}
// refreshAuthToken 刷新认证令牌
func (t *LighterTrader) refreshAuthToken() error {
// TODO: 实现认证令牌生成逻辑
// 参考 lighter-python SDK 的实现
// 需要签名特定消息并提交到API
t.accountMutex.Lock()
defer t.accountMutex.Unlock()
// 临时实现:设置过期时间为8小时后
t.tokenExpiry = time.Now().Add(8 * time.Hour)
logger.Infof("✓ 认证令牌已生成(有效期至: %s)", t.tokenExpiry.Format(time.RFC3339))
return nil
}
// ensureAuthToken 确保认证令牌有效
func (t *LighterTrader) ensureAuthToken() error {
t.accountMutex.RLock()
expired := time.Now().After(t.tokenExpiry.Add(-30 * time.Minute)) // 提前30分钟刷新
t.accountMutex.RUnlock()
if expired {
logger.Info("🔄 认证令牌即将过期,刷新中...")
return t.refreshAuthToken()
}
return nil
}
// signMessage 签名消息(Ethereum签名)
func (t *LighterTrader) signMessage(message []byte) (string, error) {
// 使用Ethereum个人签名格式
prefix := fmt.Sprintf("\x19Ethereum Signed Message:\n%d", len(message))
prefixedMessage := append([]byte(prefix), message...)
hash := crypto.Keccak256Hash(prefixedMessage)
signature, err := crypto.Sign(hash.Bytes(), t.privateKey)
if err != nil {
return "", err
}
// 调整v值(Ethereum格式)
if signature[64] < 27 {
signature[64] += 27
}
return "0x" + hex.EncodeToString(signature), nil
}
// GetName 获取交易器名称
func (t *LighterTrader) GetName() string {
return "LIGHTER"
}
// GetExchangeType 获取交易所类型
func (t *LighterTrader) GetExchangeType() string {
return "lighter"
}
// Close 关闭交易器
func (t *LighterTrader) Close() error {
logger.Info("✓ LIGHTER交易器已关闭")
return nil
}
// Run 运行交易器(实现Trader接口)
func (t *LighterTrader) Run() error {
logger.Info("⚠️ LIGHTER交易器的Run方法应由AutoTrader调用")
return fmt.Errorf("请使用AutoTrader管理交易器生命周期")
}