Skip to main content

KHY-Quant quantitative trading system — modular, extensible, SaaS-ready

Reason this release was yanked:

error

Project description

KHY-Quant Logo

KHY-Quant 量化交易系统 — 开源学习版

完整源码 · 中文注释 · 零基础可学 · 模块化架构

PyPI Python License


这是 KHY-Quant 的完全开源学习版,所有源码未经混淆,带有详细中文注释,适合:

  • 想学习量化交易系统架构的开发者
  • 想了解 Node.js 后端 + Vue 前端 + Python CLI 混合架构的同学
  • 想学习 AI 网关、多模型适配、WebSocket 流式通信的同学
  • 零基础入门量化交易编程的小白

目录


快速开始

环境要求

依赖 版本 说明
Python >= 3.8 用于 pip 安装和 CLI 入口
Node.js >= 18 后端运行环境(首次启动自动检测)
npm 自带 包管理器(随 Node.js 安装)

安装

# 基础安装
pip install khy-quant==1.0.3

# 包含数据分析库
pip install "khy-quant==1.0.3[data]"

# 包含机器学习
pip install "khy-quant==1.0.3[ml]"

# 完整安装
pip install "khy-quant==1.0.3[full]"

启动

khy          # 启动交互式终端
khy --help   # 查看帮助
khy quote 茅台  # 查询行情

首次启动会自动:检测 Node.js → 安装 npm 依赖 → 生成 .env 配置 → 初始化数据库。


完整目录结构

