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
---------
This commit is contained in:
tinkle-community
2025-12-06 01:04:26 +08:00
parent 010676c591
commit f4ece051e7
87 changed files with 6870 additions and 10584 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,89 @@
import { useState } from 'react'
import { EquityChart } from './EquityChart'
import { TradingViewChart } from './TradingViewChart'
import { useLanguage } from '../contexts/LanguageContext'
import { t } from '../i18n/translations'
import { BarChart3, CandlestickChart } from 'lucide-react'
interface ChartTabsProps {
traderId: string
}
type ChartTab = 'equity' | 'kline'
export function ChartTabs({ traderId }: ChartTabsProps) {
const { language } = useLanguage()
const [activeTab, setActiveTab] = useState<ChartTab>('equity')
console.log('[ChartTabs] rendering, activeTab:', activeTab)
return (
<div className="binance-card">
{/* Tab Headers - 这是Tab切换按钮区域 */}
<div
className="flex items-center gap-2 p-3"
style={{
borderBottom: '1px solid #2B3139',
background: '#0B0E11',
}}
>
<button
onClick={() => {
console.log('[ChartTabs] switching to equity')
setActiveTab('equity')
}}
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold"
style={
activeTab === 'equity'
? {
background: 'rgba(240, 185, 11, 0.15)',
color: '#F0B90B',
border: '1px solid rgba(240, 185, 11, 0.3)',
}
: {
background: 'transparent',
color: '#848E9C',
border: '1px solid transparent',
}
}
>
<BarChart3 className="w-4 h-4" />
{t('accountEquityCurve', language)}
</button>
<button
onClick={() => {
console.log('[ChartTabs] switching to kline')
setActiveTab('kline')
}}
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold"
style={
activeTab === 'kline'
? {
background: 'rgba(240, 185, 11, 0.15)',
color: '#F0B90B',
border: '1px solid rgba(240, 185, 11, 0.3)',
}
: {
background: 'transparent',
color: '#848E9C',
border: '1px solid transparent',
}
}
>
<CandlestickChart className="w-4 h-4" />
{t('marketChart', language)}
</button>
</div>
{/* Tab Content */}
<div>
{activeTab === 'equity' ? (
<EquityChart traderId={traderId} embedded />
) : (
<TradingViewChart height={400} embedded />
)}
</div>
</div>
)
}

View File

