@zhangxij/dsh-positions 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +92 -2
- package/client.js +562 -0
- package/cordis.patch.yml +9 -0
- package/docs/screenshots/01-overview.jpg +0 -0
- package/docs/screenshots/02-calc.jpg +0 -0
- package/docs/screenshots/03-plans.jpg +0 -0
- package/docs/screenshots/04-history.jpg +0 -0
- package/docs/screenshots/05-settings.jpg +0 -0
- package/icon-512.png +0 -0
- package/index.js +322 -0
- package/package.json +55 -4
- package/screenshots.json +7 -0
- package/seed.js +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zhang-1239
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,93 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 持仓成本台 · DSH 插件
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
在 DeepSeek Harness 里记持仓、记成交,**买入/卖出之前先算清楚成本会变成多少**。
|
|
4
|
+
|
|
5
|
+
大多数看盘软件告诉你「现在多少钱」,但不告诉你「买完这 200 股之后,我的成本、仓位、保本价会变成多少」。
|
|
6
|
+
这个插件只做这一件事,顺便把持仓和成交流水记下来。
|
|
7
|
+
|
|
8
|
+
> 不含行情、不联网、不荐股。所有数字都来自你自己录入的成交记录。
|
|
9
|
+
|
|
10
|
+
## 截图
|
|
11
|
+
|
|
12
|
+

|
|
13
|
+
|
|
14
|
+

|
|
15
|
+
|
|
16
|
+

|
|
17
|
+
|
|
18
|
+

|
|
19
|
+
|
|
20
|
+

