Finance Tracker with shared Express services and MCP server integration
📚 中文文档
一个轻量级的多平台资金追踪与记账系统,支持 A股、港股、美股、虚拟币等多种投资平台的资金管理,同时提供 MCP Server 供 AI Agent 调用。
🖼️ 预览图
| 深色主题 - 主界面总览 | 浅色主题 - 主界面总览 |
|:---:|:---:|
|
|
|
| 深色主题 - 设置页面 | 深色主题 - 交易记录管理 |
|:---:|:---:|
|
|
|
| 浅色主题 - 设置页面 | 深色主题 - 主界面总览 |
|:---:|:---:|
|
|
|
✨ 功能特性
📊 资金总览
- 全平台资金汇总展示
- 支持 CNY/HKD/USD 多币种显示
- 实时汇率转换
- 总盈亏与涨跌幅统计
🏛️ 平台管理
- 预设 A股、港股、美股、虚拟币四大平台
- 自定义初始资金设置
- 各平台独立币种配置
📝 交易记录
- 完整的交易记录管理(增删改查)
- 支持现货/合约/事件三种交易类型
- 支持开多/开空方向
- 杠杆倍数记录
- 开仓/平仓价格与时间(支持秒级精度)
- 盈亏与手续费统计
- 交易理由备注
- 高精度小数支持(适用于虚拟币等场景)
📈 统计分析
- 总统计:查看所有交易的汇总统计
- 交易次数、总盈亏、总费用、实现盈亏
- 胜率、最大盈利/亏损、平均盈亏
- 盈亏比、投资回报率(ROI)、平均持仓时间
- 交易类型分布(现货/合约/事件)
- 开仓方向分布(开多/开空)
- 按交易对分组的详细统计表格
- 交易对统计:查看单个交易对的详细统计
- 支持搜索筛选交易对
- 该交易对的完整统计数据
- 可展开查看该交易对的所有交易记录
💵 资金记录
- 资金存入/取出管理
- 自动更新平台初始资金
- 智能取出逻辑(优先扣减初始资金,不足时扣减盈利)
- 取出金额实时校验(不可超过总资金)
- 初始资金为0时涨跌幅特殊显示
💱 汇率管理
- 自动从 Bing 获取实时汇率
- 支持定时自动更新
- 备用汇率机制保证可用性
💾 数据备份与恢复
- 一键导出所有数据(平台配置、交易记录、设置)
- 支持从备份文件恢复数据
- 大数据量优化处理(分批导入,防止卡顿)
- 汇率数据自动从网络获取,无需备份
🗄️ 数据库优化
- 自动创建索引优化查询性能
- 支持游标分页,大数据量下保持高效
- 数据库维护功能(ANALYZE + VACUUM)
- 设置页面可查看数据库状态和手动优化
🤖 MCP Server(AI Agent 集成)
- 提供 MCP stdio server,供 AI Agent(如 Claude Desktop、Hermes 等)调用
- 与 Web API 共享同一套数据库和业务服务层
- 支持平台、交易、统计、资金记录、汇率等全部操作
- 详见 MCP Server 章节
🎨 用户体验
- 响应式设计,支持移动端
- 深色/浅色主题切换(带圆形扩散动画)
- 涨跌颜色风格切换(红涨绿跌/绿涨红跌)
- 现代化 UI 界面
- 持仓量自动计算(投入资金 × 杠杆 / 开仓价格)
🛠️ 技术栈
| 技术 | 说明 | |------|------| | 后端 | Node.js 20+ / Express.js 4.x | | 数据库 | SQLite (better-sqlite3) | | 前端 | 原生 HTML / CSS / JavaScript | | 汇率获取 | Cheerio + Node-fetch | | 定时任务 | Node-cron | | MCP | @modelcontextprotocol/sdk | | 容器化 | Docker + Docker Compose | | 测试 | Node.js 内置测试框架 |
📦 快速开始
方式一:Docker 部署(推荐)
前置要求
- Docker 20.10+
- Docker Compose 2.0+
部署步骤
# 1. 克隆项目
git clone https://github.com/rggameffl1/Finance-Tracker.git
cd Finance-Tracker
# 2. 使用 Docker Compose 启动
docker-compose up -d
# 3. 查看日志
docker-compose logs -f
# 4. 访问应用
# 打开浏览器访问 http://localhost:3000
Docker 常用命令
# 停止服务
docker-compose down
# 重新构建并启动
docker-compose up -d --build
# 查看容器状态
docker-compose ps
# 进入容器
docker exec -it finance-tracker sh
# 查看数据卷
docker volume ls | grep finance
# 备份数据库
docker cp finance-tracker:/app/data/finance.db ./backup/
方式二:本地开发
前置要求
- Node.js 20+
- npm 或 yarn
- Python 3 (用于编译 better-sqlite3)
- C++ 编译工具链
安装步骤
# 1. 克隆项目
git clone https://github.com/rggameffl1/Finance-Tracker.git
cd Finance-Tracker
# 2. 安装依赖
npm install
# 3. 初始化数据库
npm run init-db
# 4. 启动服务
npm start
# 或使用开发模式(自动重启)
npm run dev
📖 使用说明
首次使用
- 访问
http://localhost:3000 - 系统已预设四个平台(A股、港股、美股、虚拟币)
- 点击平台卡片上的设置按钮,配置各平台的初始资金
- 点击"新增记录"添加交易记录
交易记录管理
| 字段 | 说明 | |------|------| | 平台 | 选择交易所属平台 | | 名称 | 资产名称,如"腾讯控股"、"BTC" | | 代码 | 资产代码,如"00700.HK"、"BTC-USDT" | | 类型 | 现货、合约或事件 | | 方向 | 开多或开空 | | 杠杆 | 杠杆倍数,现货默认为1 | | 开仓价格 | 买入/开仓时的价格(支持高精度小数) | | 平仓价格 | 卖出/平仓时的价格(可选,支持高精度小数) | | 投入资金 | 本次交易投入的资金 | | 持仓量 | 持有数量,可点击"自动计算"按钮根据投入资金、杠杆和开仓价格自动计算 | | 开仓时间 | 交易开始时间(支持秒级精度,格式:YYYY-MM-DD HH:mm:ss) | | 平仓时间 | 交易结束时间(可选,支持秒级精度) | | 总盈亏 | 本次交易的盈亏金额 | | 总费用 | 手续费等费用 | | 交易理由 | 记录交易决策原因 |
资金记录管理
资金记录用于追踪平台的资金存入和取出操作,与交易记录分开管理。
| 字段 | 说明 | |------|------| | 平台 | 选择资金操作所属平台 | | 类型 | 存入或取出 | | 金额 | 操作金额 | | 时间 | 操作时间 | | 备注 | 操作备注(可选) |
资金计算公式
总资金 = 初始资金 + 总盈亏
涨跌幅 = 总盈亏 / 初始资金 × 100%
存入操作
- 存入金额会增加平台的初始资金
- 总资金相应增加,涨跌幅重新计算
取出操作
取出操作遵循以下逻辑:
- 取出金额 ≤ 初始资金:直接扣减初始资金,总盈亏不变
- 初始资金 < 取出金额 ≤ 总资金:初始资金归零,超出部分从总盈亏中扣减
- 取出金额 > 总资金:操作被阻止,提示余额不足
💡 当初始资金为0时,涨跌幅显示为"——",鼠标悬停可查看提示
数据备份与恢复
在设置页面可以进行数据备份和恢复操作:
- 导出数据:点击"导出数据"按钮,系统会生成包含所有平台配置、交易记录和设置的 JSON 文件
- 导入数据:点击"导入数据"按钮,选择之前导出的备份文件
- 默认覆盖模式:清除现有交易记录,导入备份数据
- 合并模式:保留现有数据,追加导入数据(不推荐)
💡 汇率数据不包含在备份中,系统会自动从网络获取最新汇率
数据库维护
在设置页面可以查看数据库状态和进行优化:
- 交易记录数:当前数据库中的交易记录总数
- 数据库大小:数据库文件的大小
- 索引状态:已创建的索引数量
- 优化数据库:执行 ANALYZE 和 VACUUM 操作,优化查询性能和回收空间
💡 系统会自动为新数据库创建索引,现有数据库在启动时会自动迁移添加索引
涨跌颜色设置
在设置页面可以切换涨跌颜色风格:
- 绿涨红跌(美股风格):盈利显示绿色,亏损显示红色
- 红涨绿跌(A股风格):盈利显示红色,亏损显示绿色
汇率更新
# 手动更新汇率
npm run fetch-rates
# 启动定时更新(每小时)
npm run fetch-rates:cron
🤖 MCP Server(给 Agent 使用)
本仓库同时保留原有 Express Web/API 应用,并提供通用 MCP stdio server。MCP server 与 Web API 共享 src/core 里的数据库初始化和业务服务层,因此 Agent 调用工具与前端接口会操作同一套 SQLite 数据。
启动 MCP Server
npm install
npm run mcp
# 或安装为 npm bin 后使用
npx finance-tracker-mcp
可用环境变量:
| 变量名 | 默认值 | 说明 |
|--------|--------|------|
| DATA_DIR | database/ | SQLite 数据目录 |
MCP 配置示例(Claude Desktop / Hermes 等)
{
"mcpServers": {
"finance-tracker": {
"command": "node",
"args": ["/path/to/Finance-Tracker/src/mcp/server.js"],
"env": {
"DATA_DIR": "/path/to/Finance-Tracker/database"
}
}
}
}
MCP Tools 一览
| 分类 | 工具名称 | 说明 |
|------|----------|------|
| 平台管理 | list_platforms | 列出所有平台及资金概要 |
| | get_platform | 获取单个平台详情 |
| | create_platform | 创建平台 |
| | update_platform | 更新平台信息 |
| | delete_platform | 删除平台及其关联记录 |
| 交易记录 | list_transactions | 分页查询交易记录 |
| | get_transaction | 获取单条交易记录 |
| | create_transaction | 创建交易记录 |
| | update_transaction | 更新交易记录 |
| | delete_transaction | 删除交易记录 |
| | batch_delete_transactions | 批量删除交易记录 |
| 统计分析 | get_transaction_stats | 获取汇总交易统计 |
| | list_asset_codes | 列出所有交易对 |
| | get_asset_stats | 获取指定交易对统计 |
| | get_overview | 获取资金总览 |
| | get_distribution | 获取平台资金分布 |
| | get_trend | 获取月度实现盈亏趋势 |
| 资金记录 | list_fund_records | 列出存取款记录 |
| | create_fund_record | 创建存取款记录 |
| | update_fund_record | 更新存取款记录 |
| | delete_fund_record | 删除存取款记录 |
| | get_fund_summary | 获取各平台资金流汇总 |
| | get_platform_fund_status | 获取平台资金状态 |
| 汇率与维护 | list_exchange_rates | 列出汇率 |
| | set_exchange_rate | 设置汇率 |
| | export_data | 导出所有数据 |
| | import_data | 导入数据 |
| | get_database_status | 获取数据库状态 |
| | optimize_database | 执行 ANALYZE + VACUUM |
🔌 API 接口
健康检查
GET /api/health
平台管理
GET /api/platforms # 获取所有平台
GET /api/platforms/:id # 获取单个平台
PUT /api/platforms/:id # 更新平台信息
交易记录
GET /api/transactions # 获取交易记录(支持分页和筛选)
GET /api/transactions/:id # 获取单条记录
POST /api/transactions # 创建交易记录
PUT /api/transactions/:id # 更新交易记录
DELETE /api/transactions/:id # 删除交易记录
统计分析
GET /api/transactions/stats # 获取总统计数据
GET /api/transactions/asset-codes # 获取所有交易对列表
GET /api/transactions/asset-stats/:asset_code # 获取指定交易对统计
资金记录
GET /api/fund-records # 获取资金记录(支持分页和筛选)
GET /api/fund-records/:id # 获取单条记录
POST /api/fund-records # 创建资金记录
PUT /api/fund-records/:id # 更新资金记录
DELETE /api/fund-records/:id # 删除资金记录
GET /api/fund-records/platform-status/:platformId # 获取平台资金状态
汇率
GET /api/exchange-rates # 获取所有汇率
POST /api/exchange-rates/refresh # 刷新汇率
总览
GET /api/overview # 获取资金总览数据
设置
GET /api/settings # 获取设置
PUT /api/settings/:key # 更新设置
GET /api/settings/export/all # 导出所有数据
POST /api/settings/import/all # 导入数据
GET /api/settings/database/status # 获取数据库状态
POST /api/settings/database/optimize # 优化数据库
📁 项目结构
Finance-Tracker/
├── app.js # Express 应用工厂(Web API 与测试复用)
├── server.js # 服务入口
├── database/
│ ├── db.js # 兼容旧路由的数据库连接模块
│ ├── init.js # 数据库初始化脚本
│ ├── migrate.js # 数据库迁移脚本(添加索引等)
│ └── finance.db # SQLite 数据库文件(运行时生成)
├── public/
│ ├── index.html # 前端页面
│ ├── css/
│ │ └── style.css # 样式文件
│ └── js/
│ ├── api.js # API 调用模块
│ ├── app.js # 主应用逻辑
│ └── utils.js # 工具函数
├── src/
│ ├── core/ # 共享数据库初始化与业务服务层
│ │ ├── database.js # 数据库初始化
│ │ ├── services.js # 服务聚合导出
│ │ └── services/ # 各业务模块服务
│ │ ├── common.js # 通用服务
│ │ ├── exchangeRates.js # 汇率服务
│ │ ├── fundRecords.js # 资金记录服务
│ │ ├── overview.js # 总览服务
│ │ ├── platforms.js # 平台服务
│ │ ├── settings.js # 设置服务
│ │ ├── stats.js # 统计服务
│ │ └── transactions.js # 交易服务
│ ├── http/
│ │ └── routes/ # HTTP API 路由
│ └── mcp/
│ ├── server.js # MCP stdio server
│ └── tools.js # MCP tools 定义
├── bin/
│ └── finance-tracker-mcp.js # MCP CLI 入口
├── test/ # Node 内置测试
├── routes/ # 旧版路由文件(保留参考/兼容)
├── scripts/
│ └── fetchExchangeRate.js # 汇率获取脚本
├── Dockerfile # Docker 镜像配置(多阶段构建)
├── docker-compose.yml # Docker Compose 配置
├── package.json # 项目配置
└── LICENSE # GPL v3.0 许可证
🗄️ 数据库结构
platforms 表
| 字段 | 类型 | 说明 | |------|------|------| | id | INTEGER | 主键 | | name | TEXT | 平台名称 | | currency | TEXT | 币种 (CNY/HKD/USD) | | initial_capital | REAL | 初始资金 | | created_at | DATETIME | 创建时间 | | updated_at | DATETIME | 更新时间 |
transactions 表
| 字段 | 类型 | 说明 | |------|------|------| | id | INTEGER | 主键 | | platform_id | INTEGER | 平台ID(外键) | | asset_name | TEXT | 资产名称 | | asset_code | TEXT | 资产代码 | | type | TEXT | 类型(合约/现货/事件) | | direction | TEXT | 方向(开多/开空) | | leverage | TEXT | 杠杆倍数 | | quantity | TEXT | 持仓量 | | open_price | TEXT | 开仓价格 | | close_price | TEXT | 平仓价格 | | investment | TEXT | 投入资金 | | open_time | TEXT | 开仓时间 | | close_time | TEXT | 平仓时间 | | total_profit | TEXT | 总盈亏 | | total_fee | TEXT | 总费用 | | reason | TEXT | 交易理由 |
fund_records 表
| 字段 | 类型 | 说明 | |------|------|------| | id | INTEGER | 主键 | | platform_id | INTEGER | 平台ID(外键) | | type | TEXT | 类型(存入/取出) | | amount | TEXT | 金额 | | record_time | TEXT | 记录时间 | | note | TEXT | 备注 | | created_at | DATETIME | 创建时间 | | updated_at | DATETIME | 更新时间 |
exchange_rates 表
| 字段 | 类型 | 说明 | |------|------|------| | id | INTEGER | 主键 | | from_currency | TEXT | 源币种 | | to_currency | TEXT | 目标币种 | | rate | REAL | 汇率 | | updated_at | DATETIME | 更新时间 |
🔧 环境变量
| 变量名 | 默认值 | 说明 |
|--------|--------|------|
| PORT | 3000 | 服务端口 |
| NODE_ENV | production | 运行环境 |
| TZ | Asia/Shanghai | 时区设置 |
| DATA_DIR | database/ | SQLite 数据目录(Docker 环境默认 /app/data) |
🧪 测试
npm test
📝 更新日志
v1.5.0 (2026-01-05)
- ✨ 新增总统计功能(📊 总统计按钮)
- 交易次数、总盈亏、总费用、实现盈亏统计
- 胜率、最大盈利/亏损、平均盈亏计算
- 盈亏比、投资回报率(ROI)、平均持仓时间
- 交易类型分布(现货/合约/事件)
- 开仓方向分布(开多/开空)
- 按交易对分组的详细统计表格
- ✨ 新增交易对统计功能(📈 交易对统计按钮)
- 支持搜索筛选交易对
- 查看单个交易对的详细统计数据
- 可展开查看该交易对的所有交易记录
- ✨ 新增3个统计分析API接口
- 🎨 统计模态框支持响应式布局
v1.4.0 (2026-01-04)
- 🗑️ 移除数据可视化模块(图表功能)
- 🔧 优化系统稳定性和性能
v1.3.0 (2025-12-15)
- ✨ 新增资金记录功能(存入/取出管理)
- ✨ 资金操作自动更新平台初始资金
- ✨ 智能取出逻辑(优先扣减初始资金,不足时扣减盈利)
- ✨ 取出金额实时校验(不可超过总资金)
- ✨ 初始资金为0时涨跌幅显示"——"
- 🔧 资金记录与交易记录分离管理
- 🔧 使用数据库事务确保资金操作原子性
v1.2.0 (2025-12-13)
- ✨ 新增数据库索引优化(5个索引加速查询)
- ✨ 新增游标分页支持(大数据量高效分页)
- ✨ 新增数据库维护功能(状态查看、手动优化)
- 🔧 优化导入功能(导入后自动执行 ANALYZE)
- 🔧 Docker 启动时自动执行数据库迁移
- 🔧 优化自定义下拉框组件,添加静默设置值方法
- 🐛 修复设置选项刷新后显示不正确的问题
- 🐛 修复手机端导航栏元素高度不一致的问题
- 🎨 优化移动端响应式布局
v1.1.0 (2025-12-12)
- ✨ 新增"事件"交易类型
- ✨ 新增涨跌颜色设置(红涨绿跌/绿涨红跌)
- ✨ 新增数据导入导出功能
- 🔧 优化持仓量自动计算公式(考虑杠杆)
- 🔧 优化时间输入支持秒级精度
- 🔧 优化小数存储精度(使用TEXT类型)
- 🎨 优化主题切换动画效果
v1.0.0 (2025-12-10)
- 🎉 首次发布
- ✅ 多平台资金管理
- ✅ 交易记录 CRUD
- ✅ 实时汇率获取
- ✅ 多币种支持
- ✅ Docker 部署支持
- ✅ 深色/浅色主题
🤝 贡献指南
欢迎提交 Issue 和 Pull Request!
- Fork 本仓库
- 创建特性分支 (
git checkout -b feature/AmazingFeature) - 提交更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 提交 Pull Request
📝 许可证
本项目采用 GNU General Public License v3.0 许可证
- ✅ 可自由使用、修改和分发(包括商业用途)
- 📝 修改后的代码必须开源并使用相同许可证
- 📝 必须保留原作者版权声明
📚 English Documentation
A lightweight multi-platform capital tracking and bookkeeping system that supports capital management across various investment platforms including A-shares, Hong Kong stocks, US stocks, and cryptocurrency. Also provides an MCP Server for AI Agent integration.
🖼️ Screenshots
| Dark Theme - Dashboard | Light Theme - Dashboard |
|:---:|:---:|
|
|
|
| Dark Theme - Settings | Dark Theme - Transaction Management |
|:---:|:---:|
|
|
|
| Light Theme - Settings | Dark Theme - Dashboard |
|:---:|:---:|
|
|
|
✨ Features
📊 Capital Overview
- Cross-platform capital aggregation display
- Multi-currency support (CNY/HKD/USD)
- Real-time exchange rate conversion
- Total profit/loss and percentage change statistics
🏛️ Platform Management
- Pre-configured platforms: A-shares, HK stocks, US stocks, Crypto
- Custom initial capital settings
- Independent currency configuration per platform
📝 Transaction Records
- Full CRUD transaction management
- Three transaction types: Spot / Futures / Event
- Long/Short direction support
- Leverage multiplier recording
- Open/close price and time (second-level precision)
- Profit/loss and fee statistics
- Trade reason notes
- High-precision decimal support (for cryptocurrency scenarios)
📈 Statistical Analysis
- Overall Statistics: View aggregated statistics for all trades
- Trade count, total P&L, total fees, realized P&L
- Win rate, max profit/loss, average P&L
- Profit factor, ROI, average holding time
- Transaction type distribution (Spot/Futures/Event)
- Direction distribution (Long/Short)
- Detailed statistics table grouped by trading pair
- Asset Statistics: View detailed statistics for a single trading pair
- Search and filter trading pairs
- Complete statistics for the selected pair
- Expandable view of all trades for the pair
💵 Fund Records
- Deposit/withdrawal management
- Auto-update platform initial capital
- Smart withdrawal logic (deduct from initial capital first, then from profit)
- Real-time withdrawal amount validation (cannot exceed total funds)
- Special display when initial capital is zero
💱 Exchange Rate Management
- Auto-fetch real-time rates from Bing
- Scheduled auto-update support
- Fallback rate mechanism for availability
💾 Data Backup & Restore
- One-click export of all data (platform config, transactions, settings)
- Restore from backup files
- Large dataset optimization (batch import to prevent UI freezing)
- Exchange rates auto-fetched from network, no backup needed
🗄️ Database Optimization
- Auto-create indexes for query performance
- Cursor-based pagination for large datasets
- Database maintenance (ANALYZE + VACUUM)
- View database status and manual optimization in Settings
🤖 MCP Server (AI Agent Integration)
- Provides MCP stdio server for AI Agents (Claude Desktop, Hermes, etc.)
- Shares the same database and business service layer with the Web API
- Supports all operations: platforms, transactions, statistics, fund records, exchange rates
- See MCP Server section for details
🎨 User Experience
- Responsive design with mobile support
- Dark/Light theme toggle (with circular spread animation)
- Profit/loss color style toggle (Green up/Red down or Red up/Green down)
- Modern UI interface
- Auto-calculate position size (investment × leverage / open price)
🛠️ Tech Stack
| Technology | Description | |------|------| | Backend | Node.js 20+ / Express.js 4.x | | Database | SQLite (better-sqlite3) | | Frontend | Vanilla HTML / CSS / JavaScript | | Rate Fetching | Cheerio + Node-fetch | | Scheduler | Node-cron | | MCP | @modelcontextprotocol/sdk | | Containerization | Docker + Docker Compose | | Testing | Node.js built-in test runner |
📦 Quick Start
Option 1: Docker Deployment (Recommended)
Prerequisites
- Docker 20.10+
- Docker Compose 2.0+
Deployment Steps
# 1. Clone the repository
git clone https://github.com/rggameffl1/Finance-Tracker.git
cd Finance-Tracker
# 2. Start with Docker Compose
docker-compose up -d
# 3. View logs
docker-compose logs -f
# 4. Access the application
# Open browser at http://localhost:3000
Common Docker Commands
# Stop services
docker-compose down
# Rebuild and start
docker-compose up -d --build
# Check container status
docker-compose ps
# Enter container
docker exec -it finance-tracker sh
# List data volumes
docker volume ls | grep finance
# Backup database
docker cp finance-tracker:/app/data/finance.db ./backup/
Option 2: Local Development
Prerequisites
- Node.js 20+
- npm or yarn
- Python 3 (for compiling better-sqlite3)
- C++ build toolchain
Installation Steps
# 1. Clone the repository
git clone https://github.com/rggameffl1/Finance-Tracker.git
cd Finance-Tracker
# 2. Install dependencies
npm install
# 3. Initialize database
npm run init-db
# 4. Start the server
npm start
# Or use development mode (auto-restart)
npm run dev
📖 Usage Guide
First Time Setup
- Visit
http://localhost:3000 - Four platforms are pre-configured (A-shares, HK stocks, US stocks, Crypto)
- Click the settings button on platform cards to configure initial capital
- Click "Add Record" to create transaction entries
Transaction Record Fields
| Field | Description | |-------|-------------| | Platform | Select the trading platform | | Name | Asset name, e.g. "Tencent Holdings", "BTC" | | Code | Asset code, e.g. "00700.HK", "BTC-USDT" | | Type | Spot, Futures, or Event | | Direction | Long or Short | | Leverage | Leverage multiplier (default 1 for spot) | | Open Price | Buy/open price (high-precision decimal) | | Close Price | Sell/close price (optional, high-precision decimal) | | Investment | Capital invested in this trade | | Quantity | Position size; click "Auto Calculate" to compute from investment, leverage, and open price | | Open Time | Trade start time (second-level precision, format: YYYY-MM-DD HH:mm:ss) | | Close Time | Trade end time (optional, second-level precision) | | Total P&L | Profit/loss amount for this trade | | Total Fee | Commissions and fees | | Reason | Record the rationale for the trade decision |
Fund Record Management
Fund records track deposit and withdrawal operations per platform, managed separately from transaction records.
| Field | Description | |-------|-------------| | Platform | Select the platform for the fund operation | | Type | Deposit or Withdrawal | | Amount | Operation amount | | Time | Operation time | | Note | Operation note (optional) |
Capital Calculation Formula
Total Capital = Initial Capital + Total P&L
Change % = Total P&L / Initial Capital × 100%
Deposit Operations
- Deposit amount increases the platform's initial capital
- Total capital increases accordingly, change % is recalculated
Withdrawal Operations
Withdrawal operations follow this logic:
- Withdrawal ≤ Initial Capital: Deduct directly from initial capital, total P&L unchanged
- Initial Capital < Withdrawal ≤ Total Capital: Initial capital goes to zero, excess deducted from total P&L
- Withdrawal > Total Capital: Operation blocked, insufficient balance warning
💡 When initial capital is 0, the change % displays "——"; hover for tooltip
Data Backup & Restore
In the Settings page, you can perform backup and restore operations:
- Export Data: Click "Export Data" to generate a JSON file containing all platform configurations, transaction records, and settings
- Import Data: Click "Import Data" to select a previously exported backup file
- Default overwrite mode: Clear existing transaction records and import backup data
- Merge mode: Keep existing data and append imported data (not recommended)
💡 Exchange rate data is not included in backups; the system auto-fetches the latest rates from the network
Database Maintenance
In the Settings page, you can view database status and perform optimization:
- Transaction Count: Total number of transaction records in the database
- Database Size: Size of the database file
- Index Status: Number of created indexes
- Optimize Database: Execute ANALYZE and VACUUM operations to optimize query performance and reclaim space
💡 The system automatically creates indexes for new databases; existing databases are auto-migrated on startup
Profit/Loss Color Settings
In the Settings page, you can toggle the profit/loss color style:
- Green Up / Red Down (US stock style): Profit in green, loss in red
- Red Up / Green Down (A-share style): Profit in red, loss in green
Exchange Rate Update
# Manual rate update
npm run fetch-rates
# Start scheduled update (hourly)
npm run fetch-rates:cron
🤖 MCP Server (For AI Agents)
This repository retains the original Express Web/API application and also provides a general-purpose MCP stdio server. The MCP server shares the src/core database initialization and business service layer with the Web API, so Agent tool calls and frontend interfaces operate on the same SQLite data.
Starting the MCP Server
npm install
npm run mcp
# Or install as npm bin
npx finance-tracker-mcp
Available environment variables:
| Variable | Default | Description |
|----------|---------|-------------|
| DATA_DIR | database/ | SQLite data directory |
MCP Configuration Example (Claude Desktop / Hermes)
{
"mcpServers": {
"finance-tracker": {
"command": "node",
"args": ["/path/to/Finance-Tracker/src/mcp/server.js"],
"env": {
"DATA_DIR": "/path/to/Finance-Tracker/database"
}
}
}
}
MCP Tools Overview
| Category | Tool Name | Description |
|----------|-----------|-------------|
| Platform | list_platforms | List all platforms with capital/profit summary |
| | get_platform | Get one platform by ID |
| | create_platform | Create a platform |
| | update_platform | Update a platform |
| | delete_platform | Delete a platform and cascaded records |
| Transactions | list_transactions | List trading records with pagination |
| | get_transaction | Get one trading record |
| | create_transaction | Create a trading record |
| | update_transaction | Update a trading record |
| | delete_transaction | Delete a trading record |
| | batch_delete_transactions | Delete multiple trading records |
| Statistics | get_transaction_stats | Get aggregate trading statistics |
| | list_asset_codes | List traded asset symbols |
| | get_asset_stats | Get statistics for one asset code |
| | get_overview | Get portfolio overview |
| | get_distribution | Get platform capital distribution |
| | get_trend | Get monthly realized-profit trend |
| Fund Records | list_fund_records | List deposit/withdrawal records |
| | create_fund_record | Create a deposit or withdrawal record |
| | update_fund_record | Update a fund record |
| | delete_fund_record | Delete a fund record |
| | get_fund_summary | Get fund-flow summary by platform |
| | get_platform_fund_status | Get current fund status for a platform |
| Rates & Maintenance | list_exchange_rates | List exchange rates |
| | set_exchange_rate | Set exchange rate |
| | export_data | Export all portfolio data |
| | import_data | Import portfolio data |
| | get_database_status | Get SQLite database status |
| | optimize_database | Run ANALYZE + VACUUM |
🔌 API Endpoints
Health Check
GET /api/health
Platform Management
GET /api/platforms # List all platforms
GET /api/platforms/:id # Get one platform
PUT /api/platforms/:id # Update platform info
Transaction Records
GET /api/transactions # List transactions (with pagination & filters)
GET /api/transactions/:id # Get one transaction
POST /api/transactions # Create transaction
PUT /api/transactions/:id # Update transaction
DELETE /api/transactions/:id # Delete transaction
Statistical Analysis
GET /api/transactions/stats # Get overall statistics
GET /api/transactions/asset-codes # Get all asset codes
GET /api/transactions/asset-stats/:asset_code # Get stats for an asset code
Fund Records
GET /api/fund-records # List fund records (with pagination & filters)
GET /api/fund-records/:id # Get one fund record
POST /api/fund-records # Create fund record
PUT /api/fund-records/:id # Update fund record
DELETE /api/fund-records/:id # Delete fund record
GET /api/fund-records/platform-status/:platformId # Get platform fund status
Exchange Rates
GET /api/exchange-rates # Get all exchange rates
POST /api/exchange-rates/refresh # Refresh rates
Overview
GET /api/overview # Get capital overview data
Settings
GET /api/settings # Get settings
PUT /api/settings/:key # Update setting
GET /api/settings/export/all # Export all data
POST /api/settings/import/all # Import data
GET /api/settings/database/status # Get database status
POST /api/settings/database/optimize # Optimize database
📁 Project Structure
Finance-Tracker/
├── app.js # Express app factory (shared by Web API & tests)
├── server.js # Server entry point
├── database/
│ ├── db.js # Legacy DB connection module
│ ├── init.js # Database initialization script
│ ├── migrate.js # Database migration script (add indexes, etc.)
│ └── finance.db # SQLite database file (generated at runtime)
├── public/
│ ├── index.html # Frontend page
│ ├── css/
│ │ └── style.css # Stylesheet
│ └── js/
│ ├── api.js # API call module
│ ├── app.js # Main application logic
│ └── utils.js # Utility functions
├── src/
│ ├── core/ # Shared DB initialization & business services
│ │ ├── database.js # Database initialization
│ │ ├── services.js # Service aggregation export
│ │ └── services/ # Business module services
│ │ ├── common.js # Common service
│ │ ├── exchangeRates.js # Exchange rate service
│ │ ├── fundRecords.js # Fund record service
│ │ ├── overview.js # Overview service
│ │ ├── platforms.js # Platform service
│ │ ├── settings.js # Settings service
│ │ ├── stats.js # Statistics service
│ │ └── transactions.js # Transaction service
│ ├── http/
│ │ └── routes/ # HTTP API routes
│ └── mcp/
│ ├── server.js # MCP stdio server
│ └── tools.js # MCP tools definitions
├── bin/
│ └── finance-tracker-mcp.js # MCP CLI entry point
├── test/ # Node.js built-in tests
├── routes/ # Legacy route files (kept for reference/compatibility)
├── scripts/
│ └── fetchExchangeRate.js # Exchange rate fetching script
├── Dockerfile # Docker image config (multi-stage build)
├── docker-compose.yml # Docker Compose config
├── package.json # Project configuration
└── LICENSE # GPL v3.0 License
🗄️ Database Schema
platforms Table
| Column | Type | Description | |--------|------|-------------| | id | INTEGER | Primary key | | name | TEXT | Platform name | | currency | TEXT | Currency (CNY/HKD/USD) | | initial_capital | REAL | Initial capital | | created_at | DATETIME | Creation time | | updated_at | DATETIME | Update time |
transactions Table
| Column | Type | Description | |--------|------|-------------| | id | INTEGER | Primary key | | platform_id | INTEGER | Platform ID (foreign key) | | asset_name | TEXT | Asset name | | asset_code | TEXT | Asset code | | type | TEXT | Type (Futures/Spot/Event) | | direction | TEXT | Direction (Long/Short) | | leverage | TEXT | Leverage multiplier | | quantity | TEXT | Position size | | open_price | TEXT | Open price | | close_price | TEXT | Close price | | investment | TEXT | Invested capital | | open_time | TEXT | Open time | | close_time | TEXT | Close time | | total_profit | TEXT | Total P&L | | total_fee | TEXT | Total fees | | reason | TEXT | Trade reason |
fund_records Table
| Column | Type | Description | |--------|------|-------------| | id | INTEGER | Primary key | | platform_id | INTEGER | Platform ID (foreign key) | | type | TEXT | Type (Deposit/Withdrawal) | | amount | TEXT | Amount | | record_time | TEXT | Record time | | note | TEXT | Note | | created_at | DATETIME | Creation time | | updated_at | DATETIME | Update time |
exchange_rates Table
| Column | Type | Description | |--------|------|-------------| | id | INTEGER | Primary key | | from_currency | TEXT | Source currency | | to_currency | TEXT | Target currency | | rate | REAL | Exchange rate | | updated_at | DATETIME | Update time |
🔧 Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| PORT | 3000 | Server port |
| NODE_ENV | production | Runtime environment |
| TZ | Asia/Shanghai | Timezone |
| DATA_DIR | database/ | SQLite data directory (/app/data in Docker) |
🧪 Testing
npm test
📝 Changelog
v1.5.0 (2026-01-05)
- ✨ Added overall statistics feature (📊 Overall Stats button)
- Trade count, total P&L, total fees, realized P&L
- Win rate, max profit/loss, average P&L
- Profit factor, ROI, average holding time
- Transaction type distribution (Spot/Futures/Event)
- Direction distribution (Long/Short)
- Detailed statistics table grouped by trading pair
- ✨ Added asset statistics feature (📈 Asset Stats button)
- Search and filter trading pairs
- View detailed statistics for a single pair
- Expandable view of all trades for the pair
- ✨ Added 3 statistical analysis API endpoints
- 🎨 Responsive layout for statistics modal
v1.4.0 (2026-01-04)
- 🗑️ Removed data visualization module (chart feature)
- 🔧 Improved system stability and performance
v1.3.0 (2025-12-15)
- ✨ Added fund record feature (deposit/withdrawal management)
- ✨ Auto-update platform initial capital on fund operations
- ✨ Smart withdrawal logic (deduct initial capital first, then profit)
- ✨ Real-time withdrawal amount validation
- ✨ Special display when initial capital is zero
- 🔧 Separated fund records from transaction records
- 🔧 Used database transactions for atomic fund operations
v1.2.0 (2025-12-13)
- ✨ Added database index optimization (5 indexes for faster queries)
- ✨ Added cursor-based pagination (efficient for large datasets)
- ✨ Added database maintenance feature (status view, manual optimization)
- 🔧 Optimized import (auto-run ANALYZE after import)
- 🔧 Auto-run database migration on Docker startup
- 🔧 Improved custom dropdown component
- 🐛 Fixed settings display issue after refresh
- 🐛 Fixed inconsistent navbar height on mobile
- 🎨 Improved mobile responsive layout
v1.1.0 (2025-12-12)
- ✨ Added "Event" transaction type
- ✨ Added profit/loss color settings (Red up/Green down or Green up/Red down)
- ✨ Added data import/export feature
- 🔧 Optimized position size auto-calculation (considering leverage)
- 🔧 Optimized time input with second-level precision
- 🔧 Optimized decimal storage precision (using TEXT type)
- 🎨 Improved theme switch animation
v1.0.0 (2025-12-10)
- 🎉 Initial release
- ✅ Multi-platform capital management
- ✅ Transaction record CRUD
- ✅ Real-time exchange rate fetching
- ✅ Multi-currency support
- ✅ Docker deployment support
- ✅ Dark/Light theme
🤝 Contributing
Issues and Pull Requests are welcome!
- Fork this repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Submit a Pull Request
📝 License
This project is licensed under the GNU General Public License v3.0
- ✅ Free to use, modify, and distribute (including commercial use)
- 📝 Modified code must be open-sourced under the same license
- 📝 Original author copyright notice must be retained
🙏 Acknowledgements
- Express.js - Web framework
- better-sqlite3 - SQLite driver
- Cheerio - HTML parser
- Node-cron - Task scheduler
- Model Context Protocol - MCP SDK
Made with ❤️ for better financial management