@@ -126,6 +126,11 @@ export function DecisionCard({ decision, language }: DecisionCardProps) {
background: 'rgba(14, 203, 129, 0.1)',
color: '#0ECB81',
}
: action.action === 'wait' || action.action === 'hold'
? {
background: 'rgba(132, 142, 156, 0.1)',
color: '#848E9C',
}
: {
background: 'rgba(248, 113, 113, 0.1)',
color: '#F87171',

View File

@@ -33,9 +33,10 @@ interface EquityPoint {
interface EquityChartProps {
traderId?: string
embedded?: boolean // 嵌入模式(不显示外层卡片)
}
export function EquityChart({ traderId }: EquityChartProps) {
export function EquityChart({ traderId, embedded = false }: EquityChartProps) {
const { language } = useLanguage()
const { user, token } = useAuth()
const [displayMode, setDisplayMode] = useState<'dollar' | 'percent'>('dollar')
@@ -62,7 +63,7 @@ export function EquityChart({ traderId }: EquityChartProps) {
if (error) {
return (
<div className="binance-card p-6">
<div className={embedded ? 'p-6' : 'binance-card p-6'}>
<div
className="flex items-center gap-3 p-4 rounded"
style={{
@@ -89,10 +90,12 @@ export function EquityChart({ traderId }: EquityChartProps) {
if (!validHistory || validHistory.length === 0) {
return (
<div className="binance-card p-6">
<h3 className="text-lg font-semibold mb-6" style={{ color: '#EAECEF' }}>
{t('accountEquityCurve', language)}
</h3>
<div className={embedded ? 'p-6' : 'binance-card p-6'}>
{!embedded && (
<h3 className="text-lg font-semibold mb-6" style={{ color: '#EAECEF' }}>
{t('accountEquityCurve', language)}
</h3>
)}
<div className="text-center py-16" style={{ color: '#848E9C' }}>
<div className="mb-4 flex justify-center opacity-50">
<BarChart3 className="w-16 h-16" />
@@ -193,16 +196,18 @@ export function EquityChart({ traderId }: EquityChartProps) {
}
return (
<div className="binance-card p-3 sm:p-5 animate-fade-in">
<div className={embedded ? 'p-3 sm:p-5' : 'binance-card p-3 sm:p-5 animate-fade-in'}>
{/* Header */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
<div className="flex-1">
<h3
className="text-base sm:text-lg font-bold mb-2"
style={{ color: '#EAECEF' }}
>
{t('accountEquityCurve', language)}
</h3>
{!embedded && (
<h3
className="text-base sm:text-lg font-bold mb-2"
style={{ color: '#EAECEF' }}
>
{t('accountEquityCurve', language)}
</h3>
)}
<div className="flex flex-col sm:flex-row sm:items-baseline gap-2 sm:gap-4">
<span
className="text-2xl sm:text-3xl font-bold mono"

View File

@@ -1,5 +1,4 @@
import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../contexts/LanguageContext'
import { t } from '../i18n/translations'
@@ -11,7 +10,6 @@ import { useSystemConfig } from '../hooks/useSystemConfig'
export function LoginPage() {
const { language } = useLanguage()
const { login, loginAdmin, verifyOTP } = useAuth()
const navigate = useNavigate()
const [step, setStep] = useState<'login' | 'otp'>('login')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
@@ -236,7 +234,9 @@ export function LoginPage() {
<div className="text-right mt-2">
<button
type="button"
onClick={() => navigate('/reset-password')}
onClick={() => {
window.location.href = '/reset-password'
}}
className="text-xs hover:underline"
style={{ color: '#F0B90B' }}
>
@@ -348,7 +348,9 @@ export function LoginPage() {
<p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
{' '}
<button
onClick={() => navigate('/register')}
onClick={() => {
window.location.href = '/register'
}}
className="font-semibold hover:underline transition-colors"
style={{ color: 'var(--brand-yellow)' }}
>

View File

@@ -1,5 +1,4 @@
import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../contexts/LanguageContext'
import { t } from '../i18n/translations'
@@ -14,7 +13,6 @@ import { RegistrationDisabled } from './RegistrationDisabled'
export function RegisterPage() {
const { language } = useLanguage()
const { register, completeRegistration } = useAuth()
const navigate = useNavigate()
const [step, setStep] = useState<'register' | 'setup-otp' | 'verify-otp'>(
'register'
)
@@ -530,7 +528,9 @@ export function RegisterPage() {
<p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
{' '}
<button
onClick={() => navigate('/login')}
onClick={() => {
window.location.href = '/login'
}}
className="font-semibold hover:underline transition-colors"
style={{ color: 'var(--brand-yellow)' }}
>

View File

@@ -0,0 +1,377 @@
import { useEffect, useRef, useState, memo } from 'react'
import { useLanguage } from '../contexts/LanguageContext'
import { t } from '../i18n/translations'
import { ChevronDown, TrendingUp, X } from 'lucide-react'
// 支持的交易所列表 (合约格式)
const EXCHANGES = [
{ id: 'BINANCE', name: 'Binance', prefix: 'BINANCE:', suffix: '.P' },
{ id: 'BYBIT', name: 'Bybit', prefix: 'BYBIT:', suffix: '.P' },
{ id: 'OKX', name: 'OKX', prefix: 'OKX:', suffix: '.P' },
{ id: 'BITGET', name: 'Bitget', prefix: 'BITGET:', suffix: '.P' },
{ id: 'MEXC', name: 'MEXC', prefix: 'MEXC:', suffix: '.P' },
{ id: 'GATEIO', name: 'Gate.io', prefix: 'GATEIO:', suffix: '.P' },
] as const
// 热门交易对
const POPULAR_SYMBOLS = [
'BTCUSDT',
'ETHUSDT',
'SOLUSDT',
'BNBUSDT',
'XRPUSDT',
'DOGEUSDT',
'ADAUSDT',
'AVAXUSDT',
'DOTUSDT',
'LINKUSDT',
'MATICUSDT',
'LTCUSDT',
]
// 时间周期选项
const INTERVALS = [
{ id: '1', label: '1m' },
{ id: '5', label: '5m' },
{ id: '15', label: '15m' },
{ id: '30', label: '30m' },
{ id: '60', label: '1H' },
{ id: '240', label: '4H' },
{ id: 'D', label: '1D' },
{ id: 'W', label: '1W' },
]
interface TradingViewChartProps {
defaultSymbol?: string
defaultExchange?: string
height?: number
showToolbar?: boolean
embedded?: boolean // 嵌入模式(不显示外层卡片)
}
function TradingViewChartComponent({
defaultSymbol = 'BTCUSDT',
defaultExchange = 'BINANCE',
height = 400,
showToolbar = true,
embedded = false,
}: TradingViewChartProps) {
const { language } = useLanguage()
const containerRef = useRef<HTMLDivElement>(null)
const [exchange, setExchange] = useState(defaultExchange)
const [symbol, setSymbol] = useState(defaultSymbol)
const [timeInterval, setTimeInterval] = useState('60')
const [customSymbol, setCustomSymbol] = useState('')
const [showExchangeDropdown, setShowExchangeDropdown] = useState(false)
const [showSymbolDropdown, setShowSymbolDropdown] = useState(false)
const [isFullscreen, setIsFullscreen] = useState(false)
// 获取完整的交易对符号 (合约格式: BINANCE:BTCUSDT.P)
const getFullSymbol = () => {
const exchangeInfo = EXCHANGES.find((e) => e.id === exchange)
const prefix = exchangeInfo?.prefix || 'BINANCE:'
const suffix = exchangeInfo?.suffix || '.P'
return `${prefix}${symbol}${suffix}`
}
// 加载 TradingView Widget
useEffect(() => {
if (!containerRef.current) return
// 清空容器
containerRef.current.innerHTML = ''
// 创建 widget 容器
const widgetContainer = document.createElement('div')
widgetContainer.className = 'tradingview-widget-container'
widgetContainer.style.height = '100%'
widgetContainer.style.width = '100%'
const widgetDiv = document.createElement('div')
widgetDiv.className = 'tradingview-widget-container__widget'
widgetDiv.style.height = '100%'
widgetDiv.style.width = '100%'
widgetContainer.appendChild(widgetDiv)
containerRef.current.appendChild(widgetContainer)
// 加载 TradingView 脚本
const script = document.createElement('script')
script.src =
'https://s3.tradingview.com/external-embedding/embed-widget-advanced-chart.js'
script.type = 'text/javascript'
script.async = true
script.innerHTML = JSON.stringify({
autosize: true,
symbol: getFullSymbol(),
interval: timeInterval,
timezone: 'Etc/UTC',
theme: 'dark',
style: '1',
locale: language === 'zh' ? 'zh_CN' : 'en',
enable_publishing: false,
backgroundColor: 'rgba(11, 14, 17, 1)',
gridColor: 'rgba(43, 49, 57, 0.5)',
hide_top_toolbar: !showToolbar,
hide_legend: false,
save_image: false,
calendar: false,
hide_volume: false,
support_host: 'https://www.tradingview.com',
})
widgetContainer.appendChild(script)
return () => {
if (containerRef.current) {
containerRef.current.innerHTML = ''
}
}
}, [exchange, symbol, timeInterval, language, showToolbar])
// 处理自定义交易对输入
const handleCustomSymbolSubmit = () => {
if (customSymbol.trim()) {
let sym = customSymbol.trim().toUpperCase()
// 如果没有 USDT 后缀,自动加上
if (!sym.endsWith('USDT')) {
sym = sym + 'USDT'
}
setSymbol(sym)
setCustomSymbol('')
setShowSymbolDropdown(false)
}
}
return (
<div
className={`${embedded ? '' : 'binance-card'} overflow-hidden ${embedded ? '' : 'animate-fade-in'} ${
isFullscreen
? 'fixed inset-0 z-50 rounded-none'
: ''
}`}
>
{/* Header */}
<div
className="flex flex-wrap items-center gap-2 p-3 sm:p-4"
style={{ borderBottom: embedded ? 'none' : '1px solid #2B3139' }}
>
{!embedded && (
<div className="flex items-center gap-2">
<TrendingUp className="w-5 h-5" style={{ color: '#F0B90B' }} />
<h3
className="text-base sm:text-lg font-bold"
style={{ color: '#EAECEF' }}
>
{t('marketChart', language)}
</h3>
</div>
)}
{/* Controls */}
<div className={`flex flex-wrap items-center gap-2 ${embedded ? '' : 'ml-auto'}`}>
{/* Exchange Selector */}
<div className="relative">
<button
onClick={() => {
setShowExchangeDropdown(!showExchangeDropdown)
setShowSymbolDropdown(false)
}}
className="flex items-center gap-1 px-3 py-1.5 rounded text-sm font-medium transition-all"
style={{
background: '#1E2329',
border: '1px solid #2B3139',
color: '#EAECEF',
}}
>
{EXCHANGES.find((e) => e.id === exchange)?.name || exchange}
<ChevronDown className="w-4 h-4" style={{ color: '#848E9C' }} />
</button>
{showExchangeDropdown && (
<div
className="absolute top-full left-0 mt-1 py-1 rounded-lg shadow-xl z-20 min-w-[120px]"
style={{
background: '#1E2329',
border: '1px solid #2B3139',
}}
>
{EXCHANGES.map((ex) => (
<button
key={ex.id}
onClick={() => {
setExchange(ex.id)
setShowExchangeDropdown(false)
}}
className="w-full px-4 py-2 text-left text-sm transition-all hover:bg-opacity-50"
style={{
color: exchange === ex.id ? '#F0B90B' : '#EAECEF',
background:
exchange === ex.id
? 'rgba(240, 185, 11, 0.1)'
: 'transparent',
}}
>
{ex.name}
</button>
))}
</div>
)}
</div>
{/* Symbol Selector */}
<div className="relative">
<button
onClick={() => {
setShowSymbolDropdown(!showSymbolDropdown)
setShowExchangeDropdown(false)
}}
className="flex items-center gap-1 px-3 py-1.5 rounded text-sm font-bold transition-all"
style={{
background: 'rgba(240, 185, 11, 0.1)',
border: '1px solid rgba(240, 185, 11, 0.3)',
color: '#F0B90B',
}}
>
{symbol}
<ChevronDown className="w-4 h-4" />
</button>
{showSymbolDropdown && (
<div
className="absolute top-full left-0 mt-1 py-2 rounded-lg shadow-xl z-20 w-[280px]"
style={{
background: '#1E2329',
border: '1px solid #2B3139',
}}
>
{/* Custom Input */}
<div className="px-3 pb-2" style={{ borderBottom: '1px solid #2B3139' }}>
<div className="flex gap-2">
<input
type="text"
value={customSymbol}
onChange={(e) => setCustomSymbol(e.target.value.toUpperCase())}
onKeyDown={(e) => e.key === 'Enter' && handleCustomSymbolSubmit()}
placeholder={t('enterSymbol', language)}
className="flex-1 px-3 py-1.5 rounded text-sm"
style={{
background: '#0B0E11',
border: '1px solid #2B3139',
color: '#EAECEF',
}}
/>
<button
onClick={handleCustomSymbolSubmit}
className="px-3 py-1.5 rounded text-sm font-medium"
style={{
background: '#F0B90B',
color: '#0B0E11',
}}
>
OK
</button>
</div>
</div>
{/* Popular Symbols */}
<div className="px-2 pt-2">
<div
className="text-xs px-2 py-1 mb-1"
style={{ color: '#848E9C' }}
>
{t('popularSymbols', language)}
</div>
<div className="grid grid-cols-3 gap-1">
{POPULAR_SYMBOLS.map((sym) => (
<button
key={sym}
onClick={() => {
setSymbol(sym)
setShowSymbolDropdown(false)
}}
className="px-2 py-1.5 rounded text-xs font-medium transition-all"
style={{
color: symbol === sym ? '#F0B90B' : '#EAECEF',
background:
symbol === sym
? 'rgba(240, 185, 11, 0.1)'
: 'rgba(43, 49, 57, 0.3)',
}}
>
{sym.replace('USDT', '')}
</button>
))}
</div>
</div>
</div>
)}
</div>
{/* Interval Selector */}
<div
className="flex gap-0.5 p-0.5 rounded"
style={{ background: '#0B0E11', border: '1px solid #2B3139' }}
>
{INTERVALS.map((int) => (
<button
key={int.id}
onClick={() => setTimeInterval(int.id)}
className="px-2 py-1 rounded text-xs font-medium transition-all"
style={{
background: timeInterval === int.id ? '#F0B90B' : 'transparent',
color: timeInterval === int.id ? '#0B0E11' : '#848E9C',
}}
>
{int.label}
</button>
))}
</div>
{/* Fullscreen Toggle */}
<button
onClick={() => setIsFullscreen(!isFullscreen)}
className="p-1.5 rounded transition-all"
style={{
background: isFullscreen ? '#F0B90B' : 'transparent',
color: isFullscreen ? '#0B0E11' : '#848E9C',
border: '1px solid #2B3139',
}}
title={isFullscreen ? t('exitFullscreen', language) : t('fullscreen', language)}
>
{isFullscreen ? (
<X className="w-4 h-4" />
) : (
<svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3" />
</svg>
)}
</button>
</div>
</div>
{/* Chart Container */}
<div
ref={containerRef}
style={{
height: isFullscreen ? 'calc(100vh - 60px)' : height,
background: '#0B0E11',
}}
/>
{/* Click outside to close dropdowns */}
{(showExchangeDropdown || showSymbolDropdown) && (
<div
className="fixed inset-0 z-10"
onClick={() => {
setShowExchangeDropdown(false)
setShowSymbolDropdown(false)
}}
/>
)}
</div>
)
}
// 使用 memo 避免不必要的重渲染
export const TradingViewChart = memo(TradingViewChartComponent)