Skip to main content
Glama

Echolon

PyPI Python License Status By DolphinQuant

📖 English · 简体中文

一个原生支持 LLM 智能体的期货研究回测框架。 提供 MCP 服务器、22 个内置技能、32 个编目错误代码以及类型化的 Pydantic 配置——智能体调用结构化工具,而不是从文档中猜测 API 形状。支持上期所(SHFE)日线期货的端到端回测。

这是 Qorka(DolphinQuant 的 AI 原生策略生成产品)的核心生产引擎。每个交易日都在上期所进行实盘验证。

快速入门

三个命令涵盖了新手的自然学习路径:

命令

用途

时间

echolon hello

快速演示。通过 akshare 下载上期所铝(过去 2 年)数据,搭建策略脚手架,运行回测。需要网络。

~30秒

echolon init <workspace> --market SHFE --instrument <i> --start <d> --end <d> --template <t>

启动真实项目。通过 akshare 下载市场数据(免费,无需注册),从模板搭建策略脚手架,写入工作区标记。

~1–5 分钟

echolon backtest single <strategy_dir> [--json]

编辑后迭代。向上遍历以从工作区标记恢复上下文,重新计算指标,运行回测。无需标志。

~5–10秒

pip install echolon
mkdir -p ~/echolon-playground && cd ~/echolon-playground
echolon hello                  # 30-second demo

echolon hello 会下载约 2 年的铝数据,搭建 momentum_breakout 模板,写入 .echolon-workspace.json,并运行回测。打开 ./echolon-hello/strategy/baseline/entry.py,调整参数,然后使用 echolon backtest single ./echolon-hello/strategy/baseline/ 重新运行,查看夏普比率的变化。

包内附带三个模板 — minimal、momentum_breakout、rsi_mean_reversion。echolon examples --list 可以查看它们;将 --template <name> 传递给 echolon init / echolon hello 即可从选定模板开始。

如果 pip install 在 Linux ARM64 / Alpine / FreeBSD 上失败,请运行 echolon doctor — 它会诊断 ta-lib 的 C 库,这是唯一可能需要在非标准预构建轮子平台(Linux x86_64, macOS x86_64+arm64, Windows x86_64; Python 3.11–3.12)上从源码构建的依赖项。

Related MCP server: BotSpot

从你的智能体驱动它

pip install echolon                                # 1. install
claude mcp add -s user echolon -- echolon-mcp      # 2. register MCP server (user-wide)
# 3. restart Claude Code to load mcp__echolon__* tools

然后询问:

“在铜上建立一个趋势跟踪策略,回测 2018–2024 年。”

在后台,智能体会调用 list_skills → 选择 patterns 和 quick_start → load_template("momentum_breakout") → list_indicators(has_lookback=True) → 编辑 entry.py 和 exit.py → 循环执行 validate_strategy_full(strategy_dir) 直到全部通过 → 运行回测。如果出现任何错误,它会从回溯信息中解析 [CODE-NNN] 并调用 get_error_doc(code)。它完全不需要猜测。

运行时

设置

Claude Code

claude mcp add -s user echolon -- echolon-mcp

Cursor

在 ~/.cursor/mcp.json 的 mcpServers 下添加条目:"echolon": {"command": "echolon-mcp", "args": []}

OpenAI Codex CLI

codex mcp add echolon -- echolon-mcp (将 [mcp_servers.echolon] 写入 ~/.codex/config.toml)

OpenAI Agents SDK (Python)

MCPServerStdio(name="echolon", params={"command": "echolon-mcp", "args": []})

LangChain / LangGraph

langchain-mcp-adapters: MultiServerMCPClient({"echolon": {"transport": "stdio", "command": "echolon-mcp", "args": []}})

任何其他 MCP 兼容 客户端 (CrewAI, AutoGen, …)

将其配置为 stdio 服务器,command="echolon-mcp",无参数。查看客户端的 MCP 文档了解调用格式。

对于 Claude Code:-s user 使注册应用于你所有的项目(仅限当前项目可去掉此参数);-- 将注册名称与启动命令分开。运行一次后,claude mcp list 应显示 echolon 为已连接的 stdio 服务器。智能体的指南是 llms.txt — 它也会由 echolon init / hello 放置在工作区根目录,以便进入项目的智能体无需包即可找到它。

