@@ -192,23 +192,6 @@ export interface KlineRow {
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
// ===== Watchlist =====
|
||||
export interface WatchlistEntry {
|
||||
symbol: string
|
||||
added_at: string
|
||||
note?: string
|
||||
name?: string | null
|
||||
}
|
||||
|
||||
export interface Quote {
|
||||
symbol: string
|
||||
price?: number
|
||||
pct?: number
|
||||
close?: number
|
||||
change_pct?: number
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
export interface IndexInstrument {
|
||||
symbol: string
|
||||
name?: string | null
|
||||
@@ -505,111 +488,6 @@ export interface LimitLadderResult {
|
||||
sealed_counts_down?: { real: number; fake: number; pending: number }
|
||||
}
|
||||
|
||||
// ===== Backtest =====
|
||||
export interface BacktestResult {
|
||||
run_id: string
|
||||
config: any
|
||||
stats: Record<string, any>
|
||||
equity_curve: { date: string; value: number }[]
|
||||
trades: any[]
|
||||
per_symbol_stats: { symbol: string; total_return: number }[]
|
||||
}
|
||||
|
||||
// ===== Factor Backtest =====
|
||||
export interface FactorColumn {
|
||||
id: string
|
||||
label: string
|
||||
group: string
|
||||
desc: string
|
||||
}
|
||||
|
||||
export interface GroupStat {
|
||||
group: number
|
||||
label: string
|
||||
total_return: number
|
||||
annual_return: number
|
||||
max_drawdown: number
|
||||
sharpe: number
|
||||
win_rate: number
|
||||
}
|
||||
|
||||
export interface FactorBacktestResult {
|
||||
run_id: string
|
||||
config: Record<string, any>
|
||||
ic_mean: number | null
|
||||
ic_std: number | null
|
||||
ir: number | null
|
||||
ic_win_rate: number | null
|
||||
ic_series: { date: string; ic: number }[]
|
||||
group_stats: GroupStat[]
|
||||
group_nav: Record<string, any>[]
|
||||
long_short_stats: Record<string, any>
|
||||
long_short_nav: { date: string; value: number }[]
|
||||
elapsed_ms: number
|
||||
n_symbols: number
|
||||
n_dates: number
|
||||
error: string | null
|
||||
}
|
||||
|
||||
// ===== Strategy Backtest =====
|
||||
export interface StrategyBacktestTrade {
|
||||
symbol: string
|
||||
name?: string
|
||||
entry_date: string
|
||||
exit_date: string
|
||||
entry_price: number
|
||||
exit_price: number
|
||||
pnl_pct: number
|
||||
duration: number
|
||||
exit_reason: string
|
||||
shares?: number
|
||||
lots?: number
|
||||
position_pct?: number
|
||||
entry_value?: number
|
||||
exit_value?: number
|
||||
pnl_amount?: number
|
||||
entry_score?: number | null
|
||||
entry_signal_date?: string | null
|
||||
exit_signal_date?: string | null
|
||||
blocked_exit_days?: number
|
||||
}
|
||||
|
||||
export interface StrategyBacktestResult {
|
||||
run_id: string
|
||||
config: Record<string, any>
|
||||
stats: Record<string, any>
|
||||
equity_curve: { date: string; value: number; cash?: number; positions?: number; exposure?: number }[]
|
||||
drawdown_curve: { date: string; value: number }[]
|
||||
benchmark_curve?: { date: string; value: number; close?: number; name?: string; symbol?: string }[]
|
||||
trades: StrategyBacktestTrade[]
|
||||
per_symbol_stats: {
|
||||
symbol: string
|
||||
n_trades: number
|
||||
total_return: number
|
||||
win_rate: number
|
||||
best: number
|
||||
worst: number
|
||||
}[]
|
||||
strategy_info: {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
entry_signals: string[]
|
||||
exit_signals: string[]
|
||||
stop_loss: number | null
|
||||
take_profit: number | null
|
||||
trailing_stop: number | null
|
||||
trailing_take_profit_activate: number | null
|
||||
trailing_take_profit_drawdown: number | null
|
||||
score_min: number | null
|
||||
score_max: number | null
|
||||
max_hold_days: number | null
|
||||
source: string
|
||||
}
|
||||
elapsed_ms: number
|
||||
error: string | null
|
||||
}
|
||||
|
||||
// ===== Settings =====
|
||||
|
||||
/** 端点发现清单 —— 对应 tickflow.org/endpoints.json */
|
||||
@@ -856,15 +734,6 @@ export const api = {
|
||||
body: JSON.stringify({ size }),
|
||||
}),
|
||||
|
||||
// 自选列表列配置
|
||||
watchlistColumns: () =>
|
||||
request<{ columns: any[] | null }>('/api/settings/preferences/watchlist-columns'),
|
||||
updateWatchlistColumns: (columns: any[]) =>
|
||||
request<{ columns: any[] }>('/api/settings/preferences/watchlist-columns', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ columns }),
|
||||
}),
|
||||
|
||||
// 策略结果列表列配置
|
||||
screenerResultColumns: () =>
|
||||
request<{ columns: any[] | null }>('/api/settings/preferences/screener-result-columns'),
|
||||
@@ -976,37 +845,6 @@ export const api = {
|
||||
method: 'POST',
|
||||
}),
|
||||
|
||||
watchlistList: () => request<{ symbols: WatchlistEntry[] }>('/api/watchlist'),
|
||||
watchlistAdd: (symbol: string, note = '') =>
|
||||
request<{ symbols: WatchlistEntry[] }>('/api/watchlist', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ symbol, note }),
|
||||
}),
|
||||
watchlistBatchAdd: (symbols: string[], note = '') =>
|
||||
request<{ symbols: WatchlistEntry[]; added: number }>('/api/watchlist/batch', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ symbols, note }),
|
||||
}),
|
||||
watchlistRemove: (symbol: string) =>
|
||||
request<{ symbols: WatchlistEntry[] }>(
|
||||
`/api/watchlist/${encodeURIComponent(symbol)}`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
watchlistMoveToTop: (symbol: string) =>
|
||||
request<{ symbols: WatchlistEntry[] }>(
|
||||
`/api/watchlist/${encodeURIComponent(symbol)}/top`,
|
||||
{ method: 'POST' },
|
||||
),
|
||||
watchlistClear: () =>
|
||||
request<{ removed: number }>('/api/watchlist', { method: 'DELETE' }),
|
||||
watchlistQuotes: () => request<{ quotes: Quote[] }>('/api/watchlist/quotes'),
|
||||
watchlistEnriched: (extColumns?: string) =>
|
||||
request<{ rows: any[]; as_of: string | null; elapsed_ms: number }>(
|
||||
extColumns
|
||||
? `/api/watchlist/enriched?ext_columns=${encodeURIComponent(extColumns)}`
|
||||
: '/api/watchlist/enriched',
|
||||
),
|
||||
|
||||
screenerStrategies: () => request<{ presets: ScreenerStrategy[] }>('/api/screener/strategies'),
|
||||
screenerRunPreset: (strategy_id: string, pool?: string[], asOf?: string, extColumns?: string) =>
|
||||
request<ScreenerResult>('/api/screener/run_preset', {
|
||||
@@ -1047,63 +885,6 @@ export const api = {
|
||||
)
|
||||
},
|
||||
|
||||
backtestStatus: () => request<{ available: boolean }>('/api/backtest/status'),
|
||||
|
||||
backtestRun: (payload: {
|
||||
symbols: string[]
|
||||
entries: string[]
|
||||
exits: string[]
|
||||
start?: string
|
||||
end?: string
|
||||
stop_loss_pct?: number
|
||||
max_hold_days?: number
|
||||
matching?: 'close_t' | 'open_t+1'
|
||||
}) =>
|
||||
request<BacktestResult>('/api/backtest/run', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
|
||||
factorColumns: () =>
|
||||
request<{ columns: FactorColumn[] }>('/api/backtest/factor/columns'),
|
||||
|
||||
factorRun: (payload: {
|
||||
factor_name: string
|
||||
symbols?: string[] | null
|
||||
start?: string | null
|
||||
end?: string | null
|
||||
n_groups?: number
|
||||
rebalance?: 'daily' | 'weekly' | 'monthly'
|
||||
weight?: 'equal' | 'factor_weight'
|
||||
fees_pct?: number
|
||||
slippage_bps?: number
|
||||
}) =>
|
||||
request<FactorBacktestResult>('/api/backtest/factor/run', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
|
||||
strategyBacktestRun: (payload: {
|
||||
strategy_id: string
|
||||
symbols?: string[] | null
|
||||
start?: string | null
|
||||
end?: string | null
|
||||
params?: Record<string, any> | null
|
||||
overrides?: Record<string, any> | null
|
||||
matching?: 'close_t' | 'open_t+1'
|
||||
entry_fill?: 'close_t' | 'open_t+1' | null
|
||||
exit_fill?: 'close_t' | 'open_t+1' | null
|
||||
fees_pct?: number
|
||||
slippage_bps?: number
|
||||
max_positions?: number
|
||||
initial_capital?: number
|
||||
position_sizing?: 'equal' | 'score_weight'
|
||||
}) =>
|
||||
request<StrategyBacktestResult>('/api/backtest/strategy/run', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
|
||||
pipelineRun: () => request<{ job_id: string; reused: boolean }>(
|
||||
'/api/pipeline/run', { method: 'POST' },
|
||||
),
|
||||
|
||||
@@ -1,227 +0,0 @@
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import type { StrategyBacktestResult } from './api'
|
||||
|
||||
/**
|
||||
* 全局回测任务管理 (SSE 模式 + 任务缓存 + 重连支持)。
|
||||
*
|
||||
* 特性:
|
||||
* - 实时进度: EventSource 监听后端 SSE, 推送 day/total/equity
|
||||
* - 可取消: POST /strategy/cancel/{job_key}, 后端 cancel_event
|
||||
* - 切页/刷新保持: 后端按参数 hash 缓存任务, 重连不重启
|
||||
* - 切页: 模块级 store 保持, EventSource 随组件卸载断开, 回来后重连
|
||||
* - 刷新: localStorage 存 job 参数, 刷新后重新连接到同一任务
|
||||
*/
|
||||
|
||||
export interface BacktestProgress {
|
||||
day: number
|
||||
total: number
|
||||
date: string
|
||||
equity: number
|
||||
}
|
||||
|
||||
export interface BacktestTask {
|
||||
id: number
|
||||
isPending: boolean
|
||||
result: StrategyBacktestResult | null
|
||||
progress: BacktestProgress | null
|
||||
error: string | null
|
||||
}
|
||||
|
||||
let current: BacktestTask | null = null
|
||||
const listeners = new Set<() => void>()
|
||||
let taskSeq = 0
|
||||
let eventSource: EventSource | null = null
|
||||
|
||||
const RECONNECT_KEY = 'backtest_reconnect'
|
||||
|
||||
function emit() {
|
||||
listeners.forEach(fn => fn())
|
||||
}
|
||||
|
||||
function subscribe(fn: () => void) {
|
||||
listeners.add(fn)
|
||||
return () => listeners.delete(fn)
|
||||
}
|
||||
|
||||
function getSnapshot() {
|
||||
return current
|
||||
}
|
||||
|
||||
function getServerSnapshot() {
|
||||
return null
|
||||
}
|
||||
|
||||
/** 查询字符串构建 */
|
||||
function buildQuery(params: Record<string, string | number | boolean | undefined | null>): string {
|
||||
const sp = new URLSearchParams()
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v != null && v !== '') sp.set(k, String(v))
|
||||
}
|
||||
return sp.toString()
|
||||
}
|
||||
|
||||
/** 连接 SSE (新建或重连都用这个) */
|
||||
function connectSSE(url: string): void {
|
||||
const id = current?.id ?? ++taskSeq
|
||||
|
||||
// 关闭旧连接
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
eventSource = null
|
||||
}
|
||||
|
||||
const es = new EventSource(url)
|
||||
eventSource = es
|
||||
|
||||
es.addEventListener('progress', (e: MessageEvent) => {
|
||||
if (current?.id !== id) return
|
||||
try {
|
||||
const prog = JSON.parse(e.data) as BacktestProgress
|
||||
current = { ...current, progress: prog }
|
||||
emit()
|
||||
} catch { /* ignore */ }
|
||||
})
|
||||
|
||||
es.addEventListener('done', (e: MessageEvent) => {
|
||||
if (current?.id !== id) return
|
||||
try {
|
||||
const result = JSON.parse(e.data) as StrategyBacktestResult
|
||||
current = { ...current, isPending: false, result, error: null }
|
||||
emit()
|
||||
} catch {
|
||||
current = { ...current, isPending: false, error: '结果解析失败' }
|
||||
emit()
|
||||
}
|
||||
es.close()
|
||||
eventSource = null
|
||||
localStorage.removeItem(RECONNECT_KEY)
|
||||
})
|
||||
|
||||
es.addEventListener('error', (e: MessageEvent) => {
|
||||
if (current?.id !== id) return
|
||||
// SSE error 事件: 有 data 说明是后端主动推送的错误/取消; 无 data 说明是连接断开
|
||||
if (e.data) {
|
||||
try {
|
||||
const msg = JSON.parse(e.data)?.message ?? '回测出错'
|
||||
current = { ...current, isPending: false, error: msg }
|
||||
emit()
|
||||
} catch {
|
||||
current = { ...current, isPending: false, error: '回测出错' }
|
||||
emit()
|
||||
}
|
||||
es.close()
|
||||
eventSource = null
|
||||
localStorage.removeItem(RECONNECT_KEY)
|
||||
}
|
||||
// 无 data: 连接异常断开, EventSource 会自动重连, 不改变状态
|
||||
})
|
||||
}
|
||||
|
||||
/** 启动一次 SSE 回测任务 */
|
||||
export function startBacktest(params: {
|
||||
strategy_id: string
|
||||
symbols?: string[] | null
|
||||
start?: string | null
|
||||
end?: string | null
|
||||
matching?: string
|
||||
entry_fill?: string
|
||||
exit_fill?: string
|
||||
fees_pct?: number
|
||||
slippage_bps?: number
|
||||
max_positions?: number
|
||||
max_exposure_pct?: number
|
||||
initial_capital?: number
|
||||
position_sizing?: string
|
||||
params?: Record<string, any> | null
|
||||
overrides?: Record<string, any> | null
|
||||
mode?: 'position' | 'full'
|
||||
holding_days?: number
|
||||
}): void {
|
||||
// 取消之前的任务状态
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
eventSource = null
|
||||
}
|
||||
|
||||
const id = ++taskSeq
|
||||
current = { id, isPending: true, result: null, progress: null, error: null }
|
||||
emit()
|
||||
|
||||
const qs = buildQuery({
|
||||
strategy_id: params.strategy_id,
|
||||
symbols: params.symbols?.join(','),
|
||||
start: params.start ?? undefined,
|
||||
end: params.end ?? undefined,
|
||||
matching: params.matching,
|
||||
entry_fill: params.entry_fill,
|
||||
exit_fill: params.exit_fill,
|
||||
fees_pct: params.fees_pct,
|
||||
slippage_bps: params.slippage_bps,
|
||||
max_positions: params.max_positions,
|
||||
max_exposure_pct: params.max_exposure_pct,
|
||||
initial_capital: params.initial_capital,
|
||||
position_sizing: params.position_sizing,
|
||||
params: params.params ? JSON.stringify(params.params) : undefined,
|
||||
overrides: params.overrides ? JSON.stringify(params.overrides) : undefined,
|
||||
mode: params.mode,
|
||||
holding_days: params.holding_days,
|
||||
})
|
||||
|
||||
// 存 reconnect 信息 (刷新后用)
|
||||
localStorage.setItem(RECONNECT_KEY, qs)
|
||||
|
||||
connectSSE(`/api/backtest/strategy/stream?${qs}`)
|
||||
}
|
||||
|
||||
/** 停止当前回测任务 (调后端 cancel, 后端 cancel_event → 停止计算) */
|
||||
export async function stopBacktest(): Promise<void> {
|
||||
// 从 reconnect key 提取 job_key (后端按参数 hash 算 job_key)
|
||||
const qs = localStorage.getItem(RECONNECT_KEY)
|
||||
if (qs) {
|
||||
// 解析出参数, 用 fetch 调 cancel
|
||||
try {
|
||||
// job_key 是后端算的 md5, 前端不知道。用 reconnect URL 里的参数重新请求 stream,
|
||||
// 后端会找到同一个 job 并返回它的 job_key? 不行。
|
||||
// 替代: 前端直接关闭 SSE 连接 + 调一个带参数的 cancel 接口。
|
||||
// 简化: 关闭连接即可, 后端检测断开后 (不取消)。需要 cancel 用 POST。
|
||||
// 这里用 cancel 接口: POST /strategy/cancel, body 带 qs 的参数。
|
||||
await fetch('/api/backtest/strategy/cancel', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ qs }),
|
||||
}).catch(() => {})
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
eventSource = null
|
||||
}
|
||||
if (current?.isPending) {
|
||||
current = { ...current, isPending: false, error: '已取消' }
|
||||
emit()
|
||||
}
|
||||
localStorage.removeItem(RECONNECT_KEY)
|
||||
}
|
||||
|
||||
/** 清除任务状态 (隐藏提示) */
|
||||
export function clearBacktest(): void {
|
||||
current = null
|
||||
emit()
|
||||
}
|
||||
|
||||
/** 恢复: 从 localStorage 读取 reconnect 信息, 重新连接 (刷新后调用) */
|
||||
export function tryReconnect(): boolean {
|
||||
const qs = localStorage.getItem(RECONNECT_KEY)
|
||||
if (!qs) return false
|
||||
// 有未完成的任务, 重连
|
||||
const id = ++taskSeq
|
||||
current = { id, isPending: true, result: null, progress: null, error: null }
|
||||
emit()
|
||||
connectSSE(`/api/backtest/strategy/stream?${qs}`)
|
||||
return true
|
||||
}
|
||||
|
||||
/** React hook: 读取当前全局回测任务状态 */
|
||||
export function useBacktestTask(): BacktestTask | null {
|
||||
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
}
|
||||
@@ -16,11 +16,7 @@ export const QK = {
|
||||
overviewMarket: (asOf?: string) => ['overview-market', asOf ?? 'latest'] as const,
|
||||
indexList: ['index-list'] as const,
|
||||
|
||||
// Watchlist
|
||||
watchlist: ['watchlist'] as const,
|
||||
watchlistQuotes: ['watchlist-quotes'] as const,
|
||||
watchlistEnriched: (ext?: string) => ['watchlist-enriched', ext] as const,
|
||||
watchlistKlineBatch: (symbols: string) => ['watchlist-kline-batch', symbols] as const,
|
||||
// Search
|
||||
instrumentSearch: (q: string) => ['instrument-search', q] as const,
|
||||
|
||||
// Screener
|
||||
@@ -31,9 +27,6 @@ export const QK = {
|
||||
marketSnapshot: ['market-snapshot'] as const,
|
||||
limitLadder: (asOf?: string) => ['limit-ladder', asOf] as const,
|
||||
|
||||
// Backtest
|
||||
backtestStatus: ['backtest-status'] as const,
|
||||
|
||||
// Data / Pipeline
|
||||
dataStatus: ['data-status'] as const,
|
||||
pipelineJobs: ['pipeline-jobs'] as const,
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
/**
|
||||
* 策略结果列表自定义列配置。
|
||||
*
|
||||
* 内置列与分组与自选页 (watchlist-columns) 保持一致,额外保留策略特有的
|
||||
* 「策略」「评分」两列。通用列模型/合并/扩展列参数来自 list-columns。
|
||||
*/
|
||||
import { storage } from '@/lib/storage'
|
||||
import {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 买卖触发器信号定义 — 选股页弹窗 / 回测页共用。
|
||||
* 买卖触发器信号定义 — 选股页弹窗共用。
|
||||
*
|
||||
* 信号 ID 必须与后端 backtest/strategy.py:_build_signal_mask 对齐
|
||||
* 信号 ID 必须与后端对齐
|
||||
* (signal_* 前缀为内置原子信号, csg_ 前缀为用户自定义信号)。
|
||||
*/
|
||||
|
||||
|
||||
@@ -27,27 +27,15 @@ export const storage = {
|
||||
/** 策略池 (screener) */
|
||||
strategyPool: kv<string[]>('strategy-pool'),
|
||||
|
||||
/** 自选列表列配置 */
|
||||
watchlistColumns: kv<unknown[]>('watchlist_columns'),
|
||||
|
||||
/** 个股日K信息条指标配置 */
|
||||
stockInfoBarFields: kv<unknown[]>('stock_info_bar_fields'),
|
||||
|
||||
/** 策略结果列表列配置 */
|
||||
screenerResultColumns: kv<unknown[]>('screener_result_columns'),
|
||||
|
||||
/** 自选列表视图模式 table | card */
|
||||
watchlistView: kv<string>('watchlist_view'),
|
||||
|
||||
/** 自选列表日K蜡烛图显示状态 */
|
||||
watchlistCandle: kv<boolean>('watchlist_showCandle'),
|
||||
|
||||
/** 策略结果列表日K蜡烛图显示状态 */
|
||||
screenerCandle: kv<boolean>('screener_showCandle'),
|
||||
|
||||
/** 自选列表板块筛选 */
|
||||
watchlistBoardFilter: kv<string[]>('watchlist_boardFilter'),
|
||||
|
||||
/** Screener 卡片尺寸 */
|
||||
screenerCardSize: kv<string>('screener-card-size'),
|
||||
|
||||
@@ -78,31 +66,6 @@ export const storage = {
|
||||
/** 已保存策略的原始规则(策略ID → 规则文本) */
|
||||
strategyRules: kv<Record<string, string>>('strategy-rules'),
|
||||
|
||||
/** 策略回测快捷区间按钮配置 */
|
||||
strategyBacktestQuickRanges: kv<unknown>('strategy-backtest-quick-ranges'),
|
||||
|
||||
/** 策略回测最后一次成功结果和参数 */
|
||||
strategyBacktestLast: kv<{
|
||||
selectedStrategy: string | null
|
||||
symbols: string
|
||||
start: string
|
||||
end: string
|
||||
matching: 'close_t' | 'open_t+1'
|
||||
entryFill: 'close_t' | 'open_t+1'
|
||||
exitFill: 'close_t' | 'open_t+1'
|
||||
fees: string
|
||||
slippage: string
|
||||
maxPositions: string
|
||||
maxExposure: string
|
||||
initialCapital: string
|
||||
positionSizing: 'equal' | 'score_weight'
|
||||
mode: 'position' | 'full'
|
||||
holdingDays: string
|
||||
params?: Record<string, any>
|
||||
overrides?: Record<string, any>
|
||||
result: any
|
||||
} | null>('strategy-backtest-last'),
|
||||
|
||||
/** 概念分析页面字段配置 */
|
||||
conceptAnalysisConfig: kv<Record<string, any>>('concept-analysis-config'),
|
||||
|
||||
|
||||
@@ -1,18 +1,3 @@
|
||||
/**
|
||||
* 共享 mutation hooks — 消除多页面重复的 useMutation 调用。
|
||||
*/
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { api } from './api'
|
||||
import { QK } from './queryKeys'
|
||||
|
||||
/** 批量添加自选 — Screener / Intraday 共用 */
|
||||
export function useWatchlistBatchAdd() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (symbols: string[]) => api.watchlistBatchAdd(symbols),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: QK.watchlist })
|
||||
qc.invalidateQueries({ queryKey: QK.watchlistEnriched() })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
/**
|
||||
* 自选列表自定义列配置。
|
||||
*
|
||||
* 自选页只保留业务内置列、分组和偏好持久化;通用列模型/合并/扩展列参数
|
||||
* 来自 list-columns,策略页等其它股票列表可复用同一底座。
|
||||
*/
|
||||
|
||||
import { storage } from '@/lib/storage'
|
||||
import {
|
||||
buildExtColumnsParam as buildExtColumnsParamBase,
|
||||
createExtColumn as createExtColumnBase,
|
||||
mergeColumns as mergeColumnsBase,
|
||||
serializeColumns as serializeColumnsBase,
|
||||
type ColumnConfig,
|
||||
type ColumnGroup,
|
||||
type ColumnSource,
|
||||
type ExtColumnDisplayConfig,
|
||||
type CandleColumnConfig,
|
||||
} from '@/lib/list-columns'
|
||||
|
||||
export type { ColumnConfig, ColumnGroup, ColumnSource, ExtColumnDisplayConfig, CandleColumnConfig }
|
||||
|
||||
// ===== 内置列注册表(与当前硬编码一一对应) =====
|
||||
|
||||
export const BUILTIN_COLUMNS: ColumnConfig[] = [
|
||||
// 固定列
|
||||
{ id: 'builtin:symbol', source: { type: 'builtin', key: 'symbol' }, label: '代码/名称', visible: true, pinned: true, align: 'left' },
|
||||
// 价格
|
||||
{ id: 'builtin:price', source: { type: 'builtin', key: 'price' }, label: '现价', visible: true, align: 'center' },
|
||||
{ id: 'builtin:pct', source: { type: 'builtin', key: 'pct' }, label: '涨跌幅', visible: true, align: 'center' },
|
||||
{ id: 'builtin:change_amount', source: { type: 'builtin', key: 'change_amount' }, label: '涨跌额', visible: false, align: 'center' },
|
||||
{ id: 'builtin:amplitude', source: { type: 'builtin', key: 'amplitude' }, label: '振幅', visible: false, align: 'center' },
|
||||
// 成交
|
||||
{ id: 'builtin:turnover', source: { type: 'builtin', key: 'turnover' }, label: '换手率', visible: true, align: 'center' },
|
||||
{ id: 'builtin:amount', source: { type: 'builtin', key: 'amount' }, label: '成交额', visible: false, align: 'center' },
|
||||
{ id: 'builtin:float_val', source: { type: 'builtin', key: 'float_val' }, label: '流通值', visible: false, align: 'center' },
|
||||
{ id: 'builtin:vol_ratio', source: { type: 'builtin', key: 'vol_ratio' }, label: '量比', visible: true, align: 'center' },
|
||||
{ id: 'builtin:annual_vol', source: { type: 'builtin', key: 'annual_vol' }, label: '年化波动', visible: false, align: 'center' },
|
||||
// 均线
|
||||
{ id: 'builtin:ma5', source: { type: 'builtin', key: 'ma5' }, label: 'MA5', visible: false, align: 'center' },
|
||||
{ id: 'builtin:ma10', source: { type: 'builtin', key: 'ma10' }, label: 'MA10', visible: false, align: 'center' },
|
||||
{ id: 'builtin:ma20', source: { type: 'builtin', key: 'ma20' }, label: 'MA20', visible: false, align: 'center' },
|
||||
{ id: 'builtin:ma60', source: { type: 'builtin', key: 'ma60' }, label: 'MA60', visible: false, align: 'center' },
|
||||
// 区间
|
||||
{ id: 'builtin:high_60d', source: { type: 'builtin', key: 'high_60d' }, label: '60日高', visible: false, align: 'center' },
|
||||
{ id: 'builtin:low_60d', source: { type: 'builtin', key: 'low_60d' }, label: '60日低', visible: false, align: 'center' },
|
||||
// 技术指标
|
||||
{ id: 'builtin:rsi6', source: { type: 'builtin', key: 'rsi6' }, label: 'RSI6', visible: false, align: 'center' },
|
||||
{ id: 'builtin:rsi14', source: { type: 'builtin', key: 'rsi14' }, label: 'RSI14', visible: true, align: 'center' },
|
||||
{ id: 'builtin:rsi24', source: { type: 'builtin', key: 'rsi24' }, label: 'RSI24', visible: false, align: 'center' },
|
||||
{ id: 'builtin:macd_dif', source: { type: 'builtin', key: 'macd_dif' }, label: 'MACD-DIF', visible: false, align: 'center' },
|
||||
{ id: 'builtin:macd_dea', source: { type: 'builtin', key: 'macd_dea' }, label: 'MACD-DEA', visible: false, align: 'center' },
|
||||
{ id: 'builtin:macd_hist', source: { type: 'builtin', key: 'macd_hist' }, label: 'MACD柱', visible: false, align: 'center' },
|
||||
{ id: 'builtin:kdj_k', source: { type: 'builtin', key: 'kdj_k' }, label: 'KDJ-K', visible: false, align: 'center' },
|
||||
{ id: 'builtin:kdj_d', source: { type: 'builtin', key: 'kdj_d' }, label: 'KDJ-D', visible: false, align: 'center' },
|
||||
{ id: 'builtin:kdj_j', source: { type: 'builtin', key: 'kdj_j' }, label: 'KDJ-J', visible: false, align: 'center' },
|
||||
{ id: 'builtin:boll_upper', source: { type: 'builtin', key: 'boll_upper' }, label: '布林上轨', visible: false, align: 'center' },
|
||||
{ id: 'builtin:boll_lower', source: { type: 'builtin', key: 'boll_lower' }, label: '布林下轨', visible: false, align: 'center' },
|
||||
{ id: 'builtin:atr14', source: { type: 'builtin', key: 'atr14' }, label: 'ATR14', visible: false, align: 'center' },
|
||||
{ id: 'builtin:vol_ma5', source: { type: 'builtin', key: 'vol_ma5' }, label: '量MA5', visible: false, align: 'center' },
|
||||
{ id: 'builtin:vol_ma10', source: { type: 'builtin', key: 'vol_ma10' }, label: '量MA10', visible: false, align: 'center' },
|
||||
// 动量
|
||||
{ id: 'builtin:momentum_5d', source: { type: 'builtin', key: 'momentum_5d' }, label: '5D 动量', visible: false, align: 'center' },
|
||||
{ id: 'builtin:momentum_10d', source: { type: 'builtin', key: 'momentum_10d' }, label: '10D 动量', visible: false, align: 'center' },
|
||||
{ id: 'builtin:momentum_20d', source: { type: 'builtin', key: 'momentum_20d' }, label: '20D 动量', visible: false, align: 'center' },
|
||||
{ id: 'builtin:momentum_30d', source: { type: 'builtin', key: 'momentum_30d' }, label: '30D 动量', visible: false, align: 'center' },
|
||||
{ id: 'builtin:momentum_60d', source: { type: 'builtin', key: 'momentum' }, label: '60D 动量', visible: true, align: 'center' },
|
||||
// 连板
|
||||
{ id: 'builtin:limit_ups', source: { type: 'builtin', key: 'limit_ups' }, label: '连板', visible: true, align: 'center' },
|
||||
{ id: 'builtin:limit_downs', source: { type: 'builtin', key: 'limit_downs' }, label: '连跌', visible: false, align: 'center' },
|
||||
// 信号 & 图表
|
||||
{ id: 'builtin:signals', source: { type: 'builtin', key: 'signals' }, label: '信号', visible: true, align: 'center' },
|
||||
{ id: 'builtin:candle', source: { type: 'builtin', key: 'candle' }, label: '日k', visible: false, align: 'center' },
|
||||
// 财务指标 (需 Expert 套餐 financial capability, 列默认隐藏)
|
||||
{ id: 'builtin:eps', source: { type: 'builtin', key: 'eps' }, label: 'EPS', visible: false, align: 'center' },
|
||||
{ id: 'builtin:bps', source: { type: 'builtin', key: 'bps' }, label: 'BPS', visible: false, align: 'center' },
|
||||
{ id: 'builtin:roe', source: { type: 'builtin', key: 'roe' }, label: 'ROE', visible: false, align: 'center' },
|
||||
{ id: 'builtin:pe_ttm', source: { type: 'builtin', key: 'pe_ttm' }, label: 'PE(TTM)', visible: false, align: 'center' },
|
||||
{ id: 'builtin:pb', source: { type: 'builtin', key: 'pb' }, label: 'PB', visible: false, align: 'center' },
|
||||
{ id: 'builtin:gross_margin', source: { type: 'builtin', key: 'gross_margin' }, label: '毛利率', visible: false, align: 'center' },
|
||||
{ id: 'builtin:net_margin', source: { type: 'builtin', key: 'net_margin' }, label: '净利率', visible: false, align: 'center' },
|
||||
{ id: 'builtin:revenue_yoy', source: { type: 'builtin', key: 'revenue_yoy' }, label: '营收增速', visible: false, align: 'center' },
|
||||
{ id: 'builtin:net_income_yoy', source: { type: 'builtin', key: 'net_income_yoy' }, label: '净利增速', visible: false, align: 'center' },
|
||||
{ id: 'builtin:debt_ratio', source: { type: 'builtin', key: 'debt_ratio' }, label: '负债率', visible: false, align: 'center' },
|
||||
]
|
||||
|
||||
export const COLUMN_GROUPS: ColumnGroup[] = [
|
||||
{ id: 'price', label: '价格', icon: '💰', keys: ['price', 'pct', 'change_amount', 'amplitude'] },
|
||||
{ id: 'volume', label: '成交', icon: '📊', keys: ['turnover', 'amount', 'float_val', 'vol_ratio', 'annual_vol'] },
|
||||
{ id: 'ma', label: '均线', icon: '📈', keys: ['ma5', 'ma10', 'ma20', 'ma60'] },
|
||||
{ id: 'range', label: '区间', icon: '📏', keys: ['high_60d', 'low_60d'] },
|
||||
{ id: 'tech', label: '技术指标', icon: '🔬', keys: ['rsi6', 'rsi14', 'rsi24', 'macd_dif', 'macd_dea', 'macd_hist', 'kdj_k', 'kdj_d', 'kdj_j', 'boll_upper', 'boll_lower', 'atr14', 'vol_ma5', 'vol_ma10'] },
|
||||
{ id: 'momentum', label: '动量', icon: '🚀', keys: ['momentum_5d', 'momentum_10d', 'momentum_20d', 'momentum_30d', 'momentum_60d'] },
|
||||
{ id: 'limit', label: '连板', icon: '🔥', keys: ['limit_ups', 'limit_downs'] },
|
||||
{ id: 'signal', label: '信号', icon: '📡', keys: ['signals', 'candle'] },
|
||||
{ id: 'finance', label: '财务', icon: '📋', keys: ['eps', 'bps', 'roe', 'pe_ttm', 'pb', 'gross_margin', 'net_margin', 'revenue_yoy', 'net_income_yoy', 'debt_ratio'] },
|
||||
]
|
||||
|
||||
// 操作列(始终显示,不参与自定义)
|
||||
export const ACTION_COLUMN_ID = 'builtin:action'
|
||||
|
||||
// ===== localStorage 持久化 =====
|
||||
|
||||
/** 序列化列配置(只保存用户可自定义的列,排除 pinned 和 action) */
|
||||
export function serializeColumns(columns: ColumnConfig[]): ColumnConfig[] {
|
||||
return serializeColumnsBase(columns, ACTION_COLUMN_ID)
|
||||
}
|
||||
|
||||
/** 序列化并保存到后端 + localStorage */
|
||||
export async function saveColumnConfig(columns: ColumnConfig[]): Promise<void> {
|
||||
const saveable = serializeColumns(columns)
|
||||
// 同时写 localStorage(即时)和后端(持久化)
|
||||
storage.watchlistColumns.set(saveable)
|
||||
try {
|
||||
const { api } = await import('@/lib/api')
|
||||
await api.updateWatchlistColumns(saveable)
|
||||
} catch {
|
||||
// 后端不可用时 localStorage 仍有效
|
||||
}
|
||||
}
|
||||
|
||||
/** 加载列配置:优先后端,回退 localStorage,最终用默认值 */
|
||||
export async function loadColumnConfig(): Promise<ColumnConfig[]> {
|
||||
// 1. 尝试从后端加载
|
||||
try {
|
||||
const { api } = await import('@/lib/api')
|
||||
const res = await api.watchlistColumns()
|
||||
if (res.columns && res.columns.length > 0) {
|
||||
const merged = mergeColumns(res.columns, BUILTIN_COLUMNS)
|
||||
// 同步到 localStorage
|
||||
storage.watchlistColumns.set(serializeColumns(merged))
|
||||
return merged
|
||||
}
|
||||
} catch {
|
||||
// 后端不可用,继续尝试 localStorage
|
||||
}
|
||||
|
||||
// 2. 尝试从 localStorage 加载
|
||||
const saved = storage.watchlistColumns.get([]) as ColumnConfig[]
|
||||
if (saved.length > 0) {
|
||||
return mergeColumns(saved, BUILTIN_COLUMNS)
|
||||
}
|
||||
|
||||
// 3. 默认值
|
||||
return [...BUILTIN_COLUMNS]
|
||||
}
|
||||
|
||||
/** 合并用户保存的列与默认列 */
|
||||
function mergeColumns(saved: ColumnConfig[], defaults: ColumnConfig[]): ColumnConfig[] {
|
||||
return mergeColumnsBase(saved, defaults, { actionColumnId: ACTION_COLUMN_ID })
|
||||
}
|
||||
|
||||
/** 从列配置中提取 ext 列参数,用于后端 enriched 接口 */
|
||||
export function buildExtColumnsParam(columns: ColumnConfig[]): string {
|
||||
return buildExtColumnsParamBase(columns)
|
||||
}
|
||||
|
||||
/** 根据 ext schema 数据创建 ext 列配置 */
|
||||
export function createExtColumn(
|
||||
configId: string,
|
||||
configLabel: string,
|
||||
fieldName: string,
|
||||
fieldLabel?: string,
|
||||
): ColumnConfig {
|
||||
return createExtColumnBase(configId, configLabel, fieldName, fieldLabel)
|
||||
}
|
||||
Reference in New Issue
Block a user