KHY-Quant/
│
├── khy_quant/                     # 【Python 包入口】pip install 后的可执行包
│   ├── __init__.py                #   版本号定义 (__version__)
│   ├── __main__.py                #   python -m khy_quant 入口
│   ├── cli.py                     #   ★ CLI 入口点:检查 Node.js → 定位后端 → exec 进 Node
│   └── _bootstrap.py              #   ★ 首次运行引导:npm install → .env 生成 → DB 初始化
│
├── backend/                       # 【Node.js 后端】核心业务逻辑(最重要的部分)
│   ├── bin/
│   │   └── khyquant.js            #   ★ Node.js CLI 入口:参数解析、REPL 启动、认证
│   │
│   ├── server.js                  #   Express Web 服务器(端口 8080)
│   ├── setup.js                   #   数据库迁移和初始化
│   ├── package.json               #   npm 依赖定义
│   │
│   └── src/
│       ├── cli/                   # 【CLI 交互层】命令行界面的全部逻辑
│       │   ├── repl.js            #   ★★ 核心文件:readline 交互循环、AI 聊天、命令分发
│       │   ├── router.js          #   ★★ 命令路由:解析输入 → 匹配命令 → 调用 handler
│       │   ├── ai.js              #   ★ AI 对话管理:会话历史、system prompt、工具调用
│       │   ├── aliases.js         #   命令别名表(中文/拼音/英文 → 标准命令)
│       │   ├── formatters.js      #   输出格式化:颜色、表格、图标、进度条
│       │   ├── plugins.js         #   插件系统:加载 ~/.khyquant/plugins/ 下的扩展
│       │   └── handlers/          #   命令处理器(每个文件对应一组命令)
│       │       ├── gateway.js     #     AI 网关命令:status、config、relay、model、test、server
│       │       ├── data.js        #     数据命令:quote、fetch、list、search
│       │       ├── backtest.js    #     回测命令:运行回测、查看结果
│       │       ├── init.js        #     初始化命令:init、doctor
│       │       ├── service.js     #     服务管理:server start/stop
│       │       ├── skill.js       #     技能系统:skill list、skill run
│       │       ├── pool.js        #     账号池管理:acquire、release、stats
│       │       ├── proxy.js       #     代理服务器命令
│       │       ├── ide.js         #     IDE 集成命令
│       │       └── docs.js        #     文档生成命令
│       │
│       ├── services/              # 【服务层】核心业务逻辑(最多代码的目录)
│       │   │
│       │   │  ── 数据服务 ──
│       │   ├── klineDataService.js       #  K 线数据获取与缓存
│       │   ├── marketDataService.js      #  实时行情服务
│       │   ├── realtimeDataService.js    #  实时推送服务
│       │   ├── akshareDataService.js     #  AkShare 数据源适配(Python 子进程调用)
│       │   ├── comprehensiveDataService.js  # 多源数据融合
│       │   ├── finlightNewsService.js    #  财经新闻服务
│       │   │
│       │   │  ── 策略与回测 ──
│       │   ├── strategyEngine.js         #  ★ 策略执行引擎
│       │   ├── backtestEngine.js         #  ★ 回测引擎:模拟交易、计算收益
│       │   ├── strategyMonitor.js        #  策略实时监控
│       │   ├── strategyRecommender.js    #  AI 策略推荐
│       │   │
│       │   │  ── AI 网关系统 ──
│       │   ├── gateway/                  #  ★★ AI 多模型网关(最核心的 AI 基础设施)
│       │   │   ├── aiGateway.js          #    网关主文件:适配器注册、级联路由、测试
│       │   │   ├── proxyServer.js        #    反向代理服务器(OpenAI 兼容 API)
│       │   │   ├── relayPage.js          #    Web 中转页面生成
│       │   │   └── adapters/             #    适配器目录(每个文件 = 一个 AI 提供商)
│       │   │       ├── ollamaAdapter.js  #      Ollama 本地模型
│       │   │       ├── claudeAdapter.js  #      Claude CLI 适配
│       │   │       ├── kiroAdapter.js    #      Kiro IDE 适配(AWS CodeWhisperer)
│       │   │       ├── cursorAdapter.js  #      Cursor IDE 适配
│       │   │       ├── codexAdapter.js   #      Codex CLI 适配
│       │   │       ├── apiAdapter.js     #      通用 API 适配(Gemini/Groq/OpenAI 等)
│       │   │       ├── webRelayAdapter.js #     Web 中转适配(手动复制粘贴)
│       │   │       ├── cliToolAdapter.js  #     CLI 工具桥接
│       │   │       ├── ideDetector.js     #     IDE 安装检测器
│       │   │       └── clipboardRelayAdapter.js # 剪贴板中转
│       │   │
│       │   │  ── AI 管理 ──
│       │   ├── aiManagementServer.js     #  ★ AI 管理后端(独立端口 REST + WebSocket)
│       │   ├── multiFreeService.js       #  多提供商免费 API 服务
│       │   ├── toolCalling.js            #  ★ 工具调用系统(AI 可调用的工具注册和权限)
│       │   ├── webSearchService.js       #  联网搜索服务
│       │   │
│       │   │  ── 安全与监控 ──
│       │   ├── securityGuardService.js   #  ★ 安全防护:注入检测、输出清洗、速率限制
│       │   ├── tokenUsageService.js      #  Token 用量追踪与费用计算
│       │   ├── accountPool.js            #  账号池管理(租约模式)
│       │   │
│       │   │  ── 用户与配置 ──
│       │   ├── userLogService.js         #  用户操作日志
│       │   ├── usageHabitService.js      #  使用习惯追踪
│       │   ├── growthService.js          #  用户成长体系
│       │   ├── instructionFileService.js #  khy.md 指令文件加载
│       │   │
│       │   │  ── 机器学习 ──
│       │   ├── modelTrainingService.js   #  模型训练数据收集
│       │   ├── knowledgeTeachingService.js # 知识提取
│       │   └── agentCommunicationService.js # Agent 协作通信
│       │
│       ├── routes/                # 【路由层】Express REST API 端点
│       │   ├── auth.js            #   用户认证(注册/登录/JWT)
│       │   ├── strategy.js        #   策略 CRUD
│       │   ├── backtest.js        #   回测执行与结果查询
│       │   ├── trade.js           #   交易下单
│       │   ├── klineData.js       #   K 线数据 API
│       │   ├── marketData.js      #   行情数据 API
│       │   ├── ai.js              #   AI 分析 API
│       │   ├── settings.js        #   系统设置 API
│       │   ├── dashboard.js       #   仪表盘数据
│       │   ├── watchlist.js       #   自选股
│       │   ├── instruments.js     #   品种列表
│       │   ├── admin.js           #   管理后台
│       │   └── ...                #   更多路由(30+ 个文件)
│       │
│       ├── middleware/            # 【中间件】请求处理管道
│       │   ├── auth.js            #   JWT 认证 + API Key 认证
│       │   ├── rateLimit.js       #   速率限制(本地 IP 跳过)
│       │   ├── errorHandler.js    #   全局错误处理
│       │   ├── requestLogger.js   #   请求日志
│       │   └── auditLog.js        #   审计日志
│       │
│       ├── models/                # 【数据模型】Sequelize ORM 模型
│       │   ├── User.js            #   用户模型
│       │   ├── Strategy.js        #   策略模型
│       │   ├── Trade.js           #   交易记录
│       │   ├── Backtest.js        #   回测结果
│       │   ├── Instrument.js      #   交易品种
│       │   ├── KlineData.js       #   K 线缓存
│       │   ├── Signal.js          #   交易信号
│       │   ├── ApiKey.js          #   API 密钥
│       │   └── index.js           #   模型注册和关联定义
│       │
│       ├── config/                # 【配置】数据库连接、策略配置
│       │   └── database.js        #   数据库配置(SQLite / PostgreSQL)
│       │
│       └── utils/                 # 【工具】通用辅助函数
│
├── frontend/                      # 【Vue.js 前端】Web 交易界面
│   ├── src/
│   │   ├── App.vue                #   根组件
│   │   ├── main.js                #   应用入口
│   │   ├── views/                 #   页面级组件(30+ 个)
│   │   │   ├── Dashboard.vue      #     仪表盘首页
│   │   │   ├── Trading.vue        #     交易页面
│   │   │   ├── Strategies.vue     #     策略管理
│   │   │   ├── BacktestAnalysis.vue #   回测分析
│   │   │   ├── MarketQuotes.vue   #     行情看板
│   │   │   ├── Login.vue          #     登录页
│   │   │   └── ...
│   │   ├── components/            #   可复用组件(40+ 个)
│   │   │   ├── ProfessionalTradingChart.vue  # K 线图表
│   │   │   ├── StrategyManager.vue           # 策略管理器
│   │   │   ├── TradingAgentsBotSimple.vue    # AI 交易机器人
│   │   │   └── ...
│   │   ├── services/              #   前端服务层
│   │   ├── stores/                #   Pinia 状态管理
│   │   ├── router/                #   Vue Router 路由
│   │   ├── api/                   #   后端 API 调用封装
│   │   └── utils/                 #   前端工具函数
│   ├── vite.config.js             #   Vite 构建配置
│   └── package.json
│
├── scripts/                       # 【构建脚本】
│   ├── obfuscate.js               #   JS 混淆脚本(正式版使用,学习版不启用)
│   ├── deploy-server.sh           #   服务器一键部署(Ubuntu)
│   └── seed.js                    #   数据库初始化种子数据
│
├── pyproject.toml                 #   Python 包配置
├── setup.py                       #   构建脚本(bundling + 混淆)
├── install.sh                     #   一键安装脚本
├── docker-compose.yml             #   Docker 部署配置
└── README.md                      #   本文档

