739 Commits

Author SHA1 Message Date
tinkle-community
c185cffb19 feat: add exchange_id field to trader_positions table
- Add exchange_id column to track which exchange the position is from
- Update all SELECT/INSERT queries to include exchange_id
- Set exchange_id when creating position record in AutoTrader
- Add migration to add column to existing tables
2025-12-06 01:35:26 +08:00
tinkle-community
8259daddd7 fix: use exchange.ID instead of exchange.Type in PositionSyncManager
exchange.Type is cex/dex category, exchange.ID is the actual exchange name (binance/bybit/etc)
2025-12-06 01:28:43 +08:00
tinkle-community
6922f915af update 2025-12-06 01:06:49 +08:00
tinkle-community
495209a69b 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
SkywalkerJi
499ca25bf7 fix: Fix Deepseek compatibility issues on the official website. (#1166)
* fix: Compatible with the HTTP2 stream transmission bug on DeepSeek's official website endpoint.

* fix: Remove reasoning from JSON
2025-12-04 19:19:48 +08:00
tinkle-community
4557f2e657 Revert "feat: 添加 OKX 交易所支持 (#1150)"
This reverts commit 174f59b907.
2025-12-03 11:31:50 +08:00
0xYYBB | ZYY | Bobo
174f59b907 feat: 添加 OKX 交易所支持 (#1150)
* feat: 添加 OKX 交易所支持(USDT Perpetual Swap)

## 新增功能
- 實現完整的 OKX API v5 REST 客戶端(純 Go 標準庫,無外部依賴)
- 支持 USDT 永續合約交易(BTC-USDT-SWAP 等)
- 實現 Trader 接口的 13 個核心方法

## 技術細節
### trader/okx_trader.go (NEW)
- HMAC-SHA256 簽名機制(完全符合 OKX API v5 規範)
- 餘額和持倉緩存(15秒,參考 Binance 實現)
- 支持 Demo Trading(testnet 模式)
- Symbol 格式轉換(BTCUSDT ↔ BTC-USDT-SWAP)
- 全倉模式(Cross Margin)支持
- 自動槓桿設置

### 實現的接口方法:
-  GetBalance() - 獲取賬戶餘額
-  GetPositions() - 獲取所有持倉
-  OpenLong() / OpenShort() - 開倉
-  CloseLong() / CloseShort() - 平倉
-  SetLeverage() - 設置槓桿
-  SetMarginMode() - 設置保證金模式
-  GetMarketPrice() - 獲取市場價格
-  FormatQuantity() - 格式化數量
- ⚠️  止盈止損功能標記為 TODO(非核心交易功能)

### config/database.go (MODIFIED)
- 添加 "okx" 到預設交易所列表
- 新增 okx_passphrase 字段(OKX 需要 3 個認證參數)
- 更新 ExchangeConfig 結構
- 添加數據庫遷移語句(ALTER TABLE)

### api/server.go (MODIFIED)
- 在 handleCreateTrader() 添加 OKX 初始化邏輯
- switch case "okx" 分支

## 代碼品質
- 代碼行數:~450 行
- 外部依賴:0 個
- 編譯狀態: 通過
- 測試覆蓋:待實現(下一步)

## 待完成事項
- [ ] 撰寫單元測試(目標 >80% 覆蓋率)
- [ ] 完善數據庫查詢邏輯(GetExchanges 添加 OKX passphrase 掃描)
- [ ] 實現止盈止損功能(可選)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: 完善 OKX passphrase 數據庫和 API 支持

- config/database.go:
  • GetExchanges() 添加 okx_passphrase 查詢和解密
  • UpdateExchange() 函數簽名添加 okxPassphrase 參數
  • UpdateExchange() UPDATE 邏輯添加 okx_passphrase SET 子句
  • UpdateExchange() INSERT 添加 okx_passphrase 加密和列

- api/server.go:
  • UpdateExchangeConfigRequest 添加 OKXPassphrase 字段
  • UpdateExchange 調用添加 OKXPassphrase 參數

- api/utils.go:
  • SanitizeExchangeConfigForLog 添加 OKXPassphrase 脫敏

 編譯測試通過,OKX 完整功能支持完成

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* test: 添加 OKX Trader 完整單元測試套件

📊 測試覆蓋率:92.6% (遠超 80% 目標)

 完成的測試:
- 接口兼容性測試
- NewOKXTrader 構造函數測試(5個場景)
- 符號格式轉換測試(5個場景)
- HMAC-SHA256 簽名一致性測試
- GetBalance 測試(含字段驗證)
- GetPositions 測試(含標準化數據驗證)
- GetMarketPrice 測試(3個場景)
- FormatQuantity 測試(5個場景)
- SetLeverage/SetMarginMode 測試
- OpenLong/OpenShort 測試
- CloseLong/CloseShort 測試
- 緩存機制測試
- 錯誤處理測試(API錯誤、網絡錯誤、JSON錯誤)

🔧 測試套件架構:
- OKXTraderTestSuite 繼承 TraderTestSuite
- Mock HTTP 服務器模擬 OKX API v5 響應
- 完整覆蓋所有公開方法
- 包含邊界條件和錯誤場景測試

📈 方法覆蓋率明細:
- request: 90.0%
- GetBalance: 97.0%
- GetPositions: 83.3%
- formatSymbol, OpenLong, OpenShort, CloseLong, CloseShort: 100%
- placeOrder, SetMarginMode, FormatQuantity, clearCache: 100%
- Cancel* 方法系列: 100%
- SetLeverage: 81.8%
- GetMarketPrice: 85.7%

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-12-02 10:18:13 +08:00
0xYYBB | ZYY | Bobo
adf2d54b85 fix(bybit): complete Bybit integration by adding API layer support (#1149) 2025-12-02 05:00:20 +08:00
Professor-Chen
7c43c8833c fix: resolve multiple bugs preventing trader creation and deletion (#1140)
* fix: resolve multiple bugs preventing trader creation

Bug fixes:
1. Fix time.Time scanning error - SQLite stores datetime as TEXT, now parsing manually
2. Fix foreign key mismatch - traders table referenced exchanges(id) but exchanges uses composite primary key (id, user_id)
3. Add missing backtestManager field to Server struct
4. Add missing Shutdown method to Server struct
5. Fix NewFuturesTrader call - pass userId parameter
6. Fix UpdateExchange call - pass all required parameters
7. Add migrateTradersTable() to fix existing databases

These issues prevented creating new traders with 500 errors.

* fix(api): fix balance extraction field name mismatch

Binance API returns 'availableBalance' (camelCase) but code was looking for
'available_balance' (snake_case). Now supports both formats.

Also added 'totalWalletBalance' as fallback for total balance extraction.

* fix(frontend): add missing ConfirmDialogProvider to App

The delete trader button required ConfirmDialogProvider to be wrapped
around the App component for the confirmation dialog to work.

---------

Co-authored-by: NOFX Trader <nofx@local.dev>
2025-11-30 16:09:42 +08:00
tinkle-community
2e964d704a fix: ensure tab navigation updates page state correctly
Tab buttons were only calling navigate() which changes URL but doesn't
trigger popstate events. App.tsx listens to popstate/hashchange to
update page state, so clicks appeared to do nothing.

Now all tab buttons call both onPageChange() callback and navigate()
to ensure page state updates and URL stays in sync.
2025-11-30 12:40:14 +08:00
Professor-Chen
b71272d48b fix: resolve multiple bugs preventing trader creation (#1138)
* fix: resolve multiple bugs preventing trader creation

Bug fixes:
1. Fix time.Time scanning error - SQLite stores datetime as TEXT, now parsing manually
2. Fix foreign key mismatch - traders table referenced exchanges(id) but exchanges uses composite primary key (id, user_id)
3. Add missing backtestManager field to Server struct
4. Add missing Shutdown method to Server struct
5. Fix NewFuturesTrader call - pass userId parameter
6. Fix UpdateExchange call - pass all required parameters
7. Add migrateTradersTable() to fix existing databases

These issues prevented creating new traders with 500 errors.

* fix(api): fix balance extraction field name mismatch

Binance API returns 'availableBalance' (camelCase) but code was looking for
'available_balance' (snake_case). Now supports both formats.

Also added 'totalWalletBalance' as fallback for total balance extraction.

* fix(frontend): add missing ConfirmDialogProvider to App

The delete trader button required ConfirmDialogProvider to be wrapped
around the App component for the confirmation dialog to work.

---------

Co-authored-by: NOFX Trader <nofx@local.dev>
2025-11-30 12:22:20 +08:00
Rick
7eebb4e218 Dev backtest (#1134) 2025-11-28 21:34:27 +08:00
tinkle-community
64a5734011 docs: update airdrop program text 2025-11-27 04:08:43 +08:00
tinkle-community
a7947d1c68 docs: add priority rewards for pinned issue PRs 2025-11-27 04:05:29 +08:00
tinkle-community
ac97e40477 docs: add contributor airdrop program to all READMEs 2025-11-27 04:02:22 +08:00
tinkle-community
d083c47e0c chore: remove .claude directory 2025-11-27 03:40:56 +08:00
tinkle-community
b511365082 docs: move exchanges and AI models sections after screenshots 2025-11-27 03:39:42 +08:00
tinkle-community
ad91c34047 docs: add supported AI models table to all README files 2025-11-27 03:31:37 +08:00
tinkle-community
1b1f5d1f17 docs: simplify exchange sections, consolidate into Supported Exchanges table
- Remove individual exchange registration sections from all READMEs
- Remove redundant Binance, Hyperliquid, Aster DEX detailed setup sections
- Consolidate all exchange info into Supported Exchanges table with register links and setup guides
- Rename section to "Supported Exchanges (DEX/CEX Tutorials)" in respective languages
2025-11-27 03:19:59 +08:00
tinkle-community
d094306b13 docs: add Bybit, OKX, and Lighter exchange support
- Mark Bybit, OKX as supported in CEX section
- Mark Lighter as supported in Perp-DEX section
- Add Bybit API setup guide
- Add OKX API setup guide
- Add Lighter agent wallet setup guide
- Update all READMEs (EN, ZH-CN, JA, KO)
2025-11-27 03:05:19 +08:00
tinkle-community
67d69b132d docs: add supported exchanges table and API/wallet setup guides
- Add supported exchanges table to EN, ZH-CN, JA, KO READMEs
- CEX: Binance (supported), OKX (coming soon), Bybit (coming soon)
- Perp-DEX: Hyperliquid (supported), Aster DEX (supported)
- Include referral links with fee discounts for all exchanges
- Remove What's New sections from all READMEs
- Create Binance API setup guide
- Create Hyperliquid agent wallet setup guide
- Create Aster DEX API wallet setup guide
2025-11-27 02:56:19 +08:00
tinkle-community
5517269dfe chore: trigger cache refresh 2025-11-27 01:49:30 +08:00
tinkle-community
871a939dc5 update code of conduct 2025-11-25 20:32:01 +08:00
tinkle-community
9c2eb897a1 update docs 2025-11-25 20:26:02 +08:00
tinkle-community
84acce9b77 update disclaimer 2025-11-25 20:18:29 +08:00
tinkle-community
250758959c update Security Policy 2025-11-25 20:08:48 +08:00
tinkle-community
aabd312fa1 update docs 2025-11-24 00:26:16 +08:00
tinkle-community
ff54731ccf update docs 2025-11-24 00:04:45 +08:00
tinkle-community
fad279bee1 update Korean README docs 2025-11-23 22:04:02 +08:00
tinkle-community
33dce4edcc update Korean README docs 2025-11-23 21:58:50 +08:00
tinkle-community
52fb1c902c update docs 2025-11-23 21:13:27 +08:00
tinkle-community
c258abb292 update docs 2025-11-23 21:10:37 +08:00
tinkle-community
61afbea588 fix bybit_trader future order 2025-11-23 19:51:53 +08:00
0xYYBB | ZYY | Bobo
46ec8f1d04 feat(exchange): add Bybit Futures support (#1100)
* feat(exchange): add Bybit Futures support

- Add Bybit Go SDK dependency (github.com/bybit-exchange/bybit.go.api)
- Create trader/bybit_trader.go implementing Trader interface for USDT perpetual futures
- Update config/database.go to include Bybit in default exchanges
- Update manager/trader_manager.go to handle Bybit API key configuration
- Update trader/auto_trader.go to add BybitAPIKey/BybitSecretKey fields and bybit case
- Add Bybit icon to frontend ExchangeIcons.tsx

Bybit uses standard API Key/Secret Key authentication (similar to Binance).
Only USDT perpetual futures (category=linear) are supported.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* test(bybit): add comprehensive unit tests for Bybit trader

- Add BybitTraderTestSuite following existing test patterns
- Interface compliance test (Trader interface)
- Symbol format validation tests
- FormatQuantity tests with 3-decimal precision
- API response parsing tests (success, error, permission denied)
- Position side conversion tests (Buy->long, Sell->short)
- Cache duration verification test
- Mock server integration tests for API endpoints

All 12 Bybit tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* fix(frontend): add Bybit support to exchange config forms

修復前端對 Bybit 交易所的支持:
- 添加 Bybit 到 API Key/Secret Key 輸入欄位顯示邏輯
- 添加 Bybit 的表單驗證邏輯
- 修復 ExchangeConfigModal.tsx 和 AITradersPage.tsx

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

---------

Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-23 19:23:53 +08:00
Liu
abfe366720 Update README.md (#1087) 2025-11-21 07:12:41 +08:00
0xYYBB | ZYY | Bobo
8dffff60a2 feat(lighter): 完整集成 LIGHTER DEX - SDK + 前端配置 UI (#1085)
* feat(trader): add LIGHTER DEX integration (initial implementation)

Add pure Go implementation of LIGHTER DEX trader following NOFX architecture

Features:
-  Account management with Ethereum wallet authentication
-  Order operations: market/limit orders, cancel, query
-  Position & balance queries
-  Zero-fee trading support (Standard accounts)
-  Up to 50x leverage for BTC/ETH

Implementation:
- Pure Go (no CGO dependencies) for easy deployment
- Based on hyperliquid_trader.go architecture
- Uses Ethereum ECDSA signatures (like Hyperliquid)
- API base URL: https://mainnet.zklighter.elliot.ai

Files:
- lighter_trader.go: Core trader structure & auth
- lighter_orders.go: Order management (create/cancel/query)
- lighter_account.go: Balance & position queries

Status: ⚠️ Partial implementation
-  Core structure complete
- ⏸️ Auth token generation needs implementation
- ⏸️ Transaction signing logic needs completion
- ⏸️ Config integration pending

Next steps:
1. Complete auth token generation
2. Add to config/exchange registry
3. Add frontend UI support
4. Create test suite

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* feat: Add LIGHTER DEX integration (快速整合階段)

## 🚀 新增功能
-  添加 LIGHTER DEX 作為第四個支持的交易所 (Binance, Hyperliquid, Aster, LIGHTER)
-  完整的數據庫配置支持(ExchangeConfig 新增 LighterWalletAddr, LighterPrivateKey 字段)
-  交易所註冊與初始化(initDefaultData 註冊 "lighter")
-  TraderManager 集成(配置傳遞邏輯完成)
-  AutoTrader 支持(NewAutoTrader 添加 "lighter" case)

## 📝 實現細節

### 後端整合
1. **數據庫層** (config/database.go):
   - ExchangeConfig 添加 LIGHTER 字段
   - 創建表時添加 lighter_wallet_addr, lighter_private_key 欄位
   - ALTER TABLE 語句用於向後兼容
   - UpdateExchange/CreateExchange/GetExchanges 支持 LIGHTER
   - migrateExchangesTable 支持 LIGHTER 字段

2. **API 層** (api/server.go, api/utils.go):
   - UpdateExchangeConfigRequest 添加 LIGHTER 字段
   - SanitizeExchangeConfigForLog 添加脫敏處理

3. **Trader 層** (trader/):
   - lighter_trader.go: 核心結構、認證、初始化
   - lighter_account.go: 餘額、持倉、市場價格查詢
   - lighter_orders.go: 訂單管理(創建、取消、查詢)
   - lighter_trading.go: 交易功能實現(開多/空、平倉、止損/盈)
   - 實現完整 Trader interface (13個方法)

4. **Manager 層** (manager/trader_manager.go):
   - addTraderFromDB 添加 LIGHTER 配置設置
   - AutoTraderConfig 添加 LIGHTER 字段

### 實現的功能(快速整合階段)
 基礎交易功能 (OpenLong, OpenShort, CloseLong, CloseShort)
 餘額查詢 (GetBalance, GetAccountBalance)
 持倉查詢 (GetPositions, GetPosition)
 訂單管理 (CreateOrder, CancelOrder, CancelAllOrders)
 止損/止盈 (SetStopLoss, SetTakeProfit, CancelStopLossOrders)
 市場數據 (GetMarketPrice)
 格式化工具 (FormatQuantity)

## ⚠️ TODO(完整實現階段)
- [ ] 完整認證令牌生成邏輯 (refreshAuthToken)
- [ ] 完整交易簽名邏輯(參考 Python SDK)
- [ ] 從 API 獲取幣種精度
- [ ] 區分止損/止盈訂單類型
- [ ] 前端 UI 支持
- [ ] 完整測試套件

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* feat: 完整集成 LIGHTER DEX with SDK

- 集成官方 lighter-go SDK (v0.0.0-20251104171447-78b9b55ebc48)
- 集成 Poseidon2 Goldilocks 簽名庫 (poseidon_crypto v0.0.11)
- 實現完整的 LighterTraderV2 使用官方 SDK
- 實現 17 個 Trader 接口方法(賬戶、交易、訂單管理)
- 支持雙密鑰系統(L1 錢包 + API Key)
- V1/V2 自動切換機制(向後兼容)
- 自動認證令牌管理(8小時有效期)
- 添加完整集成文檔 LIGHTER_INTEGRATION.md

新增文件:
- trader/lighter_trader_v2.go - V2 核心結構和初始化
- trader/lighter_trader_v2_account.go - 賬戶查詢方法
- trader/lighter_trader_v2_trading.go - 交易操作方法
- trader/lighter_trader_v2_orders.go - 訂單管理方法
- LIGHTER_INTEGRATION.md - 完整文檔

修改文件:
- trader/auto_trader.go - 添加 LighterAPIKeyPrivateKey 配置
- config/database.go - 添加 API Key 字段支持
- go.mod, go.sum - 添加 SDK 依賴

🤖 Generated with Claude Code

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* feat(lighter): 實現完整 HTTP 調用與動態市場映射

### 實現的功能

#### 1. submitOrder() - 真實訂單提交
- 使用 POST /api/v1/sendTx 提交已簽名訂單
- tx_type: 14 (CREATE_ORDER)
- 價格保護機制 (price_protection)
- 完整錯誤處理與響應解析

#### 2. GetActiveOrders() - 查詢活躍訂單
- GET /api/v1/accountActiveOrders
- 使用認證令牌 (Authorization header)
- 支持按市場索引過濾

#### 3. CancelOrder() - 真實取消訂單
- 使用 SDK 簽名 CancelOrderTxReq
- POST /api/v1/sendTx with tx_type: 15 (CANCEL_ORDER)
- 自動 nonce 管理

#### 4. getMarketIndex() - 動態市場映射
- 從 GET /api/v1/orderBooks 獲取市場列表
- 內存緩存 (marketIndexMap) 提高性能
- 回退到硬編碼映射(API 失敗時)
- 線程安全 (sync.RWMutex)

### 技術實現

**數據結構**:
- SendTxRequest/SendTxResponse - sendTx 請求響應
- MarketInfo - 市場信息緩存

**並發安全**:
- marketMutex - 保護市場索引緩存
- 讀寫鎖優化性能

**錯誤處理**:
- API 失敗回退機制
- 詳細日誌記錄
- HTTP 狀態碼驗證

### 測試

 編譯通過 (CGO_ENABLED=1)
 所有 Trader 接口方法實現完整
 HTTP 調用格式符合 LIGHTER API 規範

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* feat(lighter): 數據庫遷移與前端類型支持

### 數據庫變更

#### 新增欄位
- `exchanges.lighter_api_key_private_key` TEXT DEFAULT ''
- 支持 LIGHTER V2 的 40 字節 API Key 私鑰

#### 遷移腳本
- 📄 `migrations/002_add_lighter_api_key.sql`
- 包含完整的驗證和統計查詢
- 向後兼容現有配置(默認為空,使用 V1)

#### Schema 更新
- `config/database.go`:
  - 更新 CREATE TABLE 語句
  - 更新 exchanges_new 表結構
  - 新增 ALTER TABLE 遷移命令

### 前端類型更新

#### types.ts
- 新增 `Exchange` 接口字段:
  - `lighterWalletAddr?: string` - L1 錢包地址
  - `lighterPrivateKey?: string` - L1 私鑰
  - `lighterApiKeyPrivateKey?: string` - API Key 私鑰(新增)

### 技術細節

**數據庫兼容性**:
- 使用 ALTER TABLE ADD COLUMN IF NOT EXISTS
- 默認值為空字符串
- 不影響現有數據

**類型安全**:
- TypeScript 可選字段
- 與後端 ExchangeConfig 結構對齊

### 下一步

 **待完成**:
1. ExchangeConfigModal 組件更新
2. API 調用參數傳遞
3. V1/V2 狀態顯示

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* docs(lighter): 更新 LIGHTER_INTEGRATION.md 文檔狀態

* feat(lighter): 前端完整實現 - API Key 配置與 V1/V2 狀態

**英文**:
- `lighterWalletAddress`, `lighterPrivateKey`, `lighterApiKeyPrivateKey`
- `lighterWalletAddressDesc`, `lighterPrivateKeyDesc`, `lighterApiKeyPrivateKeyDesc`
- `lighterApiKeyOptionalNote` - V1 模式提示
- `lighterV1Description`, `lighterV2Description` - 狀態說明
- `lighterPrivateKeyImported` - 導入成功提示

**中文(繁體)**:
- 完整的中文翻譯對應
- 專業術語保留原文(L1、API Key、Poseidon2)

**Exchange 接口**:
- `lighterWalletAddr?: string`
- `lighterPrivateKey?: string`
- `lighterApiKeyPrivateKey?: string`

**UpdateExchangeConfigRequest 接口**:
- `lighter_wallet_addr?: string`
- `lighter_private_key?: string`
- `lighter_api_key_private_key?: string`

**狀態管理**:
- 添加 3 個 LIGHTER 狀態變量
- 更新 `secureInputTarget` 類型包含 'lighter'

**表單字段**:
- L1 錢包地址(必填,text input)
- L1 私鑰(必填,password + 安全輸入)
- API Key 私鑰(可選,password,40 字節)

**V1/V2 狀態顯示**:
- 動態背景顏色(V1: 橙色 #3F2E0F,V2: 綠色 #0F3F2E)
- 圖標指示(V1: ⚠️,V2: )
- 狀態說明文字

**驗證邏輯**:
- 必填字段:錢包地址 + L1 私鑰
- API Key 為可選字段
- 自動 V1/V2 檢測

**安全輸入**:
- 支持通過 TwoStageKeyModal 安全導入私鑰
- 導入成功後顯示 toast 提示

**handleSaveExchange**:
- 添加 3 個 LIGHTER 參數
- 更新交易所對象(新增/更新)
- 構建 API 請求(snake_case 字段)

**V1 模式(無 API Key)**:
```
┌────────────────────────────────────────┐
│ ⚠️ LIGHTER V1                          │
│ 基本模式 - 功能受限,僅用於測試框架       │
└────────────────────────────────────────┘
背景: #3F2E0F (橙色調)
邊框: #F59E0B (橙色)
```

**V2 模式(有 API Key)**:
```
┌────────────────────────────────────────┐
│  LIGHTER V2                          │
│ 完整模式 - 支持 Poseidon2 簽名和真實交易 │
└────────────────────────────────────────┘
背景: #0F3F2E (綠色調)
邊框: #10B981 (綠色)
```

1. **類型安全**
   - 完整的 TypeScript 類型定義
   - Props 接口正確對齊
   -  無 LIGHTER 相關編譯錯誤

2. **用戶體驗**
   - 清晰的必填/可選字段區分
   - 實時 V1/V2 狀態反饋
   - 安全私鑰輸入支持

3. **向後兼容**
   - 不影響現有交易所配置
   - 所有字段為可選(Optional)
   - API 請求格式統一

 TypeScript 編譯通過(無 LIGHTER 錯誤)
 類型定義完整且正確
 所有必需文件已更新
 與後端 API 格式對齊

Modified:
- `web/src/i18n/translations.ts` - 中英文翻譯
- `web/src/types.ts` - 類型定義
- `web/src/components/traders/ExchangeConfigModal.tsx` - Modal 組件
- `web/src/hooks/useTraderActions.ts` - Actions hook

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* test(lighter): 添加 V1 測試套件與修復 SafeFloat64 缺失

- 新增 trader/helpers.go: 添加 SafeFloat64/SafeString/SafeInt 輔助函數
- 新增 trader/lighter_trader_test.go: LIGHTER V1 測試套件
  -  測試通過 (7/10):
    - NewTrader 驗證 (無效私鑰, 有效私鑰格式)
    - FormatQuantity
    - GetExchangeType
    - InvalidQuantity 驗證
    - InvalidLeverage 驗證
    - HelperFunctions (SafeFloat64)
  - ⚠️ 待改進 (3/10):
    - GetBalance (需要調整 mock 響應格式)
    - GetPositions (需要調整 mock 響應格式)
    - GetMarketPrice (需要調整 mock 響應格式)

- 修復 Bug: lighter_account.go 和 lighter_trader_v2_account.go 中未定義的 SafeFloat64
- 測試框架: httptest.Server mock LIGHTER API
- 安全: 使用固定測試私鑰 (不含真實資金)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

---------

Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-20 19:29:01 +08:00
tinkle-community
f1397c7891 update docs 2025-11-19 22:49:50 +08:00
Ember
3e19f7cc8c refactor(web): redesign httpClient with axios and unified error handling (#1061)
* fix(web): remove duplicate PasswordChecklist in error block

- Remove duplicate PasswordChecklist component from error message area
- Keep only the real-time password validation checklist
- Error block now displays only the error message text

Bug was introduced in commit aa0bd93 (PR #872)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* refactor(web): redesign httpClient with axios and unified error handling

Major refactoring to improve error handling architecture:

## Changes

### 1. HTTP Client Redesign (httpClient.ts)
- Replaced native fetch with axios for better interceptor support
- Implemented request/response interceptors for centralized error handling
- Added automatic Bearer token injection in request interceptor
- Network errors and system errors (404, 403, 500) now intercepted and shown via toast
- Only business logic errors (4xx except 401/403/404) returned to caller
- New ApiResponse<T> interface for type-safe responses

### 2. API Migration (api.ts)
- Migrated all 31 API methods from legacy fetch-style to new httpClient
- Updated pattern: from `res.ok/res.json()` to `result.success/result.data`
- Removed getAuthHeaders() helper (token now auto-injected)
- Added TypeScript generics for better type safety

### 3. Component Updates
- AuthContext.tsx: Updated register() to use new API
- TraderConfigModal.tsx: Migrated 3 API calls (config, templates, balance)
- RegisterPage.tsx: Simplified error display (error type handling now in API layer)

### 4. Removed Legacy Code
- Removed legacyHttpClient compatibility wrapper (~30 lines)
- Removed legacyRequest() method
- Clean separation: API layer handles all error classification

## Benefits
- Centralized error handling - no need to check network/system errors in components
- Better UX - automatic toast notifications for system errors
- Type safety - generic ApiResponse<T> provides compile-time checks
- Cleaner business components - only handle business logic errors
- Consistent error messages across the application

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

---------

Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-17 14:48:14 +08:00
Shui
88b01c8f2a refactor(mcp) (#1042)
* improve(interface): replace with interface

* feat(mcp): 添加构建器模式支持

新增功能:
- RequestBuilder 构建器,支持流式 API
- 多轮对话支持(AddAssistantMessage)
- Function Calling / Tools 支持
- 精细参数控制(temperature, top_p, penalties 等)
- 3个预设场景(Chat, CodeGen, CreativeWriting)
- 完整的测试套件(19个新测试)

修复问题:
- Config 字段未使用(MaxRetries、Temperature 等)
- DeepSeek/Qwen SetAPIKey 的冗余 nil 检查

向后兼容:
- 保留 CallWithMessages API
- 新增 CallWithRequest API

测试:
- 81 个测试全部通过
- 覆盖率 80.6%

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

---------

Co-authored-by: zbhan <zbhan@freewheel.tv>
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-15 23:04:53 -05:00
0xYYBB | ZYY | Bobo
b66fd5fb0a fix(docker): revert healthcheck to wget for Alpine compatibility (#986)
## Problem

PR #906 changed healthcheck commands from `wget` to `curl`, but Alpine Linux
(our base image) does not include `curl` by default, causing all containers
to fail healthchecks with:

```
exec: "curl": executable file not found in $PATH
```

This creates a configuration mismatch:
- docker/Dockerfile.backend uses `wget` ( works)
- docker-compose.yml uses `curl` ( fails)

## Root Cause Analysis

Alpine Linux philosophy is minimalism:
-  `wget` is pre-installed (part of busybox)
-  `curl` requires `apk add curl` (~3MB extra)

The original PR #906 made two commits:
1. First commit (3af8760): `curl` → `wget` ( correct fix)
2. Second commit (333b2ef): `wget` → `curl` ( introduced bug)

The second commit was based on incorrect assumption that "curl is more
widely available than wget in Docker images". This is false for Alpine.

## Solution

Revert healthcheck commands back to `wget` to match:
1. Alpine's pre-installed tools
2. Dockerfile.backend healthcheck (line 68)
3. Docker and Kubernetes best practices

## Testing

 Verified `wget` exists in Alpine containers:
```bash
docker run --rm alpine:latest which wget
# Output: /usr/bin/wget
```

 Added new CI workflow to prevent regression:
- `.github/workflows/pr-docker-compose-healthcheck.yml`
- Validates healthcheck compatibility with Alpine
- Ensures containers reach healthy status

## Impact

- **Before**: Containers show (unhealthy), potential auto-restart loops
- **After**: Containers show (healthy), monitoring systems happy
- **Scope**: Only affects docker-compose deployments
- **Breaking**: None - this is a bug fix

## References

- PR #906: Original (incorrect) fix
- Alpine Linux: https://alpinelinux.org/about/
- Dockerfile.backend L68: Existing `wget` healthcheck

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
Co-authored-by: tinkle-community <tinklefund@gmail.com>
Co-authored-by: Shui <88711385+hzb1115@users.noreply.github.com>
2025-11-15 22:21:11 -05:00
Lawrence Liu
11e4022867 fix(decision): clarify field names for update_stop_loss and update_take_profit actions (#993)
* fix(decision): clarify field names for update_stop_loss and update_take_profit actions

修复 AI 决策中的字段名混淆问题:

**问题**:
AI 在使用 update_stop_loss 时错误地使用了 `stop_loss` 字段,
导致解析失败(backend 期望 `new_stop_loss` 字段)

**根因**:
系统 prompt 的字段说明不够明确,AI 无法知道 update_stop_loss
应该使用 new_stop_loss 字段而非 stop_loss

**修复**:
1. 在字段说明中明确标注:
   - update_stop_loss 时必填: new_stop_loss (不是 stop_loss)
   - update_take_profit 时必填: new_take_profit (不是 take_profit)
2. 在 JSON 示例中增加 update_stop_loss 的具体用法示例

**验证**:
decision_logs 中的错误 "新止损价格必须大于0: 0.00" 应该消失

* test(decision): add validation tests for update actions

添加针对 update_stop_loss、update_take_profit 和 partial_close
动作的字段验证单元测试:

**测试覆盖**:
1. TestUpdateStopLossValidation - 验证 new_stop_loss 字段
   - 正确使用 new_stop_loss 字段(应通过)
   - new_stop_loss 为 0(应报错)
   - new_stop_loss 为负数(应报错)

2. TestUpdateTakeProfitValidation - 验证 new_take_profit 字段
   - 正确使用 new_take_profit 字段(应通过)
   - new_take_profit 为 0(应报错)
   - new_take_profit 为负数(应报错)

3. TestPartialCloseValidation - 验证 close_percentage 字段
   - 正确使用 close_percentage 字段(应通过)
   - close_percentage 为 0(应报错)
   - close_percentage 超过 100(应报错)

**测试结果**:所有测试用例通过 ✓

---------

Co-authored-by: Shui <88711385+hzb1115@users.noreply.github.com>
2025-11-15 22:21:11 -05:00
Lawrence Liu
a74aed5a20 fix(decision): add missing actions to AI prompt (#983)
问题:AI 返回 adjust_stop_loss 导致决策验证失败
根因:prompt 只列出 6 个 action,缺少 3 个有效 action

修复(TDD):
1. 添加测试验证 prompt 包含所有 9 个有效 action
2. 最小修改:在 action 列表中补充 3 个缺失项
   - update_stop_loss
   - update_take_profit
   - partial_close

测试:
- TestBuildSystemPrompt_ContainsAllValidActions 
- TestBuildSystemPrompt_ActionListCompleteness 

Fixes: 无效的action: adjust_stop_loss
2025-11-15 22:21:11 -05:00
Ember
b690debf5e refactor(web): restructure AITradersPage into modular architecture (#1023)
* refactor(web): restructure AITradersPage into modular architecture

Refactored the massive 2652-line AITradersPage.tsx into a clean, modular architecture following React best practices.

**Changes:**
- Decomposed 2652-line component into 12 focused modules
- Introduced Zustand stores for config and modal state management
- Extracted all business logic into useTraderActions custom hook (633 lines)
- Created reusable section components (PageHeader, TradersGrid, etc.)
- Separated complex modal logic into dedicated components
- Added TraderConfig type, eliminated all any types
- Fixed critical bugs in configuredExchanges logic and getState() usage

**File Structure:**
- Main page reduced from 2652 → 234 lines (91% reduction)
- components/traders/: 7 UI components + 5 section components
- stores/: tradersConfigStore, tradersModalStore
- hooks/: useTraderActions (all business logic)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* chore: ignore PR_DESCRIPTION.md

* fix(web): restore trader dashboard navigation functionality

Fixed missing navigation logic in refactored AITradersPage. The "查看" (View) button now correctly navigates to the trader dashboard.

**Root Cause:**
During refactoring, the `useNavigate` hook and default navigation logic were inadvertently omitted from the main page component.

**Changes:**
- Added `useNavigate` import from react-router-dom
- Implemented `handleTraderSelect` function with fallback navigation
- Restored original behavior: use `onTraderSelect` prop if provided, otherwise navigate to `/dashboard?trader=${traderId}`

**Testing:**
-  Click "查看" button navigates to trader dashboard
-  Query parameter correctly passed to dashboard

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

* fix(web): correct type definitions for trader configuration

Fixed TypeScript build errors by using the correct `TraderConfigData` type instead of the incorrect `TraderConfig` type.

**Root Cause:**
During refactoring, a new `TraderConfig` type was incorrectly created that extended `CreateTraderRequest` (with fields like `name`, `ai_model_id`). However, the `TraderConfigModal` component and API responses actually use `TraderConfigData` (with fields like `trader_name`, `ai_model`).

**Changes:**
- Replaced all `TraderConfig` references with `TraderConfigData`:
  - stores/tradersModalStore.ts
  - hooks/useTraderActions.ts
  - lib/api.ts
- Removed incorrect `TraderConfig` type definition from types.ts
- Added null check for `editingTrader.trader_id` to satisfy TypeScript

**Build Status:**
-  TypeScript compilation: PASS
-  Vite production build: PASS

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: tinkle-community <tinklefund@gmail.com>

---------

Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-15 22:21:09 -05:00
Diego
c0239f2b14 fix gh job failed when pr contains issues (#1019) 2025-11-15 22:20:06 -05:00
Burt
91b7187e25 Git 工作流规范 (#974)
* Add files via upload

* Revise Git workflow guidelines and branch strategies

* Update git workflow

* Chores
2025-11-15 22:20:06 -05:00
0xYYBB | ZYY | Bobo
031cc19c99 fix(api): use UUID to ensure traderID uniqueness (#893) (#1008)
## Problem
When multiple users create traders with the same exchange + AI model
combination within the same second, they generate identical traderIDs,
causing data conflicts.

Old code (Line 496):
```go
traderID := fmt.Sprintf("%s_%s_%d", req.ExchangeID, req.AIModelID, time.Now().Unix())
```

## Solution
Use UUID to guarantee 100% uniqueness while preserving prefix for debugging:
```go
traderID := fmt.Sprintf("%s_%s_%s", req.ExchangeID, req.AIModelID, uuid.New().String())
```

Example output: `binance_gpt-4_a1b2c3d4-e5f6-7890-abcd-ef1234567890`

## Changes
- `api/server.go:495-497`: Use UUID for traderID generation
- `api/traderid_test.go`: New test file with 3 comprehensive tests

## Tests
 All tests passed (0.189s)
 TestTraderIDUniqueness - 100 unique IDs generated
 TestTraderIDFormat - 3 exchange/model combinations validated
 TestTraderIDNoCollision - 1000 iterations without collision

Fixes #893

Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
2025-11-15 22:20:06 -05:00
Diego
f23eaa534d fix(web): fix 401 unauthorized redirect not working properly (#997)
修复了token过期后页面一直遇到401错误、无法自动跳转登录页的问题

主要改动:
1. httpClient.ts
   - 去掉延迟跳转的setTimeout,改为立即跳转
   - 返回pending promise阻止SWR捕获401错误
   - 保存from401标记到sessionStorage,由登录页显示提示

2. LoginPage.tsx
   - 检测from401标记,显示"登录已过期"提示(永久显示)
   - 在登录成功时手动关闭过期提示toast
   - 支持管理员登录、普通登录、OTP验证三种场景

3. TraderConfigModal.tsx
   - 修复3处直接使用fetch()的问题,改为httpClient.get()
   - 确保所有API请求都经过统一的401拦截器

4. translations.ts
   - 添加sessionExpired的中英文翻译

修复效果:
- token过期时立即跳转登录页(无延迟)
- 登录页持续显示过期提示,直到用户登录成功或手动关闭
- 不会再看到401错误页面或重复的错误提示

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-15 22:20:06 -05:00
Shui
3f5f964a67 Improve(interface): replace some struct with interface for testing (#994)
* fix(trader): get peakPnlPct using posKey

* fix(docs): keep readme at the same page

* improve(interface): replace with interface

* refactor mcp

---------

Co-authored-by: zbhan <zbhan@freewheel.tv>
2025-11-15 22:20:06 -05:00
0xYYBB | ZYY | Bobo
79358d4776 fix(web): await mutateTraders() to eliminate 3-4s delay after operations (#989)
## Problem
When creating/editing/deleting traders, AI models, or exchanges, the UI
takes 3-4 seconds to show results, causing users to think the system is frozen.

## Root Cause
Although mutateTraders() was called after operations, it was not awaited,
causing the function to continue immediately without waiting for data refresh.
The UI relied on the refreshInterval: 5000 automatic refresh, resulting in
up to 5 seconds of delay.

## Solution
Added await before all mutateTraders() calls to ensure data is refreshed
before closing modals or showing success messages.

Changes:
- handleCreateTrader: Added await before mutateTraders()
- handleSaveEditTrader: Added await before mutateTraders()
- handleDeleteTrader: Added await before mutateTraders()
- handleToggleTrader: Added await before mutateTraders()

Impact:
- From 3-4s delay to immediate display (< 500ms)
- Significantly improved UX
- Consistent with AI model and exchange config behavior

Testing:
- Frontend build successful
- No TypeScript errors
- Ready for manual UI testing

Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
2025-11-15 22:20:06 -05:00
tinkle-community
20aa054bf3 update readme 2025-11-15 22:20:06 -05:00