{"skill":{"slug":"a-share-real-time-data","displayName":"A股实时行情数据","summary":"Fetch China A-share stock market data (bars, realtime quotes, tick-by-tick transactions) via mootdx/TDX protocol. Use when working with Chinese stock data, mootdx library, TDX quotes, intraday minute bars, transaction history, or real-time A-share market data.","description":"---\nname: mootdx-china-stock-data\ndescription: Fetch China A-share stock market data (bars, realtime quotes, tick-by-tick transactions) via mootdx/TDX protocol. Use when working with Chinese stock data, mootdx library, TDX quotes, intraday minute bars, transaction history, or real-time A-share market data.\n---\n\n# Mootdx China A-Share Stock Data Client\n\nA wrapper around the `mootdx` library (TDX protocol) for fetching China A-share market data including K-line bars, real-time quotes, and tick-by-tick transaction records.\n\n## Installation\n\n```bash\npip install mootdx\n```\n\n> `mootdx` depends on `tdxpy` internally. Both are installed together.\n\n### Verify & Demo\n\n```bash\npython scripts/setup_and_verify.py           # Install + verify + connectivity test\npython scripts/setup_and_verify.py --check   # Verify only (skip install)\npython scripts/setup_and_verify.py --demo    # Full API demo with real output\n```\n\nThe `--demo` mode exercises every major API and prints real data — useful as a runnable reference for correct calling patterns.\n\n## Critical: Time & Timezone Considerations\n\n### Trading Hours (Beijing Time, UTC+8)\n\n| Session | Time |\n|---------|------|\n| Morning | 09:30 - 11:30 (120 min) |\n| Lunch break | 11:30 - 13:00 |\n| Afternoon | 13:00 - 15:00 (120 min) |\n| **Total** | **240 trading minutes/day** |\n\n### Trading Time Bypass Patch\n\n**Problem**: `mootdx` / `tdxpy` has a built-in `time_frame()` check that blocks API calls outside trading hours. On servers with non-Beijing timezone, this breaks even during valid trading hours.\n\n**Solution**: Monkey-patch `tdxpy.hq.time_frame` to always return `True`:\n\n```python\nimport tdxpy.hq\ntdxpy.hq.time_frame = lambda: True\n```\n\nThis patch is applied automatically during `MootdxClient.__init__()`. Without it, `transactions()` and `transaction()` calls will silently return empty results outside detected trading hours.\n\n### Trading Calendar\n\nWhen querying historical data, always check if a date is a trading day. Non-trading days (weekends, holidays) have no data. The client uses `TradingCalendarStrategy.is_trading_day(date_str)` for this — you must have a trading calendar service available.\n\n### Date/Time Parameter Formats\n\n| Parameter | Format | Example |\n|-----------|--------|---------|\n| `date` | `YYYYMMDD` | `\"20250210\"` |\n| `time` | `HH:MM:SS` or `HH:MM` | `\"10:30:00\"` or `\"10:30\"` |\n\n## Stock Code Format\n\nmootdx uses **pure numeric codes** (TDX format). Convert from standard format:\n\n| Standard Format | TDX Format | Market |\n|----------------|------------|--------|\n| `000001.SZ` | `000001` | Shenzhen |\n| `600300.SH` | `600300` | Shanghai |\n| `300750.SZ` | `300750` | Shenzhen (ChiNext) |\n| `688001.SH` | `688001` | Shanghai (STAR) |\n\n**Conversion**: Strip the `.SH` / `.SZ` / `.BJ` suffix.\n\n> **Important**: mootdx does NOT support Beijing Stock Exchange (`.BJ`) stocks. Filter them out before calling.\n\n## API Reference\n\n### 1. Initialize Client\n\n```python\nfrom mootdx.quotes import Quotes\nclient = Quotes.factory(market='std')\n```\n\n### 2. `get_bars()` — K-Line / Candlestick Data\n\nFetch historical or real-time K-line bars.\n\n```python\nawait client.get_bars(\n    stock_code=\"000001.SZ\",   # Standard format (auto-converted)\n    frequency=7,               # K-line period (see table below)\n    offset=240,                # Number of bars to fetch\n    date=\"20250210\",           # Optional: specific date (YYYYMMDD)\n    time=\"10:30:00\",           # Optional: specific time (HH:MM:SS)\n    filter_by_time=True        # Filter to closest bar matching time\n)\n```\n\n**Frequency codes:**\n\n| Code | Period |\n|------|--------|\n| 7 | 1-minute bars |\n| 8 | 1-minute bars (alternative) |\n| 4 | Daily bars |\n| 9 | Daily bars (alternative) |\n\n**Return format** (list of dicts):\n\n```python\n{\n    \"stock_code\": \"000001.SZ\",\n    \"datetime\": \"2025-02-10 10:30:00\",\n    \"open\": 12.50,\n    \"high\": 12.65,\n    \"low\": 12.45,\n    \"close\": 12.60,\n    \"vol\": 150000.0,\n    \"amount\": 1890000.0\n}\n```\n\n**Start position calculation**: For historical dates, the `start` parameter is calculated as the number of trading minutes (for 1-min bars) or trading days (for daily bars) between now and the target datetime. This accounts for:\n- Whether today is a trading day\n- Current trading session status (pre-market / in-session / post-market)\n- Lunch break gap (11:30-13:00)\n\n### 3. `get_realtime_quote()` — Single Stock Real-Time Quote\n\n```python\nawait client.get_realtime_quote(stock_code=\"000001.SZ\")\n```\n\n**Returns** (dict): Price, OHLC, volume, amount, and full Level-2 order book (5-level bid/ask):\n\n```python\n{\n    \"stock_code\": \"000001.SZ\",\n    \"price\": 12.60,\n    \"last_close\": 12.50,\n    \"open\": 12.45, \"high\": 12.65, \"low\": 12.40,\n    \"volume\": 5000000, \"amount\": 63000000,\n    \"bid1\": 12.59, \"bid2\": 12.58, ..., \"bid5\": 12.55,\n    \"ask1\": 12.60, \"ask2\": 12.61, ..., \"ask5\": 12.65,\n    \"bid_vol1\": 500, ..., \"ask_vol5\": 300,\n    \"pct_chg\": 0.8\n}\n```\n\n### 4. `get_realtime_quotes()` — Batch Real-Time Quotes\n\nNative batch interface — much faster than looping `get_realtime_quote()`.\n\n```python\nawait client.get_realtime_quotes([\"000001.SZ\", \"600300.SH\", \"300750.SZ\"])\n```\n\n**Returns** (list of dicts):\n\n```python\n{\n    \"stock_code\": \"000001.SZ\",\n    \"trade_date\": \"2025-02-10\",\n    \"open\": 12.45, \"high\": 12.65, \"low\": 12.40, \"close\": 12.60,\n    \"pre_close\": 12.50,\n    \"change\": 0.15,\n    \"pct_chg\": 1.2048,\n    \"vol\": 5000000.0,\n    \"amount\": 63000000.0,\n    \"is_realtime\": true\n}\n```\n\n> `pct_chg` is calculated from **today's open price**, not previous close.\n\n### 5. `get_batch_bars()` — Batch K-Line Data\n\nParallel fetch K-line bars for multiple stocks with concurrency control.\n\n```python\nawait client.get_batch_bars(\n    stock_codes=[\"000001.SZ\", \"600300.SH\"],\n    date=\"20250210\",\n    time=\"10:30:00\",\n    max_concurrent=10\n)\n```\n\n**Returns**: `Dict[str, List[Dict]]` — `{stock_code: [bar_data, ...]}`\n\n### 6. `get_transactions_history()` — Historical Tick Data\n\nTick-by-tick transaction records for a specific historical date.\n\n```python\nawait client.get_transactions_history(\n    stock_code=\"000001.SZ\",\n    date=\"20250210\",         # Required: YYYYMMDD\n    start=0,\n    offset=1000\n)\n```\n\n**Returns** (list of dicts):\n\n```python\n{\n    \"stock_code\": \"000001.SZ\",\n    \"time\": \"09:30:05\",\n    \"price\": 12.50,\n    \"vol\": 100,\n    \"buyorsell\": 0,          # 0=buy, 1=sell, 2=neutral\n    \"num\": 5,                # Number of trades in this tick\n    \"volume\": 100\n}\n```\n\n### 7. `get_transactions_realtime()` — Real-Time Tick Data\n\nToday's live tick-by-tick transaction stream.\n\n```python\nawait client.get_transactions_realtime(\n    stock_code=\"000001.SZ\",\n    start=0,\n    offset=1000\n)\n```\n\nSame return format as `get_transactions_history()`.\n\n### 8. `get_transactions_with_fallback()` — Tick Data with Fallback\n\nTries real-time first, falls back to today's historical data if empty.\n\n```python\nawait client.get_transactions_with_fallback(\n    stock_code=\"000001.SZ\",\n    start=0, offset=1000,\n    use_history_fallback=True\n)\n```\n\n## Raw mootdx API (Low-Level)\n\nIf using `mootdx` directly without the wrapper:\n\n```python\nfrom mootdx.quotes import Quotes\n\nclient = Quotes.factory(market='std')\n\n# K-line bars\ndf = client.bars(symbol=\"000001\", frequency=7, start=0, offset=240)\n\n# Real-time quotes (supports list of symbols for batch)\ndf = client.quotes(symbol=\"000001\")\ndf = client.quotes(symbol=[\"000001\", \"600300\"])\n\n# Historical transactions\ndf = client.transactions(symbol=\"000001\", start=0, offset=1000, date=\"20250210\")\n\n# Real-time transactions\ndf = client.transaction(symbol=\"000001\", start=0, offset=1000)\n```\n\n> All raw APIs return **pandas DataFrames**.\n\n## Common Pitfalls\n\n1. **Empty results outside trading hours**: Apply the `time_frame` patch (see above)\n2. **Beijing Exchange stocks**: `.BJ` codes are NOT supported — always filter them out\n3. **Rate limiting**: Default rate limit is 0.005s between calls; adjust if connection drops\n4. **Weekend/holiday queries**: Always validate against trading calendar before querying\n5. **1-min bar offset calculation**: Must account for 240 trading minutes/day with lunch gap\n\n## Additional Resources\n\n- For detailed method signatures and time calculation logic, see [api-reference.md](api-reference.md)\n","topics":["Stock Market"],"tags":{"latest":"1.0.0"},"stats":{"comments":0,"downloads":3892,"installsAllTime":132,"installsCurrent":34,"stars":2,"versions":1},"createdAt":1770645859434,"updatedAt":1778486231449},"latestVersion":{"version":"1.0.0","createdAt":1770645859434,"changelog":"Initial release of mootdx-china-stock-data skill.\n\n- Fetch China A-share stock market data including K-line bars, real-time quotes, and tick-by-tick transactions via mootdx/TDX protocol.\n- Provides both single and batch APIs for quotes and candlestick bars.\n- Includes trading hour handling, stock code conversion, and trading calendar integration.\n- Automatic patch to bypass mootdx/tdxpy trading-hour restrictions on non-Beijing servers.\n- Full API guides and code samples included for quick integration.\n- Excludes support for Beijing Stock Exchange (.BJ) codes.","license":null},"metadata":null,"owner":{"handle":"wangdinglu","userId":"s17cmvntwhd2p8p4fkcft0gq1d8857nr","displayName":"taktiko","image":"https://avatars.githubusercontent.com/u/27430103?v=4"},"moderation":null}