架构概览

整体架构

┌──────────────────────────────────────────────────────────┐
│                    用户交互层                              │
│  ┌─────────────┐  ┌──────────────┐  ┌─────────────────┐  │
│  │  CLI 终端    │  │  Web 前端     │  │  REST API 调用  │  │
│  │ (khy 命令)   │  │ (Vue.js)     │  │  (curl/程序)    │  │
│  └──────┬──────┘  └──────┬───────┘  └────────┬────────┘  │
└─────────┼────────────────┼───────────────────┼───────────┘
          │                │                   │
┌─────────┼────────────────┼───────────────────┼───────────┐
│         ▼                ▼                   ▼            │
│  ┌─────────────────────────────────────────────────────┐  │
│  │              Express Web 服务器 (:8080)              │  │
│  │  路由 → 中间件(认证/限速/日志) → 控制器 → 服务       │  │
│  └─────────────────────────────────────────────────────┘  │
│                                                           │
│  ┌─────────────────────────────────────────────────────┐  │
│  │           AI 管理服务器 (:9090) [独立端口]            │  │
│  │  REST API + WebSocket 流式 AI 聊天                   │  │
│  └─────────────────────────────────────────────────────┘  │
│                          服务层                           │
│  ┌────────────┐ ┌────────────┐ ┌─────────────┐          │
│  │ 数据服务    │ │ 策略引擎    │ │ 回测引擎     │          │
│  │ (K线/行情)  │ │ (执行/监控) │ │ (模拟交易)   │          │
│  └─────┬──────┘ └────────────┘ └─────────────┘          │
│        │                                                  │
│  ┌─────┴───────────────────────────────────────────────┐  │
│  │              AI 网关 (aiGateway)                     │  │
│  │  ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐        │  │
│  │  │Kiro│ │Olma│ │API │ │Clau│ │Curs│ │Rela│ ...     │  │
│  │  └────┘ └────┘ └────┘ └────┘ └────┘ └────┘        │  │
│  │  适配器按优先级级联:失败自动切换下一个              │  │
│  └─────────────────────────────────────────────────────┘  │
│                                                           │
│  ┌─────────────────────────────────────────────────────┐  │
│  │  存储层: SQLite (默认) / PostgreSQL + Redis 缓存     │  │
│  └─────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────┘