当前范围

已完成端到端(生产级,每日运行):

  • 上期所日线期货研究 — 数据摄取、214 个指标目录、Backtrader 执行、Optuna TPE 优化(单目标 + 多目标)、具备部署就绪评分的向前行走分析、基于 KMeans 的稳健试验选择。

  • 智能体界面 — 23 个 MCP 工具,22 个技能,32 个错误代码,3 个工作模板。

尚未完成(如果你想推动某部分进展,请提交 issue):

  • 上期所日内回测 — 数据流水线已就绪,引擎管道正在加固中。

  • 通过 MiniQMT 进行实盘交易 — 干净的公开版本正在制作中。

  • 加密货币永续合约(CCXT 适配器已搭建)、CME 期货、股票。

  • Optuna 替代方案(无网格、无随机、无贝叶斯预算搜索)、分布式编排、Python ≤ 3.10。

  • 1.0 之前 — 公共 API 可能在次要版本之间发生变化。重大变更记录在 CHANGELOG.md 中。

使用你自己的数据

如果你已经有原始的上期所 XLS 文件(从 shfe.com.cn 下载),请直接运行 SHFEFileDayExtractor 而不是使用 akshare。对于其他格式(券商 CSV、tushare、自定义数据库),必须在 {workspace}/workspace/data/market_data/SHFE/{instrument}/ 下准备三个文件:

文件

模式

sort_by_contract/{contract}.csv

contract, date, prev_close, prev_settlement, open, high, low, close, settlement, price_change, settlement_change, volume, turnover, open_interest

sort_by_date.csv

相同的列,所有行连接并按日期排序。

trading_calendar.csv

date, is_trading_day (布尔值)。

此外,在 {workspace}/data/SHFE/{instrument_code}/ 下(注意短代码,例如 al 而不是 aluminum):

文件

模式

main_contract.csv

date, main_contract,其中 main_contract 是带有 .SF 后缀的合约代码(例如 al2401.SF)。每个主力合约变更日期一行。

Echolon 不会从原始 OHLCV 自动推导 main_contract.csv — 这是用户输入,编码了你的展期惯例(基于成交量、持仓量或到期天数的规则)。对于通过 akshare 获取的上期所数据,echolon init 会为你推导;否则请自行生成并放入指定位置。

项目信息

Apache 2.0 — 见 LICENSE。可自由用于商业或其他用途。活跃开发中,v0.1.2 beta。由 DolphinQuant 构建和维护 — 同一团队在上期所运行 Qorka。欢迎在 github.com/dolphinquant/echolon 提交问题和拉取请求。

