[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77S9E12TGBT6Q1DABRWZ6R9":3,"skill-same:01M77S9E12TGBT6Q1DABRWZ6R9":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},"01M77S9E12TGBT6Q1DABRWZ6R9","ptrade",null,"Ptrade 恒生量化交易平台 - 策略运行在券商服务器上，低延迟执行，支持A股、期货、融资融券等中国证券市场。","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\u002Fp\u002Fptrade\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: ptrade\ndescription: Ptrade 恒生量化交易平台 - 策略运行在券商服务器上，低延迟执行，支持A股、期货、融资融券等中国证券市场。\nversion: 1.2.0\nhomepage: https:\u002F\u002Fptradeapi.com\nmetadata: {\"clawdbot\":{\"emoji\":\"🏦\",\"requires\":{\"bins\":[\"python3\"]}}}\n---\n\n# Ptrade（恒生量化交易平台）\n\n[Ptrade](https:\u002F\u002Fptradeapi.com) 是恒生电子开发的专业量化交易平台。策略运行在**券商服务器**（内网）上，低延迟执行。采用事件驱动的Python策略框架。\n\n> ⚠️ **需要券商开通Ptrade权限**。策略运行在券商云端——无法访问外网。不能pip安装，仅可使用内置第三方库。\n\n## 支持的市场和业务类型\n\n**回测支持：**\n1. 普通股票交易（单位：股）\n2. 可转债交易（单位：张，T+0）\n3. 融资融券担保品买卖（单位：股）\n4. 期货投机交易（单位：手，T+0）\n5. LOF基金交易（单位：份）\n6. ETF基金交易（单位：份）\n\n**实盘交易支持：**\n1. 普通股票交易（单位：股）\n2. 可转债交易（T+0）\n3. 融资融券交易（单位：股）\n4. ETF申赎、套利（单位：份）\n5. 国债逆回购（单位：份）\n6. 期货投机交易（单位：手，T+0）\n7. ETF基金交易（单位：份）\n\n**默认支持Level2十档行情**。部分券商提供免费L2逐笔数据。\n\n### 价格精度规则\n\n| 资产类型 | 最小变动单位 | 小数位数 |\n|---|---|---|\n| 股票 | 0.01 | 2 |\n| 可转债 | 0.001 | 3 |\n| LOF \u002F ETF | 0.001 | 3 |\n| 国债逆回购 | 0.005 | 3 |\n| 股指期货 | 0.2 | 1 |\n| 国债期货 | 0.005 | 3 |\n| ETF期权 | 0.0001 | 4 |\n\n> ⚠️ 使用 `limit_price` 下单时，价格必须符合正确的小数精度，否则订单将被拒绝。\n\n## 股票代码格式\n\n- Shanghai: `600570.SS`\n- Shenzhen: `000001.SZ`\n- Index: `000300.SS` (CSI 300)\n\n---\n\n## 策略生命周期（事件驱动）\n\n```python\ndef initialize(context):\n    \"\"\"Required — Called once at startup. Used to set stock pool, benchmark, and scheduled tasks.\"\"\"\n    g.security = '600570.SS'\n    set_universe(g.security)\n\ndef before_trading_start(context, data):\n    \"\"\"Optional — Called before market open.\n    Backtest mode: Executes at 8:30 each trading day.\n    Live mode: Executes immediately on first start, then at 9:10 daily (default, broker-configurable).\"\"\"\n    log.info('Pre-market preparation')\n\ndef handle_data(context, data):\n    \"\"\"Required — Triggered on each bar.\n    Daily mode: Executes once at 14:50 daily (default).\n    Minute mode: Executes at each minute bar close.\n    data[sid] provides: open, high, low, close, price, volume, money.\"\"\"\n    current_price = data[g.security]['close']\n    cash = context.portfolio.cash\n\ndef after_trading_end(context, data):\n    \"\"\"Optional — Called at 15:30 after market close.\"\"\"\n    log.info('Trading day ended')\n\ndef tick_data(context, data):\n    \"\"\"Optional — Triggered every 3 seconds during market hours (9:30-14:59, live only).\n    Must use order_tick() to place orders in this function.\n    data format: {stock_code: {'order': DataFrame\u002FNone, 'tick': DataFrame, 'transcation': DataFrame\u002FNone}}\"\"\"\n    for stock, d in data.items():\n        tick = d['tick']\n        price = tick['last_px']           # Latest price\n        bid1 = tick['bid_grp'][1]         # Best bid [price, volume, count]\n        ask1 = tick['offer_grp'][1]       # Best ask [price, volume, count]\n        log.info(f'{stock}: {price}, upper_limit={tick[\"up_px\"]}, lower_limit={tick[\"down_px\"]}')\n        # Level2 fields (requires L2 access, otherwise None):\n        order_data = d['order']           # Tick-by-tick orders\n        trans_data = d['transcation']     # Tick-by-tick trades\n\ndef on_order_response(context, order_list):\n    \"\"\"Optional — Triggered on order status changes (faster than get_orders).\n    order_list is a list of dicts containing: entrust_no, stock_code, amount, price,\n    business_amount, status, order_id, entrust_type, entrust_prop, error_info, order_time.\"\"\"\n    for o in order_list:\n        log.info(f'Order {o[\"stock_code\"]}: status={o[\"status\"]}, filled={o[\"business_amount\"]}\u002F{o[\"amount\"]}')\n\ndef on_trade_response(context, trade_list):\n    \"\"\"Optional — Triggered on trade execution (faster than get_trades).\n    trade_list is a list of dicts containing: entrust_no, stock_code, business_amount,\n    business_price, business_balance, business_id, status, order_id, entrust_bs, business_time.\n    Note: status=9 means rejected order.\"\"\"\n    for t in trade_list:\n        direction = 'Buy' if t['entrust_bs'] == '1' else 'Sell'\n        log.info(f'{direction} {t[\"stock_code\"]}: {t[\"business_amount\"]}@{t[\"business_price\"]}')\n```\n\n### 策略执行频率\n\n| 模式 | 频率 | 执行时间 |\n|---|---|---|\n| **日线** | 每日一次 | 回测: 15:00, 实盘: 14:50（可配置） |\n| **分钟** | 每分钟一次 | 每根分钟K线收盘时 |\n| **Tick** | 每3秒 | 9:30–14:59，通过 `tick_data` 或 `run_interval` |\n\n### 时间参考\n\n| 阶段 | 时间 | 可用函数 |\n|---|---|---|\n| **盘前** | 9:30之前 | `before_trading_start`, `run_daily(time='09:15')` |\n| **盘中** | 9:30–15:00 | `handle_data`, `run_daily`, `run_interval`, `tick_data` |\n| **盘后** | 15:30 | `after_trading_end`, `run_daily(time='15:10')` |\n\n---\n\n## 初始化设置函数（仅在initialize中使用）\n\n### 股票池与基准\n\n```python\ndef initialize(context):\n    set_universe(['600570.SS', '000001.SZ'])   # Required: Set stock pool\n    set_benchmark('000300.SS')                  # Backtest benchmark index\n```\n\n### 手续费与滑点（仅回测）\n\n```python\ndef initialize(context):\n    # 设置手续费: buy 0.03%, sell 0.13% (incl. stamp tax), based on trade value, min 5 CNY\n    set_commission(PerTrade(buy_cost=0.0003, sell_cost=0.0013, unit='perValue', min_cost=5))\n    set_slippage(FixedSlippage(0.02))           # 固定滑点 of 0.02 CNY\n    set_volume_ratio(0.025)                     # Max fill ratio of daily volume\n    set_limit_mode(0)                           # 0=limit by volume ratio, 1=limit by fixed quantity\n```\n\n### 定时任务\n\n```python\ndef initialize(context):\n    # run_daily: Execute function at specified time each day\n    run_daily(context, my_morning_task, time='09:31')\n    run_daily(context, my_afternoon_task, time='14:50')\n\n    # run_interval: Execute function every N seconds (live only, min 3 seconds)\n    run_interval(context, my_tick_handler, seconds=10)\n```\n\n### 策略参数（可从UI配置）\n\n```python\ndef initialize(context):\n    # Set parameters that can be dynamically modified from the Ptrade UI without code changes\n    set_parameters(\n        context,\n        ma_fast=5,         # Fast moving average period\n        ma_slow=20,        # Slow moving average period\n        position_ratio=0.95  # Position ratio\n    )\n```\n\n---\n\n## 数据函数\n\n### get_history — 获取最近N根K线\n\n```python\nget_history(count, frequency='1d', field='close', security_list=None, fq=None, include=False, fill='nan', is_dict=False)\n```\n\n```python\n# Get OHLCV data for the last 20 trading days\ndf = get_history(20, '1d', ['open', 'high', 'low', 'close', 'volume'], '600570.SS', fq='pre')\n\n# Bar periods: 1m, 5m, 15m, 30m, 60m, 120m, 1d, 1w\u002Fweekly, mo\u002Fmonthly, 1q\u002Fquarter, 1y\u002Fyearly\n# fq adjustment: None (unadjusted), 'pre' (forward-adjusted), 'post' (backward-adjusted), 'dypre' (dynamic forward-adjusted)\n# Available fields: open, high, low, close, volume, money, price, is_open, preclose, high_limit, low_limit, unlimited (daily only)\n```\n\n### get_price — 按日期范围查询\n\n```python\nget_price(security, start_date=None, end_date=None, frequency='1d', fields=None, fq=None, count=None, is_dict=False)\n```\n\n```python\n# Query by date range\ndf = get_price('600570.SS', start_date='20240101', end_date='20240630', frequency='1d',\n               fields=['open', 'high', 'low', 'close', 'volume'])\n\n# Query by count (last N bars)\ndf = get_price('600570.SS', end_date='20240630', frequency='1d', count=20)\n\n# Multi-stock query\ndf = get_price(['600570.SS', '000001.SZ'], start_date='20240101', end_date='20240630')\n\n# Minute data query\ndf = get_price('600570.SS', start_date='2024-06-01 09:30', end_date='2024-06-01 15:00', frequency='5m')\n```\n\n> ⚠️ `get_history` and `get_price` cannot be called concurrently from different threads (e.g., when `run_daily` and `handle_data` execute simultaneously).\n\n### get_snapshot — 实时行情快照（仅实盘）\n\n```python\nsnapshot = get_snapshot('600570.SS')\n# 收益率 a dict with fields:\n# last_px (latest price), open_px (open price), high_px (high price), low_px (low price), preclose_px (previous close)\n# up_px (upper limit price), down_px (lower limit price), business_amount (total volume), business_balance (total turnover)\n# bid_grp (bid levels: {1:[price,volume,count], 2:...}), offer_grp (ask levels)\n# pe_rate (dynamic P\u002FE ratio), pb_rate (P\u002FB ratio), turnover_ratio (turnover rate), vol_ratio (volume ratio)\n# entrust_rate (order ratio), entrust_diff (order difference), wavg_px (VWAP), px_change_rate (price change %)\n# circulation_amount (circulating shares), trade_status (trading status)\n# business_amount_in (inner volume), business_amount_out (outer volume)\n\n# Multi-stock query\nsnapshots = get_snapshot(['600570.SS', '000001.SZ'])\nprice = snapshots['600570.SS']['last_px']\n```\n\n### get_gear_price — 盘口深度（仅实盘）\n\n```python\ngear = get_gear_price('600570.SS')\n# 收益率: {'bid_grp': {1: [price, volume, count], 2: ...}, 'offer_grp': {1: [price, volume, count], 2: ...}}\nbid1_price, bid1_vol, bid1_count = gear['bid_grp'][1]   # Best bid\nask1_price, ask1_vol, ask1_count = gear['offer_grp'][1] # Best ask\n\n# Multi-stock query\ngears = get_gear_price(['600570.SS', '000001.SZ'])\n```\n\n### Level2数据（需L2权限）\n\n```python\n# Tick-by-tick order data\nentrust = get_individual_entrust(\n    stocks=['600570.SS'],\n    data_count=50,       # Max 200 records\n    start_pos=0,         # Start position\n    search_direction=1,  # 1=forward, 2=backward\n    is_dict=False        # True returns dict format (faster)\n)\n# Fields: business_time (time), hq_px (price), business_amount (volume), order_no (order number),\n#         business_direction (direction: 0=sell, 1=buy), trans_kind (type: 1=market, 2=limit, 3=best)\n\n# Tick-by-tick trade data\ntransaction = get_individual_transaction(\n    stocks=['600570.SS'],\n    data_count=50,\n    is_dict=False\n)\n# Fields: business_time, hq_px, business_amount, trade_index, business_direction, buy_no, sell_no, trans_flag\n```\n\n---\n\n## 股票与参考数据\n\n### 基本信息\n\n```python\nname = get_stock_name('600570.SS')               # Get stock name\ninfo = get_stock_info('600570.SS')                # Get basic information\nstatus = get_stock_status('600570.SS')            # Get status (suspended\u002Flimit up\u002Fdown, etc.)\nexrights = get_stock_exrights('600570.SS')        # Get ex-rights\u002Fex-dividend info\nblocks = get_stock_blocks('600570.SS')            # Get sector\u002Fblock membership\n\nstocks = get_index_stocks('000300.SS')            # Get index constituents\nstocks = get_industry_stocks('银行')              # 获取行业成分股\nstocks = get_Ashares()                            # Get all A-share list\netfs = get_etf_list()                             # Get ETF list\n```\n\n### 可转债数据\n\n```python\ncb_codes = get_cb_list()                          # Get convertible bond code list\ncb_info = get_cb_info()                           # Get convertible bond info DataFrame\n# Fields: bond_code (bond code), bond_name (bond name), stock_code (underlying stock code), stock_name (underlying stock name),\n#         list_date (listing date), premium_rate (premium rate %), convert_date (conversion start date),\n#         maturity_date (maturity date), convert_rate (conversion ratio), convert_price (conversion price), convert_value (conversion value)\n```\n\n### 财务数据\n\n```python\nget_fundamentals(security, table, fields=None, date=None, start_year=None, end_year=None,\n                 report_types=None, date_type=None, merge_type=None)\n```\n\n```python\n# Query by date (returns the latest report data before that date)\ndf = get_fundamentals('600570.SS', 'balance_statement', 'total_assets', date='20240630')\n\n# Query by year range\ndf = get_fundamentals('600570.SS', 'income_statement', fields=['revenue', 'net_profit'],\n                      start_year='2022', end_year='2024')\n\n# report_types: '1'=Q1 report, '2'=semi-annual, '3'=Q3 report, '4'=annual\n# date_type: None=by disclosure date, 1=by accounting period\n# merge_type: None=original data (avoids look-ahead bias), 1=latest revised data\n\n# Available tables: balance_statement, income_statement,\n#                   cash_flow_statement, valuation, indicator\n```\n\n> ⚠️ Rate limit: Max 100 calls per second, max 500 records per call. Add `sleep` for batch queries.\n\n### 交易日历\n\n```python\ntoday = get_trading_day()                         # Get current trading day\nall_days = get_all_trades_days()                  # 获取全部交易日 list\ndays = get_trade_days('2024-01-01', '2024-06-30') # Get trading days in range\n```\n\n---\n\n## 交易函数\n\n### order — 按数量买卖\n\n```python\norder(security, amount, limit_price=None)\n# amount: positive=buy, negative=sell\n# 收益率: order_id (str) or None\n\norder('600570.SS', 100)                           # 买入100股 at latest price\norder('600570.SS', 100, limit_price=39.0)         # 买入100股 at limit price 39.0\norder('600570.SS', -500)                          # Sell 500 shares\norder('131810.SZ', -10)                           # Treasury reverse repo 1000 CNY (10 lots)\n```\n\n### order_target — 调仓到目标数量\n\n```python\norder_target('600570.SS', 1000)                   # Adjust position to 1000 shares\norder_target('600570.SS', 0)                      # Close position\n```\n\n### order_value — 按金额买入\n\n```python\norder_value('600570.SS', 100000)                  # Buy 100,000 CNY worth of stock\n```\n\n### order_target_value — 调仓到目标金额\n\n```python\norder_target_value('600570.SS', 200000)           # Adjust position value to 200,000 CNY\n```\n\n### order_market — 市价单类型（仅实盘）\n\n```python\norder_market(security, amount, market_type, limit_price=None)\n# market_type:\n#   0 = Best counterparty price\n#   1 = Best 5 levels fill, remainder to limit (Shanghai only, requires limit_price)\n#   2 = Best own-side price\n#   3 = Immediate fill, remainder cancel (Shenzhen only)\n#   4 = Best 5 levels fill, remainder cancel\n#   5 = Fill all or cancel (Shenzhen only)\n\norder_market('600570.SS', 100, 0, limit_price=35.0)    # Shanghai: best counterparty + protective limit\norder_market('000001.SZ', 100, 4)                       # Shenzhen: best 5 levels fill, remainder cancel\n```\n\n> ⚠️ Shanghai stocks require `limit_price` when using `order_market`. Convertible bonds are not supported.\n\n### order_tick — Tick触发下单（仅在tick_data中使用）\n\n```python\ndef tick_data(context, data):\n    order_tick('600570.SS', 100, limit_price=39.0)\n```\n\n### cancel_order — 撤单\n\n```python\ncancel_order(order_id)          # 撤单\ncancel_order_ex(order_id)       # Extended cancel order\n```\n\n### 新股申购\n\n```python\nipo_stocks_order()              # One-click IPO stock\u002Fbond subscription\n```\n\n### 盘后固定价格委托\n\n```python\nafter_trading_order('600570.SS', 100)             # After-hours fixed price order\nafter_trading_cancel_order(order_id)              # After-hours cancel order\n```\n\n### ETF操作\n\n```python\n# ETF constituent basket order\netf_basket_order('510050.SS', 1,\n                 price_style='S3',     # B1-B5 (bid levels), S1-S5 (ask levels), 'new' (latest price)\n                 position=True,        # Use existing holdings as substitutes\n                 info={'600000.SS': {'cash_replace_flag': 1, 'position_replace_flag': 1, 'limit_price': 12}})\n\n# ETF creation\u002Fredemption\netf_purchase_redemption('510050.SS', 900000)      # Positive=creation\netf_purchase_redemption('510050.SS', -900000)     # Negative=redemption\n```\n\n---\n\n## 查询函数\n\n### 持仓查询\n\n```python\npos = get_position('600570.SS')\n# Position object: amount (holding quantity), cost_basis (cost price), last_sale_price (latest price), sid (security code), ...\n\npositions = get_positions(['600570.SS', '000001.SZ'])  # 查询持仓 for multiple stocks\n```\n\n### 委托查询\n\n```python\nopen_orders = get_open_orders()                   # Query unfilled orders\norder = get_order(order_id)                       # Query specific order\norders = get_orders()                             # Query all orders today (within strategy)\nall_orders = get_all_orders()                     # Query all orders today (including manual)\ntrades = get_trades()                             # Query today's trades\n```\n\n### 账户信息（通过context）\n\n```python\ncontext.portfolio.cash                            # 可用资金\ncontext.portfolio.total_value                     # 总资产 (cash + position value)\ncontext.portfolio.positions_value                 # 持仓市值\ncontext.portfolio.positions                       # Position dict (Position objects)\ncontext.capital_base                              # Initial capital\ncontext.previous_date                             # Previous trading day\ncontext.blotter.current_dt                        # 当前日期time\n```\n\n---\n\n## 融资融券\n\n### 交易操作\n\n```python\nmargin_trade('600570.SS', 1000, limit_price=39.0) # Collateral buy\u002Fsell\nmargincash_open('600570.SS', 1000, limit_price=39.0)   # Margin buy (borrow cash)\nmargincash_close('600570.SS', 1000, limit_price=40.0)  # Sell to repay margin loan\nmargincash_direct_refund(amount=100000)                 # Direct cash repayment\nmarginsec_open('600570.SS', 1000, limit_price=40.0)    # Short sell (borrow securities)\nmarginsec_close('600570.SS', 1000, limit_price=39.0)   # Buy to return borrowed securities\nmarginsec_direct_refund('600570.SS', 1000)              # Direct securities return\n```\n\n### 查询操作\n\n```python\ncash_stocks = get_margincash_stocks()             # Query margin-eligible stocks (cash borrowing)\nsec_stocks = get_marginsec_stocks()               # Query margin-eligible stocks (securities borrowing)\ncontract = get_margin_contract()                  # Query margin contract\nmargin_asset = get_margin_assert()                # Query margin account assets\nassure_list = get_assure_security_list()           # Query collateral securities list\nmax_buy = get_margincash_open_amount('600570.SS')  # Query max margin buy quantity\nmax_sell = get_margincash_close_amount('600570.SS') # Query max sell-to-repay quantity\nmax_short = get_marginsec_open_amount('600570.SS') # Query max short sell quantity\nmax_cover = get_marginsec_close_amount('600570.SS') # Query max buy-to-cover quantity\n```\n\n---\n\n## 期货交易\n\n### 交易操作\n\n```python\nbuy_open('IF2401.CFX', 1, limit_price=3500.0)     # Long open (buy to open)\nsell_close('IF2401.CFX', 1, limit_price=3550.0)   # Long close (sell to close)\nsell_open('IF2401.CFX', 1, limit_price=3550.0)    # Short open (sell to open)\nbuy_close('IF2401.CFX', 1, limit_price=3500.0)    # Short close (buy to close)\n```\n\n### 查询与设置（回测）\n\n```python\nmargin_rate = get_margin_rate('IF2401.CFX')       # Query margin rate\ninstruments = get_instruments('IF2401.CFX')       # Query contract information\nset_future_commission(0.000023)                   # Set futures commission (backtest only)\nset_margin_rate('IF2401.CFX', 0.15)               # Set margin rate (backtest only)\n```\n\n---\n\n## 内置技术指标\n\n```python\nmacd = get_MACD('600570.SS', N1=12, N2=26, M=9)  # MACD indicator\nkdj = get_KDJ('600570.SS', N=9, M1=3, M2=3)      # KDJ indicator\nrsi = get_RSI('600570.SS', N=14)                  # RSI indicator\ncci = get_CCI('600570.SS', N=14)                  # CCI indicator\n```\n\n---\n\n## 工具函数\n\n```python\nlog.info('message')                               # Logging (also log.warn, log.error)\nis_trade('600570.SS')                             # Check if tradable\ncheck_limit('600570.SS')                          # Check limit up\u002Fdown status\nfreq = get_frequency()                            # Get current strategy execution frequency\n```\n\n### 通知函数\n\n```python\nsend_email(context, subject='Signal', content='Buy 600570', to_address='you@email.com')\nsend_qywx(context, msg='Buy signal triggered')   # WeCom (Enterprise WeChat) notification\n```\n\n---\n\n## 全局对象与上下文\n\n```python\n# g — Global object (persisted across bars, auto-serialized)\ng.my_var = 100\ng.stock_list = ['600570.SS', '000001.SZ']\n# Variables prefixed with '__' are private and will not be persisted:\ng.__my_class_instance = SomeClass()\n\n# context — Strategy context\ncontext.portfolio.cash              # 可用资金\ncontext.portfolio.total_value       # 总资产\ncontext.portfolio.positions_value   # 持仓市值\ncontext.portfolio.positions         # Position dict (Position objects)\ncontext.capital_base                # Initial capital\ncontext.previous_date               # Previous trading day\ncontext.blotter.current_dt          # 当前日期time (datetime.datetime)\n```\n\n---\n\n## 持久化机制\n\nPtrade automatically serializes and saves the `g` object using pickle after `before_trading_start`, `handle_data`, and `after_trading_end` execute. On restart, `initialize` runs first, then persisted data is restored.\n\nCustom persistence example:\n\n```python\nimport pickle\nNOTEBOOK_PATH = get_research_path()\n\ndef initialize(context):\n    # Try to restore persisted data from file\n    try:\n        with open(NOTEBOOK_PATH + 'hold_days.pkl', 'rb') as f:\n            g.hold_days = pickle.load(f)\n    except:\n        g.hold_days = {}  # Initialize as empty dict on first run\n    g.security = '600570.SS'\n    set_universe(g.security)\n\ndef handle_data(context, data):\n    # ... trading logic ...\n    # Save persisted data\n    with open(NOTEBOOK_PATH + 'hold_days.pkl', 'wb') as f:\n        pickle.dump(g.hold_days, f, -1)\n```\n\n> ⚠️ IO objects (open files, class instances) cannot be serialized. Use `g.__private_var` (double underscore prefix) for non-serializable objects.\n\n---\n\n## 策略示例\n\n### 示例1：集合竞价追涨停\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n    # Execute call auction function at 9:23 daily\n    run_daily(context, aggregate_auction_func, time='9:23')\n\ndef aggregate_auction_func(context):\n    stock = g.security\n    # Get real-time snapshot to check if at limit up\n    snapshot = get_snapshot(stock)\n    price = snapshot[stock]['last_px']      # Current price\n    up_limit = snapshot[stock]['up_px']     # Upper limit price\n    if float(price) >= float(up_limit):\n        # Price at upper limit, place buy order at limit-up price\n        order(g.security, 100, limit_price=up_limit)\n\ndef handle_data(context, data):\n    pass\n```\n\n### 示例2：Tick级别均线策略\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n    # Execute strategy function every 3 seconds\n    run_interval(context, func, seconds=3)\n\ndef before_trading_start(context, data):\n    # Pre-market: get last 10 days' close prices for MA calculation\n    history = get_history(10, '1d', 'close', g.security, fq='pre', include=False)\n    g.close_array = history['close'].values\n\ndef func(context):\n    stock = g.security\n    # Get latest price\n    snapshot = get_snapshot(stock)\n    price = snapshot[stock]['last_px']\n    # Calculate 5-day and 10-day MAs (using historical data + current price)\n    ma5 = (g.close_array[-4:].sum() + price) \u002F 5\n    ma10 = (g.close_array[-9:].sum() + price) \u002F 10\n    cash = context.portfolio.cash\n\n    if ma5 > ma10:\n        # 5-day MA above 10-day MA, buy\n        order_value(stock, cash)\n        log.info('Buy %s' % stock)\n    elif ma5 \u003C ma10 and get_position(stock).amount > 0:\n        # 5-day MA below 10-day MA and holding position, sell\n        order_target(stock, 0)\n        log.info('Sell %s' % stock)\n\ndef handle_data(context, data):\n    pass\n```\n\n### 示例3：双均线策略\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n\ndef handle_data(context, data):\n    security = g.security\n    # Get last 20 days' close prices\n    df = get_history(20, '1d', 'close', security, fq=None, include=False)\n    ma5 = df['close'][-5:].mean()      # 5-day MA\n    ma20 = df['close'][-20:].mean()    # 20-day MA\n    current_price = data[security]['close']\n    cash = context.portfolio.cash\n    position = get_position(security)\n\n    # Price breaks above 20-day MA by 1% and no position, buy\n    if current_price > 1.01 * ma20 and position.amount == 0:\n        order_value(security, cash * 0.95)\n        log.info(f'Buy {security}')\n    # Price drops below 5-day MA and holding position, sell\n    elif current_price \u003C ma5 and position.amount > 0:\n        order_target(security, 0)\n        log.info(f'Sell {security}')\n```\n\n### 示例4：盘后逆回购 + 新股申购\n\n```python\ndef initialize(context):\n    g.security = '131810.SZ'           # Shenzhen 1-day treasury reverse repo\n    set_universe(g.security)\n    run_daily(context, reverse_repo, time='14:50')    # Execute reverse repo at 14:50 daily\n    run_daily(context, ipo_subscribe, time='09:31')   # Execute IPO subscription at 09:31 daily\n\ndef reverse_repo(context):\n    cash = context.portfolio.cash\n    lots = int(cash \u002F 1000) * 10       # Calculate lots (100 CNY per lot)\n    if lots >= 10:\n        order(g.security, -lots)       # Negative means reverse repo sell\n        log.info(f'Reverse repo: {lots} lots')\n\ndef ipo_subscribe(context):\n    ipo_stocks_order()                 # One-click subscribe to today's IPOs\n    log.info('IPO subscription submitted')\n\ndef handle_data(context, data):\n    pass\n```\n\n---\n\n## 订单状态码\n\n| 状态码 | 描述 |\n|---|---|\n| 0 | 未报 |\n| 1 | 待报 |\n| 2 | 已报 |\n| 5 | 部分成交 |\n| 6 | 全部成交（回测） |\n| 7 | 部分撤单 |\n| 8 | 全部成交（实盘） |\n| 9 | 废单 |\n| a | 已撤 |\n\n---\n\n## 使用技巧\n\n- Strategies run on **broker intranet servers** — no external network access, cannot `pip install`.\n- Use `g` (global object) to persist variables across functions. Variables prefixed with `__` will not be persisted.\n- Built-in third-party libraries include: pandas, numpy, talib, scipy, sklearn, etc.\n- `handle_data` execution frequency depends on strategy period setting (tick\u002F1m\u002F5m\u002F1d, etc.).\n- Backtest and live trading use the same code — `set_commission`\u002F`set_slippage` only take effect in backtesting.\n- Always add exception handling (`try\u002Fexcept`) in trading strategies to prevent unexpected termination.\n- `get_history` and `get_price` **cannot be called concurrently from different threads**.\n- When using limit orders, ensure price decimal precision matches the asset type.\n- When multiple strategies run concurrently, callback events are **independent of each other**.\n- Use `get_research_path()` for file I\u002FO (CSV, pickle files).\n- Documentation: https:\u002F\u002Fptradeapi.com\n- QMT API Documentation: http:\u002F\u002Fqmt.ptradeapi.com\n\n---\n\n## 进阶示例\n\n### Tick级量价策略 — 大单跟踪\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n    g.big_order_threshold = 500000   # Large order threshold: 500,000 CNY\n    g.buy_signal_count = 0           # Large buy order signal count\n    g.sell_signal_count = 0          # Large sell order signal count\n    g.signal_window = 10             # Signal window (trigger after N accumulated large order signals)\n\ndef tick_data(context, data):\n    \"\"\"Triggered every 3 seconds, analyzes tick-by-tick trade data\"\"\"\n    stock = g.security\n    if stock not in data:\n        return\n\n    tick = data[stock]['tick']\n    trans = data[stock].get('transcation', None)  # Tick-by-tick trades (requires L2 access)\n\n    # 获取当前价格 and price change\n    last_price = tick['last_px']\n    pre_close = tick['preclose_px']\n    change_pct = (last_price - pre_close) \u002F pre_close * 100\n\n    if trans is not None and len(trans) > 0:\n        # Analyze large orders in tick-by-tick trades\n        for _, row in trans.iterrows():\n            amount = row['hq_px'] * row['business_amount']  # Trade value\n            if amount >= g.big_order_threshold:\n                direction = 'Buy' if row['business_direction'] == 1 else 'Sell'\n                log.info(f'Large {direction} order: {amount\u002F10000:.1f}0k CNY @ {row[\"hq_px\"]}')\n                if row['business_direction'] == 1:\n                    g.buy_signal_count += 1\n                else:\n                    g.sell_signal_count += 1\n\n    # Accumulated large buy signals reach threshold and no position, buy\n    position = get_position(stock)\n    cash = context.portfolio.cash\n\n    if g.buy_signal_count >= g.signal_window and position.amount == 0:\n        order_value(stock, cash * 0.9)\n        log.info(f'Large order tracking buy: accumulated {g.buy_signal_count} large buy orders')\n        g.buy_signal_count = 0\n        g.sell_signal_count = 0\n\n    # Accumulated large sell signals reach threshold and holding position, sell\n    elif g.sell_signal_count >= g.signal_window and position.amount > 0:\n        order_target(stock, 0)\n        log.info(f'Large order tracking sell: accumulated {g.sell_signal_count} large sell orders')\n        g.buy_signal_count = 0\n        g.sell_signal_count = 0\n\ndef handle_data(context, data):\n    pass\n\ndef after_trading_end(context, data):\n    # Reset signal counts after market close each day\n    g.buy_signal_count = 0\n    g.sell_signal_count = 0\n    log.info('Signal counts reset')\n```\n\n### ETF套利策略 — 溢价\u002F折价监控与交易\n\n```python\ndef initialize(context):\n    g.etf_code = '510050.SS'       # SSE 50 ETF\n    set_universe(g.etf_code)\n    g.premium_threshold = 0.005    # Premium threshold 0.5% (short ETF when premium exceeds this)\n    g.discount_threshold = -0.005  # Discount threshold -0.5% (long ETF when discount exceeds this)\n    g.min_unit = 900000            # ETF minimum creation\u002Fredemption unit (shares)\n    # Check premium\u002Fdiscount every 10 seconds\n    run_interval(context, check_premium, seconds=10)\n\ndef check_premium(context):\n    \"\"\"Check ETF premium\u002Fdiscount rate and execute arbitrage\"\"\"\n    etf = g.etf_code\n    snapshot = get_snapshot(etf)\n    if etf not in snapshot:\n        return\n\n    etf_price = snapshot[etf]['last_px']       # ETF market price\n    # Note: Actual IOPV needs to be calculated from ETF creation\u002Fredemption list; simplified here\n    # In real scenarios, use the iopv field from get_snapshot (if provided by broker)\n    nav_estimate = snapshot[etf].get('iopv', etf_price)  # ETF NAV estimate\n\n    if nav_estimate \u003C= 0 or etf_price \u003C= 0:\n        return\n\n    # Calculate premium\u002Fdiscount rate\n    premium_rate = (etf_price - nav_estimate) \u002F nav_estimate\n    log.info(f'ETF price={etf_price:.4f}, NAV={nav_estimate:.4f}, premium\u002Fdiscount={premium_rate*100:.3f}%')\n\n    position = get_position(etf)\n    cash = context.portfolio.cash\n\n    if premium_rate > g.premium_threshold:\n        # Premium arbitrage: Create ETF → Sell ETF\n        # Step 1: Buy constituent basket and create ETF\n        if cash > nav_estimate * g.min_unit:\n            etf_basket_order(etf, 1, price_style='S1', position=True)\n            log.info(f'Premium arbitrage: create ETF basket, premium rate={premium_rate*100:.3f}%')\n            # Step 2: Sell ETF (need to wait for creation to complete, sell in next cycle)\n\n    elif premium_rate \u003C g.discount_threshold:\n        # Discount arbitrage: Buy ETF → Redeem ETF → Sell constituents\n        if cash > etf_price * g.min_unit:\n            order(etf, g.min_unit, limit_price=etf_price)\n            log.info(f'Discount arbitrage: buy ETF, discount rate={premium_rate*100:.3f}%')\n            # Follow-up: Redeem ETF and sell constituent stocks\n\ndef handle_data(context, data):\n    pass\n```\n\n### 可转债T+0日内交易策略\n\n```python\ndef initialize(context):\n    # Convertible bonds support T+0 trading\n    g.cb_list = []                  # Convertible bond pool (dynamically updated)\n    g.intraday_profit = 0.003      # Intraday target profit 0.3%\n    g.stop_loss = -0.005           # Intraday stop loss -0.5%\n    g.max_hold_value = 100000      # Max holding value per convertible bond\n    set_universe(['110059.SS'])     # Example: SPDB convertible bond\n    run_interval(context, intraday_trade, seconds=10)\n\ndef before_trading_start(context, data):\n    # Pre-market: screen convertible bonds with low premium and active trading\n    cb_info = get_cb_info()\n    if cb_info is not None and len(cb_info) > 0:\n        # Filter: premium rate \u003C 20% and already listed\n        filtered = cb_info[cb_info['premium_rate'] \u003C 20]\n        g.cb_list = filtered['bond_code'].tolist()[:10]  # Take top 10\n        log.info(f'Today\\'s CB pool: {len(g.cb_list)} bonds')\n\ndef intraday_trade(context):\n    \"\"\"Intraday T+0 trading logic\"\"\"\n    for cb_code in g.cb_list[:5]:  # Monitor max 5 at a time\n        try:\n            snapshot = get_snapshot(cb_code)\n            if cb_code not in snapshot:\n                continue\n\n            price = snapshot[cb_code]['last_px']\n            pre_close = snapshot[cb_code]['preclose_px']\n            change_pct = (price - pre_close) \u002F pre_close if pre_close > 0 else 0\n\n            position = get_position(cb_code)\n            hold_amount = position.amount if position else 0\n\n            if hold_amount > 0:\n                # Holding position: check if take-profit or stop-loss triggered\n                cost = position.cost_basis\n                pnl = (price - cost) \u002F cost if cost > 0 else 0\n\n                if pnl >= g.intraday_profit:\n                    # Take profit (convertible bonds are T+0, can sell same day)\n                    order_target(cb_code, 0)\n                    log.info(f'CB take profit: {cb_code} profit {pnl*100:.2f}%')\n                elif pnl \u003C= g.stop_loss:\n                    # Stop loss\n                    order_target(cb_code, 0)\n                    log.info(f'CB stop loss: {cb_code} loss {pnl*100:.2f}%')\n            else:\n                # No position: look for buy opportunities\n                # Simple strategy: buy on small pullback (change between -1% and 0%)\n                if -0.01 \u003C change_pct \u003C 0:\n                    buy_value = min(g.max_hold_value, context.portfolio.cash * 0.2)\n                    if buy_value > 1000:\n                        order_value(cb_code, buy_value)\n                        log.info(f'CB buy: {cb_code} @ {price:.3f}')\n        except Exception as e:\n            log.error(f'CB trading error: {cb_code}, {str(e)}')\n\ndef handle_data(context, data):\n    pass\n```\n\n### 定时任务综合策略 — 盘前选股 + 盘中交易 + 盘后总结\n\n```python\nimport pickle\n\nNOTEBOOK_PATH = get_research_path()\n\ndef initialize(context):\n    g.stock_pool = []              # Today's stock pool\n    g.traded_today = False         # Whether traded today\n    set_universe(['000300.SS'])    # Benchmark: CSI 300\n\n    # Schedule tasks\n    run_daily(context, morning_select, time='09:25')    # Pre-market stock selection\n    run_daily(context, morning_trade, time='09:35')     # Opening trade\n    run_daily(context, noon_check, time='13:05')        # Midday check\n    run_daily(context, afternoon_close, time='14:50')   # End-of-day operations\n\ndef morning_select(context):\n    \"\"\"Pre-market stock selection: screen stocks based on previous day's data\"\"\"\n    # 获取沪深300成分股\n    hs300 = get_index_stocks('000300.SS')\n\n    candidates = []\n    for stock in hs300[:50]:  # Process 50 at a time to avoid timeout\n        try:\n            # Get last 20 days' bars\n            df = get_history(20, '1d', ['close', 'volume'], stock, fq='pre', include=False)\n            if len(df) \u003C 20:\n                continue\n\n            close = df['close'].values\n            volume = df['volume'].values\n\n            # Selection criteria:\n            # 1. 5-day MA > 20-day MA (uptrend)\n            ma5 = close[-5:].mean()\n            ma20 = close.mean()\n            if ma5 \u003C= ma20:\n                continue\n\n            # 2. Recent 5-day volume increase (volume ratio > 1.2)\n            vol_5d = volume[-5:].mean()\n            vol_20d = volume.mean()\n            if vol_5d \u002F vol_20d \u003C 1.2:\n                continue\n\n            # 3. Price near 20-day MA (within 5%)\n            if abs(close[-1] - ma20) \u002F ma20 > 0.05:\n                continue\n\n            candidates.append({\n                'stock': stock,\n                'ma5': ma5,\n                'ma20': ma20,\n                'vol_ratio': vol_5d \u002F vol_20d\n            })\n        except:\n            continue\n\n    # Sort by volume ratio, select top 5\n    candidates.sort(key=lambda x: x['vol_ratio'], reverse=True)\n    g.stock_pool = [c['stock'] for c in candidates[:5]]\n    g.traded_today = False\n    log.info(f'Pre-market selection complete: {g.stock_pool}')\n\ndef morning_trade(context):\n    \"\"\"Opening trade: buy selected stocks\"\"\"\n    if g.traded_today or not g.stock_pool:\n        return\n\n    cash = context.portfolio.cash\n    per_stock_value = cash * 0.9 \u002F len(g.stock_pool)  # Equal-weight allocation\n\n    for stock in g.stock_pool:\n        try:\n            if not is_trade(stock):\n                continue\n            # Check if at limit up (don't buy at limit up)\n            status = check_limit(stock)\n            if status == 1:  # Limit up\n                continue\n            order_value(stock, per_stock_value)\n            log.info(f'Buy: {stock}, value={per_stock_value:.0f}')\n        except Exception as e:\n            log.error(f'Buy error: {stock}, {str(e)}')\n\n    g.traded_today = True\n\ndef noon_check(context):\n    \"\"\"Midday check: stop loss and exception handling\"\"\"\n    positions = context.portfolio.positions\n    for stock, pos in positions.items():\n        if pos.amount \u003C= 0:\n            continue\n        # Calculate P&L\n        pnl = (pos.last_sale_price - pos.cost_basis) \u002F pos.cost_basis if pos.cost_basis > 0 else 0\n        if pnl \u003C -0.03:\n            # Loss exceeds 3%, midday stop loss\n            order_target(stock, 0)\n            log.info(f'Midday stop loss: {stock}, loss={pnl*100:.2f}%')\n\ndef afternoon_close(context):\n    \"\"\"End-of-day operations: summarize today's P&L\"\"\"\n    total_value = context.portfolio.total_value\n    cash = context.portfolio.cash\n    positions = context.portfolio.positions\n\n    log.info(f'=== End-of-Day Summary ===')\n    log.info(f'Total assets: {total_value:.2f}')\n    log.info(f'Available cash: {cash:.2f}')\n    log.info(f'Number of positions: {len([p for p in positions.values() if p.amount > 0])}')\n\n    for stock, pos in positions.items():\n        if pos.amount > 0:\n            pnl = (pos.last_sale_price - pos.cost_basis) \u002F pos.cost_basis * 100\n            log.info(f'  {stock}: {pos.amount} shares, cost={pos.cost_basis:.2f}, '\n                     f'price={pos.last_sale_price:.2f}, P&L={pnl:.2f}%')\n\n    # Persist trade log\n    try:\n        with open(NOTEBOOK_PATH + 'trade_log.pkl', 'rb') as f:\n            trade_log = pickle.load(f)\n    except:\n        trade_log = []\n\n    trade_log.append({\n        'date': str(context.blotter.current_dt),\n        'total_value': total_value,\n        'cash': cash,\n        'stock_pool': g.stock_pool\n    })\n\n    with open(NOTEBOOK_PATH + 'trade_log.pkl', 'wb') as f:\n        pickle.dump(trade_log, f, -1)\n\ndef handle_data(context, data):\n    pass\n```\n\n### 多策略并行 — MACD + KDJ双信号确认\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n\ndef handle_data(context, data):\n    stock = g.security\n    # Get last 60 days' bar data\n    df = get_history(60, '1d', ['open', 'high', 'low', 'close', 'volume'], stock, fq='pre')\n    if len(df) \u003C 60:\n        return\n\n    close = df['close'].values\n    high = df['high'].values\n    low = df['low'].values\n\n    # 计算MACD指标\n    macd = get_MACD(stock, N1=12, N2=26, M=9)\n    dif = macd['DIF']\n    dea = macd['DEA']\n    macd_hist = macd['MACD']\n\n    # Calculate KDJ indicator\n    kdj = get_KDJ(stock, N=9, M1=3, M2=3)\n    k_value = kdj['K']\n    d_value = kdj['D']\n    j_value = kdj['J']\n\n    # Calculate RSI indicator\n    rsi = get_RSI(stock, N=14)\n    rsi_value = rsi['RSI']\n\n    position = get_position(stock)\n    cash = context.portfolio.cash\n    current_price = data[stock]['close']\n\n    # Buy conditions (triple confirmation):\n    # 1. MACD golden cross (DIF crosses above DEA)\n    # 2. KDJ golden cross (K crosses above D) and J \u003C 80 (not overbought)\n    # 3. RSI between 30-70 (not in extreme zone)\n    macd_golden = dif > dea  # Simplified check\n    kdj_golden = k_value > d_value and j_value \u003C 80\n    rsi_normal = 30 \u003C rsi_value \u003C 70\n\n    if macd_golden and kdj_golden and rsi_normal and position.amount == 0:\n        order_value(stock, cash * 0.95)\n        log.info(f'Buy signal: MACD golden cross + KDJ golden cross + RSI normal, DIF={dif:.2f}, K={k_value:.1f}, RSI={rsi_value:.1f}')\n\n    # Sell conditions (any one triggers):\n    # 1. MACD death cross (DIF crosses below DEA)\n    # 2. KDJ overbought (J > 100)\n    # 3. RSI overbought (RSI > 80)\n    elif position.amount > 0:\n        if dif \u003C dea or j_value > 100 or rsi_value > 80:\n            reason = []\n            if dif \u003C dea: reason.append('MACD death cross')\n            if j_value > 100: reason.append(f'KDJ overbought J={j_value:.1f}')\n            if rsi_value > 80: reason.append(f'RSI overbought={rsi_value:.1f}')\n            order_target(stock, 0)\n            log.info(f'Sell signal: {\"+\".join(reason)}')\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","# Ptrade（恒生量化交易平台）\n\n[Ptrade](https:\u002F\u002Fptradeapi.com) 是恒生电子开发的专业量化交易平台。策略运行在**券商服务器**（内网）上，低延迟执行。采用事件驱动的Python策略框架。\n\n> ⚠️ **需要券商开通Ptrade权限**。策略运行在券商云端——无法访问外网。不能pip安装，仅可使用内置第三方库。\n\n## 支持的市场和业务类型\n\n**回测支持：**\n1. 普通股票交易（单位：股）\n2. 可转债交易（单位：张，T+0）\n3. 融资融券担保品买卖（单位：股）\n4. 期货投机交易（单位：手，T+0）\n5. LOF基金交易（单位：份）\n6. ETF基金交易（单位：份）\n\n**实盘交易支持：**\n1. 普通股票交易（单位：股）\n2. 可转债交易（T+0）\n3. 融资融券交易（单位：股）\n4. ETF申赎、套利（单位：份）\n5. 国债逆回购（单位：份）\n6. 期货投机交易（单位：手，T+0）\n7. ETF基金交易（单位：份）\n\n**默认支持Level2十档行情**。部分券商提供免费L2逐笔数据。\n\n### 价格精度规则\n\n| 资产类型 | 最小变动单位 | 小数位数 |\n|---|---|---|\n| 股票 | 0.01 | 2 |\n| 可转债 | 0.001 | 3 |\n| LOF \u002F ETF | 0.001 | 3 |\n| 国债逆回购 | 0.005 | 3 |\n| 股指期货 | 0.2 | 1 |\n| 国债期货 | 0.005 | 3 |\n| ETF期权 | 0.0001 | 4 |\n\n> ⚠️ 使用 `limit_price` 下单时，价格必须符合正确的小数精度，否则订单将被拒绝。\n\n## 股票代码格式\n\n- Shanghai: `600570.SS`\n- Shenzhen: `000001.SZ`\n- Index: `000300.SS` (CSI 300)\n\n---\n\n## 策略生命周期（事件驱动）\n\n```python\ndef initialize(context):\n    \"\"\"Required — Called once at startup. Used to set stock pool, benchmark, and scheduled tasks.\"\"\"\n    g.security = '600570.SS'\n    set_universe(g.security)\n\ndef before_trading_start(context, data):\n    \"\"\"Optional — Called before market open.\n    Backtest mode: Executes at 8:30 each trading day.\n    Live mode: Executes immediately on first start, then at 9:10 daily (default, broker-configurable).\"\"\"\n    log.info('Pre-market preparation')\n\ndef handle_data(context, data):\n    \"\"\"Required — Triggered on each bar.\n    Daily mode: Executes once at 14:50 daily (default).\n    Minute mode: Executes at each minute bar close.\n    data[sid] provides: open, high, low, close, price, volume, money.\"\"\"\n    current_price = data[g.security]['close']\n    cash = context.portfolio.cash\n\ndef after_trading_end(context, data):\n    \"\"\"Optional — Called at 15:30 after market close.\"\"\"\n    log.info('Trading day ended')\n\ndef tick_data(context, data):\n    \"\"\"Optional — Triggered every 3 seconds during market hours (9:30-14:59, live only).\n    Must use order_tick() to place orders in this function.\n    data format: {stock_code: {'order': DataFrame\u002FNone, 'tick': DataFrame, 'transcation': DataFrame\u002FNone}}\"\"\"\n    for stock, d in data.items():\n        tick = d['tick']\n        price = tick['last_px']           # Latest price\n        bid1 = tick['bid_grp'][1]         # Best bid [price, volume, count]\n        ask1 = tick['offer_grp'][1]       # Best ask [price, volume, count]\n        log.info(f'{stock}: {price}, upper_limit={tick[\"up_px\"]}, lower_limit={tick[\"down_px\"]}')\n        # Level2 fields (requires L2 access, otherwise None):\n        order_data = d['order']           # Tick-by-tick orders\n        trans_data = d['transcation']     # Tick-by-tick trades\n\ndef on_order_response(context, order_list):\n    \"\"\"Optional — Triggered on order status changes (faster than get_orders).\n    order_list is a list of dicts containing: entrust_no, stock_code, amount, price,\n    business_amount, status, order_id, entrust_type, entrust_prop, error_info, order_time.\"\"\"\n    for o in order_list:\n        log.info(f'Order {o[\"stock_code\"]}: status={o[\"status\"]}, filled={o[\"business_amount\"]}\u002F{o[\"amount\"]}')\n\ndef on_trade_response(context, trade_list):\n    \"\"\"Optional — Triggered on trade execution (faster than get_trades).\n    trade_list is a list of dicts containing: entrust_no, stock_code, business_amount,\n    business_price, business_balance, business_id, status, order_id, entrust_bs, business_time.\n    Note: status=9 means rejected order.\"\"\"\n    for t in trade_list:\n        direction = 'Buy' if t['entrust_bs'] == '1' else 'Sell'\n        log.info(f'{direction} {t[\"stock_code\"]}: {t[\"business_amount\"]}@{t[\"business_price\"]}')\n```\n\n### 策略执行频率\n\n| 模式 | 频率 | 执行时间 |\n|---|---|---|\n| **日线** | 每日一次 | 回测: 15:00, 实盘: 14:50（可配置） |\n| **分钟** | 每分钟一次 | 每根分钟K线收盘时 |\n| **Tick** | 每3秒 | 9:30–14:59，通过 `tick_data` 或 `run_interval` |\n\n### 时间参考\n\n| 阶段 | 时间 | 可用函数 |\n|---|---|---|\n| **盘前** | 9:30之前 | `before_trading_start`, `run_daily(time='09:15')` |\n| **盘中** | 9:30–15:00 | `handle_data`, `run_daily`, `run_interval`, `tick_data` |\n| **盘后** | 15:30 | `after_trading_end`, `run_daily(time='15:10')` |\n\n---\n\n## 初始化设置函数（仅在initialize中使用）\n\n### 股票池与基准\n\n```python\ndef initialize(context):\n    set_universe(['600570.SS', '000001.SZ'])   # Required: Set stock pool\n    set_benchmark('000300.SS')                  # Backtest benchmark index\n```\n\n### 手续费与滑点（仅回测）\n\n```python\ndef initialize(context):\n    # 设置手续费: buy 0.03%, sell 0.13% (incl. stamp tax), based on trade value, min 5 CNY\n    set_commission(PerTrade(buy_cost=0.0003, sell_cost=0.0013, unit='perValue', min_cost=5))\n    set_slippage(FixedSlippage(0.02))           # 固定滑点 of 0.02 CNY\n    set_volume_ratio(0.025)                     # Max fill ratio of daily volume\n    set_limit_mode(0)                           # 0=limit by volume ratio, 1=limit by fixed quantity\n```\n\n### 定时任务\n\n```python\ndef initialize(context):\n    # run_daily: Execute function at specified time each day\n    run_daily(context, my_morning_task, time='09:31')\n    run_daily(context, my_afternoon_task, time='14:50')\n\n    # run_interval: Execute function every N seconds (live only, min 3 seconds)\n    run_interval(context, my_tick_handler, seconds=10)\n```\n\n### 策略参数（可从UI配置）\n\n```python\ndef initialize(context):\n    # Set parameters that can be dynamically modified from the Ptrade UI without code changes\n    set_parameters(\n        context,\n        ma_fast=5,         # Fast moving average period\n        ma_slow=20,        # Slow moving average period\n        position_ratio=0.95  # Position ratio\n    )\n```\n\n---\n\n## 数据函数\n\n### get_history — 获取最近N根K线\n\n```python\nget_history(count, frequency='1d', field='close', security_list=None, fq=None, include=False, fill='nan', is_dict=False)\n```\n\n```python\n# Get OHLCV data for the last 20 trading days\ndf = get_history(20, '1d', ['open', 'high', 'low', 'close', 'volume'], '600570.SS', fq='pre')\n\n# Bar periods: 1m, 5m, 15m, 30m, 60m, 120m, 1d, 1w\u002Fweekly, mo\u002Fmonthly, 1q\u002Fquarter, 1y\u002Fyearly\n# fq adjustment: None (unadjusted), 'pre' (forward-adjusted), 'post' (backward-adjusted), 'dypre' (dynamic forward-adjusted)\n# Available fields: open, high, low, close, volume, money, price, is_open, preclose, high_limit, low_limit, unlimited (daily only)\n```\n\n### get_price — 按日期范围查询\n\n```python\nget_price(security, start_date=None, end_date=None, frequency='1d', fields=None, fq=None, count=None, is_dict=False)\n```\n\n```python\n# Query by date range\ndf = get_price('600570.SS', start_date='20240101', end_date='20240630', frequency='1d',\n               fields=['open', 'high', 'low', 'close', 'volume'])\n\n# Query by count (last N bars)\ndf = get_price('600570.SS', end_date='20240630', frequency='1d', count=20)\n\n# Multi-stock query\ndf = get_price(['600570.SS', '000001.SZ'], start_date='20240101', end_date='20240630')\n\n# Minute data query\ndf = get_price('600570.SS', start_date='2024-06-01 09:30', end_date='2024-06-01 15:00', frequency='5m')\n```\n\n> ⚠️ `get_history` and `get_price` cannot be called concurrently from different threads (e.g., when `run_daily` and `handle_data` execute simultaneously).\n\n### get_snapshot — 实时行情快照（仅实盘）\n\n```python\nsnapshot = get_snapshot('600570.SS')\n# 收益率 a dict with fields:\n# last_px (latest price), open_px (open price), high_px (high price), low_px (low price), preclose_px (previous close)\n# up_px (upper limit price), down_px (lower limit price), business_amount (total volume), business_balance (total turnover)\n# bid_grp (bid levels: {1:[price,volume,count], 2:...}), offer_grp (ask levels)\n# pe_rate (dynamic P\u002FE ratio), pb_rate (P\u002FB ratio), turnover_ratio (turnover rate), vol_ratio (volume ratio)\n# entrust_rate (order ratio), entrust_diff (order difference), wavg_px (VWAP), px_change_rate (price change %)\n# circulation_amount (circulating shares), trade_status (trading status)\n# business_amount_in (inner volume), business_amount_out (outer volume)\n\n# Multi-stock query\nsnapshots = get_snapshot(['600570.SS', '000001.SZ'])\nprice = snapshots['600570.SS']['last_px']\n```\n\n### get_gear_price — 盘口深度（仅实盘）\n\n```python\ngear = get_gear_price('600570.SS')\n# 收益率: {'bid_grp': {1: [price, volume, count], 2: ...}, 'offer_grp': {1: [price, volume, count], 2: ...}}\nbid1_price, bid1_vol, bid1_count = gear['bid_grp'][1]   # Best bid\nask1_price, ask1_vol, ask1_count = gear['offer_grp'][1] # Best ask\n\n# Multi-stock query\ngears = get_gear_price(['600570.SS', '000001.SZ'])\n```\n\n### Level2数据（需L2权限）\n\n```python\n# Tick-by-tick order data\nentrust = get_individual_entrust(\n    stocks=['600570.SS'],\n    data_count=50,       # Max 200 records\n    start_pos=0,         # Start position\n    search_direction=1,  # 1=forward, 2=backward\n    is_dict=False        # True returns dict format (faster)\n)\n# Fields: business_time (time), hq_px (price), business_amount (volume), order_no (order number),\n#         business_direction (direction: 0=sell, 1=buy), trans_kind (type: 1=market, 2=limit, 3=best)\n\n# Tick-by-tick trade data\ntransaction = get_individual_transaction(\n    stocks=['600570.SS'],\n    data_count=50,\n    is_dict=False\n)\n# Fields: business_time, hq_px, business_amount, trade_index, business_direction, buy_no, sell_no, trans_flag\n```\n\n---\n\n## 股票与参考数据\n\n### 基本信息\n\n```python\nname = get_stock_name('600570.SS')               # Get stock name\ninfo = get_stock_info('600570.SS')                # Get basic information\nstatus = get_stock_status('600570.SS')            # Get status (suspended\u002Flimit up\u002Fdown, etc.)\nexrights = get_stock_exrights('600570.SS')        # Get ex-rights\u002Fex-dividend info\nblocks = get_stock_blocks('600570.SS')            # Get sector\u002Fblock membership\n\nstocks = get_index_stocks('000300.SS')            # Get index constituents\nstocks = get_industry_stocks('银行')              # 获取行业成分股\nstocks = get_Ashares()                            # Get all A-share list\netfs = get_etf_list()                             # Get ETF list\n```\n\n### 可转债数据\n\n```python\ncb_codes = get_cb_list()                          # Get convertible bond code list\ncb_info = get_cb_info()                           # Get convertible bond info DataFrame\n# Fields: bond_code (bond code), bond_name (bond name), stock_code (underlying stock code), stock_name (underlying stock name),\n#         list_date (listing date), premium_rate (premium rate %), convert_date (conversion start date),\n#         maturity_date (maturity date), convert_rate (conversion ratio), convert_price (conversion price), convert_value (conversion value)\n```\n\n### 财务数据\n\n```python\nget_fundamentals(security, table, fields=None, date=None, start_year=None, end_year=None,\n                 report_types=None, date_type=None, merge_type=None)\n```\n\n```python\n# Query by date (returns the latest report data before that date)\ndf = get_fundamentals('600570.SS', 'balance_statement', 'total_assets', date='20240630')\n\n# Query by year range\ndf = get_fundamentals('600570.SS', 'income_statement', fields=['revenue', 'net_profit'],\n                      start_year='2022', end_year='2024')\n\n# report_types: '1'=Q1 report, '2'=semi-annual, '3'=Q3 report, '4'=annual\n# date_type: None=by disclosure date, 1=by accounting period\n# merge_type: None=original data (avoids look-ahead bias), 1=latest revised data\n\n# Available tables: balance_statement, income_statement,\n#                   cash_flow_statement, valuation, indicator\n```\n\n> ⚠️ Rate limit: Max 100 calls per second, max 500 records per call. Add `sleep` for batch queries.\n\n### 交易日历\n\n```python\ntoday = get_trading_day()                         # Get current trading day\nall_days = get_all_trades_days()                  # 获取全部交易日 list\ndays = get_trade_days('2024-01-01', '2024-06-30') # Get trading days in range\n```\n\n---\n\n## 交易函数\n\n### order — 按数量买卖\n\n```python\norder(security, amount, limit_price=None)\n# amount: positive=buy, negative=sell\n# 收益率: order_id (str) or None\n\norder('600570.SS', 100)                           # 买入100股 at latest price\norder('600570.SS', 100, limit_price=39.0)         # 买入100股 at limit price 39.0\norder('600570.SS', -500)                          # Sell 500 shares\norder('131810.SZ', -10)                           # Treasury reverse repo 1000 CNY (10 lots)\n```\n\n### order_target — 调仓到目标数量\n\n```python\norder_target('600570.SS', 1000)                   # Adjust position to 1000 shares\norder_target('600570.SS', 0)                      # Close position\n```\n\n### order_value — 按金额买入\n\n```python\norder_value('600570.SS', 100000)                  # Buy 100,000 CNY worth of stock\n```\n\n### order_target_value — 调仓到目标金额\n\n```python\norder_target_value('600570.SS', 200000)           # Adjust position value to 200,000 CNY\n```\n\n### order_market — 市价单类型（仅实盘）\n\n```python\norder_market(security, amount, market_type, limit_price=None)\n# market_type:\n#   0 = Best counterparty price\n#   1 = Best 5 levels fill, remainder to limit (Shanghai only, requires limit_price)\n#   2 = Best own-side price\n#   3 = Immediate fill, remainder cancel (Shenzhen only)\n#   4 = Best 5 levels fill, remainder cancel\n#   5 = Fill all or cancel (Shenzhen only)\n\norder_market('600570.SS', 100, 0, limit_price=35.0)    # Shanghai: best counterparty + protective limit\norder_market('000001.SZ', 100, 4)                       # Shenzhen: best 5 levels fill, remainder cancel\n```\n\n> ⚠️ Shanghai stocks require `limit_price` when using `order_market`. Convertible bonds are not supported.\n\n### order_tick — Tick触发下单（仅在tick_data中使用）\n\n```python\ndef tick_data(context, data):\n    order_tick('600570.SS', 100, limit_price=39.0)\n```\n\n### cancel_order — 撤单\n\n```python\ncancel_order(order_id)          # 撤单\ncancel_order_ex(order_id)       # Extended cancel order\n```\n\n### 新股申购\n\n```python\nipo_stocks_order()              # One-click IPO stock\u002Fbond subscription\n```\n\n### 盘后固定价格委托\n\n```python\nafter_trading_order('600570.SS', 100)             # After-hours fixed price order\nafter_trading_cancel_order(order_id)              # After-hours cancel order\n```\n\n### ETF操作\n\n```python\n# ETF constituent basket order\netf_basket_order('510050.SS', 1,\n                 price_style='S3',     # B1-B5 (bid levels), S1-S5 (ask levels), 'new' (latest price)\n                 position=True,        # Use existing holdings as substitutes\n                 info={'600000.SS': {'cash_replace_flag': 1, 'position_replace_flag': 1, 'limit_price': 12}})\n\n# ETF creation\u002Fredemption\netf_purchase_redemption('510050.SS', 900000)      # Positive=creation\netf_purchase_redemption('510050.SS', -900000)     # Negative=redemption\n```\n\n---\n\n## 查询函数\n\n### 持仓查询\n\n```python\npos = get_position('600570.SS')\n# Position object: amount (holding quantity), cost_basis (cost price), last_sale_price (latest price), sid (security code), ...\n\npositions = get_positions(['600570.SS', '000001.SZ'])  # 查询持仓 for multiple stocks\n```\n\n### 委托查询\n\n```python\nopen_orders = get_open_orders()                   # Query unfilled orders\norder = get_order(order_id)                       # Query specific order\norders = get_orders()                             # Query all orders today (within strategy)\nall_orders = get_all_orders()                     # Query all orders today (including manual)\ntrades = get_trades()                             # Query today's trades\n```\n\n### 账户信息（通过context）\n\n```python\ncontext.portfolio.cash                            # 可用资金\ncontext.portfolio.total_value                     # 总资产 (cash + position value)\ncontext.portfolio.positions_value                 # 持仓市值\ncontext.portfolio.positions                       # Position dict (Position objects)\ncontext.capital_base                              # Initial capital\ncontext.previous_date                             # Previous trading day\ncontext.blotter.current_dt                        # 当前日期time\n```\n\n---\n\n## 融资融券\n\n### 交易操作\n\n```python\nmargin_trade('600570.SS', 1000, limit_price=39.0) # Collateral buy\u002Fsell\nmargincash_open('600570.SS', 1000, limit_price=39.0)   # Margin buy (borrow cash)\nmargincash_close('600570.SS', 1000, limit_price=40.0)  # Sell to repay margin loan\nmargincash_direct_refund(amount=100000)                 # Direct cash repayment\nmarginsec_open('600570.SS', 1000, limit_price=40.0)    # Short sell (borrow securities)\nmarginsec_close('600570.SS', 1000, limit_price=39.0)   # Buy to return borrowed securities\nmarginsec_direct_refund('600570.SS', 1000)              # Direct securities return\n```\n\n### 查询操作\n\n```python\ncash_stocks = get_margincash_stocks()             # Query margin-eligible stocks (cash borrowing)\nsec_stocks = get_marginsec_stocks()               # Query margin-eligible stocks (securities borrowing)\ncontract = get_margin_contract()                  # Query margin contract\nmargin_asset = get_margin_assert()                # Query margin account assets\nassure_list = get_assure_security_list()           # Query collateral securities list\nmax_buy = get_margincash_open_amount('600570.SS')  # Query max margin buy quantity\nmax_sell = get_margincash_close_amount('600570.SS') # Query max sell-to-repay quantity\nmax_short = get_marginsec_open_amount('600570.SS') # Query max short sell quantity\nmax_cover = get_marginsec_close_amount('600570.SS') # Query max buy-to-cover quantity\n```\n\n---\n\n## 期货交易\n\n### 交易操作\n\n```python\nbuy_open('IF2401.CFX', 1, limit_price=3500.0)     # Long open (buy to open)\nsell_close('IF2401.CFX', 1, limit_price=3550.0)   # Long close (sell to close)\nsell_open('IF2401.CFX', 1, limit_price=3550.0)    # Short open (sell to open)\nbuy_close('IF2401.CFX', 1, limit_price=3500.0)    # Short close (buy to close)\n```\n\n### 查询与设置（回测）\n\n```python\nmargin_rate = get_margin_rate('IF2401.CFX')       # Query margin rate\ninstruments = get_instruments('IF2401.CFX')       # Query contract information\nset_future_commission(0.000023)                   # Set futures commission (backtest only)\nset_margin_rate('IF2401.CFX', 0.15)               # Set margin rate (backtest only)\n```\n\n---\n\n## 内置技术指标\n\n```python\nmacd = get_MACD('600570.SS', N1=12, N2=26, M=9)  # MACD indicator\nkdj = get_KDJ('600570.SS', N=9, M1=3, M2=3)      # KDJ indicator\nrsi = get_RSI('600570.SS', N=14)                  # RSI indicator\ncci = get_CCI('600570.SS', N=14)                  # CCI indicator\n```\n\n---\n\n## 工具函数\n\n```python\nlog.info('message')                               # Logging (also log.warn, log.error)\nis_trade('600570.SS')                             # Check if tradable\ncheck_limit('600570.SS')                          # Check limit up\u002Fdown status\nfreq = get_frequency()                            # Get current strategy execution frequency\n```\n\n### 通知函数\n\n```python\nsend_email(context, subject='Signal', content='Buy 600570', to_address='you@email.com')\nsend_qywx(context, msg='Buy signal triggered')   # WeCom (Enterprise WeChat) notification\n```\n\n---\n\n## 全局对象与上下文\n\n```python\n# g — Global object (persisted across bars, auto-serialized)\ng.my_var = 100\ng.stock_list = ['600570.SS', '000001.SZ']\n# Variables prefixed with '__' are private and will not be persisted:\ng.__my_class_instance = SomeClass()\n\n# context — Strategy context\ncontext.portfolio.cash              # 可用资金\ncontext.portfolio.total_value       # 总资产\ncontext.portfolio.positions_value   # 持仓市值\ncontext.portfolio.positions         # Position dict (Position objects)\ncontext.capital_base                # Initial capital\ncontext.previous_date               # Previous trading day\ncontext.blotter.current_dt          # 当前日期time (datetime.datetime)\n```\n\n---\n\n## 持久化机制\n\nPtrade automatically serializes and saves the `g` object using pickle after `before_trading_start`, `handle_data`, and `after_trading_end` execute. On restart, `initialize` runs first, then persisted data is restored.\n\nCustom persistence example:\n\n```python\nimport pickle\nNOTEBOOK_PATH = get_research_path()\n\ndef initialize(context):\n    # Try to restore persisted data from file\n    try:\n        with open(NOTEBOOK_PATH + 'hold_days.pkl', 'rb') as f:\n            g.hold_days = pickle.load(f)\n    except:\n        g.hold_days = {}  # Initialize as empty dict on first run\n    g.security = '600570.SS'\n    set_universe(g.security)\n\ndef handle_data(context, data):\n    # ... trading logic ...\n    # Save persisted data\n    with open(NOTEBOOK_PATH + 'hold_days.pkl', 'wb') as f:\n        pickle.dump(g.hold_days, f, -1)\n```\n\n> ⚠️ IO objects (open files, class instances) cannot be serialized. Use `g.__private_var` (double underscore prefix) for non-serializable objects.\n\n---\n\n## 策略示例\n\n### 示例1：集合竞价追涨停\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n    # Execute call auction function at 9:23 daily\n    run_daily(context, aggregate_auction_func, time='9:23')\n\ndef aggregate_auction_func(context):\n    stock = g.security\n    # Get real-time snapshot to check if at limit up\n    snapshot = get_snapshot(stock)\n    price = snapshot[stock]['last_px']      # Current price\n    up_limit = snapshot[stock]['up_px']     # Upper limit price\n    if float(price) >= float(up_limit):\n        # Price at upper limit, place buy order at limit-up price\n        order(g.security, 100, limit_price=up_limit)\n\ndef handle_data(context, data):\n    pass\n```\n\n### 示例2：Tick级别均线策略\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n    # Execute strategy function every 3 seconds\n    run_interval(context, func, seconds=3)\n\ndef before_trading_start(context, data):\n    # Pre-market: get last 10 days' close prices for MA calculation\n    history = get_history(10, '1d', 'close', g.security, fq='pre', include=False)\n    g.close_array = history['close'].values\n\ndef func(context):\n    stock = g.security\n    # Get latest price\n    snapshot = get_snapshot(stock)\n    price = snapshot[stock]['last_px']\n    # Calculate 5-day and 10-day MAs (using historical data + current price)\n    ma5 = (g.close_array[-4:].sum() + price) \u002F 5\n    ma10 = (g.close_array[-9:].sum() + price) \u002F 10\n    cash = context.portfolio.cash\n\n    if ma5 > ma10:\n        # 5-day MA above 10-day MA, buy\n        order_value(stock, cash)\n        log.info('Buy %s' % stock)\n    elif ma5 \u003C ma10 and get_position(stock).amount > 0:\n        # 5-day MA below 10-day MA and holding position, sell\n        order_target(stock, 0)\n        log.info('Sell %s' % stock)\n\ndef handle_data(context, data):\n    pass\n```\n\n### 示例3：双均线策略\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n\ndef handle_data(context, data):\n    security = g.security\n    # Get last 20 days' close prices\n    df = get_history(20, '1d', 'close', security, fq=None, include=False)\n    ma5 = df['close'][-5:].mean()      # 5-day MA\n    ma20 = df['close'][-20:].mean()    # 20-day MA\n    current_price = data[security]['close']\n    cash = context.portfolio.cash\n    position = get_position(security)\n\n    # Price breaks above 20-day MA by 1% and no position, buy\n    if current_price > 1.01 * ma20 and position.amount == 0:\n        order_value(security, cash * 0.95)\n        log.info(f'Buy {security}')\n    # Price drops below 5-day MA and holding position, sell\n    elif current_price \u003C ma5 and position.amount > 0:\n        order_target(security, 0)\n        log.info(f'Sell {security}')\n```\n\n### 示例4：盘后逆回购 + 新股申购\n\n```python\ndef initialize(context):\n    g.security = '131810.SZ'           # Shenzhen 1-day treasury reverse repo\n    set_universe(g.security)\n    run_daily(context, reverse_repo, time='14:50')    # Execute reverse repo at 14:50 daily\n    run_daily(context, ipo_subscribe, time='09:31')   # Execute IPO subscription at 09:31 daily\n\ndef reverse_repo(context):\n    cash = context.portfolio.cash\n    lots = int(cash \u002F 1000) * 10       # Calculate lots (100 CNY per lot)\n    if lots >= 10:\n        order(g.security, -lots)       # Negative means reverse repo sell\n        log.info(f'Reverse repo: {lots} lots')\n\ndef ipo_subscribe(context):\n    ipo_stocks_order()                 # One-click subscribe to today's IPOs\n    log.info('IPO subscription submitted')\n\ndef handle_data(context, data):\n    pass\n```\n\n---\n\n## 订单状态码\n\n| 状态码 | 描述 |\n|---|---|\n| 0 | 未报 |\n| 1 | 待报 |\n| 2 | 已报 |\n| 5 | 部分成交 |\n| 6 | 全部成交（回测） |\n| 7 | 部分撤单 |\n| 8 | 全部成交（实盘） |\n| 9 | 废单 |\n| a | 已撤 |\n\n---\n\n## 使用技巧\n\n- Strategies run on **broker intranet servers** — no external network access, cannot `pip install`.\n- Use `g` (global object) to persist variables across functions. Variables prefixed with `__` will not be persisted.\n- Built-in third-party libraries include: pandas, numpy, talib, scipy, sklearn, etc.\n- `handle_data` execution frequency depends on strategy period setting (tick\u002F1m\u002F5m\u002F1d, etc.).\n- Backtest and live trading use the same code — `set_commission`\u002F`set_slippage` only take effect in backtesting.\n- Always add exception handling (`try\u002Fexcept`) in trading strategies to prevent unexpected termination.\n- `get_history` and `get_price` **cannot be called concurrently from different threads**.\n- When using limit orders, ensure price decimal precision matches the asset type.\n- When multiple strategies run concurrently, callback events are **independent of each other**.\n- Use `get_research_path()` for file I\u002FO (CSV, pickle files).\n- Documentation: https:\u002F\u002Fptradeapi.com\n- QMT API Documentation: http:\u002F\u002Fqmt.ptradeapi.com\n\n---\n\n## 进阶示例\n\n### Tick级量价策略 — 大单跟踪\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n    g.big_order_threshold = 500000   # Large order threshold: 500,000 CNY\n    g.buy_signal_count = 0           # Large buy order signal count\n    g.sell_signal_count = 0          # Large sell order signal count\n    g.signal_window = 10             # Signal window (trigger after N accumulated large order signals)\n\ndef tick_data(context, data):\n    \"\"\"Triggered every 3 seconds, analyzes tick-by-tick trade data\"\"\"\n    stock = g.security\n    if stock not in data:\n        return\n\n    tick = data[stock]['tick']\n    trans = data[stock].get('transcation', None)  # Tick-by-tick trades (requires L2 access)\n\n    # 获取当前价格 and price change\n    last_price = tick['last_px']\n    pre_close = tick['preclose_px']\n    change_pct = (last_price - pre_close) \u002F pre_close * 100\n\n    if trans is not None and len(trans) > 0:\n        # Analyze large orders in tick-by-tick trades\n        for _, row in trans.iterrows():\n            amount = row['hq_px'] * row['business_amount']  # Trade value\n            if amount >= g.big_order_threshold:\n                direction = 'Buy' if row['business_direction'] == 1 else 'Sell'\n                log.info(f'Large {direction} order: {amount\u002F10000:.1f}0k CNY @ {row[\"hq_px\"]}')\n                if row['business_direction'] == 1:\n                    g.buy_signal_count += 1\n                else:\n                    g.sell_signal_count += 1\n\n    # Accumulated large buy signals reach threshold and no position, buy\n    position = get_position(stock)\n    cash = context.portfolio.cash\n\n    if g.buy_signal_count >= g.signal_window and position.amount == 0:\n        order_value(stock, cash * 0.9)\n        log.info(f'Large order tracking buy: accumulated {g.buy_signal_count} large buy orders')\n        g.buy_signal_count = 0\n        g.sell_signal_count = 0\n\n    # Accumulated large sell signals reach threshold and holding position, sell\n    elif g.sell_signal_count >= g.signal_window and position.amount > 0:\n        order_target(stock, 0)\n        log.info(f'Large order tracking sell: accumulated {g.sell_signal_count} large sell orders')\n        g.buy_signal_count = 0\n        g.sell_signal_count = 0\n\ndef handle_data(context, data):\n    pass\n\ndef after_trading_end(context, data):\n    # Reset signal counts after market close each day\n    g.buy_signal_count = 0\n    g.sell_signal_count = 0\n    log.info('Signal counts reset')\n```\n\n### ETF套利策略 — 溢价\u002F折价监控与交易\n\n```python\ndef initialize(context):\n    g.etf_code = '510050.SS'       # SSE 50 ETF\n    set_universe(g.etf_code)\n    g.premium_threshold = 0.005    # Premium threshold 0.5% (short ETF when premium exceeds this)\n    g.discount_threshold = -0.005  # Discount threshold -0.5% (long ETF when discount exceeds this)\n    g.min_unit = 900000            # ETF minimum creation\u002Fredemption unit (shares)\n    # Check premium\u002Fdiscount every 10 seconds\n    run_interval(context, check_premium, seconds=10)\n\ndef check_premium(context):\n    \"\"\"Check ETF premium\u002Fdiscount rate and execute arbitrage\"\"\"\n    etf = g.etf_code\n    snapshot = get_snapshot(etf)\n    if etf not in snapshot:\n        return\n\n    etf_price = snapshot[etf]['last_px']       # ETF market price\n    # Note: Actual IOPV needs to be calculated from ETF creation\u002Fredemption list; simplified here\n    # In real scenarios, use the iopv field from get_snapshot (if provided by broker)\n    nav_estimate = snapshot[etf].get('iopv', etf_price)  # ETF NAV estimate\n\n    if nav_estimate \u003C= 0 or etf_price \u003C= 0:\n        return\n\n    # Calculate premium\u002Fdiscount rate\n    premium_rate = (etf_price - nav_estimate) \u002F nav_estimate\n    log.info(f'ETF price={etf_price:.4f}, NAV={nav_estimate:.4f}, premium\u002Fdiscount={premium_rate*100:.3f}%')\n\n    position = get_position(etf)\n    cash = context.portfolio.cash\n\n    if premium_rate > g.premium_threshold:\n        # Premium arbitrage: Create ETF → Sell ETF\n        # Step 1: Buy constituent basket and create ETF\n        if cash > nav_estimate * g.min_unit:\n            etf_basket_order(etf, 1, price_style='S1', position=True)\n            log.info(f'Premium arbitrage: create ETF basket, premium rate={premium_rate*100:.3f}%')\n            # Step 2: Sell ETF (need to wait for creation to complete, sell in next cycle)\n\n    elif premium_rate \u003C g.discount_threshold:\n        # Discount arbitrage: Buy ETF → Redeem ETF → Sell constituents\n        if cash > etf_price * g.min_unit:\n            order(etf, g.min_unit, limit_price=etf_price)\n            log.info(f'Discount arbitrage: buy ETF, discount rate={premium_rate*100:.3f}%')\n            # Follow-up: Redeem ETF and sell constituent stocks\n\ndef handle_data(context, data):\n    pass\n```\n\n### 可转债T+0日内交易策略\n\n```python\ndef initialize(context):\n    # Convertible bonds support T+0 trading\n    g.cb_list = []                  # Convertible bond pool (dynamically updated)\n    g.intraday_profit = 0.003      # Intraday target profit 0.3%\n    g.stop_loss = -0.005           # Intraday stop loss -0.5%\n    g.max_hold_value = 100000      # Max holding value per convertible bond\n    set_universe(['110059.SS'])     # Example: SPDB convertible bond\n    run_interval(context, intraday_trade, seconds=10)\n\ndef before_trading_start(context, data):\n    # Pre-market: screen convertible bonds with low premium and active trading\n    cb_info = get_cb_info()\n    if cb_info is not None and len(cb_info) > 0:\n        # Filter: premium rate \u003C 20% and already listed\n        filtered = cb_info[cb_info['premium_rate'] \u003C 20]\n        g.cb_list = filtered['bond_code'].tolist()[:10]  # Take top 10\n        log.info(f'Today\\'s CB pool: {len(g.cb_list)} bonds')\n\ndef intraday_trade(context):\n    \"\"\"Intraday T+0 trading logic\"\"\"\n    for cb_code in g.cb_list[:5]:  # Monitor max 5 at a time\n        try:\n            snapshot = get_snapshot(cb_code)\n            if cb_code not in snapshot:\n                continue\n\n            price = snapshot[cb_code]['last_px']\n            pre_close = snapshot[cb_code]['preclose_px']\n            change_pct = (price - pre_close) \u002F pre_close if pre_close > 0 else 0\n\n            position = get_position(cb_code)\n            hold_amount = position.amount if position else 0\n\n            if hold_amount > 0:\n                # Holding position: check if take-profit or stop-loss triggered\n                cost = position.cost_basis\n                pnl = (price - cost) \u002F cost if cost > 0 else 0\n\n                if pnl >= g.intraday_profit:\n                    # Take profit (convertible bonds are T+0, can sell same day)\n                    order_target(cb_code, 0)\n                    log.info(f'CB take profit: {cb_code} profit {pnl*100:.2f}%')\n                elif pnl \u003C= g.stop_loss:\n                    # Stop loss\n                    order_target(cb_code, 0)\n                    log.info(f'CB stop loss: {cb_code} loss {pnl*100:.2f}%')\n            else:\n                # No position: look for buy opportunities\n                # Simple strategy: buy on small pullback (change between -1% and 0%)\n                if -0.01 \u003C change_pct \u003C 0:\n                    buy_value = min(g.max_hold_value, context.portfolio.cash * 0.2)\n                    if buy_value > 1000:\n                        order_value(cb_code, buy_value)\n                        log.info(f'CB buy: {cb_code} @ {price:.3f}')\n        except Exception as e:\n            log.error(f'CB trading error: {cb_code}, {str(e)}')\n\ndef handle_data(context, data):\n    pass\n```\n\n### 定时任务综合策略 — 盘前选股 + 盘中交易 + 盘后总结\n\n```python\nimport pickle\n\nNOTEBOOK_PATH = get_research_path()\n\ndef initialize(context):\n    g.stock_pool = []              # Today's stock pool\n    g.traded_today = False         # Whether traded today\n    set_universe(['000300.SS'])    # Benchmark: CSI 300\n\n    # Schedule tasks\n    run_daily(context, morning_select, time='09:25')    # Pre-market stock selection\n    run_daily(context, morning_trade, time='09:35')     # Opening trade\n    run_daily(context, noon_check, time='13:05')        # Midday check\n    run_daily(context, afternoon_close, time='14:50')   # End-of-day operations\n\ndef morning_select(context):\n    \"\"\"Pre-market stock selection: screen stocks based on previous day's data\"\"\"\n    # 获取沪深300成分股\n    hs300 = get_index_stocks('000300.SS')\n\n    candidates = []\n    for stock in hs300[:50]:  # Process 50 at a time to avoid timeout\n        try:\n            # Get last 20 days' bars\n            df = get_history(20, '1d', ['close', 'volume'], stock, fq='pre', include=False)\n            if len(df) \u003C 20:\n                continue\n\n            close = df['close'].values\n            volume = df['volume'].values\n\n            # Selection criteria:\n            # 1. 5-day MA > 20-day MA (uptrend)\n            ma5 = close[-5:].mean()\n            ma20 = close.mean()\n            if ma5 \u003C= ma20:\n                continue\n\n            # 2. Recent 5-day volume increase (volume ratio > 1.2)\n            vol_5d = volume[-5:].mean()\n            vol_20d = volume.mean()\n            if vol_5d \u002F vol_20d \u003C 1.2:\n                continue\n\n            # 3. Price near 20-day MA (within 5%)\n            if abs(close[-1] - ma20) \u002F ma20 > 0.05:\n                continue\n\n            candidates.append({\n                'stock': stock,\n                'ma5': ma5,\n                'ma20': ma20,\n                'vol_ratio': vol_5d \u002F vol_20d\n            })\n        except:\n            continue\n\n    # Sort by volume ratio, select top 5\n    candidates.sort(key=lambda x: x['vol_ratio'], reverse=True)\n    g.stock_pool = [c['stock'] for c in candidates[:5]]\n    g.traded_today = False\n    log.info(f'Pre-market selection complete: {g.stock_pool}')\n\ndef morning_trade(context):\n    \"\"\"Opening trade: buy selected stocks\"\"\"\n    if g.traded_today or not g.stock_pool:\n        return\n\n    cash = context.portfolio.cash\n    per_stock_value = cash * 0.9 \u002F len(g.stock_pool)  # Equal-weight allocation\n\n    for stock in g.stock_pool:\n        try:\n            if not is_trade(stock):\n                continue\n            # Check if at limit up (don't buy at limit up)\n            status = check_limit(stock)\n            if status == 1:  # Limit up\n                continue\n            order_value(stock, per_stock_value)\n            log.info(f'Buy: {stock}, value={per_stock_value:.0f}')\n        except Exception as e:\n            log.error(f'Buy error: {stock}, {str(e)}')\n\n    g.traded_today = True\n\ndef noon_check(context):\n    \"\"\"Midday check: stop loss and exception handling\"\"\"\n    positions = context.portfolio.positions\n    for stock, pos in positions.items():\n        if pos.amount \u003C= 0:\n            continue\n        # Calculate P&L\n        pnl = (pos.last_sale_price - pos.cost_basis) \u002F pos.cost_basis if pos.cost_basis > 0 else 0\n        if pnl \u003C -0.03:\n            # Loss exceeds 3%, midday stop loss\n            order_target(stock, 0)\n            log.info(f'Midday stop loss: {stock}, loss={pnl*100:.2f}%')\n\ndef afternoon_close(context):\n    \"\"\"End-of-day operations: summarize today's P&L\"\"\"\n    total_value = context.portfolio.total_value\n    cash = context.portfolio.cash\n    positions = context.portfolio.positions\n\n    log.info(f'=== End-of-Day Summary ===')\n    log.info(f'Total assets: {total_value:.2f}')\n    log.info(f'Available cash: {cash:.2f}')\n    log.info(f'Number of positions: {len([p for p in positions.values() if p.amount > 0])}')\n\n    for stock, pos in positions.items():\n        if pos.amount > 0:\n            pnl = (pos.last_sale_price - pos.cost_basis) \u002F pos.cost_basis * 100\n            log.info(f'  {stock}: {pos.amount} shares, cost={pos.cost_basis:.2f}, '\n                     f'price={pos.last_sale_price:.2f}, P&L={pnl:.2f}%')\n\n    # Persist trade log\n    try:\n        with open(NOTEBOOK_PATH + 'trade_log.pkl', 'rb') as f:\n            trade_log = pickle.load(f)\n    except:\n        trade_log = []\n\n    trade_log.append({\n        'date': str(context.blotter.current_dt),\n        'total_value': total_value,\n        'cash': cash,\n        'stock_pool': g.stock_pool\n    })\n\n    with open(NOTEBOOK_PATH + 'trade_log.pkl', 'wb') as f:\n        pickle.dump(trade_log, f, -1)\n\ndef handle_data(context, data):\n    pass\n```\n\n### 多策略并行 — MACD + KDJ双信号确认\n\n```python\ndef initialize(context):\n    g.security = '600570.SS'\n    set_universe(g.security)\n\ndef handle_data(context, data):\n    stock = g.security\n    # Get last 60 days' bar data\n    df = get_history(60, '1d', ['open', 'high', 'low', 'close', 'volume'], stock, fq='pre')\n    if len(df) \u003C 60:\n        return\n\n    close = df['close'].values\n    high = df['high'].values\n    low = df['low'].values\n\n    # 计算MACD指标\n    macd = get_MACD(stock, N1=12, N2=26, M=9)\n    dif = macd['DIF']\n    dea = macd['DEA']\n    macd_hist = macd['MACD']\n\n    # Calculate KDJ indicator\n    kdj = get_KDJ(stock, N=9, M1=3, M2=3)\n    k_value = kdj['K']\n    d_value = kdj['D']\n    j_value = kdj['J']\n\n    # Calculate RSI indicator\n    rsi = get_RSI(stock, N=14)\n    rsi_value = rsi['RSI']\n\n    position = get_position(stock)\n    cash = context.portfolio.cash\n    current_price = data[stock]['close']\n\n    # Buy conditions (triple confirmation):\n    # 1. MACD golden cross (DIF crosses above DEA)\n    # 2. KDJ golden cross (K crosses above D) and J \u003C 80 (not overbought)\n    # 3. RSI between 30-70 (not in extreme zone)\n    macd_golden = dif > dea  # Simplified check\n    kdj_golden = k_value > d_value and j_value \u003C 80\n    rsi_normal = 30 \u003C rsi_value \u003C 70\n\n    if macd_golden and kdj_golden and rsi_normal and position.amount == 0:\n        order_value(stock, cash * 0.95)\n        log.info(f'Buy signal: MACD golden cross + KDJ golden cross + RSI normal, DIF={dif:.2f}, K={k_value:.1f}, RSI={rsi_value:.1f}')\n\n    # Sell conditions (any one triggers):\n    # 1. MACD death cross (DIF crosses below DEA)\n    # 2. KDJ overbought (J > 100)\n    # 3. RSI overbought (RSI > 80)\n    elif position.amount > 0:\n        if dif \u003C dea or j_value > 100 or rsi_value > 80:\n            reason = []\n            if dif \u003C dea: reason.append('MACD death cross')\n            if j_value > 100: reason.append(f'KDJ overbought J={j_value:.1f}')\n            if rsi_value > 80: reason.append(f'RSI overbought={rsi_value:.1f}')\n            order_target(stock, 0)\n            log.info(f'Sell signal: {\"+\".join(reason)}')\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","https:\u002F\u002Fptradeapi.com",{"clawdbot":27},{"emoji":28,"requires":29},"🏦",{"bins":30},[31],"python3","master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fp\u002Fptrade",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 ptrade",{"tool":47,"command":48},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill ptrade",{"tool":50,"command":51},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill ptrade","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fp\u002Fptrade\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",[],[]]