数据流

用户输入 "分析茅台"
    │
    ▼
CLI repl.js 接收输入
    │
    ▼
router.js 匹配命令(aliases.js 转换中文→标准命令)
    │
    ├── 匹配到已知命令 → 调用对应 handler
    │
    └── 未匹配 → 送入 AI 对话 (ai.js)
            │
            ▼
        ai.js → securityGuardService 安全检查
            │
            ▼
        aiGateway.generate() 级联路由
            │
            ├── 优先适配器(如 Kiro) → 成功 → 返回
            ├── 失败 → onFallback 通知 → 下一个适配器
            ├── Ollama → 成功 → 返回
            └── 全部失败 → 错误信息
            │
            ▼
        ai.js 解析回复:
            ├── 提取 [CMD:...] 工具命令 → 自动执行
            ├── sanitizeOutput 清洗输出
            └── recordUsage 记录用量
            │
            ▼
        repl.js 格式化显示 → 等待下一个输入

Python → Node.js 混合架构

pip install khy-quant
         │
         ▼
  Python 包 (khy_quant/)
  cli.py → check_node() → 确保 Node.js >= 18
         │
         ▼
  _bootstrap.py → npm install → .env 生成 → DB 初始化
         │
         ▼
  os.execvpe(node, ["node", "bin/khyquant.js", ...args])
         │
         ▼
  Node.js 接管整个进程 → CLI 或 Web 服务器

为什么用 Python + Node.js?

  • Python: pip 安装生态更成熟,用户只需 pip install 一条命令
  • Node.js: Web 后端生态(Express、WebSocket)更成熟,异步性能更好
  • Python 只是一个薄启动层(<200 行),所有业务逻辑在 Node.js 中

从零开始学习路线

第 1 阶段:理解项目入口(30 分钟)

建议阅读顺序:

  1. khy_quant/cli.py — Python 入口,理解 pip 包如何启动 Node.js
  2. backend/bin/khyquant.js — Node.js 入口,理解参数解析和模式选择
  3. backend/src/cli/repl.js — 交互式终端的核心循环

关键概念:

  • Python 是启动器,Node.js 是引擎
  • REPL = Read-Eval-Print Loop(读取-执行-打印循环)
  • readline 模块用于终端交互

第 2 阶段:命令系统(1 小时)

  1. backend/src/cli/router.js — 命令如何被解析和路由
  2. backend/src/cli/aliases.js — 中文/拼音别名如何映射
  3. backend/src/cli/handlers/data.js — 一个简单的命令处理器

动手练习: 添加一个新命令 hello,在终端输出 "Hello World"

第 3 阶段:AI 网关(2 小时)

  1. backend/src/services/gateway/aiGateway.js — 多模型网关核心
  2. backend/src/services/gateway/adapters/ollamaAdapter.js — 最简单的适配器
  3. backend/src/services/gateway/adapters/apiAdapter.js — API 调用适配
  4. backend/src/cli/ai.js — AI 对话管理

