eltdx Python API

repository·main·Indexed 42 days ago

https://github.com/electkismet/eltdx

A high-performance Python API driven by a Rust engine for the Tongdaxin (Tdx) market data protocol. It provides comprehensive A-share market data, including real-time quotes, 5-level order books, K-lines, and F10 company information. The library supports modular helpers, raw protocol access (7709/7615), MCP tools, and a cross-language gateway via HTTP/WebSocket for integration with Java, Go, and Node.js.

Tokens
220.9K
Snippets
552
Records
832
Agent score
55%

What's inside eltdx

  1. Overview of eltdx Capabilities

    main

    eltdx is a Rust-driven Python API for the Tongdaxin (Tdx) market data protocol. It provides access to A-share market data including quotes, K-lines, company information (F10), and more.

    Core Abstractions

    • Modular API & Helpers: The preferred way for most users to fetch data (e.g., client.quotes, client.bars, client.helpers).
    • Native Protocol (7709/7615): For protocol research, users can interact directly with raw commands.
    • MCP Tools: Provides market data and F10 capabilities to MCP clients.
    • Cross-language Gateway: Allows non-Python languages (Java, Go, C#, Node.js) to call the service via HTTP JSON or WebSocket RPC.

    Data Categories

    • Market Quotes: Real-time snapshots, depth (5-level), and category-based lists.
    • K-Lines & Intraday: Minute, day, week, month, etc., with support for adjustment factors.
    • Corporate/F10: Company profiles, capital changes, financial basics, and announcements.
    • Specialized Indicators: Auction data, short-line indicators, and real-time rankings.
  2. Overview of available data helpers

    main

    The eltdx library provides several categories of financial data helpers:

    Stocks and Market Data

    • Sector/Plate Data: Sector market trends (板块行情) and constituent stock trends (板块成分股行情).
    • Full Quotes: Complete market quotes and 5-level order book data (完整行情).
    • Stock Lists: Latest stock lists, ST stocks, and suspended stocks.
    • Indicators: Daily share capital, daily limit prices, real-time leaderboards, buying/selling strength, volume comparison, continuous limit-up ladders, and topic strength rankings.
    • Short-term Indicators: Circulating market cap, opening volume ratio, ordinary circulating share capital, order imbalance, and consecutive limit-up days (短线指标).

    Topics and Concepts

    • Stock Concepts: Query which concept sectors a specific stock belongs to (个股概念板块).
    • Sector Constituents: Query which stocks belong to a specific concept sector (概念板块成分股).

    Auction Data

    • Call Auction: Access data related to the collection auction (竞价数据).
  3. Understand the eltdx 3.0 Architecture

    main

    In eltdx 3.0, the core logic has been migrated to Rust for performance and reliability. While the public API, business logic, and CLI remain in Python, the 7709 wire decoding and network runtime are implemented in Rust.

    Key architectural shifts:

    • No Pure Python Fallback: The 7709 protocol implementation is strictly Rust-based. If a compatible Rust-backed wheel is not available, the package will not function.
    • Layered Design: The system is split into the Python Product Layer (public API), a Python Compatibility Facade (for legacy imports), the PyO3 Boundary (for FFI), the Protocol Core (7709 commands/decoding), and the Runtime Core (Engine/Supervisor/Slots).
    • Native Engine: The eltdx._native.NativeEngine handles the heavy lifting, including connection pooling, task scheduling (Slots), and protocol handling via a Tokio runtime.
  4. Identify the authoritative Actor Transport refactor state

    main

    The ACTOR_REFACTOR_RESULT.md serves as the permanent audit and recovery record for the eltdx Actor transport refactor. It tracks the evolution of the refactor through various correction cycles (F00-F10) and identifies the specific, frozen commits that constitute the production-ready runtime and measurement sources.

    Note: The status of the delivery is only considered COMPLETE once the SELF documentation commit passes its own exact CI and Pages gates. Do not rely on source-evidence checks as a substitute for these gates.

  5. Choose between limit_up_down_list and limit_ladder

    main

    Decide which method to use based on your specific requirement:

    RequirementRecommended Method
    Real-time intra-day monitoring (current seals, board height, real-time orders)client.helpers.limit_ladder()
    Querying historical limit up/down details for a specific dateclient.f10.limit_up_down_list()
    Querying a date range and getting statistics per dayclient.f10.limit_up_down_list(start, end)
    Reading market turnover and advancing/declining counts alongside detailsclient.f10.limit_up_down_list(..., include_summary=True)
  6. Understand FinanceRecord fields and unit conversions

    main

    The FinanceRecord object contains both raw data (suffixed with _raw or _raw_float) and derived, human-readable fields.

    Unit Conversions

    To ensure accuracy when working with raw data, note the following unit scales:

    • Share Capital (股本类): Raw values are in 10,000 shares (万股).
      • circulating_shares = liu_tong_gu_ben_raw_float * 10000
      • total_shares = zong_gu_ben_raw_float * 10000
    • Monetary Amounts (金额类): Raw values are in 1,000 CNY (千元).
      • total_assets_yuan = zong_zi_chan_raw_float * 1000
      • net_profit_yuan = jing_li_run_raw_float * 1000
    • Per Share (每股类): Raw values are directly in CNY (元).
    • Dates (日期类): Converted from YYYYMMDD format to date objects.

    Common Derived Fields

    FieldCalculation / Source
    circulating_sharesliu_tong_gu_ben_raw_float * 10000
    total_shareszong_gu_ben_raw_float * 10000
    total_assets_yuanzong_zi_chan_raw_float * 1000
    net_profit_yuanjing_li_run_raw_float * 1000

    Field Filtering Aliases

    You can use Chinese aliases in the fields parameter for local filtering:

    • 流通股本 $\rightarrow$ circulating_shares
    • 总股本 $\rightarrow$ total_shares
    • 总资产 $\rightarrow$ total_assets_yuan
    • 净利润 $\rightarrow$ net_profit_yuan
  7. General conventions for eltdx parameters and fields

    main

    When using eltdx, several naming conventions apply to parameters and returned fields:

    • code: Supports full codes like sz000001, sh600000, or bj920001. In some scenarios, 6-digit codes are supported and the market is inferred automatically.
    • market: Represents the market. Common values are sz, sh, bj, or numeric identifiers 0, 1, 2.
    • include_raw: A boolean flag to preserve the original payload or record hex, useful for packet capture comparison and protocol debugging.
    • refresh: Supported by some Helper methods; used to skip memory caches and force a new request to the server.
    • full_code: A model property equal to exchange + code.
    • *_raw: Refers to the protocol's original value or raw bytes, used for debugging parsing.
    • *_milli: Represents price in milli-units. Typically, price = price_milli / 1000.
    • volume: In transaction details, time-sharing, or K-lines, this is usually understood as 'lots' (手), but check specific model documentation for details.
  8. Understand Native Engine memory management and limits

    main

    The Native Engine implements hierarchical memory budgeting to prevent exhaustion when scaling to many connections:

    1. Slot-level limit: Each individual Slot maintains a local limit of 8 MiB for the decoded queue.
    2. Engine-level budget: To prevent the theoretical total (e.g., 1.28 GiB for 160 slots) from overwhelming the system, the engine maintains global budgets for raw, decoded, and push bytes that scale with the number of Slots.

    Error Handling: If a single Slot exceeds its local limit, the engine performs a retirement of the current generation for that specific Slot rather than failing the entire Engine.

  9. Handle ShortlineIndicator date alignment and errors

    main

    The helper ensures data integrity by aligning the target trading day (from TDX handshake) and the previous trading day (from SSE Index K-lines).

    Alignment Status

    alignment_status indicates how the statistical files relate to the target day:

    • same_day: The file date equals the target trading day. Uses the file's prev_* columns.
    • previous_trading_day: The file date equals the previous trading day. Uses the file's current columns as the target day's 'yesterday' values.

    Errors

    • ShortlineIndicatorsNotReadyError: Thrown if called before 09:25 when real-time auction data is not yet complete.
    • TdxStatsDateError: Thrown if the statistical file date is neither the target trading day nor the previous trading day.

    If a specific stock has a date mismatch, the row will return None for historical denominators and set the alignment_status to indicate the reason, rather than performing an incorrect cross-day calculation.

  10. Understand Actor fatal errors

    main

    In the Actor model, not all errors are considered fatal:

    • Network anomalies are treated as normal state machine events.
    • Unexpected exceptions are caught by the top-level runner, causing the runtime to transition to FAILED.

    When a runtime enters the FAILED state, it fails all active tickets and wakes up waiters/push pollers to release resources. The system does not automatically create a replacement Actor. The recommended pattern for callers is to explicitly close() the failed client and create a new one.

  11. Manage request capacity and timeouts with Admission and Deadlines

    main

    Request capacity is governed by pool_size + max_pending_requests.

    • Admission: Requests enter a FIFO queue. Once a request acquires a 'waiting permit', it is queued. When promoted, it exchanges the permit for a 'Slot lease'.
    • Deadlines: Every request has a single monotonic absolute deadline. This deadline covers the entire lifecycle: queuing, connection, handshake, sending, and a maximum of one safe retry.
    • Retries: Only 21 specific commands (marked as retry-safe in the manifest) can be retried once. Future commands will not be retryable by default. If a retry occurs after a partial send, the library must first complete the retirement of the old generation using the original deadline.