Commit Graph

15 Commits

Author SHA1 Message Date
icy 7d58f56e49 feat: implement hybrid database architecture and frontend encryption
- Add PostgreSQL + SQLite hybrid database support with automatic switching
- Implement frontend AES-GCM + RSA-OAEP encryption for sensitive data
- Add comprehensive DatabaseInterface with all required methods
- Fix compilation issues with interface consistency
- Update all database method signatures to use DatabaseInterface
- Add missing UpdateTraderInitialBalance method to PostgreSQL implementation
- Integrate RSA public key distribution via /api/config endpoint
- Add frontend crypto service with proper error handling
- Support graceful degradation between encrypted and plaintext transmission
- Add directory creation for RSA keys and PEM parsing fixes
- Test both SQLite and PostgreSQL modes successfully
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-06 01:50:06 +08:00
Luna Martinez 97f2eec7fc Merge pull request #88 from fanyinghao/fix-decision-result
fix: Correct error handling in GetFullDecision function
2025-11-01 23:03:55 -04:00
SkywalkerJi 5ad135310f Supports custom system prompts and custom models. 2025-11-01 19:45:54 +08:00
SkywalkerJi 4d0e24feda Reordering system prompts. 2025-11-01 16:25:36 +08:00
SkywalkerJi 631f7b6cfe Eliminating Model Shorting Bias. 2025-11-01 14:44:07 +08:00
icy ceb2f7b435 account system、custom prompt 2025-10-31 03:42:01 +08:00
Yinghao Fan c9f9f4318e fix: Correct error handling in decision parsing
Changes:
- Updated error handling in `GetFullDecision` and `parseFullDecisionResponse` functions to return the decision object even when an error occurs, improving the clarity of error messages.
This ensures that the decision object is consistently returned, allowing for better debugging and handling of errors in the decision-making process.
2025-10-31 02:06:20 +08:00
tpkeeper b773d7289a Fix mcp defaultConfig override issue in multi-trader, multi-AI model scenario 2025-10-30 15:46:17 +08:00
sue 3b4a4d34aa fix: 修复配置硬编码问题
## 修复内容
### 1. AI决策杠杆配置动态化 (decision/engine.go)
- **问题**: System Prompt 中硬编码 50x/20x 杠杆,导致 AI 生成的决策不符合用户配置(5x)
- **修复**:
  - buildSystemPrompt() 新增 btcEthLeverage, altcoinLeverage 参数
  - System Prompt 文本使用动态杠杆值(第225-226行)
  - 示例 JSON 使用配置杠杆值(第299行)
  - 调用时传入实际配置值(第100行)
- **影响**: AI 现在会根据用户配置的杠杆限制生成决策
### 2. 前端初始余额显示优化 (web/src/components/EquityChart.tsx)
- **问题**: 初始余额硬编码为 1000 USDT,与用户配置的 100 USDT 不符
- **修复**: 实现三级回退机制
  1. 优先使用历史数据第一个点的 total_equity
  2. 备用使用当前账户 account.total_equity
  3. 最后使用默认值 100(匹配常见配置)
- **影响**: 前端显示的初始余额现在与实际配置一致
## 技术细节
**函数签名变更**:
```go
// 修改前
func buildSystemPrompt(accountEquity float64) string
// 修改后
func buildSystemPrompt(accountEquity float64, btcEthLeverage, altcoinLeverage int) string
```
**React 状态优化**:
```typescript
// 修改前
const initialBalance = history[0]?.total_equity || 1000;
// 修改后
const initialBalance = history[0]?.total_equity || account?.total_equity || 100;
```
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-30 02:43:14 +08:00
tinkle-community 3735df24dc Refactor: Improve AI prompt with more technical analysis methods
Changes to decision/engine.go:
- Clean up Context struct field alignment for better readability
- Enhance system prompt to include more technical analysis methods:
  * Added: technical resistance levels, Fibonacci, volatility bands
  * Changed wording from "you can do X" to "you can do but not limited to X"
  to encourage AI to use broader range of analysis techniques