关键模式:

  • 适配器模式(Adapter Pattern):每个 AI 提供商一个适配器
  • 级联路由(Cascade Routing):按优先级依次尝试
  • 流式输出(Streaming):通过 onChunk 回调实时输出

第 4 阶段:数据与策略(2 小时)

  1. backend/src/services/klineDataService.js — K 线数据获取
  2. backend/src/services/backtestEngine.js — 回测引擎
  3. backend/src/services/strategyEngine.js — 策略执行

第 5 阶段:Web 服务(1 小时)

  1. backend/server.js — Express 服务器配置
  2. backend/src/middleware/auth.js — JWT 认证原理
  3. backend/src/routes/strategy.js — REST API 示例
  4. backend/src/services/aiManagementServer.js — 独立 AI 管理服务

第 6 阶段:前端(2 小时)

  1. frontend/src/views/Trading.vue — 交易主页面
  2. frontend/src/components/ProfessionalTradingChart.vue — K 线图表
  3. frontend/src/services/websocketService.js — WebSocket 实时通信

核心模块详解

1. CLI 交互系统 (backend/src/cli/)

CLI 是用户最先接触的部分。核心文件是 repl.js

// repl.js 简化版工作流程:
const rl = readline.createInterface({ input, output, prompt: 'KHY> ' });

rl.on('line', async (input) => {
    // 1. 解析输入
    const { command, args } = parse(input);

    // 2. 尝试命令路由
    const handled = await router.route(command, args);

    // 3. 未匹配的输入送入 AI
    if (!handled) {
        const result = await ai.chat(input, { onChunk });
        display(result.reply);
    }

    rl.prompt();
});

2. AI 网关 (backend/src/services/gateway/)

网关是 AI 功能的核心基础设施:

// aiGateway.js 简化版:
class AIGateway {
    _adapters = [
        { key: 'kiro',    adapter: kiroAdapter,   priority: 2 },
        { key: 'ollama',  adapter: ollamaAdapter,  priority: 6 },
        { key: 'api',     adapter: apiAdapter,     priority: 8 },
        { key: 'relay',   adapter: relayAdapter,   priority: 10 },
        // ... 共 12 个适配器
    ];

    async generate(prompt, options) {
        // 按优先级依次尝试每个适配器
        for (const entry of this._adapters) {
            if (!entry.enabled || !entry.available) continue;

            try {
                const result = await entry.adapter.generate(prompt, options);
                if (result.success) return result;
            } catch (err) {
                // 通知调用者发生了切换
                options.onFallback?.({
                    failedAdapter: entry.name,
                    failedError: err.message,
                    nextAdapter: nextEntry?.name,
                });
            }
        }
    }
}

适配器接口规范(所有适配器都实现这些方法):

module.exports = {
    detect(forceRefresh),    // 检测适配器是否可用 → boolean
    generate(prompt, opts),  // 生成 AI 回复 → { success, content, provider }
    getStatus(),             // 获取状态 → { name, type, available, detail }
    listModels(),            // 列出可用模型 → [{ id, name }](可选)
    destroy(),               // 清理资源(可选)
};

3. 安全防护 (securityGuardService.js)

三层安全机制保护 AI 对话:

第 1 层:输入注入检测
    analyzeInput(userMessage) → { safe, threat, refusal }
    59 条正则规则检测 prompt injection

第 2 层:输出清洗
    sanitizeOutput(aiResponse) → cleanedText
    移除泄露的内部路径、模块名、环境变量

第 3 层:速率限制
    checkRateLimit() → { allowed, cooldownRemaining }
    60 秒内最多 3 次可疑请求

4. 工具调用系统 (toolCalling.js)

AI 可以通过 [CMD:xxx] 标记调用内置工具:

// 内置工具注册示例:
const BUILTIN_TOOLS = [
    {
        name: 'quote',
        description: 'Get real-time stock quote',
        risk: 'safe',               // safe = 自动执行
        handler: async (params) => {
            await handleQuote(params.symbol);
        },
    },
    {
        name: 'execute_code',
        risk: 'high',               // high = 需要用户确认
        handler: async (params) => { ... },
    },
];

