17 Commits

Author SHA1 Message Date
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
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
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
Linden
e2d05639a7 fix:完善aster账户净值和盈亏计算|Improve the calculation of the net value and profit/loss of the aster account (#695)
Co-authored-by: LindenWang <linden@Lindens-MacBookPro-2.local>
2025-11-07 13:38:39 +08:00
Icyoung
6f3fb71ac7 Merge branch 'dev' into fix/bug-fixes-collection-v2 2025-11-05 15:56:58 +08:00
SkywalkerJi
160efc5410 Merge pull request #480 from SkywalkerJi/dev
fix(AI): Change the default model to qwen3-max to mitigate output quality issues caused by model downgrading.
2025-11-05 11:02:06 +09:00
SkywalkerJi
96e5d4b56c Change the default model to qwen3-max to mitigate output quality issues caused by model downgrading. 2025-11-05 09:50:05 +08:00
Liu Xiang Qian
edea0209a0 fix: add AI_MAX_TOKENS environment variable to prevent response truncation
## Problem
AI responses were being truncated due to a hardcoded max_tokens limit of 2000,
causing JSON parsing failures. The error occurred when:
1. AI's thought process analysis was cut off mid-response
2. extractDecisions() incorrectly extracted MACD data arrays from the input prompt
3. Go failed to unmarshal numbers into Decision struct

Error message:
```
json: cannot unmarshal number into Go value of type decision.Decision
JSON内容: [-867.759, -937.406, -1020.435, ...]
```

## Solution
- Add MaxTokens field to mcp.Client struct
- Read AI_MAX_TOKENS from environment variable (default: 2000)
- Set AI_MAX_TOKENS=4000 in docker-compose.yml for production use
- This provides enough tokens for complete analysis with the 800-line trading strategy prompt

## Testing
- Verify environment variable is read correctly
- Confirm AI responses are no longer truncated
- Check decision logs for complete JSON output
2025-11-05 09:31:58 +08:00
ZhouYongyou
b92a1d68ac chore: run go fmt to fix formatting issues 2025-11-04 17:39:00 +08:00
ZhouYongyou
4e6f990093 fix: 添加 HTTP/2 stream error 到可重試錯誤列表
問題:
- 用戶遇到錯誤:stream error: stream ID 1; INTERNAL_ERROR
- 這是 HTTP/2 連接被服務端關閉的錯誤
- 當前重試機制不包含此類錯誤,導致直接失敗

修復:
- 添加 "stream error" 到可重試列表
- 添加 "INTERNAL_ERROR" 到可重試列表
- 遇到此類錯誤時會自動重試(最多 3 次)

影響:
- 提高 API 調用穩定性
- 自動處理服務端臨時故障
- 減少因網絡波動導致的失敗
2025-11-04 17:35:26 +08:00
SkywalkerJi
6efdc47379 * Fixed the custom model URL.
*   Added functionality for custom model names.
2025-11-01 16:09:15 +08:00
tpkeeper
f3f9ef4963 optimize(mcp/client): correct receiver name 2025-10-31 22:24:10 +08:00
tpkeeper
9195b2b373 Fix mcp defaultConfig override issue in multi-trader, multi-AI model scenario 2025-10-30 15:46:17 +08:00
SkywalkerJi
10c68aa1b7 When a custom URL ends with #, force the use of the full URL without appending /chat/completions. 2025-10-30 10:38:15 +08:00
btcman
27ba298eed Feature: Add support for custom OpenAI-compatible API
This update enables users to configure any OpenAI-compatible API endpoint,
allowing the use of:
- OpenAI official API (GPT-4, GPT-4o, etc.)
- OpenRouter (access to multiple models)
- Local deployed models (Ollama, LM Studio, etc.)
- Other OpenAI-format compatible API services

Changes:
- config: Add custom_api_url, custom_api_key, custom_model_name fields
- mcp: Add SetCustomAPI function and ProviderCustom constant
- trader: Update AI initialization logic to support custom API
- manager: Pass custom API config to trader instances
- Add CUSTOM_API.md documentation with usage examples
- Update config.json.example with custom API sample

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

Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 22:48:28 +08:00
tinkle-community
ace4a4904f Refactor: Modularize codebase with separate decision and MCP packages
Architecture improvements:
- Extract AI decision engine to dedicated `decision` package
- Create `mcp` package for Model Context Protocol client
- Separate market data structures into `market/data.go`
- Update trader to use new modular structure

New packages:
- `decision/engine.go` - AI decision logic and prompt building
- `mcp/client.go` - Unified AI API client (DeepSeek/Qwen)
- `market/data.go` - Market data type definitions

Benefits:
- Better separation of concerns
- Improved code organization and maintainability
- Easier to test individual components
- More flexible AI provider integration
- Cleaner dependency management

Updated imports:
- trader/auto_trader.go now uses decision and mcp packages
- Consistent API across different AI providers

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

Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 06:14:57 +08:00