@software{echolon,
  title = {Echolon: AI-native quantitative trading engine},
  author = {DolphinQuant},
  year = {2026},
  url = {https://github.com/dolphinquant/echolon},
}

Available Tools

23 tools
describe_component_apiA

Return the live BaseComponent + IMarketData API surface.

    Use this BEFORE writing any component code. The return value is
    produced via ``inspect.signature()`` on the actual classes, so it
    always reflects the current echolon version — there is no skill /
    doc drift. If a method appears here, it exists; if it doesn't, it
    doesn't. Pip-install or editable-install, same answer.

    Returns a dict with shape::

        {
          "BaseComponent": {
            "override_methods": [{"name": ..., "signature": ..., "doc": ...}, ...],
            "helper_methods":   [{...}, ...],
            "properties":       [{"name": ..., "doc": ...}, ...],
          },
          "IMarketData": {
            "methods": [{"name": ..., "signature": ..., "doc": ...}, ...],
          },
        }

    ``override_methods`` are the four BaseComponent stubs each component
    file must override (``generate_signal`` / ``should_exit`` /
    ``can_trade`` / ``calculate_size``). ``helper_methods`` are concrete
    helpers strategies may call (``get_current_bar``, ``get_indicator``,
    ``log_*_output``, etc.). ``properties`` are read-only attribute
    accessors (``self.market_data``, ``self.portfolio``, ``self.params``).

    ``signature`` is the formatted ``inspect.Signature`` (e.g.
    ``"(self, name: str, index: int = 0) -> float"``). ``doc`` is the
    first line of the docstring; full docstrings live on the source.
    

Inputs: no named parameters.

generate_strategy_paramsA

Generate strategy_params.py from params_to_optimize.json.

    Deterministic code generation: parses the JSON → determines parameter
    ownership across components → emits ComponentParameterTemplate classes
    + framework registration + optuna_search_space with crossover
    constraints → writes the target file. Period parameters that exceed
    the frequency-appropriate indicator cap are auto-clamped and reported.

    Args:
        params_file_path: Absolute path to ``params_to_optimize.json``.
        output_path: Absolute path to write ``strategy_params.py``.
        frequency: ``"interday"`` (caps: TEMA≤62, ADX≤93, default≤180)
            or ``"intraday"`` (caps: TEMA≤500, ADX≤750, default≤1000).

    Returns ``{"success": bool, "output_path": str, "corrections":
    [{"param", "type", "old_*", "new_*", "cap", "category", "changes"?}],
    "message": str}``. Parse / IO failures surface as
    ``success=False`` rather than raising.
    

Inputs: params_file_path (required), output_path (required), frequency.

get_docA

Read any markdown file under echolon/native/ and return its body.

    Generic fallback for content not covered by the dedicated tools
    (``get_pattern``, ``get_skill``, ``get_error_doc``, ``load_template``).
    Useful for skill-cross-reference resolution and supplementary files
    (``echolon/native/skills/SKILLS.md``,
    ``echolon/native/errors/codes/README.md``, template READMEs).

    Args:
        path: Relative path under ``echolon/native/`` (e.g.
            ``"skills/SKILLS.md"``, ``"errors/codes/README.md"``,
            ``"templates/minimal/README.md"``). Absolute paths and
            paths escaping the package root are refused with
            ``error="path_outside_native"``.

    Returns ``{path, body}`` on success, or
    ``{error, message, path}`` on failure (path-traversal attempt,
    file not found, not a markdown file).
    

Inputs: path (required). Returns: result

get_error_docA

Fetch the structured error documentation for a given error code.

    ``what`` and ``why`` come from the in-memory registry
    (``echolon.errors.ERROR_CATALOG``); the long-form sections (``fix``,
    ``example``, ``common_causes``, ``related``) come from the per-code
    markdown at ``echolon/native/errors/codes/{code}.md``. The full
    markdown body is also returned as ``long_form_markdown`` so an
    agent can consume the prose verbatim if the parsed sections are
    empty (parser-resilience fallback).

    Args:
        code: Error code like 'VAL-001' or 'IND-003'.
    

Inputs: code (required).

get_patternB

Return a pattern's structured content, or None if unknown.

Inputs: name (required). Returns: result

get_skillA

Return one skill's body, or None if unknown.

    Returns ``{name, description, body, body_no_frontmatter}``.
    ``body`` is the full file (including YAML frontmatter); use
    ``body_no_frontmatter`` for the prose alone.
    

Inputs: name (required). Returns: result

indicator_infoB

Return structured info for one indicator, or None if unknown.

    Keys: ``name``, ``has_lookback``, ``function``, ``file``, ``params``
    (list of ``{name, default, type}`` dicts). Column names emitted at
    runtime by ``processor._build_suffix`` (handles multi-param sweeps).
    

Inputs: name (required). Returns: result

indicator_paramsA

Return the tunable parameters for an indicator, or None if unknown.

    Convenience accessor — same as ``indicator_info(name)["params"]`` but
    skips the wrapper dict. Each entry is ``{"name": str, "default": any, "type": str}``.
    

Inputs: name (required). Returns: result

list_indicatorsA

Return all indicator names in the echolon catalog, optionally filtered by lookback semantics.

    Args:
        has_lookback: Optional filter.
            ``True`` → only indicators with a period-like parameter
            (e.g. RSI, ATR — sweepable single-dim lookback).
            ``False`` → only indicators without a period parameter
            (no-param indicators like OBV, multi-param scalar indicators
            like BBANDS, special-config indicators).
            Omit for all.
    

Inputs: has_lookback. Returns: result

list_patternsA

Return all canonical pattern names.

Inputs: no named parameters. Returns: result

list_skillsA

Return all in-package skills as [{name, description}].

    Each skill is one ``SKILL.md`` packet under
    ``echolon/native/skills/echolon_api/<name>/``. Description comes
    from the YAML frontmatter ``description:`` field. Use this as a
    directory of "what doctrine is available" before calling
    ``get_skill(name)`` for the body.
    

Inputs: no named parameters. Returns: result

list_templatesA

Return all shipped strategy template names.

Inputs: no named parameters. Returns: result

load_templateC

Load a template's files. Returns {'name': ..., 'files': {filename: content}}.

Inputs: name (required). Returns: result

scaffold_componentA

Write a framework-correct scaffold for a strategy component file.

    Produces a minimal stub that matches echolon's loader contract —
    class name + method signature + return schema — but contains no
    trading logic. Coding agents refine the stub into real pathways.

    Args:
        kind: One of ``"entry"``, ``"exit"``, ``"risk"``, ``"sizer"``, ``"strategy"``.
        strategy_dir: Absolute path to the directory where the file is written.
        force: If True, overwrite an existing file. If False (default), refuse
            and return ``success=False`` with ``error="file_exists"``.

    Returns:
        {
            "success": bool,
            "output_path": str (path to the scaffolded file, if success),
            "kind": str (echoes the input),
            "error": str | None (one of: "unknown_kind", "file_exists", None),
            "message": str (human-readable summary),
        }
    

Inputs: kind (required), strategy_dir (required), force.

suggest_similarA

Return up to limit catalog names close to name (difflib + substring).

Inputs: name (required), limit. Returns: result

validate_component_integrationA

Import each component module via StrategyLoader and check its method arity + strategy_params.DEFAULT_PARAMS top-level shape.

    - STR-002: module fails to import (= guaranteed runtime failure).
    - PRM-002: DEFAULT_PARAMS missing a required top-level key, or a
      value isn't a dict.
    - VAL-005: method's required-positional arity (after ``self``)
      doesn't match the protocol. Arg NAMES are not checked — the
      framework calls positionally, so names are the author's choice.

    Returns ``{"any_errors": bool, "findings": [...]}``.
    

Inputs: strategy_dir (required).

validate_component_loggingB

AST-check that each component's required method calls the matching self.log_<component>_output(...) with a BaseModel instance (not a dict, not a wrong schema).

    Also flags ``self.params.get(...)`` anywhere in the file (PRM-004 —
    defensive dict-access antipattern on the params container).

    Returns ``{"any_errors": bool, "findings": [...]}``.
    

Inputs: strategy_dir (required).

validate_component_protocol_signaturesA

AST-check that each required component class has the required method with a matching return-type annotation (if annotated at all).

    - STR-003: class is missing the required method.
    - VAL-006: method declares a return annotation but it doesn't match
      the expected BaseModel (EntrySignalOutput / ExitSignalOutput / ...).

    Missing annotations are NOT flagged (policy vs correctness — missing
    annotation is a stylistic choice, Pydantic catches runtime
    mismatches). Missing files are silently skipped (preflight STR-001
    territory).

    Returns ``{"any_errors": bool, "findings": [...]}``.
    

Inputs: strategy_dir (required).

validate_debug_completionA

Validate post-run debug artifacts landed on disk with the right shape.

    Three deterministic checks:
    - STR-001: ``selected_robust_trial.json`` + log file both exist.
    - VAL-003: artifact JSON parses and carries every required top-level key.
    - BT-010: log contains each required marker substring (order irrelevant).

    Args:
        artifact_path: Absolute path to the JSON artifact (typically
            ``<workspace>/backtest/selected_robust_trial.json``).
        log_path: Absolute path to the debug log file.
        required_json_keys: Top-level keys expected on the artifact.
            Defaults to ``["trial_number", "params", "metrics"]``.
        required_log_markers: Substrings expected in the log. Defaults
            to ``["STAGE 4 COMPLETE", "STAGE 5 COMPLETE", "FINAL SUCCESS"]``.

    Returns ``{"any_errors": bool, "findings": [{"code", "message",
    "context"}, ...]}``. Never raises — parse / file-access failures
    surface as findings with the appropriate error code.
    

Inputs: artifact_path (required), log_path (required), required_json_keys, required_log_markers.

validate_indicator_listA

Validate a flat-dict strategy_indicator_list.json payload against the catalog.

    Args:
        payload_json: JSON string of the flat-dict
            (e.g. ``'{"rsi": {"timeperiod": [10, 20]}}'``).

    Returns a dict ``{"valid": bool, "errors": [{code, field, message, suggestion}]}``.
    Bad JSON surfaces as a structured error, not a raise.
    

Inputs: payload_json (required).

validate_parameter_accessA

AST-check for hardcoded threshold literals (PRM-003) and defensive self.params.get() calls (PRM-004) across the 4 component files.

    Highest FP-risk of the B1 validators — PRM-003 findings include
    ``context["severity"] = "warning"`` so callers can treat them as
    non-blocking while the allowlist is tuned. PRM-004 findings are
    always bugs (framework contract violation).

    Allowlist covers: range() args, index slicing, keyword args, default
    args, None comparisons, small integer constants ``{-1, 0, 1, -1.0, 0.0, 1.0}``,
    and string-literal comparisons (framework-defined regime / signal enums).

    Returns ``{"any_errors": bool, "findings": [...]}``.
    

Inputs: strategy_dir (required).

validate_strategyB

Validate a strategy directory against echolon contracts.

    Args:
        path: Absolute path to the strategy directory.

    Returns a dict with keys: status ("VALID"|"INVALID"), errors (list of dicts).
    

Inputs: path (required).

validate_strategy_fullA

Run every shipped validator and return merged findings.

    Composes the individual MCP validators (``validate_strategy`` /
    ``validate_component_protocol_signatures`` /
    ``validate_component_integration`` / ``validate_component_logging``
    / ``validate_parameter_access``) so an agent gets a complete
    validation report from a single tool call.

    Args:
        strategy_dir: Absolute path to the strategy directory.

    Returns:
        ``{status, any_errors, total_findings, findings: [{code, ...}],
        invocations: [{validator, count}]}``. ``status`` is ``"VALID"``
        iff no findings were reported by any validator.
    

Inputs: strategy_dir (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 23 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: API introspection, parameter generation, documentation retrieval, catalog listing, scaffolding, and various validation checks. Overlap among validation tools is resolved by specific validation targets (integration, logging, protocol, parameters, etc.).

    Naming Consistency4/5

    Tools follow a mostly consistent verb_noun pattern (e.g., get_doc, list_indicators, validate_strategy). Minor deviations like 'indicator_info' instead of 'get_indicator_info' and 'suggest_similar' instead of 'get_suggestions' are tolerable.

    Tool Count5/5

    23 tools cover a comprehensive set of operations for a strategy framework: API description, parameter generation, documentation, catalog browsing, scaffolding, and multiple validation checks. The count is well-scoped for the domain.

    Completeness4/5

    The tool surface covers key development and validation workflows. Minor gaps exist (e.g., no tool for creating a new strategy directory or running backtests), but the core lifecycle of building and validating components is well-supported.

    Maintenance

    ActivityNo data
    ResponsivenessSyncing

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      D
      maintenance
      An extensible framework that exposes quantitative research functions and financial data connectors, such as FRED, via an MCP server. It enables users to perform complex financial modelling, data retrieval, and autonomous research loops with built-in guardrails and pluggable components.
      6
      4
      MIT
    • F
      license
      Not graded
      quality
      B
      maintenance
      Full-lifecycle algorithmic trading MCP server. AI strategy generation from plain English, backtesting, live bot deployment to 10+ brokers, portfolio monitoring, and prediction markets. Stocks, options, crypto, futures. 32 tools. Free tier.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Local-first backtesting engine with built-in overfitting detection (PBO, deflated Sharpe, bootstrap CI, walk-forward) and a native MCP server for AI agents to validate trading strategies.
      4
      Apache 2.0
    • A
      license
      A
      quality
      B
      maintenance
      MCP server for the FLOX trading framework. About 30 tools to run backtests, scaffold strategies, validate for lookahead bias, compute indicators, place orders, and query PnL from Claude/Cursor.
      38
      945 PyPI
      231
      MIT