CLI 命令系统

命令路由原理

用户输入: "hq 茅台"
    │
    ▼ aliases.js
"hq" → "quote"     (拼音别名)
"茅台" → 保持不变   (参数)
    │
    ▼ router.js
匹配 COMMANDS 数组中的 "quote"
    │
    ▼ handlers/data.js
handleQuote("茅台")
    │
    ▼ klineDataService.js
搜索品种 → 获取行情 → 格式化输出

支持的命令列表

命令 中文 拼音 说明
quote 行情 hq 查询实时行情
backtest 回测 bt 运行策略回测
analyze 分析 fx AI 分析股票
data fetch 下载 xz 下载 K 线数据
data list 品种 pz 查看品种列表
strategy list 策略 cl 查看策略列表
gateway status 查看 AI 网关状态
gateway model 选择 AI 模型
gateway test 测试 AI 连通性
gateway server 启动 AI 管理服务器
cost 费用 查看 Token 费用
help 帮助 bz 显示帮助

AI 网关系统

适配器优先级

优先级 1: CLI 工具桥接 (Claude Code / Codex / Aider)
优先级 2: Kiro IDE (AWS CodeWhisperer)
优先级 3: Cursor IDE
优先级 4: Claude CLI
优先级 5: Codex CLI
优先级 6: Ollama 本地模型
优先级 7: VS Code / Windsurf / Trae
优先级 8: API 直连 (Gemini/Groq/OpenAI 等)
优先级 9: Web 中转
优先级 10: 剪贴板中转

两步连通测试

khy gateway test
  Ollama
    ① 连接  ● 已连接 (12ms)
    ② 模型  ● 可用 (8ms · 3 models) qwen2.5:7b, llama3.2

  Gemini API
    ① 连接  ● 失败: ECONNREFUSED

AI 管理服务器

独立 HTTP + WebSocket 服务器(端口 9090):

khy gateway server          # 启动
khy gateway server stop     # 停止
khy gateway server status   # 查看状态

REST API:

GET  /api/health            — 健康检查
GET  /api/status            — 适配器状态
GET  /api/models            — 模型列表(含健康指标)
POST /api/test/:adapter     — 两步连通测试
GET  /api/config            — 网关配置
PUT  /api/config            — 更新配置
GET  /api/conversations     — 会话列表
GET  /api/usage             — Token 用量
GET  /api/tools             — 工具列表
POST /api/tools/:name       — 执行工具

