[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77YZ1QF4G3JP923KZQ5QZ3J":3,"skill-same:01M77YZ1QF4G3JP923KZQ5QZ3J":55},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":35,"repositoryHtmlUrl":36,"repositoryHomepageUrl":37,"ownerHtmlUrl":38,"ownerBlogUrl":6,"ownerDescription":39,"updatedAt":40,"install":41,"resources":54},"01M77YZ1QF4G3JP923KZQ5QZ3J","xtdata",null,"XtQuant行情数据模块 - 为QMT\u002FminiQMT提供实时行情、K线、Tick、Level2和财务数据。","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fx\u002Fxtdata\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: xtdata\ndescription: XtQuant行情数据模块 - 为QMT\u002FminiQMT提供实时行情、K线、Tick、Level2和财务数据。\nversion: 1.2.0\nhomepage: http:\u002F\u002Fdict.thinktrader.net\u002FnativeApi\u002Fxtdata.html\nmetadata: {\"clawdbot\":{\"emoji\":\"📡\",\"requires\":{\"bins\":[\"python3\"]}}}\n---\n\n# XtData（XtQuant行情数据模块）\n\n`xtdata` is the market data module of [XtQuant](http:\u002F\u002Fdict.thinktrader.net\u002FnativeApi\u002Fstart_now.html), providing real-time and historical market data through the local miniQMT client.\n\n> ⚠️ **Requires miniQMT running locally**. xtdata communicates with miniQMT via TCP to retrieve data.\n\n## 安装\n\n```bash\npip install xtquant\n```\n\n## 连接\n\n```python\nfrom xtquant import xtdata\n\n# Connect to the local miniQMT market data service\nxtdata.connect()\n```\n\nOptionally specify a data directory:\n\n```python\n# Manually specify the miniQMT data directory path\nxtdata.data_dir = r'D:\\QMT\\userdata_mini'\n```\n\n## API分类\n\nThe xtdata API is divided into three main categories:\n\n- **Subscription** — `subscribe_quote`, `subscribe_whole_quote`: Register real-time data callbacks; data is continuously pushed until unsubscribed\n- **Retrieval** — `get_market_data_ex`, `get_local_data`, `get_full_tick`, `get_financial_data`: Read data from local cache; returns immediately\n- **Download** — `download_history_data`, `download_financial_data`: Download data from the server to local cache; blocks synchronously until complete\n\n> **Key Pattern**: When retrieving historical data, you must first `download` to local cache, then `get` from cache. For real-time data, use `subscribe`.\n\n## 通用类型约定\n\n- **stock_code**: `'SecurityCode.MarketCode'` format, e.g. `'600000.SH'`, `'000001.SZ'`\n- **period**: `'tick'`, `'1m'`, `'5m'`, `'15m'`, `'30m'`, `'1h'`, `'1d'`, `'1w'`, `'1mon'`\n- **start_time \u002F end_time**: `'YYYYMMDDHHmmss'` or `'YYYYMMDD'` format strings\n- **dividend_type**: `'none'` (no adjustment), `'front'` (forward adjustment), `'back'` (backward adjustment), `'front_ratio'` (proportional forward adjustment), `'back_ratio'` (proportional backward adjustment)\n\n## 请求限制\n\n- Historical data download requests are rate-limited; avoid excessive concurrent downloads.\n- Batch queries (multiple stocks) are more efficient than looping one by one; batch mode is recommended.\n- Full-market subscription (`subscribe_whole_quote`) may require Level2 data permissions for some data types.\n\n---\n\n## 下载历史数据\n\nYou must download data before retrieving it locally:\n\n```python\n# Download daily K-line data\nxtdata.download_history_data('000001.SZ', '1d', start_time='20240101', end_time='20240630')\n\n# Download 1-minute K-line data\nxtdata.download_history_data('000001.SZ', '1m', start_time='20240101', end_time='20240630')\n\n# Download Tick data\nxtdata.download_history_data('000001.SZ', 'tick', start_time='20240601', end_time='20240630')\n```\n\n### 下载退市\u002F到期合约数据\n\n```python\n# Use download_history_data2 to download data for delisted or expired contracts\nxtdata.download_history_data2(['IC2312.IF'], '1d', start_time='20230101', end_time='20231231')\n```\n\n## 获取K线数据\n\n```python\n# Retrieve market data (returns a dict of DataFrames keyed by stock code)\ndata = xtdata.get_market_data_ex(\n    [],                    # field_list, empty list means all fields\n    ['000001.SZ'],         # stock_list, list of stock codes\n    period='1d',           # period: tick, 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1mon\n    start_time='20240101',\n    end_time='20240630',\n    count=-1,              # -1 means retrieve all data\n    dividend_type='front',  # adjustment type: none, front, back, front_ratio, back_ratio\n    fill_data=True         # whether to fill suspended trading data\n)\ndf = data['000001.SZ']\n# Returned fields: open, high, low, close, volume, amount, settelementPrice, openInterest, preClose, suspendFlag\n```\n\n### 获取最新交易日K线\n\n```python\n# count=1 retrieves the latest single K-line bar\ndata = xtdata.get_market_data_ex([], ['000001.SZ'], period='1d', count=1)\n```\n\n## 获取本地缓存数据\n\n```python\n# If data is already cached, read directly from local storage (no need to download again)\ndata = xtdata.get_local_data(\n    field_list=[],\n    stock_list=['000001.SZ'],\n    period='1d',\n    start_time='20240101',\n    end_time='20240630'\n)\n```\n\n## 实时行情订阅\n\n### 订阅单只股票\n\n```python\ndef on_data(datas):\n    \"\"\"Quote callback function, receives pushed real-time data\"\"\"\n    for stock_code, data in datas.items():\n        print(stock_code, data)\n\n# subscribe_quote(stock_code, period, start_time, end_time, count, callback)\nxtdata.subscribe_quote('000001.SZ', period='tick', callback=on_data)\nxtdata.run()  # Block the current thread, continuously receiving callback data\n```\n\n### 订阅全市场行情（全推）\n\n```python\n# Subscribe to full-market quote push\nxtdata.subscribe_whole_quote(['SH', 'SZ'], callback=on_data)\n# Market codes: 'SH' (Shanghai), 'SZ' (Shenzhen), 'BJ' (Beijing)\nxtdata.run()\n```\n\n### 取消订阅\n\n```python\n# Unsubscribe using the sequence number returned by subscribe_quote\nseq = xtdata.subscribe_quote('000001.SZ', period='tick', callback=on_data)\nxtdata.unsubscribe_quote(seq)\n```\n\n## 获取全市场快照\n\n```python\n# Retrieve the latest Tick snapshot for the entire market\ndata = xtdata.get_full_tick(['SH', 'SZ'])\n# 收益率 a dict: {stock_code: tick_data, ...}\n```\n\n---\n\n## 财务数据\n\n```python\n# First download financial data to local cache\nxtdata.download_financial_data(['000001.SZ'])\n\n# Then retrieve financial data from local cache\ndata = xtdata.get_financial_data(['000001.SZ'])\n```\n\n### 可用财务报表\n\n| Statement | Description |\n|---|---|\n| `Balance` | Balance Sheet |\n| `Income` | Income Statement |\n| `CashFlow` | Cash Flow Statement |\n| `PershareIndex` | Per-Share Indicators |\n| `CapitalStructure` | Capital Structure |\n| `TOP10HOLDER` | Top 10 Shareholders |\n| `TOP10FLOWHOLDER` | Top 10 Tradable Shareholders |\n| `SHAREHOLDER` | Shareholder Count |\n\n### 资产负债表关键字段\n\n```python\n'cash_equivalents'          # Cash and cash equivalents\n'tradable_fin_assets'       # Trading financial assets\n'account_receivable'        # Accounts receivable\n'inventories'               # Inventories\n'total_current_assets'      # Total current assets\n'fix_assets'                # Fixed assets\n'intang_assets'             # Intangible assets\n'tot_assets'                # 总资产\n'shortterm_loan'            # Short-term borrowings\n'total_current_liability'   # Total current liabilities\n'tot_liab'                  # Total liabilities\n'cap_stk'                   # Paid-in capital (or share capital)\n'undistributed_profit'      # Retained earnings\n'total_equity'              # Total owners' equity\n'tot_liab_shrhldr_eqy'      # Total liabilities and shareholders' equity\n```\n\n### 利润表关键字段\n\n```python\n'revenue'                              # Total operating revenue\n'revenue_inc'                          # Operating revenue\n'total_expense'                        # Operating costs\n'sale_expense'                         # Selling expenses\n'less_gerl_admin_exp'                  # Administrative expenses\n'financial_expense'                    # Financial expenses\n'oper_profit'                          # Operating profit\n'tot_profit'                           # Total profit\n'net_profit_incl_min_int_inc'          # 净利润\n'net_profit_excl_min_int_inc'          # 净利润 attributable to parent company\n's_fa_eps_basic'                       # Basic earnings per share\n's_fa_eps_diluted'                     # Diluted earnings per share\n```\n\n### 现金流量表关键字段\n\n```python\n'goods_sale_and_service_render_cash'   # Cash received from sales of goods and services\n'net_cash_flows_oper_act'              # Net cash flows from operating activities\n'net_cash_flows_inv_act'               # Net cash flows from investing activities\n'net_cash_flows_fnc_act'               # Net cash flows from financing activities\n'net_incr_cash_cash_equ'               # Net increase in cash and cash equivalents\n```\n\n### 每股指标关键字段\n\n```python\n's_fa_eps_basic'                       # Basic earnings per share\n's_fa_bps'                             # Book value per share\n's_fa_ocfps'                           # Operating cash flow per share\n'du_return_on_equity'                  # 净资产收益率（ROE）\n'sales_gross_profit'                   # Gross profit margin\n'inc_revenue_rate'                     # Year-over-year revenue growth rate\n'du_profit_rate'                       # Year-over-year net profit growth rate\n'gear_ratio'                          # Debt-to-asset ratio\n'inventory_turnover'                   # Inventory turnover ratio\n```\n\n### 股本结构字段\n\n```python\n'total_capital'                        # Total share capital\n'circulating_capital'                  # Listed tradable A-shares\n'restrict_circulating_capital'         # Restricted tradable shares\n```\n\n### 前十大股东字段\n\n```python\n'declareDate'     # Announcement date\n'endDate'         # Reporting period end date\n'name'            # Shareholder name\n'quantity'        # Number of shares held\n'ratio'           # Shareholding ratio\n'nature'          # Share type\n'rank'            # Shareholding rank\n```\n\n---\n\n## 除权除息数据\n\n```python\n# Retrieve ex-dividend adjustment factor data\ndata = xtdata.get_divid_factors('000001.SZ')\n# Returned fields: interest (dividend per share), stockBonus (bonus shares per share), stockGift (capitalization shares per share),\n#         allotNum (rights issue shares per share), allotPrice (rights issue price), gugai (share reform flag), dr (ex-dividend factor)\n```\n\n## 合约信息\n\n```python\n# Retrieve detailed instrument information\ninfo = xtdata.get_instrument_detail('000001.SZ')\n# 收益率 a dict containing: InstrumentName (instrument name), ExchangeID (market code), ProductID (product code),\n#   UpStopPrice (upper price limit), DownStopPrice (lower price limit), PreClose (previous close),\n#   FloatVolume (tradable shares), TotalVolume (total shares), PriceTick (minimum price increment),\n#   VolumeMultiple (contract multiplier), CreateDate (creation date), OpenDate (listing date),\n#   ExpireDate (expiration date), MainContract (main contract flag), IsTrading (whether tradable), etc.\n\n# Retrieve security type\nitype = xtdata.get_instrument_type('000001.SZ')  # 收益率 'stock', 'index', 'fund', 'bond', etc.\n\n# Retrieve trading day list\ndays = xtdata.get_trading_dates('SH', start_time='20240101', end_time='20240630')\n\n# Retrieve trading calendar\ncalendar = xtdata.get_trading_calendar('SH')\n\n# Download and retrieve holiday data\nxtdata.download_holiday_data()\nholidays = xtdata.get_holidays()\n```\n\n## 板块管理\n\n```python\n# Retrieve sector list\nsectors = xtdata.get_sector_list()\n\n# Retrieve stock list within a sector\nstocks = xtdata.get_stock_list_in_sector('沪深A股')\n\n# Download sector classification data\nxtdata.download_sector_data()\n\n# Custom sector management\nxtdata.create_sector_folder('', 'MyFolder')          # Create a folder at root level\nxtdata.create_sector('MyFolder', 'MyBlock')           # Create a sector under the folder\nxtdata.add_sector('MyBlock', ['000001.SZ', '600000.SH'])  # Add stocks to the sector\nxtdata.remove_stock_from_sector('MyBlock', ['000001.SZ']) # Remove stocks from the sector\nxtdata.reset_sector('MyBlock', ['600000.SH'])         # Reset sector contents\nxtdata.remove_sector('MyBlock')                       # Delete the sector\n```\n\n## 指数成分股\n\n```python\n# First download index weight data\nxtdata.download_index_weight()\n\n# Retrieve index constituent weights\nweights = xtdata.get_index_weight('000300.SH')\n# 收益率: {stock_code: weight, ...}\n```\n\n## 可转债信息\n\n```python\n# Download and retrieve convertible bond data\nxtdata.download_cb_data()\ndata = xtdata.get_cb_data()\n```\n\n## 新股申购信息\n\n```python\n# Retrieve IPO subscription information\ndata = xtdata.get_ipo_info()\n```\n\n## ETF申赎清单\n\n```python\n# Download and retrieve ETF creation\u002Fredemption information\nxtdata.download_etf_info()\ndata = xtdata.get_etf_info()\n```\n\n## 可用数据周期\n\n`tick`, `1m`, `5m`, `15m`, `30m`, `1h`, `1d`, `1w`, `1mon`\n\n---\n\n## 数据字段参考\n\n### Tick数据字段\n\n```python\n'time'                  # Timestamp\n'lastPrice'             # Latest price\n'open'                  # Opening price\n'high'                  # Highest price\n'low'                   # Lowest price\n'lastClose'             # Previous close price\n'amount'                # Total turnover\n'volume'                # Total volume\n'pvolume'               # Raw total volume\n'stockStatus'           # Security status\n'openInt'               # Open interest\n'lastSettlementPrice'   # Previous settlement price\n'askPrice'              # Ask prices (list, 5 levels)\n'bidPrice'              # Bid prices (list, 5 levels)\n'askVol'                # Ask volumes (list, 5 levels)\n'bidVol'                # Bid volumes (list, 5 levels)\n'transactionNum'        # Number of transactions\n```\n\n### K线数据字段（1m \u002F 5m \u002F 1d等）\n\n```python\n'time'                  # Timestamp\n'open'                  # Opening price\n'high'                  # Highest price\n'low'                   # Lowest price\n'close'                 # Closing price\n'volume'                # Volume\n'amount'                # Turnover\n'settelementPrice'      # Settlement price\n'openInterest'          # Open interest\n'preClose'              # Previous close price\n'suspendFlag'           # Suspension flag: 0 - normal, 1 - suspended, -1 - resumed from today\n```\n\n### 证券状态码\n\n```\n0,10 - Unknown           11 - Pre-open S          12 - Call auction C\n13 - Continuous trading T 14 - Break B             15 - Closed E\n16 - Volatility interrupt V  17 - Temporary halt P  18 - Closing call auction U\n19 - Intraday call auction M  20 - Halted until close N  21 - Field retrieval error\n22 - After-hours fixed price trading  23 - After-hours fixed price trading ended\n```\n\n---\n\n## Level2数据\n\nIf your broker supports Level2 data:\n\n### l2quote — Level2实时行情快照\n\n```python\n'time'                  # Timestamp\n'lastPrice'             # Latest price\n'open' \u002F 'high' \u002F 'low' # Opening \u002F Highest \u002F Lowest price\n'amount' \u002F 'volume'     # Turnover \u002F Volume\n'transactionNum'        # Number of transactions\n'pe'                    # 市盈率\n'askPrice' \u002F 'bidPrice' # Multi-level ask \u002F bid prices\n'askVol' \u002F 'bidVol'     # Multi-level ask \u002F bid volumes\n```\n\n### l2order — Level2逐笔委托\n\n```python\n'time'              # Timestamp\n'price'             # Order price\n'volume'            # Order quantity\n'entrustNo'         # Order number\n'entrustType'       # Order type (0 - unknown, 1 - normal, 2 - fill-or-kill remainder cancel, 4 - best five levels, 5 - fill-or-cancel, 6 - best own side, 7 - best counterparty)\n'entrustDirection'  # Order direction (1 - buy, 2 - sell, 3 - cancel buy (SSE), 4 - cancel sell (SSE))\n```\n\n### l2transaction — Level2逐笔成交\n\n```python\n'time'          # Timestamp\n'price'         # Trade price\n'volume'        # Trade quantity\n'amount'        # Trade amount\n'tradeIndex'    # Trade record number\n'buyNo'         # Buyer order number\n'sellNo'        # Seller order number\n'tradeType'     # Trade type\n'tradeFlag'     # Trade flag (0 - unknown, 1 - active buy, 2 - active sell, 3 - cancellation (SZSE))\n```\n\n### l2quoteaux — 买卖汇总\n\n```python\n'avgBidPrice'           # Average bid price\n'totalBidQuantity'      # Total bid quantity\n'avgOffPrice'           # Average ask price\n'totalOffQuantity'      # Total ask quantity\n'withdrawBidQuantity'   # Total bid cancellation quantity\n'withdrawOffQuantity'   # Total ask cancellation quantity\n```\n\n### l2orderqueue — 最优买卖委托队列\n\n```python\n'bidLevelPrice' \u002F 'offerLevelPrice'    # Bid \u002F Ask price\n'bidLevelVolume' \u002F 'offerLevelVolume'  # Bid \u002F Ask volume\n'bidLevelNumber' \u002F 'offLevelNumber'    # Bid \u002F Ask order count\n```\n\n### l2transactioncount — 逐笔成交统计\n\nIncludes ddx\u002Fddy\u002Fddz indicators, net order\u002Fcancellation volumes, and buy\u002Fsell statistics categorized by order size (extra-large \u002F large \u002F medium \u002F small orders).\n\n### l2thousand — 千档盘口\n\nUp to 1000 levels of bid\u002Fask prices and volumes.\n\n### limitupperformance — 涨停连板数据\n\n```python\n'startUp' \u002F 'endUp'   # Limit-up start \u002F end time\n'breakUp'              # Number of limit-up breaks\n'sealCount'            # Consecutive limit-up days\n'sealVolRatio'         # Seal-to-volume ratio\n'direct'               # Direction: 0 - none, 1 - limit up, 2 - limit down\n```\n\n### snapshotindex — 快照指标\n\n```python\n'volRatio'          # Volume ratio\n'speed1' \u002F 'speed5' # 1-minute \u002F 5-minute price change speed\n'gainRate3\u002F5\u002F10'    # 3\u002F5\u002F10-day price change percentage\n'turnoverRate3\u002F5\u002F10' # 3\u002F5\u002F10-day turnover rate\n```\n\n### announcement — 公告与新闻\n\n```python\n'headline'  # Headline\n'summary'   # Summary\n'content'   # Content\n'type'      # Type: 0 - other, 1 - financial report\n```\n\n### hfiopv — 高频IOPV（100ms推送频率）\n\nETF IOPV data, including dynamic IOPV, limit-up\u002Fdown IOPV, and premium\u002Fdiscount estimates.\n\n### fullspeedorderbook — 全速盘口（20档）\n\n```python\n'bidPrice' \u002F 'askPrice'    # Multi-level bid \u002F ask price list (levels 1-20)\n'bidVolume' \u002F 'askVolume'  # Multi-level bid \u002F ask volume list (levels 1-20)\n```\n\n---\n\n## 合约信息 Fields\n\n```python\n'InstrumentName'        # Instrument name\n'ExchangeID'            # Market code\n'PreClose'              # Previous close price\n'UpStopPrice'           # Daily upper price limit\n'DownStopPrice'         # Daily lower price limit\n'FloatVolume'           # Tradable shares\n'TotalVolume'           # Total shares\n'PriceTick'             # Minimum price increment\n'VolumeMultiple'        # Contract multiplier\n'MainContract'          # Main contract flag (1 - primary, 2 - secondary, 3 - tertiary)\n'OpenDate'              # IPO date \u002F Listing date\n'ExpireDate'            # Delisting date or expiration date\n'IsTrading'             # Whether the instrument is tradable\n'OptExercisePrice'      # Option exercise price \u002F Convertible bond conversion price\n'OptionType'            # Option type (-1 not an option, 0 call, 1 put)\n'MaxLimitOrderVolume'   # Maximum limit order volume\n'MinLimitOrderVolume'   # Minimum limit order volume\n```\n\n## ETF现金替代标志\n\n```\n0 - Cash substitution prohibited (stock required)\n1 - Cash substitution allowed (use stock first, cash for shortfall)\n2 - Cash substitution mandatory\n3 - Non-SSE cash substitution with settlement\n4 - Non-SSE mandatory cash substitution\n```\n\n## 时间戳转换工具\n\n```python\nimport time\n\ndef conv_time(ct):\n    '''Convert millisecond timestamp to string format: conv_time(1476374400000) --> \"20161014000000.000\"'''\n    local_time = time.localtime(ct \u002F 1000)\n    data_head = time.strftime('%Y%m%d%H%M%S', local_time)\n    data_secs = (ct - int(ct)) * 1000\n    return '%s.%03d' % (data_head, data_secs)\n```\n\n## 使用技巧\n\n- Before retrieving data for the first time, always call `xtdata.download_history_data()` to download to local cache.\n- Downloaded data is cached locally — subsequent reads are extremely fast.\n- `xtdata.run()` blocks the current thread — if you need to trade simultaneously, run it in a separate thread.\n- Prefer `get_market_data_ex` (recommended) over `get_local_data` — the former supports more features like dividend adjustment.\n- For delisted\u002Fexpired contract data, use `download_history_data2`.\n- Financial data timestamp notes: `m_anntime` = disclosure date, `m_timetag` = reporting period end date.\n- Documentation: http:\u002F\u002Fdict.thinktrader.net\u002FnativeApi\u002Fxtdata.html\n\n---\n\n## 进阶示例\n\n### 批量下载多只股票历史数据\n\n```python\nfrom xtquant import xtdata\nimport time\n\n# Connect to miniQMT market data service\nxtdata.connect()\n\n# Define the stock list to download (common A-share stocks)\nstock_list = [\n    '600519.SH',  # Kweichow Moutai\n    '000001.SZ',  # Ping An Bank\n    '300750.SZ',  # CATL\n    '601318.SH',  # Ping An Insurance\n    '000858.SZ',  # Wuliangye\n    '600036.SH',  # China Merchants Bank\n    '002594.SZ',  # BYD\n]\n\n# Batch download daily K-line data (forward adjusted)\nfor stock in stock_list:\n    print(f\"Downloading daily K-line data for {stock}...\")\n    xtdata.download_history_data(stock, '1d', start_time='20230101', end_time='20241231')\n    time.sleep(0.5)  # Add delay to avoid triggering rate limits\n\n# Batch retrieve data and merge for analysis\nall_data = {}\nfor stock in stock_list:\n    data = xtdata.get_market_data_ex(\n        [],                     # Empty list means all fields\n        [stock],                # 股票代码 list\n        period='1d',            # Daily K-line\n        start_time='20230101',\n        end_time='20241231',\n        dividend_type='front',  # Forward adjusted\n        fill_data=True          # Fill suspended trading data\n    )\n    df = data[stock]\n    all_data[stock] = df\n    print(f\"{stock} retrieved {len(df)} records\")\n\n# Compare closing price trends across multiple stocks\nimport pandas as pd\nclose_df = pd.DataFrame({stock: all_data[stock]['close'] for stock in stock_list})\nprint(\"Latest closing prices:\")\nprint(close_df.tail(5))\n```\n\n### 实时行情监控 + 条件预警\n\n```python\nfrom xtquant import xtdata\nimport datetime\n\n# Connect to market data service\nxtdata.connect()\n\n# Define watchlist and alert conditions\nwatch_list = ['600519.SH', '000001.SZ', '300750.SZ']\nalert_config = {\n    '600519.SH': {'upper': 1900.0, 'lower': 1700.0},  # Moutai: alert at 1900 or 1700\n    '000001.SZ': {'upper': 15.0, 'lower': 10.0},       # Ping An Bank: alert at 15 or 10\n    '300750.SZ': {'upper': 250.0, 'lower': 180.0},     # CATL: alert at 250 or 180\n}\n\ndef on_realtime_data(datas):\n    \"\"\"Real-time quote callback — checks alert conditions on each push\"\"\"\n    now = datetime.datetime.now().strftime('%H:%M:%S')\n    for stock_code, tick_data in datas.items():\n        # Get latest price\n        last_price = tick_data['lastPrice']\n        pre_close = tick_data['lastClose']\n        # Calculate price change percentage\n        change_pct = (last_price - pre_close) \u002F pre_close * 100 if pre_close > 0 else 0\n\n        print(f\"[{now}] {stock_code}: Latest={last_price:.2f}, Change={change_pct:.2f}%\")\n\n        # Check alert conditions\n        if stock_code in alert_config:\n            config = alert_config[stock_code]\n            if last_price >= config['upper']:\n                print(f\"  ⚠️ Alert: {stock_code} price {last_price:.2f} breached upper limit {config['upper']}\")\n            elif last_price \u003C= config['lower']:\n                print(f\"  ⚠️ Alert: {stock_code} price {last_price:.2f} breached lower limit {config['lower']}\")\n\n# Subscribe to Tick data for multiple stocks\nfor stock in watch_list:\n    xtdata.subscribe_quote(stock, period='tick', callback=on_realtime_data)\n\nprint(\"Real-time monitoring started, press Ctrl+C to exit...\")\nxtdata.run()  # Block main thread, continuously receiving data\n```\n\n### Level2逐笔成交分析（大单跟踪）\n\n```python\nfrom xtquant import xtdata\nimport pandas as pd\n\n# Connect to market data service\nxtdata.connect()\n\nstock = '600519.SH'\n\n# Download Level2 trade-by-trade data (requires L2 data permissions)\nxtdata.download_history_data(stock, 'l2transaction', start_time='20240601', end_time='20240601')\n\n# Retrieve trade-by-trade data\ndata = xtdata.get_market_data_ex([], [stock], period='l2transaction',\n                                  start_time='20240601', end_time='20240601')\ndf = data[stock]\n\nif len(df) > 0:\n    # Convert trade amount to 10-thousands (wan yuan)\n    df['amount_wan'] = df['amount'] \u002F 10000\n\n    # Categorize by trade amount (Extra-large >1M, Large >200K, Medium >50K, Small \u003C50K)\n    df['order_size'] = pd.cut(\n        df['amount_wan'],\n        bins=[0, 5, 20, 100, float('inf')],\n        labels=['小单(\u003C5万)', '中单(5-20万)', '大单(20-100万)', '特大单(>100万)']\n    )\n\n    # Statistics by trade direction and order size\n    # tradeFlag: 1=active buy, 2=active sell\n    buy_stats = df[df['tradeFlag'] == 1].groupby('order_size')['amount_wan'].sum()\n    sell_stats = df[df['tradeFlag'] == 2].groupby('order_size')['amount_wan'].sum()\n\n    print(f\"\\n{stock} Trade-by-Trade Statistics (unit: 10K yuan)\")\n    print(\"=\" * 50)\n    print(\"[Active Buy]\")\n    print(buy_stats)\n    print(\"\\n[Active Sell]\")\n    print(sell_stats)\n    print(f\"\\nNet buy amount: {buy_stats.sum() - sell_stats.sum():.2f} (10K yuan)\")\n```\n\n### 财务数据筛选 — 低估值高成长选股\n\n```python\nfrom xtquant import xtdata\nimport pandas as pd\n\n# Connect to market data service\nxtdata.connect()\n\n# Retrieve A-share stock list\nstock_list = xtdata.get_stock_list_in_sector('沪深A股')\nprint(f\"Total A-shares: {len(stock_list)}\")\n\n# Download financial data\nxtdata.download_financial_data(stock_list)\n\n# Retrieve financial data\nfin_data = xtdata.get_financial_data(stock_list)\n\n# Build screening DataFrame\nresults = []\nfor stock, data_list in fin_data.items():\n    if not data_list:\n        continue\n    # Take the latest financial report\n    latest = data_list[-1] if isinstance(data_list, list) else data_list\n\n    # Extract key indicators\n    try:\n        roe = latest.get('du_return_on_equity', None)          # 净资产收益率（ROE）\n        revenue_growth = latest.get('inc_revenue_rate', None)   # Year-over-year revenue growth\n        profit_growth = latest.get('du_profit_rate', None)      # Year-over-year net profit growth\n        eps = latest.get('s_fa_eps_basic', None)                # Basic earnings per share\n        bps = latest.get('s_fa_bps', None)                      # Book value per share\n        gear = latest.get('gear_ratio', None)                   # Debt-to-asset ratio\n\n        if all(v is not None for v in [roe, revenue_growth, eps, bps]):\n            results.append({\n                '股票代码': stock,\n                'ROE(%)': roe,\n                '营收增长率(%)': revenue_growth,\n                '净利润增长率(%)': profit_growth,\n                '每股收益': eps,\n                '每股净资产': bps,\n                '资产负债率(%)': gear\n            })\n    except:\n        continue\n\ndf = pd.DataFrame(results)\n\n# Screening criteria: ROE>15%, revenue growth>10%, net profit growth>10%, debt-to-asset ratio\u003C70%\nfiltered = df[\n    (df['ROE(%)'] > 15) &\n    (df['营收增长率(%)'] > 10) &\n    (df['净利润增长率(%)'] > 10) &\n    (df['资产负债率(%)'] \u003C 70)\n].sort_values('ROE(%)', ascending=False)\n\nprint(f\"\\nScreened {len(filtered)} high-growth low-valuation stocks:\")\nprint(filtered.head(20).to_string(index=False))\n```\n\n### 板块管理 — Custom Stock Pools\n\n```python\nfrom xtquant import xtdata\n\n# Connect to market data service\nxtdata.connect()\n\n# Download sector classification data\nxtdata.download_sector_data()\n\n# View system sector list\nsectors = xtdata.get_sector_list()\nprint(\"System sector list (first 20):\")\nfor s in sectors[:20]:\n    print(f\"  {s}\")\n\n# Retrieve CSI 300 constituents\nxtdata.download_index_weight()\nhs300_weights = xtdata.get_index_weight('000300.SH')\nprint(f\"\\nCSI 300 has {len(hs300_weights)} constituents\")\n# Sort by weight, show top 10\nsorted_weights = sorted(hs300_weights.items(), key=lambda x: x[1], reverse=True)\nprint(\"Top 10 by weight:\")\nfor stock, weight in sorted_weights[:10]:\n    print(f\"  {stock}: {weight:.4f}\")\n\n# Create custom sector — save screened stocks as a watchlist\nxtdata.create_sector_folder('', '我的策略')                    # Create folder\nxtdata.create_sector('我的策略', '高ROE成长股')                 # Create sector\nmy_stocks = ['600519.SH', '000858.SZ', '601318.SH', '300750.SZ']\nxtdata.add_sector('高ROE成长股', my_stocks)                    # Add stocks\n\n# Verify sector contents\nstocks_in_sector = xtdata.get_stock_list_in_sector('高ROE成长股')\nprint(f\"\\nCustom sector '高ROE成长股' contains {len(stocks_in_sector)} stocks:\")\nfor s in stocks_in_sector:\n    print(f\"  {s}\")\n```\n\n### 多周期K线数据对比分析\n\n```python\nfrom xtquant import xtdata\nimport pandas as pd\n\n# Connect to market data service\nxtdata.connect()\n\nstock = '600519.SH'\n\n# Download data for multiple periods\nperiods = ['1m', '5m', '15m', '30m', '1h', '1d']\nfor period in periods:\n    xtdata.download_history_data(stock, period, start_time='20240601', end_time='20240630')\n\n# Retrieve data for each period and compute statistics\nprint(f\"\\n{stock} Multi-Period Data Statistics (June 2024)\")\nprint(\"=\" * 60)\nfor period in periods:\n    data = xtdata.get_market_data_ex([], [stock], period=period,\n                                      start_time='20240601', end_time='20240630',\n                                      dividend_type='front')\n    df = data[stock]\n    if len(df) > 0:\n        print(f\"\\n[{period} period] {len(df)} K-line bars\")\n        print(f\"  Highest: {df['high'].max():.2f}\")\n        print(f\"  Lowest: {df['low'].min():.2f}\")\n        print(f\"  Average volume: {df['volume'].mean():.0f}\")\n        print(f\"  Total turnover: {df['amount'].sum() \u002F 1e8:.2f} (100M yuan)\")\n```\n\n### 可转债数据分析\n\n```python\nfrom xtquant import xtdata\nimport pandas as pd\n\n# Connect to market data service\nxtdata.connect()\n\n# Download convertible bond data\nxtdata.download_cb_data()\ncb_data = xtdata.get_cb_data()\n\nprint(f\"Retrieved {len(cb_data)} convertible bonds\")\n\n# Download convertible bond market data (using a subset as example)\ncb_codes = list(cb_data.keys())[:20]  # Take the first 20\nfor code in cb_codes:\n    xtdata.download_history_data(code, '1d', start_time='20240101', end_time='20241231')\n\n# Retrieve market data and analyze\nresults = []\nfor code in cb_codes:\n    data = xtdata.get_market_data_ex([], [code], period='1d', count=1)\n    if code in data and len(data[code]) > 0:\n        last = data[code].iloc[-1]\n        info = xtdata.get_instrument_detail(code)\n        results.append({\n            '转债代码': code,\n            '转债名称': info.get('InstrumentName', ''),\n            '最新价': last['close'],\n            '成交额(万)': last['amount'] \u002F 10000,\n        })\n\ndf = pd.DataFrame(results)\nprint(\"\\nConvertible bond market overview:\")\nprint(df.to_string(index=False))\n```\n\n### ETF申赎清单与套利分析\n\n```python\nfrom xtquant import xtdata\n\n# Connect to market data service\nxtdata.connect()\n\n# Download ETF creation\u002Fredemption information\nxtdata.download_etf_info()\netf_info = xtdata.get_etf_info()\n\nprint(f\"Retrieved {len(etf_info)} ETF creation\u002Fredemption records\")\n\n# Compare ETF real-time quotes with IOPV (requires real-time data)\netf_list = ['510300.SH', '510050.SH', '510500.SH', '159919.SZ']  # Common broad-based ETFs\nfor etf in etf_list:\n    xtdata.download_history_data(etf, '1d', start_time='20240101', end_time='20241231')\n    data = xtdata.get_market_data_ex([], [etf], period='1d', count=5, dividend_type='none')\n    if etf in data and len(data[etf]) > 0:\n        df = data[etf]\n        info = xtdata.get_instrument_detail(etf)\n        print(f\"\\n{info.get('InstrumentName', etf)} ({etf}):\")\n        print(f\"  Latest close: {df['close'].iloc[-1]:.4f}\")\n        print(f\"  5-day avg turnover: {df['amount'].mean() \u002F 1e8:.2f} (100M yuan)\")\n        print(f\"  5-day change: {(df['close'].iloc[-1] \u002F df['close'].iloc[0] - 1) * 100:.2f}%\")\n```\n\n---\n\n---\n\n## 🤖 AI Agent 高阶使用指南\n\n对于 AI Agent，在使用该量化\u002F数据工具时应遵循以下高阶策略和最佳实践，以确保任务的高效完成：\n\n### 1. 数据校验与错误处理\n在获取数据或执行操作后，AI 应当主动检查返回的结果格式是否符合预期，以及是否存在缺失值（NaN）或空数据。\n* **示例策略**：在通过 API 获取数据框（DataFrame）后，使用 `if df.empty:` 进行校验；捕获 `Exception` 以防网络或接口错误导致进程崩溃。\n\n### 2. 多步组合分析\nAI 经常需要进行宏观经济分析或跨市场对比。应善于将当前接口与其他数据源或工具组合使用。\n* **示例策略**：先获取板块或指数的宏观数据，再筛选成分股，最后对具体标的进行深入的财务或技术面分析，形成完整的决策链条。\n\n### 3. 构建动态监控与日志\n对于交易和策略类任务，AI 可以定期拉取数据并建立监控机制。\n* **示例策略**：使用循环或定时任务检查特定标的的异动（如涨跌停、放量），并在发现满足条件的信号时输出结构化日志或触发预警。\n\n---\n\n## 社区与支持\n\n由 **大佬量化** 维护 — 量化交易教学与策略研发团队。\n\n微信客服: **bossquant1** · [Bilibili](https:\u002F\u002Fspace.bilibili.com\u002F48693330) · 搜索 **大佬量化** — 微信公众号 \u002F Bilibili \u002F 抖音\n","# XtData（XtQuant行情数据模块）\n\n`xtdata` is the market data module of [XtQuant](http:\u002F\u002Fdict.thinktrader.net\u002FnativeApi\u002Fstart_now.html), providing real-time and historical market data through the local miniQMT client.\n\n> ⚠️ **Requires miniQMT running locally**. xtdata communicates with miniQMT via TCP to retrieve data.\n\n## 安装\n\n```bash\npip install xtquant\n```\n\n## 连接\n\n```python\nfrom xtquant import xtdata\n\n# Connect to the local miniQMT market data service\nxtdata.connect()\n```\n\nOptionally specify a data directory:\n\n```python\n# Manually specify the miniQMT data directory path\nxtdata.data_dir = r'D:\\QMT\\userdata_mini'\n```\n\n## API分类\n\nThe xtdata API is divided into three main categories:\n\n- **Subscription** — `subscribe_quote`, `subscribe_whole_quote`: Register real-time data callbacks; data is continuously pushed until unsubscribed\n- **Retrieval** — `get_market_data_ex`, `get_local_data`, `get_full_tick`, `get_financial_data`: Read data from local cache; returns immediately\n- **Download** — `download_history_data`, `download_financial_data`: Download data from the server to local cache; blocks synchronously until complete\n\n> **Key Pattern**: When retrieving historical data, you must first `download` to local cache, then `get` from cache. For real-time data, use `subscribe`.\n\n## 通用类型约定\n\n- **stock_code**: `'SecurityCode.MarketCode'` format, e.g. `'600000.SH'`, `'000001.SZ'`\n- **period**: `'tick'`, `'1m'`, `'5m'`, `'15m'`, `'30m'`, `'1h'`, `'1d'`, `'1w'`, `'1mon'`\n- **start_time \u002F end_time**: `'YYYYMMDDHHmmss'` or `'YYYYMMDD'` format strings\n- **dividend_type**: `'none'` (no adjustment), `'front'` (forward adjustment), `'back'` (backward adjustment), `'front_ratio'` (proportional forward adjustment), `'back_ratio'` (proportional backward adjustment)\n\n## 请求限制\n\n- Historical data download requests are rate-limited; avoid excessive concurrent downloads.\n- Batch queries (multiple stocks) are more efficient than looping one by one; batch mode is recommended.\n- Full-market subscription (`subscribe_whole_quote`) may require Level2 data permissions for some data types.\n\n---\n\n## 下载历史数据\n\nYou must download data before retrieving it locally:\n\n```python\n# Download daily K-line data\nxtdata.download_history_data('000001.SZ', '1d', start_time='20240101', end_time='20240630')\n\n# Download 1-minute K-line data\nxtdata.download_history_data('000001.SZ', '1m', start_time='20240101', end_time='20240630')\n\n# Download Tick data\nxtdata.download_history_data('000001.SZ', 'tick', start_time='20240601', end_time='20240630')\n```\n\n### 下载退市\u002F到期合约数据\n\n```python\n# Use download_history_data2 to download data for delisted or expired contracts\nxtdata.download_history_data2(['IC2312.IF'], '1d', start_time='20230101', end_time='20231231')\n```\n\n## 获取K线数据\n\n```python\n# Retrieve market data (returns a dict of DataFrames keyed by stock code)\ndata = xtdata.get_market_data_ex(\n    [],                    # field_list, empty list means all fields\n    ['000001.SZ'],         # stock_list, list of stock codes\n    period='1d',           # period: tick, 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1mon\n    start_time='20240101',\n    end_time='20240630',\n    count=-1,              # -1 means retrieve all data\n    dividend_type='front',  # adjustment type: none, front, back, front_ratio, back_ratio\n    fill_data=True         # whether to fill suspended trading data\n)\ndf = data['000001.SZ']\n# Returned fields: open, high, low, close, volume, amount, settelementPrice, openInterest, preClose, suspendFlag\n```\n\n### 获取最新交易日K线\n\n```python\n# count=1 retrieves the latest single K-line bar\ndata = xtdata.get_market_data_ex([], ['000001.SZ'], period='1d', count=1)\n```\n\n## 获取本地缓存数据\n\n```python\n# If data is already cached, read directly from local storage (no need to download again)\ndata = xtdata.get_local_data(\n    field_list=[],\n    stock_list=['000001.SZ'],\n    period='1d',\n    start_time='20240101',\n    end_time='20240630'\n)\n```\n\n## 实时行情订阅\n\n### 订阅单只股票\n\n```python\ndef on_data(datas):\n    \"\"\"Quote callback function, receives pushed real-time data\"\"\"\n    for stock_code, data in datas.items():\n        print(stock_code, data)\n\n# subscribe_quote(stock_code, period, start_time, end_time, count, callback)\nxtdata.subscribe_quote('000001.SZ', period='tick', callback=on_data)\nxtdata.run()  # Block the current thread, continuously receiving callback data\n```\n\n### 订阅全市场行情（全推）\n\n```python\n# Subscribe to full-market quote push\nxtdata.subscribe_whole_quote(['SH', 'SZ'], callback=on_data)\n# Market codes: 'SH' (Shanghai), 'SZ' (Shenzhen), 'BJ' (Beijing)\nxtdata.run()\n```\n\n### 取消订阅\n\n```python\n# Unsubscribe using the sequence number returned by subscribe_quote\nseq = xtdata.subscribe_quote('000001.SZ', period='tick', callback=on_data)\nxtdata.unsubscribe_quote(seq)\n```\n\n## 获取全市场快照\n\n```python\n# Retrieve the latest Tick snapshot for the entire market\ndata = xtdata.get_full_tick(['SH', 'SZ'])\n# 收益率 a dict: {stock_code: tick_data, ...}\n```\n\n---\n\n## 财务数据\n\n```python\n# First download financial data to local cache\nxtdata.download_financial_data(['000001.SZ'])\n\n# Then retrieve financial data from local cache\ndata = xtdata.get_financial_data(['000001.SZ'])\n```\n\n### 可用财务报表\n\n| Statement | Description |\n|---|---|\n| `Balance` | Balance Sheet |\n| `Income` | Income Statement |\n| `CashFlow` | Cash Flow Statement |\n| `PershareIndex` | Per-Share Indicators |\n| `CapitalStructure` | Capital Structure |\n| `TOP10HOLDER` | Top 10 Shareholders |\n| `TOP10FLOWHOLDER` | Top 10 Tradable Shareholders |\n| `SHAREHOLDER` | Shareholder Count |\n\n### 资产负债表关键字段\n\n```python\n'cash_equivalents'          # Cash and cash equivalents\n'tradable_fin_assets'       # Trading financial assets\n'account_receivable'        # Accounts receivable\n'inventories'               # Inventories\n'total_current_assets'      # Total current assets\n'fix_assets'                # Fixed assets\n'intang_assets'             # Intangible assets\n'tot_assets'                # 总资产\n'shortterm_loan'            # Short-term borrowings\n'total_current_liability'   # Total current liabilities\n'tot_liab'                  # Total liabilities\n'cap_stk'                   # Paid-in capital (or share capital)\n'undistributed_profit'      # Retained earnings\n'total_equity'              # Total owners' equity\n'tot_liab_shrhldr_eqy'      # Total liabilities and shareholders' equity\n```\n\n### 利润表关键字段\n\n```python\n'revenue'                              # Total operating revenue\n'revenue_inc'                          # Operating revenue\n'total_expense'                        # Operating costs\n'sale_expense'                         # Selling expenses\n'less_gerl_admin_exp'                  # Administrative expenses\n'financial_expense'                    # Financial expenses\n'oper_profit'                          # Operating profit\n'tot_profit'                           # Total profit\n'net_profit_incl_min_int_inc'          # 净利润\n'net_profit_excl_min_int_inc'          # 净利润 attributable to parent company\n's_fa_eps_basic'                       # Basic earnings per share\n's_fa_eps_diluted'                     # Diluted earnings per share\n```\n\n### 现金流量表关键字段\n\n```python\n'goods_sale_and_service_render_cash'   # Cash received from sales of goods and services\n'net_cash_flows_oper_act'              # Net cash flows from operating activities\n'net_cash_flows_inv_act'               # Net cash flows from investing activities\n'net_cash_flows_fnc_act'               # Net cash flows from financing activities\n'net_incr_cash_cash_equ'               # Net increase in cash and cash equivalents\n```\n\n### 每股指标关键字段\n\n```python\n's_fa_eps_basic'                       # Basic earnings per share\n's_fa_bps'                             # Book value per share\n's_fa_ocfps'                           # Operating cash flow per share\n'du_return_on_equity'                  # 净资产收益率（ROE）\n'sales_gross_profit'                   # Gross profit margin\n'inc_revenue_rate'                     # Year-over-year revenue growth rate\n'du_profit_rate'                       # Year-over-year net profit growth rate\n'gear_ratio'                          # Debt-to-asset ratio\n'inventory_turnover'                   # Inventory turnover ratio\n```\n\n### 股本结构字段\n\n```python\n'total_capital'                        # Total share capital\n'circulating_capital'                  # Listed tradable A-shares\n'restrict_circulating_capital'         # Restricted tradable shares\n```\n\n### 前十大股东字段\n\n```python\n'declareDate'     # Announcement date\n'endDate'         # Reporting period end date\n'name'            # Shareholder name\n'quantity'        # Number of shares held\n'ratio'           # Shareholding ratio\n'nature'          # Share type\n'rank'            # Shareholding rank\n```\n\n---\n\n## 除权除息数据\n\n```python\n# Retrieve ex-dividend adjustment factor data\ndata = xtdata.get_divid_factors('000001.SZ')\n# Returned fields: interest (dividend per share), stockBonus (bonus shares per share), stockGift (capitalization shares per share),\n#         allotNum (rights issue shares per share), allotPrice (rights issue price), gugai (share reform flag), dr (ex-dividend factor)\n```\n\n## 合约信息\n\n```python\n# Retrieve detailed instrument information\ninfo = xtdata.get_instrument_detail('000001.SZ')\n# 收益率 a dict containing: InstrumentName (instrument name), ExchangeID (market code), ProductID (product code),\n#   UpStopPrice (upper price limit), DownStopPrice (lower price limit), PreClose (previous close),\n#   FloatVolume (tradable shares), TotalVolume (total shares), PriceTick (minimum price increment),\n#   VolumeMultiple (contract multiplier), CreateDate (creation date), OpenDate (listing date),\n#   ExpireDate (expiration date), MainContract (main contract flag), IsTrading (whether tradable), etc.\n\n# Retrieve security type\nitype = xtdata.get_instrument_type('000001.SZ')  # 收益率 'stock', 'index', 'fund', 'bond', etc.\n\n# Retrieve trading day list\ndays = xtdata.get_trading_dates('SH', start_time='20240101', end_time='20240630')\n\n# Retrieve trading calendar\ncalendar = xtdata.get_trading_calendar('SH')\n\n# Download and retrieve holiday data\nxtdata.download_holiday_data()\nholidays = xtdata.get_holidays()\n```\n\n## 板块管理\n\n```python\n# Retrieve sector list\nsectors = xtdata.get_sector_list()\n\n# Retrieve stock list within a sector\nstocks = xtdata.get_stock_list_in_sector('沪深A股')\n\n# Download sector classification data\nxtdata.download_sector_data()\n\n# Custom sector management\nxtdata.create_sector_folder('', 'MyFolder')          # Create a folder at root level\nxtdata.create_sector('MyFolder', 'MyBlock')           # Create a sector under the folder\nxtdata.add_sector('MyBlock', ['000001.SZ', '600000.SH'])  # Add stocks to the sector\nxtdata.remove_stock_from_sector('MyBlock', ['000001.SZ']) # Remove stocks from the sector\nxtdata.reset_sector('MyBlock', ['600000.SH'])         # Reset sector contents\nxtdata.remove_sector('MyBlock')                       # Delete the sector\n```\n\n## 指数成分股\n\n```python\n# First download index weight data\nxtdata.download_index_weight()\n\n# Retrieve index constituent weights\nweights = xtdata.get_index_weight('000300.SH')\n# 收益率: {stock_code: weight, ...}\n```\n\n## 可转债信息\n\n```python\n# Download and retrieve convertible bond data\nxtdata.download_cb_data()\ndata = xtdata.get_cb_data()\n```\n\n## 新股申购信息\n\n```python\n# Retrieve IPO subscription information\ndata = xtdata.get_ipo_info()\n```\n\n## ETF申赎清单\n\n```python\n# Download and retrieve ETF creation\u002Fredemption information\nxtdata.download_etf_info()\ndata = xtdata.get_etf_info()\n```\n\n## 可用数据周期\n\n`tick`, `1m`, `5m`, `15m`, `30m`, `1h`, `1d`, `1w`, `1mon`\n\n---\n\n## 数据字段参考\n\n### Tick数据字段\n\n```python\n'time'                  # Timestamp\n'lastPrice'             # Latest price\n'open'                  # Opening price\n'high'                  # Highest price\n'low'                   # Lowest price\n'lastClose'             # Previous close price\n'amount'                # Total turnover\n'volume'                # Total volume\n'pvolume'               # Raw total volume\n'stockStatus'           # Security status\n'openInt'               # Open interest\n'lastSettlementPrice'   # Previous settlement price\n'askPrice'              # Ask prices (list, 5 levels)\n'bidPrice'              # Bid prices (list, 5 levels)\n'askVol'                # Ask volumes (list, 5 levels)\n'bidVol'                # Bid volumes (list, 5 levels)\n'transactionNum'        # Number of transactions\n```\n\n### K线数据字段（1m \u002F 5m \u002F 1d等）\n\n```python\n'time'                  # Timestamp\n'open'                  # Opening price\n'high'                  # Highest price\n'low'                   # Lowest price\n'close'                 # Closing price\n'volume'                # Volume\n'amount'                # Turnover\n'settelementPrice'      # Settlement price\n'openInterest'          # Open interest\n'preClose'              # Previous close price\n'suspendFlag'           # Suspension flag: 0 - normal, 1 - suspended, -1 - resumed from today\n```\n\n### 证券状态码\n\n```\n0,10 - Unknown           11 - Pre-open S          12 - Call auction C\n13 - Continuous trading T 14 - Break B             15 - Closed E\n16 - Volatility interrupt V  17 - Temporary halt P  18 - Closing call auction U\n19 - Intraday call auction M  20 - Halted until close N  21 - Field retrieval error\n22 - After-hours fixed price trading  23 - After-hours fixed price trading ended\n```\n\n---\n\n## Level2数据\n\nIf your broker supports Level2 data:\n\n### l2quote — Level2实时行情快照\n\n```python\n'time'                  # Timestamp\n'lastPrice'             # Latest price\n'open' \u002F 'high' \u002F 'low' # Opening \u002F Highest \u002F Lowest price\n'amount' \u002F 'volume'     # Turnover \u002F Volume\n'transactionNum'        # Number of transactions\n'pe'                    # 市盈率\n'askPrice' \u002F 'bidPrice' # Multi-level ask \u002F bid prices\n'askVol' \u002F 'bidVol'     # Multi-level ask \u002F bid volumes\n```\n\n### l2order — Level2逐笔委托\n\n```python\n'time'              # Timestamp\n'price'             # Order price\n'volume'            # Order quantity\n'entrustNo'         # Order number\n'entrustType'       # Order type (0 - unknown, 1 - normal, 2 - fill-or-kill remainder cancel, 4 - best five levels, 5 - fill-or-cancel, 6 - best own side, 7 - best counterparty)\n'entrustDirection'  # Order direction (1 - buy, 2 - sell, 3 - cancel buy (SSE), 4 - cancel sell (SSE))\n```\n\n### l2transaction — Level2逐笔成交\n\n```python\n'time'          # Timestamp\n'price'         # Trade price\n'volume'        # Trade quantity\n'amount'        # Trade amount\n'tradeIndex'    # Trade record number\n'buyNo'         # Buyer order number\n'sellNo'        # Seller order number\n'tradeType'     # Trade type\n'tradeFlag'     # Trade flag (0 - unknown, 1 - active buy, 2 - active sell, 3 - cancellation (SZSE))\n```\n\n### l2quoteaux — 买卖汇总\n\n```python\n'avgBidPrice'           # Average bid price\n'totalBidQuantity'      # Total bid quantity\n'avgOffPrice'           # Average ask price\n'totalOffQuantity'      # Total ask quantity\n'withdrawBidQuantity'   # Total bid cancellation quantity\n'withdrawOffQuantity'   # Total ask cancellation quantity\n```\n\n### l2orderqueue — 最优买卖委托队列\n\n```python\n'bidLevelPrice' \u002F 'offerLevelPrice'    # Bid \u002F Ask price\n'bidLevelVolume' \u002F 'offerLevelVolume'  # Bid \u002F Ask volume\n'bidLevelNumber' \u002F 'offLevelNumber'    # Bid \u002F Ask order count\n```\n\n### l2transactioncount — 逐笔成交统计\n\nIncludes ddx\u002Fddy\u002Fddz indicators, net order\u002Fcancellation volumes, and buy\u002Fsell statistics categorized by order size (extra-large \u002F large \u002F medium \u002F small orders).\n\n### l2thousand — 千档盘口\n\nUp to 1000 levels of bid\u002Fask prices and volumes.\n\n### limitupperformance — 涨停连板数据\n\n```python\n'startUp' \u002F 'endUp'   # Limit-up start \u002F end time\n'breakUp'              # Number of limit-up breaks\n'sealCount'            # Consecutive limit-up days\n'sealVolRatio'         # Seal-to-volume ratio\n'direct'               # Direction: 0 - none, 1 - limit up, 2 - limit down\n```\n\n### snapshotindex — 快照指标\n\n```python\n'volRatio'          # Volume ratio\n'speed1' \u002F 'speed5' # 1-minute \u002F 5-minute price change speed\n'gainRate3\u002F5\u002F10'    # 3\u002F5\u002F10-day price change percentage\n'turnoverRate3\u002F5\u002F10' # 3\u002F5\u002F10-day turnover rate\n```\n\n### announcement — 公告与新闻\n\n```python\n'headline'  # Headline\n'summary'   # Summary\n'content'   # Content\n'type'      # Type: 0 - other, 1 - financial report\n```\n\n### hfiopv — 高频IOPV（100ms推送频率）\n\nETF IOPV data, including dynamic IOPV, limit-up\u002Fdown IOPV, and premium\u002Fdiscount estimates.\n\n### fullspeedorderbook — 全速盘口（20档）\n\n```python\n'bidPrice' \u002F 'askPrice'    # Multi-level bid \u002F ask price list (levels 1-20)\n'bidVolume' \u002F 'askVolume'  # Multi-level bid \u002F ask volume list (levels 1-20)\n```\n\n---\n\n## 合约信息 Fields\n\n```python\n'InstrumentName'        # Instrument name\n'ExchangeID'            # Market code\n'PreClose'              # Previous close price\n'UpStopPrice'           # Daily upper price limit\n'DownStopPrice'         # Daily lower price limit\n'FloatVolume'           # Tradable shares\n'TotalVolume'           # Total shares\n'PriceTick'             # Minimum price increment\n'VolumeMultiple'        # Contract multiplier\n'MainContract'          # Main contract flag (1 - primary, 2 - secondary, 3 - tertiary)\n'OpenDate'              # IPO date \u002F Listing date\n'ExpireDate'            # Delisting date or expiration date\n'IsTrading'             # Whether the instrument is tradable\n'OptExercisePrice'      # Option exercise price \u002F Convertible bond conversion price\n'OptionType'            # Option type (-1 not an option, 0 call, 1 put)\n'MaxLimitOrderVolume'   # Maximum limit order volume\n'MinLimitOrderVolume'   # Minimum limit order volume\n```\n\n## ETF现金替代标志\n\n```\n0 - Cash substitution prohibited (stock required)\n1 - Cash substitution allowed (use stock first, cash for shortfall)\n2 - Cash substitution mandatory\n3 - Non-SSE cash substitution with settlement\n4 - Non-SSE mandatory cash substitution\n```\n\n## 时间戳转换工具\n\n```python\nimport time\n\ndef conv_time(ct):\n    '''Convert millisecond timestamp to string format: conv_time(1476374400000) --> \"20161014000000.000\"'''\n    local_time = time.localtime(ct \u002F 1000)\n    data_head = time.strftime('%Y%m%d%H%M%S', local_time)\n    data_secs = (ct - int(ct)) * 1000\n    return '%s.%03d' % (data_head, data_secs)\n```\n\n## 使用技巧\n\n- Before retrieving data for the first time, always call `xtdata.download_history_data()` to download to local cache.\n- Downloaded data is cached locally — subsequent reads are extremely fast.\n- `xtdata.run()` blocks the current thread — if you need to trade simultaneously, run it in a separate thread.\n- Prefer `get_market_data_ex` (recommended) over `get_local_data` — the former supports more features like dividend adjustment.\n- For delisted\u002Fexpired contract data, use `download_history_data2`.\n- Financial data timestamp notes: `m_anntime` = disclosure date, `m_timetag` = reporting period end date.\n- Documentation: http:\u002F\u002Fdict.thinktrader.net\u002FnativeApi\u002Fxtdata.html\n\n---\n\n## 进阶示例\n\n### 批量下载多只股票历史数据\n\n```python\nfrom xtquant import xtdata\nimport time\n\n# Connect to miniQMT market data service\nxtdata.connect()\n\n# Define the stock list to download (common A-share stocks)\nstock_list = [\n    '600519.SH',  # Kweichow Moutai\n    '000001.SZ',  # Ping An Bank\n    '300750.SZ',  # CATL\n    '601318.SH',  # Ping An Insurance\n    '000858.SZ',  # Wuliangye\n    '600036.SH',  # China Merchants Bank\n    '002594.SZ',  # BYD\n]\n\n# Batch download daily K-line data (forward adjusted)\nfor stock in stock_list:\n    print(f\"Downloading daily K-line data for {stock}...\")\n    xtdata.download_history_data(stock, '1d', start_time='20230101', end_time='20241231')\n    time.sleep(0.5)  # Add delay to avoid triggering rate limits\n\n# Batch retrieve data and merge for analysis\nall_data = {}\nfor stock in stock_list:\n    data = xtdata.get_market_data_ex(\n        [],                     # Empty list means all fields\n        [stock],                # 股票代码 list\n        period='1d',            # Daily K-line\n        start_time='20230101',\n        end_time='20241231',\n        dividend_type='front',  # Forward adjusted\n        fill_data=True          # Fill suspended trading data\n    )\n    df = data[stock]\n    all_data[stock] = df\n    print(f\"{stock} retrieved {len(df)} records\")\n\n# Compare closing price trends across multiple stocks\nimport pandas as pd\nclose_df = pd.DataFrame({stock: all_data[stock]['close'] for stock in stock_list})\nprint(\"Latest closing prices:\")\nprint(close_df.tail(5))\n```\n\n### 实时行情监控 + 条件预警\n\n```python\nfrom xtquant import xtdata\nimport datetime\n\n# Connect to market data service\nxtdata.connect()\n\n# Define watchlist and alert conditions\nwatch_list = ['600519.SH', '000001.SZ', '300750.SZ']\nalert_config = {\n    '600519.SH': {'upper': 1900.0, 'lower': 1700.0},  # Moutai: alert at 1900 or 1700\n    '000001.SZ': {'upper': 15.0, 'lower': 10.0},       # Ping An Bank: alert at 15 or 10\n    '300750.SZ': {'upper': 250.0, 'lower': 180.0},     # CATL: alert at 250 or 180\n}\n\ndef on_realtime_data(datas):\n    \"\"\"Real-time quote callback — checks alert conditions on each push\"\"\"\n    now = datetime.datetime.now().strftime('%H:%M:%S')\n    for stock_code, tick_data in datas.items():\n        # Get latest price\n        last_price = tick_data['lastPrice']\n        pre_close = tick_data['lastClose']\n        # Calculate price change percentage\n        change_pct = (last_price - pre_close) \u002F pre_close * 100 if pre_close > 0 else 0\n\n        print(f\"[{now}] {stock_code}: Latest={last_price:.2f}, Change={change_pct:.2f}%\")\n\n        # Check alert conditions\n        if stock_code in alert_config:\n            config = alert_config[stock_code]\n            if last_price >= config['upper']:\n                print(f\"  ⚠️ Alert: {stock_code} price {last_price:.2f} breached upper limit {config['upper']}\")\n            elif last_price \u003C= config['lower']:\n                print(f\"  ⚠️ Alert: {stock_code} price {last_price:.2f} breached lower limit {config['lower']}\")\n\n# Subscribe to Tick data for multiple stocks\nfor stock in watch_list:\n    xtdata.subscribe_quote(stock, period='tick', callback=on_realtime_data)\n\nprint(\"Real-time monitoring started, press Ctrl+C to exit...\")\nxtdata.run()  # Block main thread, continuously receiving data\n```\n\n### Level2逐笔成交分析（大单跟踪）\n\n```python\nfrom xtquant import xtdata\nimport pandas as pd\n\n# Connect to market data service\nxtdata.connect()\n\nstock = '600519.SH'\n\n# Download Level2 trade-by-trade data (requires L2 data permissions)\nxtdata.download_history_data(stock, 'l2transaction', start_time='20240601', end_time='20240601')\n\n# Retrieve trade-by-trade data\ndata = xtdata.get_market_data_ex([], [stock], period='l2transaction',\n                                  start_time='20240601', end_time='20240601')\ndf = data[stock]\n\nif len(df) > 0:\n    # Convert trade amount to 10-thousands (wan yuan)\n    df['amount_wan'] = df['amount'] \u002F 10000\n\n    # Categorize by trade amount (Extra-large >1M, Large >200K, Medium >50K, Small \u003C50K)\n    df['order_size'] = pd.cut(\n        df['amount_wan'],\n        bins=[0, 5, 20, 100, float('inf')],\n        labels=['小单(\u003C5万)', '中单(5-20万)', '大单(20-100万)', '特大单(>100万)']\n    )\n\n    # Statistics by trade direction and order size\n    # tradeFlag: 1=active buy, 2=active sell\n    buy_stats = df[df['tradeFlag'] == 1].groupby('order_size')['amount_wan'].sum()\n    sell_stats = df[df['tradeFlag'] == 2].groupby('order_size')['amount_wan'].sum()\n\n    print(f\"\\n{stock} Trade-by-Trade Statistics (unit: 10K yuan)\")\n    print(\"=\" * 50)\n    print(\"[Active Buy]\")\n    print(buy_stats)\n    print(\"\\n[Active Sell]\")\n    print(sell_stats)\n    print(f\"\\nNet buy amount: {buy_stats.sum() - sell_stats.sum():.2f} (10K yuan)\")\n```\n\n### 财务数据筛选 — 低估值高成长选股\n\n```python\nfrom xtquant import xtdata\nimport pandas as pd\n\n# Connect to market data service\nxtdata.connect()\n\n# Retrieve A-share stock list\nstock_list = xtdata.get_stock_list_in_sector('沪深A股')\nprint(f\"Total A-shares: {len(stock_list)}\")\n\n# Download financial data\nxtdata.download_financial_data(stock_list)\n\n# Retrieve financial data\nfin_data = xtdata.get_financial_data(stock_list)\n\n# Build screening DataFrame\nresults = []\nfor stock, data_list in fin_data.items():\n    if not data_list:\n        continue\n    # Take the latest financial report\n    latest = data_list[-1] if isinstance(data_list, list) else data_list\n\n    # Extract key indicators\n    try:\n        roe = latest.get('du_return_on_equity', None)          # 净资产收益率（ROE）\n        revenue_growth = latest.get('inc_revenue_rate', None)   # Year-over-year revenue growth\n        profit_growth = latest.get('du_profit_rate', None)      # Year-over-year net profit growth\n        eps = latest.get('s_fa_eps_basic', None)                # Basic earnings per share\n        bps = latest.get('s_fa_bps', None)                      # Book value per share\n        gear = latest.get('gear_ratio', None)                   # Debt-to-asset ratio\n\n        if all(v is not None for v in [roe, revenue_growth, eps, bps]):\n            results.append({\n                '股票代码': stock,\n                'ROE(%)': roe,\n                '营收增长率(%)': revenue_growth,\n                '净利润增长率(%)': profit_growth,\n                '每股收益': eps,\n                '每股净资产': bps,\n                '资产负债率(%)': gear\n            })\n    except:\n        continue\n\ndf = pd.DataFrame(results)\n\n# Screening criteria: ROE>15%, revenue growth>10%, net profit growth>10%, debt-to-asset ratio\u003C70%\nfiltered = df[\n    (df['ROE(%)'] > 15) &\n    (df['营收增长率(%)'] > 10) &\n    (df['净利润增长率(%)'] > 10) &\n    (df['资产负债率(%)'] \u003C 70)\n].sort_values('ROE(%)', ascending=False)\n\nprint(f\"\\nScreened {len(filtered)} high-growth low-valuation stocks:\")\nprint(filtered.head(20).to_string(index=False))\n```\n\n### 板块管理 — Custom Stock Pools\n\n```python\nfrom xtquant import xtdata\n\n# Connect to market data service\nxtdata.connect()\n\n# Download sector classification data\nxtdata.download_sector_data()\n\n# View system sector list\nsectors = xtdata.get_sector_list()\nprint(\"System sector list (first 20):\")\nfor s in sectors[:20]:\n    print(f\"  {s}\")\n\n# Retrieve CSI 300 constituents\nxtdata.download_index_weight()\nhs300_weights = xtdata.get_index_weight('000300.SH')\nprint(f\"\\nCSI 300 has {len(hs300_weights)} constituents\")\n# Sort by weight, show top 10\nsorted_weights = sorted(hs300_weights.items(), key=lambda x: x[1], reverse=True)\nprint(\"Top 10 by weight:\")\nfor stock, weight in sorted_weights[:10]:\n    print(f\"  {stock}: {weight:.4f}\")\n\n# Create custom sector — save screened stocks as a watchlist\nxtdata.create_sector_folder('', '我的策略')                    # Create folder\nxtdata.create_sector('我的策略', '高ROE成长股')                 # Create sector\nmy_stocks = ['600519.SH', '000858.SZ', '601318.SH', '300750.SZ']\nxtdata.add_sector('高ROE成长股', my_stocks)                    # Add stocks\n\n# Verify sector contents\nstocks_in_sector = xtdata.get_stock_list_in_sector('高ROE成长股')\nprint(f\"\\nCustom sector '高ROE成长股' contains {len(stocks_in_sector)} stocks:\")\nfor s in stocks_in_sector:\n    print(f\"  {s}\")\n```\n\n### 多周期K线数据对比分析\n\n```python\nfrom xtquant import xtdata\nimport pandas as pd\n\n# Connect to market data service\nxtdata.connect()\n\nstock = '600519.SH'\n\n# Download data for multiple periods\nperiods = ['1m', '5m', '15m', '30m', '1h', '1d']\nfor period in periods:\n    xtdata.download_history_data(stock, period, start_time='20240601', end_time='20240630')\n\n# Retrieve data for each period and compute statistics\nprint(f\"\\n{stock} Multi-Period Data Statistics (June 2024)\")\nprint(\"=\" * 60)\nfor period in periods:\n    data = xtdata.get_market_data_ex([], [stock], period=period,\n                                      start_time='20240601', end_time='20240630',\n                                      dividend_type='front')\n    df = data[stock]\n    if len(df) > 0:\n        print(f\"\\n[{period} period] {len(df)} K-line bars\")\n        print(f\"  Highest: {df['high'].max():.2f}\")\n        print(f\"  Lowest: {df['low'].min():.2f}\")\n        print(f\"  Average volume: {df['volume'].mean():.0f}\")\n        print(f\"  Total turnover: {df['amount'].sum() \u002F 1e8:.2f} (100M yuan)\")\n```\n\n### 可转债数据分析\n\n```python\nfrom xtquant import xtdata\nimport pandas as pd\n\n# Connect to market data service\nxtdata.connect()\n\n# Download convertible bond data\nxtdata.download_cb_data()\ncb_data = xtdata.get_cb_data()\n\nprint(f\"Retrieved {len(cb_data)} convertible bonds\")\n\n# Download convertible bond market data (using a subset as example)\ncb_codes = list(cb_data.keys())[:20]  # Take the first 20\nfor code in cb_codes:\n    xtdata.download_history_data(code, '1d', start_time='20240101', end_time='20241231')\n\n# Retrieve market data and analyze\nresults = []\nfor code in cb_codes:\n    data = xtdata.get_market_data_ex([], [code], period='1d', count=1)\n    if code in data and len(data[code]) > 0:\n        last = data[code].iloc[-1]\n        info = xtdata.get_instrument_detail(code)\n        results.append({\n            '转债代码': code,\n            '转债名称': info.get('InstrumentName', ''),\n            '最新价': last['close'],\n            '成交额(万)': last['amount'] \u002F 10000,\n        })\n\ndf = pd.DataFrame(results)\nprint(\"\\nConvertible bond market overview:\")\nprint(df.to_string(index=False))\n```\n\n### ETF申赎清单与套利分析\n\n```python\nfrom xtquant import xtdata\n\n# Connect to market data service\nxtdata.connect()\n\n# Download ETF creation\u002Fredemption information\nxtdata.download_etf_info()\netf_info = xtdata.get_etf_info()\n\nprint(f\"Retrieved {len(etf_info)} ETF creation\u002Fredemption records\")\n\n# Compare ETF real-time quotes with IOPV (requires real-time data)\netf_list = ['510300.SH', '510050.SH', '510500.SH', '159919.SZ']  # Common broad-based ETFs\nfor etf in etf_list:\n    xtdata.download_history_data(etf, '1d', start_time='20240101', end_time='20241231')\n    data = xtdata.get_market_data_ex([], [etf], period='1d', count=5, dividend_type='none')\n    if etf in data and len(data[etf]) > 0:\n        df = data[etf]\n        info = xtdata.get_instrument_detail(etf)\n        print(f\"\\n{info.get('InstrumentName', etf)} ({etf}):\")\n        print(f\"  Latest close: {df['close'].iloc[-1]:.4f}\")\n        print(f\"  5-day avg turnover: {df['amount'].mean() \u002F 1e8:.2f} (100M yuan)\")\n        print(f\"  5-day change: {(df['close'].iloc[-1] \u002F df['close'].iloc[0] - 1) * 100:.2f}%\")\n```\n\n---\n\n---\n\n## 🤖 AI Agent 高阶使用指南\n\n对于 AI Agent，在使用该量化\u002F数据工具时应遵循以下高阶策略和最佳实践，以确保任务的高效完成：\n\n### 1. 数据校验与错误处理\n在获取数据或执行操作后，AI 应当主动检查返回的结果格式是否符合预期，以及是否存在缺失值（NaN）或空数据。\n* **示例策略**：在通过 API 获取数据框（DataFrame）后，使用 `if df.empty:` 进行校验；捕获 `Exception` 以防网络或接口错误导致进程崩溃。\n\n### 2. 多步组合分析\nAI 经常需要进行宏观经济分析或跨市场对比。应善于将当前接口与其他数据源或工具组合使用。\n* **示例策略**：先获取板块或指数的宏观数据，再筛选成分股，最后对具体标的进行深入的财务或技术面分析，形成完整的决策链条。\n\n### 3. 构建动态监控与日志\n对于交易和策略类任务，AI 可以定期拉取数据并建立监控机制。\n* **示例策略**：使用循环或定时任务检查特定标的的异动（如涨跌停、放量），并在发现满足条件的信号时输出结构化日志或触发预警。\n\n---\n\n## 社区与支持\n\n由 **大佬量化** 维护 — 量化交易教学与策略研发团队。\n\n微信客服: **bossquant1** · [Bilibili](https:\u002F\u002Fspace.bilibili.com\u002F48693330) · 搜索 **大佬量化** — 微信公众号 \u002F Bilibili \u002F 抖音\n",{"name":5,"version":24,"homepage":25,"metadata":26,"description":7},"1.2.0","http:\u002F\u002Fdict.thinktrader.net\u002FnativeApi\u002Fxtdata.html",{"clawdbot":27},{"emoji":28,"requires":29},"📡",{"bins":30},[31],"python3","master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fx\u002Fxtdata",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":42,"prompt":52,"zipAvailable":53},[43,46,49],{"tool":44,"command":45},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill xtdata",{"tool":47,"command":48},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill xtdata",{"tool":50,"command":51},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill xtdata","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fx\u002Fxtdata\u002FSKILL.md",true,[],[56,63,70,77,84,91],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]