This gives the AI decision engine more explicit guidance on available
technical analysis tools while maintaining flexibility.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 22:05:58 +08:00
PorunC cf9fdeafb2 Feat: Integrate leverage configuration across trading system
- Pass leverage config through TraderManager to AutoTrader
- Add BTCETHLeverage and AltcoinLeverage fields to Context and AutoTraderConfig
- Update decision validation to use configured leverage limits
- Display configured leverage in startup message
- Update error messages to show current leverage limits
Changes:
- main.go: Pass leverage config to AddTrader, update startup message
- manager/trader_manager.go: Accept and forward leverage config
- trader/auto_trader.go: Store leverage config, pass to Context
- decision/engine.go: Use dynamic leverage limits in validation
This completes the leverage configuration feature implementation.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 20:30:04 +08:00
tinkle-community d7d2d5c880 Refactor: Give AI full freedom to analyze raw sequence data
Remove prescriptive indicator combinations and let AI freely use all available data.
**Changes**:
- Emphasized AI has access to **raw sequence data** (MidPrices array, 4h candles)
- Listed all available sequences: price, technical (EMA/MACD/RSI), and capital flow (volume/OI)
- Removed hard-coded indicator combinations (e.g., "MACD + RSI + Volume")
- Changed from prescriptive examples to open-ended analysis freedom
- AI can now freely perform trend analysis, pattern recognition, support/resistance calculation
- Reduced minimum close-open interval from 30min to 15min for more flexibility
**Before**:
```
强信号示例:
- 趋势突破 + 多个指标确认(MACD + RSI + 成交量)
- 持仓量暴增 + 价格突破关键位
```
**After**:
```
你拥有的完整数据:
- 📊 原始序列:3分钟价格序列(MidPrices数组) + 4小时K线序列
- 📈 技术序列:EMA20序列、MACD序列、RSI7序列、RSI14序列
- 💰 资金序列:成交量序列、持仓量(OI)序列、资金费率
分析方法(完全由你自主决定):
- 自由运用序列数据,你可以做趋势分析、形态识别、支撑阻力计算
- 多维度交叉验证(价格+量+OI+指标+序列形态)
- 用你认为最有效的方法发现高确定性机会
```
**Philosophy**: Trust AI to discover effective patterns in raw data rather than constraining it to pre-defined indicator combinations.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 14:33:54 +08:00
tinkle-community d4a5c0534d Feature: Add position holding duration to AI decision context
Track and display how long each position has been held to help AI make better timing decisions.
**Implementation**:
- Added UpdateTime field to PositionInfo struct (decision/engine.go:26)
- Added positionFirstSeenTime map to AutoTrader for tracking (trader/auto_trader.go:60)
- Record opening time when position is created successfully:
  - executeOpenLongWithRecord: Records timestamp for long positions (trader/auto_trader.go:540-541)
  - executeOpenShortWithRecord: Records timestamp for short positions (trader/auto_trader.go:593-594)
- Fallback tracking in buildTradingContext for program restart scenarios (trader/auto_trader.go:386-392)
- Auto-cleanup closed positions from tracking map (trader/auto_trader.go:409-414)
- Display duration in user prompt with smart formatting:
  - Under 60 min: "持仓时长25分钟"
  - Over 60 min: "持仓时长2小时15分钟"
**Example Output**:
```
1. TAOUSDT LONG | 入场价435.5300 当前价433.1900 | 盈亏-0.54% | 杠杆20x | 保证金25 | 强平价418.1528 | 持仓时长2小时15分钟
```
**Benefits**:
- AI can see how long positions have been held
- Helps enforce minimum holding period (30-60 min) from system prompt
- Simple implementation with minimal overhead
- Auto-cleanup prevents memory leaks
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 14:20:40 +08:00
tinkle-community 00291617f1 Refactor: Enhance AI decision engine with Sharpe ratio optimization
Major improvements to the AI trading decision engine:
**Core Changes in decision/engine.go** (175 lines modified):
1. **Sharpe Ratio Optimization Focus**
   - Restructured system prompt to emphasize Sharpe ratio maximization
   - Added clear guidance: high-quality trades over frequent trading
   - Explained that 3-minute scan interval ≠ trade every cycle
2. **Trading Frequency Controls**
   - Defined optimal frequency: 2-4 trades/day (0.1-0.2 trades/hour)
   - Over-trading threshold: >2 trades/hour indicates issues
   - Minimum holding period: 30-60 minutes per position
3. **Long/Short Balance Incentives**
   - Emphasized equal profit potential for long and short positions
   - Removed long-bias with explicit short trading encouragement
   - Clear guidance: uptrend→long, downtrend→short, sideways→wait
4. **Stricter Entry Signal Standards**
   - Strong signals only: confidence ≥75, multi-indicator confirmation
   - Weak signals explicitly discouraged (single indicator, unclear trend)
   - Self-check mechanism to prevent premature re-entry (<30min)
5. **Enhanced Sharpe Ratio Feedback Loop**
   - Sharpe < -0.5: Stop trading for 6+ cycles (18min), deep reflection
   - Sharpe -0.5~0: Strict control, confidence >80 only
   - Sharpe 0~0.7: Maintain current strategy
   - Sharpe >0.7: Consider position size increase
6. **Risk-Reward Ratio Validation**
   - Added hard constraint: R:R must be ≥ 3.0:1
   - Automatic calculation and validation in `validateDecision()`
   - Rejects trades with insufficient risk-reward ratio
7. **Improved Prompt Structure**
   - More organized sections with clear headers
   - Actionable guidance instead of abstract principles
   - Better examples for JSON output format
**Impact**: These changes should significantly improve trading quality,
reduce over-trading, and increase Sharpe ratio through better risk management
and trade selection discipline.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 12:49:34 +08:00
tinkle-community b2c6925c89 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
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 06:14:57 +08:00