WebSocket (ws://localhost:9090/ws):

 {"type": "auth", "token": "..."}
 {"type": "auth_ok", "sessionId": "..."}
 {"type": "chat", "message": "分析茅台"}
 {"type": "thinking", "text": "..."}
 {"type": "text", "text": "..."}
 {"type": "chat_complete", "elapsed": 1200}

策略与回测引擎

回测流程

// backtestEngine.js 简化版:
async function runBacktest(stockCode, strategyId, startDate, endDate) {
    // 1. 获取历史 K 线数据
    const klines = await klineDataService.getKlineData(stockCode, startDate, endDate);

    // 2. 加载策略
    const strategy = loadStrategy(strategyId);

    // 3. 逐日模拟
    let position = 0, cash = 100000;
    for (const bar of klines) {
        const signal = strategy.evaluate(bar, history);
        if (signal === 'BUY' && cash > 0) {
            position = Math.floor(cash / bar.close);
            cash -= position * bar.close;
        } else if (signal === 'SELL' && position > 0) {
            cash += position * bar.close;
            position = 0;
        }
    }

    // 4. 计算收益指标
    return { totalReturn, maxDrawdown, sharpeRatio, winRate };
}

Web API 接口

认证方式

所有 API 端点(除 /health 外)需要认证:

# 方式一:JWT Bearer Token
curl -H "Authorization: Bearer <token>" http://localhost:8080/api/strategy

# 方式二:API Key
curl -H "X-API-Key: <key>" http://localhost:8080/api/strategy

响应格式

所有 API 返回统一的 JSON 格式:

{
    "success": true,
    "data": { ... },
    "message": "操作成功"
}

错误响应:

{
    "success": false,
    "message": "错误描述",
    "error": "详细错误信息"
}

前端页面

技术栈

  • Vue 3 + Composition API
  • Vite 构建工具
  • Pinia 状态管理
  • Element Plus UI 组件库
  • Lightweight Charts K 线图表库

主要页面

路径 组件 说明
/ Dashboard.vue 仪表盘首页
/trading Trading.vue 交易主页面
/strategies Strategies.vue 策略管理
/backtest BacktestAnalysis.vue 回测分析
/market MarketQuotes.vue 行情看板
/login Login.vue 登录
/admin AdminDashboard.vue 管理后台

开发指南

本地开发环境搭建

# 克隆代码
git clone <repo>
cd KHY-Quant

# 后端
cd backend
npm install
cp .env.example .env    # 或让系统自动生成
npm run dev             # 启动开发服务器 (nodemon 热重载)

# 前端(另一个终端)
cd frontend
npm install
npm run dev             # 启动 Vite 开发服务器

添加新的 CLI 命令

  1. router.jsCOMMANDS 数组中添加命令名
  2. handlers/ 中创建处理函数
  3. router.jsswitch 中添加路由
  4. (可选)在 aliases.js 中添加中文/拼音别名

添加新的 AI 适配器

  1. gateway/adapters/ 中创建新文件(参考 ollamaAdapter.js
  2. 实现标准接口:detect(), generate(), getStatus()
  3. aiGateway.js 中注册适配器
  4. 设置优先级

添加新的 REST API

  1. routes/ 中创建路由文件
  2. server.js 中挂载路由
  3. 使用 middleware/auth.js 保护端点

常见问题

安装后提示找不到 Node.js?
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo bash -
sudo apt install -y nodejs

# macOS
brew install node

# Windows
winget install OpenJS.NodeJS.LTS
npm install 失败怎么办?
# 使用淘宝镜像
npm config set registry https://registry.npmmirror.com
cd backend && npm install
如何配置 AI?
khy gateway config     # 交互式配置 API Key
khy gateway status     # 查看各通道状态
khy gateway model      # 选择模型

无 API Key 也可使用:安装 Ollama 后拉取模型 ollama pull qwen2.5:7b

代码结构太复杂,从哪里开始看?

建议顺序:

  1. khy_quant/cli.py → 理解 Python 如何启动 Node.js
  2. backend/src/cli/repl.js → 理解交互式终端
  3. backend/src/cli/router.js → 理解命令路由
  4. backend/src/services/gateway/aiGateway.js → 理解 AI 网关

每个文件都有详细的中文注释,跟着注释读即可。


许可证

本项目基于 MIT License 开源。


Made with ❤️ by KHY-Quant Team | khyquant.top

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

khy_quant-1.0.3.tar.gz (1.8 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

khy_quant-1.0.3-py3-none-any.whl (2.0 MB view details)

Uploaded Python 3

File details

Details for the file khy_quant-1.0.3.tar.gz.

File metadata

  • Download URL: khy_quant-1.0.3.tar.gz
  • Upload date:
  • Size: 1.8 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for khy_quant-1.0.3.tar.gz
Algorithm Hash digest
SHA256 76b40d51c8c893661dee75d04ac4261c48b72503432a4440514435601ae384a1
MD5 bd461880b15f49e34a8ccb35968078b9
BLAKE2b-256 8c71f521fd53bc0fff4c67e5bb115de0562d5246f0a9e0d98bcc8d3fc1edea59

See more details on using hashes here.

File details

Details for the file khy_quant-1.0.3-py3-none-any.whl.

File metadata

  • Download URL: khy_quant-1.0.3-py3-none-any.whl
  • Upload date:
  • Size: 2.0 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for khy_quant-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 5ff2db3236b123fcbcc6d0dd6e3ecfea72ef5051ef86e4e54afaa15146d27be1
MD5 0a45014f1ad0f3b4721120c825d74410
BLAKE2b-256 7ecbe407cb05c530040f6de18bea45da91f5249e0e28dfc461d9ae97b82dfe83

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page