|
|
21
|
+
|
|
22
|
+
## 安装
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
dsh plugin --profile web add @zhangxij/dsh-positions
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
装完重启 DSH,左侧栏会多一个「持仓」入口。
|
|
29
|
+
|
|
30
|
+
本地开发时(未发布 npm):
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
dsh plugin --profile web add file:D:\path\to\dsh-positions
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
具体参数以 `dsh plugin --help` 为准。
|
|
37
|
+
|
|
38
|
+
## 怎么用
|
|
39
|
+
|
|
40
|
+
1. **记一笔**:顶部一行填股票、日期、买卖、价格、数量(费用可留空,会按费率估算),点「写入历史」。
|
|
41
|
+
2. **理论评价**:勾选维度后,表格右侧会多出对应列(当前显示「待规则」,规则留到后续版本)。
|
|
42
|
+
3. **分组**:展开某只股票,在详情里改「分组」,表格会按分组聚合出汇总行。
|
|
43
|
+
4. **测算**:展开股票 → 测算区填方向/价格/数量 → 立刻看到费用、累计数量、新成本;可以加多组一起比较,点「保存测算」会记住。
|
|
44
|
+
5. **现价/当日盈亏**:展开后填,用于计算市值与仓位占比。这是你自己填的数字,不是行情。
|
|
45
|
+
|
|
46
|
+
## 数据在哪
|
|
47
|
+
|
|
48
|
+
优先级从高到低:
|
|
49
|
+
|
|
50
|
+
1. `cordis.patch.yml` 里的 `config.dataDir`
|
|
51
|
+
2. 环境变量 `DSH_POSITIONS_DATA`
|
|
52
|
+
3. 仓库内 `data/`(仅开发目录存在时使用)
|
|
53
|
+
4. `%LOCALAPPDATA%\dsh-positions`(Windows)/ `~/.local/share/dsh-positions`(其他系统)
|
|
54
|
+
|
|
55
|
+
文件只有一个:`state.json`,每次修改立即落盘。**不会写进 `node_modules`。**
|
|
56
|
+
|
|
57
|
+
首次启动会写入 5 只示例股票,保证装完不是空白页;示例可以直接删。
|
|
58
|
+
|
|
59
|
+
## 隐私与权限
|
|
60
|
+
|
|
61
|
+
- 不发起任何外部网络请求(没有行情、没有统计、没有遥测)。
|
|
62
|
+
- 只读写上面那个数据目录里的 `state.json`。
|
|
63
|
+
- 服务端路由挂在 DSH 自身 HTTP 服务下(`/positions/*`),会校验同源,跨站请求直接 403。
|
|
64
|
+
- 卸载插件不会删数据目录,需要清空请手动删。
|
|
65
|
+
|
|
66
|
+
## 已知限制
|
|
67
|
+
|
|
68
|
+
- 没有行情,所以「市值 / 当日盈亏」要你自己填现价与盈亏。
|
|
69
|
+
- 理论评价目前只有标签位,规则判定要到后续版本。
|
|
70
|
+
- 单机单用户,没有账号体系(数据在你自己电脑上)。
|
|
71
|
+
- 无导出功能(后续加 JSON/CSV 导出)。
|
|
72
|
+
|
|
73
|
+
## 开发
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
index.js 服务端:数据目录、读写、/positions 路由
|
|
77
|
+
client.js 浏览器端:左侧栏入口 + 单页面板
|
|
78
|
+
seed.js 首次启动的示例数据
|
|
79
|
+
cordis.patch.yml 插件挂载与默认配置
|
|
80
|
+
test/ 服务端测试
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
跑测试:
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
node test/server.test.mjs
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
测试会用一个临时目录,不会碰你的真实数据。
|
|
90
|
+
|
|
91
|
+
## 免责声明
|
|
92
|
+
|
|
93
|
+
本插件只做记账与成本推算,不提供行情、不构成投资建议。市场有风险,决策请自负。
|
package/client.js
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 持仓成本台 · 浏览器端
|
|
3
|
+
*
|
|
4
|
+
* 与网页版持仓页一致:
|
|
5
|
+
* 分组管理(整行) → 持仓表 → 展开/测算(同一张表里的行内测算)
|
|
6
|
+
* 视觉上照搬网页版:白底、浅灰表头、测算行蓝底、行尾 保存/删除。
|
|
7
|
+
*/
|
|
8
|
+
window.__ModuleLoader__.load({
|
|
9
|
+
id: '@zhangxij/dsh-positions',
|
|
10
|
+
factory(require) {
|
|
11
|
+
const React = require('react')
|
|
12
|
+
const h = React.createElement
|
|
13
|
+
const { useEffect, useMemo, useState } = React
|
|
14
|
+
|
|
15
|
+
const API = '/positions'
|
|
16
|
+
const PANEL_ID = 'positions'
|
|
17
|
+
|
|
18
|
+
/* ------------------------------------------------------------ 计算 */
|
|
19
|
+
|
|
20
|
+
function calcRecords(records, feeRate) {
|
|
21
|
+
const rate = Number(feeRate) > 0 ? Number(feeRate) : 0.0003
|
|
22
|
+
let cumQty = 0
|
|
23
|
+
let cumInvest = 0
|
|
24
|
+
return (records || [])
|
|
25
|
+
.slice()
|
|
26
|
+
.sort((a, b) => String(a.date).localeCompare(String(b.date)))
|
|
27
|
+
.map((r) => {
|
|
28
|
+
const turnover = Number(r.price) * Number(r.qty)
|
|
29
|
+
const fee = r.feeOverride !== undefined && r.feeOverride !== null ? Number(r.feeOverride) : turnover * rate
|
|
30
|
+
const net = r.side === '买入' ? turnover + fee : turnover - fee
|
|
31
|
+
if (r.side === '买入') {
|
|
32
|
+
cumQty += Number(r.qty)
|
|
33
|
+
cumInvest += net
|
|
34
|
+
} else {
|
|
35
|
+
cumQty -= Number(r.qty)
|
|
36
|
+
cumInvest -= net
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
date: r.date,
|
|
40
|
+
side: r.side,
|
|
41
|
+
price: Number(r.price),
|
|
42
|
+
qty: Number(r.qty),
|
|
43
|
+
fee,
|
|
44
|
+
net,
|
|
45
|
+
cumQty,
|
|
46
|
+
cumInvest,
|
|
47
|
+
cost: cumQty > 0 ? cumInvest / cumQty : null,
|
|
48
|
+
feeFromImport: r.feeOverride !== undefined
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function previewCalc(base, row, feeRate) {
|
|
54
|
+
const rate = Number(feeRate) > 0 ? Number(feeRate) : 0.0003
|
|
55
|
+
const price = Number(row.price)
|
|
56
|
+
const qty = Number(row.qty)
|
|
57
|
+
if (!(price > 0) || !(qty > 0)) return { fee: '—', net: '—', cumQty: '—', cumInvest: '—', cost: '—', error: '' }
|
|
58
|
+
const turnover = price * qty
|
|
59
|
+
const fee = turnover * rate
|
|
60
|
+
const net = row.side === '卖出' ? turnover - fee : turnover + fee
|
|
61
|
+
if (row.side === '卖出' && qty > base.cumQty) {
|
|
62
|
+
return { fee: '—', net: '—', cumQty: '—', cumInvest: '—', cost: '超量', error: '超量' }
|
|
63
|
+
}
|
|
64
|
+
const q = row.side === '买入' ? base.cumQty + qty : base.cumQty - qty
|
|
65
|
+
const invest = row.side === '买入' ? base.cumInvest + net : base.cumInvest - net
|
|
66
|
+
return {
|
|
67
|
+
fee: fee.toFixed(2),
|
|
68
|
+
net: net.toFixed(2),
|
|
69
|
+
cumQty: q,
|
|
70
|
+
cumInvest: invest.toFixed(2),
|
|
71
|
+
cost: q > 0 ? (invest / q).toFixed(3) : '—',
|
|
72
|
+
error: ''
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const money = (v) => '¥' + Number(v || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
|
77
|
+
const signed = (v) => {
|
|
78
|
+
const n = Number(v || 0)
|
|
79
|
+
return (n >= 0 ? '+' : '-') + Math.abs(n).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
|
80
|
+
}
|
|
81
|
+
const today = () => new Date().toISOString().slice(0, 10)
|
|
82
|
+
const rawIndexOf = (state, name, row) => {
|
|
83
|
+
const stock = state.stocks.find((s) => s.name === name)
|
|
84
|
+
if (!stock) return -1
|
|
85
|
+
return stock.records.findIndex(
|
|
86
|
+
(r) => r.date === row.date && r.side === row.side && Number(r.price) === Number(row.price) && Number(r.qty) === Number(row.qty)
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/* -------------------------------------------------------------- CSS */
|
|
91
|
+
|
|
92
|
+
const CSS = `
|
|
93
|
+
.pos-root { display:flex; flex-direction:column; height:100%; min-height:0; overflow:auto;
|
|
94
|
+
background:#f5f7fb; color:#1f2937; font-size:13px; line-height:1.55; }
|
|
95
|
+
.pos-root * { box-sizing:border-box; }
|
|
96
|
+
.pos-wrap { max-width:1320px; width:100%; margin:0 auto; padding:18px 24px 48px; }
|
|
97
|
+
.pos-title { margin:0; font-size:20px; font-weight:600; color:#1f2937; }
|
|
98
|
+
.pos-sub { margin:4px 0 0; font-size:12px; color:#667085; }
|
|
99
|
+
.pos-head { display:flex; align-items:flex-start; gap:16px; margin-bottom:12px; }
|
|
100
|
+
.pos-head-actions { margin-left:auto; display:flex; gap:8px; }
|
|
101
|
+
.pos-btn { height:32px; padding:0 12px; border-radius:8px; font-size:12px; cursor:pointer;
|
|
102
|
+
border:1px solid #dde3ee; background:#fff; color:#1f2937; }
|
|
103
|
+
.pos-btn:hover { border-color:#2457d6; color:#2457d6; }
|
|
104
|
+
.pos-btn.primary { background:#2457d6; border-color:#2457d6; color:#fff; }
|
|
105
|
+
.pos-btn.primary:hover { background:#1d4ac0; color:#fff; }
|
|
106
|
+
.pos-btn:disabled { opacity:.5; cursor:default; }
|
|
107
|
+
.pos-card { background:#fff; border:1px solid #dde3ee; border-radius:12px; }
|
|
108
|
+
.pos-form { display:flex; gap:8px; align-items:center; flex-wrap:wrap; padding:10px 12px; margin-bottom:12px; }
|
|
109
|
+
.pos-input, .pos-select { height:30px; border-radius:8px; border:1px solid #dde3ee; background:#fff; color:#1f2937; padding:0 8px; font-size:12px; }
|
|
110
|
+
.pos-input.num { width:100px; text-align:right; }
|
|
111
|
+
.pos-filter { padding:10px 12px; margin-bottom:12px; }
|
|
112
|
+
.pos-filter-head { display:flex; align-items:center; justify-content:space-between; font-weight:600; font-size:13px; margin-bottom:8px; gap:8px; }
|
|
113
|
+
.pos-chips { display:flex; gap:6px; flex-wrap:wrap; }
|
|
114
|
+
.pos-chip { display:inline-flex; align-items:center; gap:6px; height:26px; padding:0 10px; border-radius:999px;
|
|
115
|
+
border:1px solid #dde3ee; background:#fff; font-size:12px; color:#344054; }
|
|
116
|
+
.pos-chip .n { color:#667085; font-size:11px; }
|
|
117
|
+
.pos-mini { font-size:12px; padding:0 10px; height:26px; border-radius:8px; cursor:pointer; border:1px solid #dde3ee; background:#fff; color:#1f2937; }
|
|
118
|
+
.pos-mini:hover { border-color:#2457d6; color:#2457d6; }
|
|
119
|
+
.pos-link { border:none; background:none; color:#2457d6; cursor:pointer; font-size:12px; padding:0 4px; }
|
|
120
|
+
.pos-link:hover { text-decoration:underline; }
|
|
121
|
+
.pos-link.danger { color:#b42318; }
|
|
122
|
+
.pos-table-wrap { overflow:auto; background:#fff; border:1px solid #dde3ee; border-radius:12px; }
|
|
123
|
+
.pos-table { width:100%; border-collapse:collapse; font-size:13px; white-space:nowrap; }
|
|
124
|
+
.pos-table th, .pos-table td { padding:8px 10px; text-align:left; border-bottom:1px solid #eef1f6; }
|
|
125
|
+
.pos-table th { background:#f8fafc; font-weight:600; color:#344054; }
|
|
126
|
+
.pos-table tr:last-child td { border-bottom:none; }
|
|
127
|
+
.pos-group td { background:#f8fafc; }
|
|
128
|
+
.pos-group-inner { display:flex; align-items:center; gap:18px; flex-wrap:wrap; font-size:12px; color:#475467; }
|
|
129
|
+
.pos-tag { display:inline-block; padding:2px 10px; border-radius:6px; border:1px solid; font-size:12px; font-weight:600; }
|
|
130
|
+
.pos-muted { color:#667085; }
|
|
131
|
+
.pos-up { color:#b42318; }
|
|
132
|
+
.pos-down { color:#047857; }
|
|
133
|
+
.pos-row { cursor:pointer; }
|
|
134
|
+
.pos-row:hover td { background:#f8faff; }
|
|
135
|
+
.pos-detail td { background:#f8fafc; padding:0 !important; }
|
|
136
|
+
.pos-detail-box { padding:14px 16px 18px; }
|
|
137
|
+
.pos-list { width:100%; border-collapse:collapse; font-size:12px; background:#fff; border:1px solid #eef1f6; border-radius:10px; overflow:hidden; }
|
|
138
|
+
.pos-list th, .pos-list td { padding:7px 10px; text-align:left; border-bottom:1px solid #eef1f6; }
|
|
139
|
+
.pos-list th { background:#f8fafc; font-weight:600; color:#475467; }
|
|
140
|
+
.pos-list tr:last-child td { border-bottom:none; }
|
|
141
|
+
.pos-calc-tr td { background:#eef4ff; }
|
|
142
|
+
.pos-calc-tr.pending td { background:#f8fafc; color:#667085; }
|
|
143
|
+
.pos-calc-tr.error td { background:#feeceb; }
|
|
144
|
+
.pos-calc-tr.saved td { background:#e8f7f0; }
|
|
145
|
+
.pos-chip.ok { background:#e8f7f0; border-color:#b7e4cf; color:#047857; }
|
|
146
|
+
.pos-cell-input { width:100%; min-width:70px; border:1px solid #dde3ee; border-radius:6px; background:#fff; color:#1f2937; padding:4px 6px; font-size:12px; }
|
|
147
|
+
.pos-calc-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:10px; }
|
|
148
|
+
.pos-note { font-size:11px; color:#98a2b3; margin:8px 0 0; }
|
|
149
|
+
.pos-empty { padding:48px; text-align:center; color:#667085; }
|
|
150
|
+
.pos-error { color:#b42318; font-size:12px; margin-bottom:8px; }
|
|
151
|
+
.pos-mask { position:fixed; inset:0; background:rgba(15,23,42,.45); z-index:60; display:flex; align-items:center; justify-content:center; padding:24px; }
|
|
152
|
+
.pos-modal { width:100%; max-width:1120px; max-height:88vh; overflow:auto; background:#fff; border-radius:14px;
|
|
153
|
+
box-shadow:0 24px 60px rgba(0,0,0,.28); color:#1f2937; }
|
|
154
|
+
.pos-modal-head { position:sticky; top:0; display:flex; align-items:center; justify-content:space-between; gap:12px;
|
|
155
|
+
padding:12px 16px; background:#fff; border-bottom:1px solid #dde3ee; }
|
|
156
|
+
.pos-modal-head strong { font-size:15px; }
|
|
157
|
+
.pos-modal-body { padding:14px 16px 20px; }
|
|
158
|
+
.pos-grow { display:flex; align-items:center; gap:12px; padding:8px 0; border-bottom:1px solid #eef1f6; }
|
|
159
|
+
.pos-grow:last-child { border-bottom:none; }
|
|
160
|
+
.pos-grow .name { min-width:110px; font-weight:600; }
|
|
161
|
+
.pos-grow .pos-input { width:120px; }
|
|
162
|
+
`
|
|
163
|
+
|
|
164
|
+
/* ------------------------------------------------------------ 图标 */
|
|
165
|
+
|
|
166
|
+
function Icon(props) {
|
|
167
|
+
const size = props?.size || 16
|
|
168
|
+
return h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true' },
|
|
169
|
+
h('rect', { x: 1.5, y: 2.5, width: 13, height: 11, rx: 2, stroke: 'currentColor', strokeWidth: 1.2 }),
|
|
170
|
+
h('path', { d: 'M5 7.2h6M5 9.8h4', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round' })
|
|
171
|
+
)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function Modal(props) {
|
|
175
|
+
return h('div', { className: 'pos-mask', onClick: (e) => { if (e.target === e.currentTarget) props.onClose() } },
|
|
176
|
+
h('div', { className: 'pos-modal', style: props.maxWidth ? { maxWidth: props.maxWidth } : undefined },
|
|
177
|
+
h('div', { className: 'pos-modal-head' },
|
|
178
|
+
h('strong', null, props.title),
|
|
179
|
+
h('button', { className: 'pos-btn', onClick: props.onClose }, '关闭')
|
|
180
|
+
),
|
|
181
|
+
h('div', { className: 'pos-modal-body' }, props.children)
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/* --------------------------------------------------- 历史 + 测算表 */
|
|
187
|
+
|
|
188
|
+
function Ledger(props) {
|
|
189
|
+
const { stock, feeRate, savedRows, onSave, onDeleteRecord } = props
|
|
190
|
+
const [rows, setRows] = useState(() => (savedRows || []).map((r) => Object.assign({}, r)))
|
|
191
|
+
const [dirty, setDirty] = useState(false)
|
|
192
|
+
const base = { cumQty: stock.cumQty, cumInvest: stock.cumInvest }
|
|
193
|
+
|
|
194
|
+
const update = (i, field, value) => {
|
|
195
|
+
setRows((prev) => prev.map((row, idx) => (idx === i ? Object.assign({}, row, { [field]: value, saved: false }) : row)))
|
|
196
|
+
setDirty(true)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const persist = async (next) => {
|
|
200
|
+
setRows(next)
|
|
201
|
+
setDirty(false)
|
|
202
|
+
await onSave(next)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const saveRow = async (i) => {
|
|
206
|
+
const row = rows[i]
|
|
207
|
+
if (!(Number(row.price) > 0) || !(Number(row.qty) > 0)) return
|
|
208
|
+
await persist(rows.map((r, idx) => (idx === i ? Object.assign({}, r, { saved: true }) : r)))
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const saveAll = async () => {
|
|
212
|
+
const next = rows.map((r) => (Number(r.price) > 0 && Number(r.qty) > 0 ? Object.assign({}, r, { saved: true }) : r))
|
|
213
|
+
await persist(next)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return h('div', null,
|
|
217
|
+
h('div', { className: 'pos-muted', style: { fontSize: 12, marginBottom: 8 } }, '历史记录 + 测算'),
|
|
218
|
+
|
|
219
|
+
h('table', { className: 'pos-list' },
|
|
220
|
+
h('thead', null, h('tr', null,
|
|
221
|
+
['日期', '方向', '价格', '数量', '费用', '当次含费用投入', '累计数量', '累计投入', '累计成本', '类型']
|
|
222
|
+
.map((t, i) => h('th', { key: i }, t))
|
|
223
|
+
)),
|
|
224
|
+
h('tbody', null,
|
|
225
|
+
stock.records.map((r, i) => h('tr', { key: 'h' + i },
|
|
226
|
+
h('td', null, r.date),
|
|
227
|
+
h('td', null, r.side),
|
|
228
|
+
h('td', null, r.price.toFixed(2)),
|
|
229
|
+
h('td', null, r.qty),
|
|
230
|
+
h('td', null, r.feeFromImport ? r.fee.toFixed(2) + '*' : r.fee.toFixed(2)),
|
|
231
|
+
h('td', null, r.net.toFixed(2)),
|
|
232
|
+
h('td', null, r.cumQty),
|
|
233
|
+
h('td', null, r.cumInvest.toFixed(2)),
|
|
234
|
+
h('td', null, r.cost === null ? '—' : r.cost.toFixed(3)),
|
|
235
|
+
h('td', null,
|
|
236
|
+
h('span', { className: 'pos-chip', style: { height: 22, fontSize: 11 } }, '实际成交'),
|
|
237
|
+
h('button', { className: 'pos-link danger', style: { marginLeft: 6 }, onClick: () => onDeleteRecord(stock.name, r) }, '删除')
|
|
238
|
+
)
|
|
239
|
+
)),
|
|
240
|
+
|
|
241
|
+
rows.map((row, i) => {
|
|
242
|
+
const p = previewCalc(base, row, feeRate)
|
|
243
|
+
const valid = Number(row.price) > 0 && Number(row.qty) > 0
|
|
244
|
+
let cls = 'pos-calc-tr'
|
|
245
|
+
if (row.saved) cls += ' saved'
|
|
246
|
+
else if (!valid) cls += ' pending'
|
|
247
|
+
else if (p.error) cls += ' error'
|
|
248
|
+
|
|
249
|
+
return h('tr', { key: 'c' + i, className: cls },
|
|
250
|
+
h('td', null, h('span', { className: 'pos-chip', style: { height: 22, fontSize: 11, background: '#fff7e6', borderColor: '#f3d19e', color: '#b45309' } }, '测算 ' + (i + 1))),
|
|
251
|
+
h('td', null, h('select', {
|
|
252
|
+
className: 'pos-cell-input', value: row.side,
|
|
253
|
+
onChange: (e) => update(i, 'side', e.target.value)
|
|
254
|
+
}, h('option', { value: '买入' }, '买入'), h('option', { value: '卖出' }, '卖出'))),
|
|
255
|
+
h('td', null, h('input', { className: 'pos-cell-input', type: 'number', step: '0.01', placeholder: '价格', value: row.price, onChange: (e) => update(i, 'price', e.target.value) })),
|
|
256
|
+
h('td', null, h('input', { className: 'pos-cell-input', type: 'number', step: '1', placeholder: '数量', value: row.qty, onChange: (e) => update(i, 'qty', e.target.value) })),
|
|
257
|
+
h('td', null, p.fee),
|
|
258
|
+
h('td', null, p.net),
|
|
259
|
+
h('td', null, p.cumQty),
|
|
260
|
+
h('td', null, p.cumInvest),
|
|
261
|
+
h('td', null, p.cost),
|
|
262
|
+
h('td', null,
|
|
263
|
+
row.saved
|
|
264
|
+
? h('span', { className: 'pos-chip ok', style: { height: 22, fontSize: 11 } }, '已保存')
|
|
265
|
+
: h('button', { className: 'pos-link', onClick: () => saveRow(i) }, '保存'),
|
|
266
|
+
h('button', { className: 'pos-link danger', style: { marginLeft: 4 }, onClick: () => { setRows((prev) => prev.filter((_, idx) => idx !== i)); setDirty(true) } }, '删除')
|
|
267
|
+
)
|
|
268
|
+
)
|
|
269
|
+
})
|
|
270
|
+
)
|
|
271
|
+
),
|
|
272
|
+
|
|
273
|
+
h('div', { className: 'pos-calc-actions' },
|
|
274
|
+
h('button', { className: 'pos-mini', onClick: () => { setRows((prev) => prev.concat([{ side: '买入', price: '', qty: '' }])); setDirty(true) } }, '+ 添加一组测算'),
|
|
275
|
+
h('button', { className: 'pos-btn primary', onClick: saveAll }, '保存全部测算')
|
|
276
|
+
),
|
|
277
|
+
|
|
278
|
+
h('p', { className: 'pos-note' }, '测算只用于比较,不写入历史;保存后留在本机。')
|
|
279
|
+
)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/* -------------------------------------------------------- 分组弹窗 */
|
|
283
|
+
|
|
284
|
+
function GroupModal(props) {
|
|
285
|
+
const { stocks, onClose, onSave } = props
|
|
286
|
+
const [draft, setDraft] = useState(() => {
|
|
287
|
+
const map = {}
|
|
288
|
+
stocks.forEach((s) => { map[s.name] = { group: s.group || '', price: s.price ?? '', dayPnl: s.dayPnl ?? '' } })
|
|
289
|
+
return map
|
|
290
|
+
})
|
|
291
|
+
|
|
292
|
+
return h(Modal, { title: '股票分组管理', onClose, maxWidth: 760 },
|
|
293
|
+
h('p', { className: 'pos-sub', style: { marginTop: 0 } },
|
|
294
|
+
'给股票输入组名,例如「红」「双底」;留空表示不分组。相同组名在表格中合并为同一分组行。'),
|
|
295
|
+
h('datalist', { id: 'pos-group-options' },
|
|
296
|
+
Array.from(new Set(stocks.map((s) => s.group).filter(Boolean))).map((g) => h('option', { key: g, value: g }))
|
|
297
|
+
),
|
|
298
|
+
stocks.map((s) => h('div', { key: s.name, className: 'pos-grow' },
|
|
299
|
+
h('span', { className: 'name' }, s.name),
|
|
300
|
+
h('input', {
|
|
301
|
+
className: 'pos-input', list: 'pos-group-options', placeholder: '组名(可空)',
|
|
302
|
+
value: draft[s.name].group,
|
|
303
|
+
onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { group: e.target.value }) }))
|
|
304
|
+
}),
|
|
305
|
+
h('span', { className: 'pos-muted' }, '现价'),
|
|
306
|
+
h('input', {
|
|
307
|
+
className: 'pos-input num', type: 'number', step: '0.01', value: draft[s.name].price,
|
|
308
|
+
onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { price: e.target.value }) }))
|
|
309
|
+
}),
|
|
310
|
+
h('span', { className: 'pos-muted' }, '当日盈亏'),
|
|
311
|
+
h('input', {
|
|
312
|
+
className: 'pos-input num', type: 'number', step: '0.01', value: draft[s.name].dayPnl,
|
|
313
|
+
onChange: (e) => setDraft(Object.assign({}, draft, { [s.name]: Object.assign({}, draft[s.name], { dayPnl: e.target.value }) }))
|
|
314
|
+
})
|
|
315
|
+
)),
|
|
316
|
+
h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 } },
|
|
317
|
+
h('button', { className: 'pos-btn', onClick: onClose }, '取消'),
|
|
318
|
+
h('button', { className: 'pos-btn primary', onClick: () => onSave(draft) }, '保存分组')
|
|
319
|
+
)
|
|
320
|
+
)
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/* -------------------------------------------------------------- 页面 */
|
|
324
|
+
|
|
325
|
+
function Page() {
|
|
326
|
+
const [data, setData] = useState(null)
|
|
327
|
+
const [error, setError] = useState('')
|
|
328
|
+
const [expanded, setExpanded] = useState('')
|
|
329
|
+
const [calcFor, setCalcFor] = useState('')
|
|
330
|
+
const [groupOpen, setGroupOpen] = useState(false)
|
|
331
|
+
const [busy, setBusy] = useState(false)
|
|
332
|
+
const [form, setForm] = useState({ name: '', date: today(), side: '买入', price: '', qty: '', fee: '' })
|
|
333
|
+
|
|
334
|
+
const load = () => {
|
|
335
|
+
fetch(API + '/state', { cache: 'no-store' })
|
|
336
|
+
.then((res) => res.json())
|
|
337
|
+
.then((json) => {
|
|
338
|
+
if (!json.ok) throw new Error(json.error || '读取失败')
|
|
339
|
+
setData(json)
|
|
340
|
+
setError('')
|
|
341
|
+
})
|
|
342
|
+
.catch((err) => setError(String(err.message || err)))
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
useEffect(() => { load() }, [])
|
|
346
|
+
|
|
347
|
+
const act = async (type, payload) => {
|
|
348
|
+
setBusy(true)
|
|
349
|
+
try {
|
|
350
|
+
const res = await fetch(API + '/action', {
|
|
351
|
+
method: 'POST',
|
|
352
|
+
headers: { 'content-type': 'application/json' },
|
|
353
|
+
body: JSON.stringify({ type, payload })
|
|
354
|
+
})
|
|
355
|
+
const json = await res.json()
|
|
356
|
+
if (!json.ok) throw new Error(json.error || '操作失败')
|
|
357
|
+
setData((prev) => Object.assign({}, prev, { state: json.state }))
|
|
358
|
+
} catch (err) {
|
|
359
|
+
setError(String(err.message || err))
|
|
360
|
+
} finally {
|
|
361
|
+
setBusy(false)
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const state = data && data.state
|
|
366
|
+
const feeRate = state ? state.feeRate : 0.0003
|
|
367
|
+
|
|
368
|
+
const view = useMemo(() => {
|
|
369
|
+
if (!state) return null
|
|
370
|
+
const stocks = state.stocks.map((s) => {
|
|
371
|
+
const records = calcRecords(s.records, feeRate)
|
|
372
|
+
const last = records.length ? records[records.length - 1] : null
|
|
373
|
+
const cumQty = last ? last.cumQty : 0
|
|
374
|
+
const cumInvest = last ? last.cumInvest : 0
|
|
375
|
+
const mv = Number(s.price || 0) * cumQty
|
|
376
|
+
return Object.assign({}, s, { records, cumQty, cumInvest, last, mv })
|
|
377
|
+
})
|
|
378
|
+
const totalMv = stocks.reduce((sum, s) => sum + s.mv, 0)
|
|
379
|
+
const groups = []
|
|
380
|
+
const index = new Map()
|
|
381
|
+
stocks.forEach((s) => {
|
|
382
|
+
const name = s.group || '未分组'
|
|
383
|
+
if (!index.has(name)) {
|
|
384
|
+
index.set(name, { name, stocks: [], mv: 0, pnl: 0 })
|
|
385
|
+
groups.push(index.get(name))
|
|
386
|
+
}
|
|
387
|
+
const group = index.get(name)
|
|
388
|
+
group.stocks.push(s)
|
|
389
|
+
group.mv += s.mv
|
|
390
|
+
group.pnl += Number(s.dayPnl || 0)
|
|
391
|
+
})
|
|
392
|
+
groups.forEach((g) => { g.pos = totalMv > 0 ? (g.mv / totalMv) * 100 : null })
|
|
393
|
+
return { stocks, groups, totalMv }
|
|
394
|
+
}, [state, feeRate])
|
|
395
|
+
|
|
396
|
+
if (error && !data) {
|
|
397
|
+
return h('div', { className: 'pos-root' }, h('style', null, CSS),
|
|
398
|
+
h('div', { className: 'pos-empty' }, h('p', null, '读取失败:' + error), h('button', { className: 'pos-btn', onClick: load }, '重试')))
|
|
399
|
+
}
|
|
400
|
+
if (!data || !view) {
|
|
401
|
+
return h('div', { className: 'pos-root' }, h('style', null, CSS), h('div', { className: 'pos-empty' }, '加载中…'))
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const columns = 11
|
|
405
|
+
const calcStock = calcFor ? view.stocks.find((s) => s.name === calcFor) : null
|
|
406
|
+
|
|
407
|
+
const addTrade = async () => {
|
|
408
|
+
if (!form.name.trim() || !form.price || !form.qty) return
|
|
409
|
+
await act('addTrade', {
|
|
410
|
+
name: form.name.trim(),
|
|
411
|
+
date: form.date || today(),
|
|
412
|
+
side: form.side,
|
|
413
|
+
price: form.price,
|
|
414
|
+
qty: form.qty,
|
|
415
|
+
feeOverride: form.fee === '' ? undefined : form.fee
|
|
416
|
+
})
|
|
417
|
+
setForm(Object.assign({}, form, { price: '', qty: '', fee: '' }))
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const saveGroups = async (draft) => {
|
|
421
|
+
for (const name of Object.keys(draft)) {
|
|
422
|
+
const stock = state.stocks.find((s) => s.name === name)
|
|
423
|
+
if (!stock) continue
|
|
424
|
+
const next = draft[name]
|
|
425
|
+
if ((stock.group || '') !== (next.group || '').trim()) await act('setGroup', { name, group: next.group })
|
|
426
|
+
if (String(stock.price ?? '') !== String(next.price)) await act('setPrice', { name, price: next.price })
|
|
427
|
+
if (String(stock.dayPnl ?? '') !== String(next.dayPnl)) await act('setDayPnl', { name, dayPnl: next.dayPnl })
|
|
428
|
+
}
|
|
429
|
+
setGroupOpen(false)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const ledgerProps = (s) => ({
|
|
433
|
+
stock: s,
|
|
434
|
+
feeRate,
|
|
435
|
+
savedRows: state.calc[s.name],
|
|
436
|
+
onSave: (rows) => act('saveCalc', { name: s.name, rows }),
|
|
437
|
+
onDeleteRecord: (name, row) => act('deleteRecord', { name, index: rawIndexOf(state, name, row), match: { date: row.date, side: row.side, price: row.price, qty: row.qty } })
|
|
438
|
+
})
|
|
439
|
+
|
|
440
|
+
return h('div', { className: 'pos-root' },
|
|
441
|
+
h('style', null, CSS),
|
|
442
|
+
h('div', { className: 'pos-wrap' },
|
|
443
|
+
|
|
444
|
+
h('div', { className: 'pos-head' },
|
|
445
|
+
h('div', null,
|
|
446
|
+
h('h1', { className: 'pos-title' }, '持仓成本台'),
|
|
447
|
+
h('p', { className: 'pos-sub' }, '只记你自己的持仓与成交,不含行情 · 数据目录 ' + (data.dataDir || ''))
|
|
448
|
+
),
|
|
449
|
+
h('div', { className: 'pos-head-actions' },
|
|
450
|
+
h('button', { className: 'pos-btn', onClick: load, disabled: busy }, '刷新')
|
|
451
|
+
)
|
|
452
|
+
),
|
|
453
|
+
|
|
454
|
+
error ? h('div', { className: 'pos-error' }, error) : null,
|
|
455
|
+
|
|
456
|
+
h('div', { className: 'pos-card pos-form' },
|
|
457
|
+
h('span', { className: 'pos-muted' }, '记一笔'),
|
|
458
|
+
h('input', { className: 'pos-input', placeholder: '股票名称', value: form.name, list: 'pos-names',
|
|
459
|
+
onChange: (e) => setForm(Object.assign({}, form, { name: e.target.value })) }),
|
|
460
|
+
h('datalist', { id: 'pos-names' }, state.stocks.map((s) => h('option', { key: s.name, value: s.name }))),
|
|
461
|
+
h('input', { className: 'pos-input', type: 'date', value: form.date,
|
|
462
|
+
onChange: (e) => setForm(Object.assign({}, form, { date: e.target.value })) }),
|
|
463
|
+
h('select', { className: 'pos-select', value: form.side,
|
|
464
|
+
onChange: (e) => setForm(Object.assign({}, form, { side: e.target.value })) },
|
|
465
|
+
h('option', { value: '买入' }, '买入'), h('option', { value: '卖出' }, '卖出')),
|
|
466
|
+
h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: '价格', value: form.price,
|
|
467
|
+
onChange: (e) => setForm(Object.assign({}, form, { price: e.target.value })) }),
|
|
468
|
+
h('input', { className: 'pos-input num', type: 'number', step: '1', placeholder: '数量', value: form.qty,
|
|
469
|
+
onChange: (e) => setForm(Object.assign({}, form, { qty: e.target.value })) }),
|
|
470
|
+
h('input', { className: 'pos-input num', type: 'number', step: '0.01', placeholder: '费用(可空)', value: form.fee,
|
|
471
|
+
onChange: (e) => setForm(Object.assign({}, form, { fee: e.target.value })) }),
|
|
472
|
+
h('button', { className: 'pos-btn primary', onClick: addTrade, disabled: busy }, '写入历史')
|
|
473
|
+
),
|
|
474
|
+
|
|
475
|
+
h('div', { className: 'pos-card pos-filter' },
|
|
476
|
+
h('div', { className: 'pos-filter-head' },
|
|
477
|
+
h('span', null, '分组管理'),
|
|
478
|
+
h('button', { className: 'pos-mini', onClick: () => setGroupOpen(true) }, '编辑分组')
|
|
479
|
+
),
|
|
480
|
+
h('div', { className: 'pos-chips' },
|
|
481
|
+
view.groups.map((g) => h('span', { key: g.name, className: 'pos-chip' },
|
|
482
|
+
g.name, h('span', { className: 'n' }, String(g.stocks.length))))
|
|
483
|
+
)
|
|
484
|
+
),
|
|
485
|
+
|
|
486
|
+
h('div', { className: 'pos-table-wrap' },
|
|
487
|
+
h('table', { className: 'pos-table' },
|
|
488
|
+
h('thead', null, h('tr', null,
|
|
489
|
+
h('th', null, '股票'), h('th', null, '日期'), h('th', null, '方向'), h('th', null, '价格'),
|
|
490
|
+
h('th', null, '数量'), h('th', null, '费用'), h('th', null, '当次含费用投入'), h('th', null, '累计数量'),
|
|
491
|
+
h('th', null, '累计投入'), h('th', null, '累计成本'), h('th', null, '操作')
|
|
492
|
+
)),
|
|
493
|
+
h('tbody', null,
|
|
494
|
+
view.groups.map((group) => [
|
|
495
|
+
h('tr', { key: 'g-' + group.name, className: 'pos-group' },
|
|
496
|
+
h('td', { colSpan: columns },
|
|
497
|
+
h('div', { className: 'pos-group-inner' },
|
|
498
|
+
h('span', { className: 'pos-tag', style: { color: '#b42318', borderColor: '#fecdca' } }, group.name || '未分组'),
|
|
499
|
+
h('span', null, '市值 ' + money(group.mv)),
|
|
500
|
+
h('span', { className: group.pnl >= 0 ? 'pos-up' : 'pos-down' }, signed(group.pnl)),
|
|
501
|
+
h('span', null, '仓位 ' + (group.pos === null ? '—' : group.pos.toFixed(2) + '%')),
|
|
502
|
+
h('span', { className: 'pos-muted' }, group.stocks.length + ' 只')
|
|
503
|
+
)
|
|
504
|
+
)
|
|
505
|
+
),
|
|
506
|
+
...group.stocks.map((s) => {
|
|
507
|
+
const isOpen = expanded === s.name
|
|
508
|
+
const rows = []
|
|
509
|
+
rows.push(h('tr', { key: 's-' + s.name, className: 'pos-row', onClick: () => setExpanded(isOpen ? '' : s.name) },
|
|
510
|
+
h('td', null, s.name),
|
|
511
|
+
h('td', null, s.last ? s.last.date : '—'),
|
|
512
|
+
h('td', null, s.last ? s.last.side : '—'),
|
|
513
|
+
h('td', null, s.last ? s.last.price.toFixed(2) : '—'),
|
|
514
|
+
h('td', null, s.last ? s.last.qty : '—'),
|
|
515
|
+
h('td', null, s.last ? s.last.fee.toFixed(2) : '—'),
|
|
516
|
+
h('td', null, s.last ? s.last.net.toFixed(2) : '—'),
|
|
517
|
+
h('td', null, s.cumQty),
|
|
518
|
+
h('td', null, s.cumInvest.toFixed(2)),
|
|
519
|
+
h('td', null, s.last && s.last.cost !== null ? s.last.cost.toFixed(3) : '—'),
|
|
520
|
+
h('td', null,
|
|
521
|
+
h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setCalcFor(s.name) } }, '测算'),
|
|
522
|
+
h('button', { className: 'pos-link', onClick: (e) => { e.stopPropagation(); setExpanded(isOpen ? '' : s.name) } }, isOpen ? '收起' : '展开')
|
|
523
|
+
)
|
|
524
|
+
))
|
|
525
|
+
if (isOpen) {
|
|
526
|
+
rows.push(h('tr', { key: 'd-' + s.name, className: 'pos-detail' },
|
|
527
|
+
h('td', { colSpan: columns }, h('div', { className: 'pos-detail-box' }, h(Ledger, ledgerProps(s))))
|
|
528
|
+
))
|
|
529
|
+
}
|
|
530
|
+
return rows
|
|
531
|
+
})
|
|
532
|
+
])
|
|
533
|
+
)
|
|
534
|
+
)
|
|
535
|
+
),
|
|
536
|
+
|
|
537
|
+
view.stocks.length === 0 ? h('div', { className: 'pos-empty' }, '还没有持仓,用上方的「记一笔」开始。') : null,
|
|
538
|
+
|
|
539
|
+
h('p', { className: 'pos-note' },
|
|
540
|
+
'费用默认按成交额 × ' + (feeRate * 100).toFixed(2) + '% 估算;成交记录里写了费用就优先用记录值(* 号标注)。')
|
|
541
|
+
),
|
|
542
|
+
|
|
543
|
+
groupOpen ? h(GroupModal, { stocks: view.stocks, onClose: () => setGroupOpen(false), onSave: saveGroups }) : null,
|
|
544
|
+
|
|
545
|
+
calcStock ? h(Modal, { title: calcStock.name + ' · 历史记录与测算', onClose: () => setCalcFor('') },
|
|
546
|
+
h(Ledger, ledgerProps(calcStock))
|
|
547
|
+
) : null
|
|
548
|
+
)
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function apply(ctx) {
|
|
552
|
+
ctx.slots.inject('sidebar.panellist', () =>
|
|
553
|
+
ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 8, label: () => '台账' }, Icon)
|
|
554
|
+
)
|
|
555
|
+
ctx.slots.inject('main', () =>
|
|
556
|
+
ctx.slots.register({ name: 'main', key: PANEL_ID }, () => h(Page))
|
|
557
|
+
)
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
return { inject: ['slots'], apply }
|
|
561
|
+
}
|
|
562
|
+
})
|
package/cordis.patch.yml
ADDED
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/icon-512.png
ADDED
|
Binary file
|
package/index.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 持仓成本台 · 服务端
|
|
3
|
+
*
|
|
4
|
+
* 只做三件事:
|
|
5
|
+
* 1. 把 state.json 读写到本机磁盘(自动持久化,重启还在)
|
|
6
|
+
* 2. 提供 GET /positions/state 读取全部数据
|
|
7
|
+
* 3. 提供 POST /positions/action 修改数据并落盘
|
|
8
|
+
*
|
|
9
|
+
* 没有联网、没有行情、没有遥测。
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { homedir } from 'node:os'
|
|
13
|
+
import { dirname, join, resolve } from 'node:path'
|
|
14
|
+
import { fileURLToPath } from 'node:url'
|
|
15
|
+
import seed from './seed.js'
|
|
16
|
+
|
|
17
|
+
const ROUTE = '/positions'
|
|
18
|
+
const MAX_BODY_BYTES = 256 * 1024
|
|
19
|
+
const HERE = dirname(fileURLToPath(import.meta.url))
|
|
20
|
+
|
|
21
|
+
export const inject = ['webServer']
|
|
22
|
+
|
|
23
|
+
/* ------------------------------------------------------------------ 数据目录 */
|
|
24
|
+
|
|
25
|
+
function resolveDataDir(config) {
|
|
26
|
+
const explicit = typeof config?.dataDir === 'string' ? config.dataDir.trim() : ''
|
|
27
|
+
if (explicit) return resolve(explicit)
|
|
28
|
+
|
|
29
|
+
const env = typeof process.env.DSH_POSITIONS_DATA === 'string' ? process.env.DSH_POSITIONS_DATA.trim() : ''
|
|
30
|
+
if (env) return resolve(env)
|
|
31
|
+
|
|
32
|
+
// 仓库内 data/ 只给开发时用;装进 node_modules 后绝不写那里
|
|
33
|
+
const repoData = join(HERE, 'data')
|
|
34
|
+
if (!HERE.includes('node_modules') && existsSync(join(repoData, 'state.json'))) return repoData
|
|
35
|
+
|
|
36
|
+
const base = process.env.LOCALAPPDATA || join(homedir(), '.local', 'share')
|
|
37
|
+
return join(base, 'dsh-positions')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/* -------------------------------------------------------------------- 规范化 */
|
|
41
|
+
|
|
42
|
+
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
43
|
+
const str = (v, fallback = '') => (typeof v === 'string' ? v : fallback)
|
|
44
|
+
const num = (v, fallback = 0) => (Number.isFinite(Number(v)) ? Number(v) : fallback)
|
|
45
|
+
|
|
46
|
+
function normalizeRecord(raw) {
|
|
47
|
+
if (!isObject(raw)) return null
|
|
48
|
+
const date = str(raw.date)
|
|
49
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return null
|
|
50
|
+
const side = raw.side === '卖出' ? '卖出' : raw.side === '买入' ? '买入' : null
|
|
51
|
+
const price = num(raw.price)
|
|
52
|
+
const qty = num(raw.qty)
|
|
53
|
+
if (!side || price <= 0 || qty <= 0) return null
|
|
54
|
+
const record = { date, side, price, qty }
|
|
55
|
+
if (raw.feeOverride !== undefined && raw.feeOverride !== null && raw.feeOverride !== '') {
|
|
56
|
+
const fee = num(raw.feeOverride, NaN)
|
|
57
|
+
if (Number.isFinite(fee) && fee >= 0) record.feeOverride = fee
|
|
58
|
+
}
|
|
59
|
+
return record
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function normalizeStock(raw) {
|
|
63
|
+
if (!isObject(raw) || !str(raw.name).trim()) return null
|
|
64
|
+
return {
|
|
65
|
+
name: str(raw.name).trim(),
|
|
66
|
+
group: str(raw.group).trim(),
|
|
67
|
+
price: Math.max(0, num(raw.price)),
|
|
68
|
+
dayPnl: num(raw.dayPnl),
|
|
69
|
+
records: Array.isArray(raw.records) ? raw.records.map(normalizeRecord).filter(Boolean) : []
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function normalizeState(raw) {
|
|
74
|
+
const state = isObject(raw) ? raw : {}
|
|
75
|
+
const stocks = Array.isArray(state.stocks) ? state.stocks.map(normalizeStock).filter(Boolean) : []
|
|
76
|
+
return {
|
|
77
|
+
version: 1,
|
|
78
|
+
feeRate: num(state.feeRate) > 0 ? num(state.feeRate) : 0.0003,
|
|
79
|
+
tags: Array.isArray(state.tags) ? state.tags.map((t) => str(t).trim()).filter(Boolean) : seed.tags.slice(),
|
|
80
|
+
activeTags: Array.isArray(state.activeTags) ? state.activeTags.map((t) => str(t).trim()).filter(Boolean) : [],
|
|
81
|
+
calc: isObject(state.calc) ? state.calc : {},
|
|
82
|
+
stocks
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/* -------------------------------------------------------------------- 动作 */
|
|
87
|
+
|
|
88
|
+
function findStock(state, name) {
|
|
89
|
+
return state.stocks.find((s) => s.name === name) || null
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const actions = {
|
|
93
|
+
addTrade(state, payload) {
|
|
94
|
+
const name = str(payload?.name).trim()
|
|
95
|
+
const record = normalizeRecord(payload)
|
|
96
|
+
if (!name) throw bad('缺少股票名称')
|
|
97
|
+
if (!record) throw bad('成交记录不完整(日期/方向/价格/数量)')
|
|
98
|
+
let stock = findStock(state, name)
|
|
99
|
+
if (!stock) {
|
|
100
|
+
stock = { name, group: str(payload?.group).trim(), price: 0, dayPnl: 0, records: [] }
|
|
101
|
+
state.stocks.push(stock)
|
|
102
|
+
}
|
|
103
|
+
stock.records.push(record)
|
|
104
|
+
if (payload?.price !== undefined && !stock.price) stock.price = record.price
|
|
105
|
+
return state
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
deleteStock(state, payload) {
|
|
109
|
+
const name = str(payload?.name).trim()
|
|
110
|
+
state.stocks = state.stocks.filter((s) => s.name !== name)
|
|
111
|
+
delete state.calc[name]
|
|
112
|
+
return state
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
deleteRecord(state, payload) {
|
|
116
|
+
const name = str(payload?.name).trim()
|
|
117
|
+
const stock = findStock(state, name)
|
|
118
|
+
if (!stock) throw bad('找不到这只股票')
|
|
119
|
+
|
|
120
|
+
let index = num(payload?.index, -1)
|
|
121
|
+
const match = payload?.match
|
|
122
|
+
if (isObject(match)) {
|
|
123
|
+
index = stock.records.findIndex(
|
|
124
|
+
(r) =>
|
|
125
|
+
r.date === match.date &&
|
|
126
|
+
r.side === match.side &&
|
|
127
|
+
Number(r.price) === Number(match.price) &&
|
|
128
|
+
Number(r.qty) === Number(match.qty)
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
if (index < 0 || index >= stock.records.length) throw bad('找不到这条成交')
|
|
132
|
+
stock.records.splice(index, 1)
|
|
133
|
+
return state
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
setGroup(state, payload) {
|
|
137
|
+
const stock = findStock(state, str(payload?.name).trim())
|
|
138
|
+
if (!stock) throw bad('找不到这只股票')
|
|
139
|
+
stock.group = str(payload?.group).trim()
|
|
140
|
+
return state
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
setPrice(state, payload) {
|
|
144
|
+
const stock = findStock(state, str(payload?.name).trim())
|
|
145
|
+
if (!stock) throw bad('找不到这只股票')
|
|
146
|
+
const price = num(payload?.price)
|
|
147
|
+
if (price < 0) throw bad('价格不能为负')
|
|
148
|
+
stock.price = price
|
|
149
|
+
return state
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
setDayPnl(state, payload) {
|
|
153
|
+
const stock = findStock(state, str(payload?.name).trim())
|
|
154
|
+
if (!stock) throw bad('找不到这只股票')
|
|
155
|
+
stock.dayPnl = num(payload?.dayPnl)
|
|
156
|
+
return state
|
|
157
|
+
},
|
|
158
|
+
|
|
159
|
+
setFeeRate(state, payload) {
|
|
160
|
+
const rate = num(payload?.feeRate)
|
|
161
|
+
if (!(rate >= 0 && rate <= 0.01)) throw bad('费率应在 0 ~ 0.01 之间')
|
|
162
|
+
state.feeRate = rate
|
|
163
|
+
return state
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
addTag(state, payload) {
|
|
167
|
+
const label = str(payload?.label).trim()
|
|
168
|
+
if (!label) throw bad('标签不能为空')
|
|
169
|
+
if (!state.tags.includes(label)) state.tags.push(label)
|
|
170
|
+
return state
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
removeTag(state, payload) {
|
|
174
|
+
const label = str(payload?.label).trim()
|
|
175
|
+
state.tags = state.tags.filter((t) => t !== label)
|
|
176
|
+
state.activeTags = state.activeTags.filter((t) => t !== label)
|
|
177
|
+
return state
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
toggleTag(state, payload) {
|
|
181
|
+
const label = str(payload?.label).trim()
|
|
182
|
+
if (!state.tags.includes(label)) return state
|
|
183
|
+
state.activeTags = state.activeTags.includes(label)
|
|
184
|
+
? state.activeTags.filter((t) => t !== label)
|
|
185
|
+
: state.activeTags.concat(label)
|
|
186
|
+
return state
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
saveCalc(state, payload) {
|
|
190
|
+
const name = str(payload?.name).trim()
|
|
191
|
+
if (!name) throw bad('缺少股票名称')
|
|
192
|
+
const rows = Array.isArray(payload?.rows) ? payload.rows : []
|
|
193
|
+
state.calc[name] = rows.slice(0, 20).map((row) => ({
|
|
194
|
+
side: row?.side === '卖出' ? '卖出' : '买入',
|
|
195
|
+
price: row?.price === '' || row?.price === undefined ? '' : num(row.price),
|
|
196
|
+
qty: row?.qty === '' || row?.qty === undefined ? '' : num(row.qty),
|
|
197
|
+
saved: row?.saved === true
|
|
198
|
+
}))
|
|
199
|
+
return state
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function bad(message) {
|
|
204
|
+
const error = new Error(message)
|
|
205
|
+
error.status = 400
|
|
206
|
+
return error
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/* -------------------------------------------------------------------- HTTP */
|
|
210
|
+
|
|
211
|
+
function send(res, status, payload) {
|
|
212
|
+
const body = JSON.stringify(payload)
|
|
213
|
+
res.writeHead(status, {
|
|
214
|
+
'content-type': 'application/json; charset=utf-8',
|
|
215
|
+
'content-length': Buffer.byteLength(body),
|
|
216
|
+
'cache-control': 'no-store'
|
|
217
|
+
})
|
|
218
|
+
res.end(body)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function sameOrigin(req) {
|
|
222
|
+
const origin = req.headers.origin
|
|
223
|
+
if (origin === undefined) return true
|
|
224
|
+
try {
|
|
225
|
+
return new URL(origin).host === req.headers.host
|
|
226
|
+
} catch {
|
|
227
|
+
return false
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function readJson(req) {
|
|
232
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
233
|
+
let size = 0
|
|
234
|
+
const chunks = []
|
|
235
|
+
req.on('data', (chunk) => {
|
|
236
|
+
size += chunk.length
|
|
237
|
+
if (size > MAX_BODY_BYTES) {
|
|
238
|
+
const error = new Error('请求体过大')
|
|
239
|
+
error.status = 413
|
|
240
|
+
rejectPromise(error)
|
|
241
|
+
req.destroy()
|
|
242
|
+
return
|
|
243
|
+
}
|
|
244
|
+
chunks.push(chunk)
|
|
245
|
+
})
|
|
246
|
+
req.on('end', () => {
|
|
247
|
+
if (!chunks.length) return resolvePromise({})
|
|
248
|
+
try {
|
|
249
|
+
resolvePromise(JSON.parse(Buffer.concat(chunks).toString('utf8')))
|
|
250
|
+
} catch {
|
|
251
|
+
const error = new Error('请求体不是合法 JSON')
|
|
252
|
+
error.status = 400
|
|
253
|
+
rejectPromise(error)
|
|
254
|
+
}
|
|
255
|
+
})
|
|
256
|
+
req.on('error', rejectPromise)
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function apply(ctx, config) {
|
|
261
|
+
const dataDir = resolveDataDir(config)
|
|
262
|
+
const stateFile = join(dataDir, 'state.json')
|
|
263
|
+
mkdirSync(dataDir, { recursive: true })
|
|
264
|
+
|
|
265
|
+
function load() {
|
|
266
|
+
try {
|
|
267
|
+
return normalizeState(JSON.parse(readFileSync(stateFile, 'utf8')))
|
|
268
|
+
} catch {
|
|
269
|
+
const initial = normalizeState(seed)
|
|
270
|
+
persist(initial)
|
|
271
|
+
return initial
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function persist(state) {
|
|
276
|
+
const tmp = stateFile + '.tmp'
|
|
277
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8')
|
|
278
|
+
renameSync(tmp, stateFile)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
let state = load()
|
|
282
|
+
|
|
283
|
+
async function handler(req, res) {
|
|
284
|
+
if (!sameOrigin(req)) {
|
|
285
|
+
send(res, 403, { ok: false, error: '跨站请求被拒绝' })
|
|
286
|
+
return
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
290
|
+
const suffix = url.pathname.slice(ROUTE.length) || '/'
|
|
291
|
+
|
|
292
|
+
try {
|
|
293
|
+
if (req.method === 'GET' && (suffix === '/state' || suffix === '/')) {
|
|
294
|
+
send(res, 200, { ok: true, dataDir, state })
|
|
295
|
+
return
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (req.method === 'POST' && suffix === '/action') {
|
|
299
|
+
const body = await readJson(req)
|
|
300
|
+
const type = str(body?.type)
|
|
301
|
+
const action = actions[type]
|
|
302
|
+
if (!action) {
|
|
303
|
+
send(res, 400, { ok: false, error: '未知操作:' + type })
|
|
304
|
+
return
|
|
305
|
+
}
|
|
306
|
+
state = action(state, isObject(body.payload) ? body.payload : {})
|
|
307
|
+
persist(state)
|
|
308
|
+
send(res, 200, { ok: true, state })
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
send(res, 404, { ok: false, error: 'not found' })
|
|
313
|
+
} catch (error) {
|
|
314
|
+
const status = typeof error?.status === 'number' ? error.status : 500
|
|
315
|
+
if (status >= 500) ctx.logger?.warn?.('positions: ' + (error?.message ?? String(error)))
|
|
316
|
+
send(res, status, { ok: false, error: error?.message ?? 'internal error' })
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: ROUTE, handler }))
|
|
321
|
+
ctx.logger?.info?.(`positions: data dir ${dataDir}`)
|
|
322
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhangxij/dsh-positions",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "持仓成本台:记持仓、记成交,测算买卖之后的成本、仓位与保本价。不含行情、不联网。",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/zhang-1239/dsh-positions.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/zhang-1239/dsh-positions#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/zhang-1239/dsh-positions/issues"
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"test": "node test/server.test.mjs"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"dsh",
|
|
21
|
+
"dsh-plugin",
|
|
22
|
+
"deepseek",
|
|
23
|
+
"harness",
|
|
24
|
+
"positions",
|
|
25
|
+
"cost-basis",
|
|
26
|
+
"portfolio"
|
|
27
|
+
],
|
|
28
|
+
"files": [
|
|
29
|
+
"index.js",
|
|
30
|
+
"client.js",
|
|
31
|
+
"seed.js",
|
|
32
|
+
"cordis.patch.yml",
|
|
33
|
+
"icon-512.png",
|
|
34
|
+
"screenshots.json",
|
|
35
|
+
"docs/screenshots",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
],
|
|
39
|
+
"exports": {
|
|
40
|
+
".": "./index.js",
|
|
41
|
+
"./client": "./client.js",
|
|
42
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
43
|
+
"./package.json": "./package.json"
|
|
44
|
+
},
|
|
45
|
+
"dsh": {
|
|
46
|
+
"bundle": {
|
|
47
|
+
"patch": "./cordis.patch.yml"
|
|
48
|
+
},
|
|
49
|
+
"client": {
|
|
50
|
+
"platform": "web",
|
|
51
|
+
"inject": [
|
|
52
|
+
"@deepseek-ai/dsh-client-ui-sidebar",
|
|
53
|
+
"@deepseek-ai/dsh-client-ui-layout"
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
package/screenshots.json
ADDED
package/seed.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 首次启动写入的示例数据。装完第一眼不是空的。
|
|
3
|
+
* 价格与当日盈亏都是「你自己填」的数字,不是行情。
|
|
4
|
+
*/
|
|
5
|
+
export default {
|
|
6
|
+
version: 1,
|
|
7
|
+
updatedAt: '2027-03-15',
|
|
8
|
+
feeRate: 0.0003,
|
|
9
|
+
tags: ['量比/换手/振幅', '偏态', '趋势4项', '股东数', '全球流动性'],
|
|
10
|
+
activeTags: [],
|
|
11
|
+
calc: {},
|
|
12
|
+
stocks: [
|
|
13
|
+
{
|
|
14
|
+
name: '示例股票A',
|
|
15
|
+
group: '红',
|
|
16
|
+
price: 10.42,
|
|
17
|
+
dayPnl: 320,
|
|
18
|
+
records: [
|
|
19
|
+
{ date: '2027-01-05', side: '买入', price: 10.0, qty: 1000 },
|
|
20
|
+
{ date: '2027-02-10', side: '买入', price: 9.5, qty: 500 },
|
|
21
|
+
{ date: '2027-03-02', side: '卖出', price: 11.0, qty: 300, feeOverride: 3.2 }
|
|
22
|
+
]
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
name: '示例股票B',
|
|
26
|
+
group: '红',
|
|
27
|
+
price: 27.33,
|
|
28
|
+
dayPnl: -150,
|
|
29
|
+
records: [
|
|
30
|
+
{ date: '2027-01-12', side: '买入', price: 20.0, qty: 200 },
|
|
31
|
+
{ date: '2027-02-18', side: '买入', price: 18.5, qty: 100 }
|
|
32
|
+
]
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
name: '示例股票C',
|
|
36
|
+
group: '双底',
|
|
37
|
+
price: 5.2,
|
|
38
|
+
dayPnl: 210,
|
|
39
|
+
records: [{ date: '2027-02-03', side: '买入', price: 5.2, qty: 2000 }]
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
name: '示例股票D',
|
|
43
|
+
group: '双底',
|
|
44
|
+
price: 34.0,
|
|
45
|
+
dayPnl: -90,
|
|
46
|
+
records: [
|
|
47
|
+
{ date: '2027-01-20', side: '买入', price: 30.0, qty: 300 },
|
|
48
|
+
{ date: '2027-03-15', side: '卖出', price: 28.0, qty: 100 }
|
|
49
|
+
]
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: '示例股票E',
|
|
53
|
+
group: '',
|
|
54
|
+
price: 12.0,
|
|
55
|
+
dayPnl: 60,
|
|
56
|
+
records: [{ date: '2027-02-22', side: '买入', price: 12.0, qty: 400 }]
|
|
57
|
+
}
|
|
58
|
+
]
|
|
59
|
+
}
|