### Context Now Return Example Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of the datetime object returned by context.now. ```python 2020-09-01 09:40:00+08:00 ``` -------------------------------- ### Convertible Bond Data Acquisition/Trading Example Source: https://www.myquant.cn/docs2/sdk/python/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B.html This example shows how to get convertible bond basic information and historical market data. It also includes examples for placing orders for convertible bonds and subscribing to their real-time tick data. Note that convertible bond put, call, and put cancellation operations require a live brokerage environment and are not available in simulation backtesting. ```python # coding=utf-8 from __future__ import print_function, absolute_import from gm.api import * def init(context): # 获取可转债基本信息,输入可转债代码即可 infos = get_symbol_infos(sec_type1=1030, symbols='SHSE.113038', df=True) # 输入可转债标的代码,可以获取到历史行情 history_data = history(symbol='SHSE.113038', frequency='60s', start_time='2021-02-24 14:50:00', end_time='2021-02-24 15:30:30', adjust=ADJUST_PREV, df=True) # 可转债回售、转股、转股撤销,需要券商实盘环境,仿真回测不可用。 # bond_convertible_call('SHSE.110051', 100, 0) # bond_convertible_put('SHSE.183350', 100, 0) # bond_convertible_put_cancel('SHSE.183350', 100) # 可转债下单,仅将symbol替换为可转债标的代码即可 order_volume(symbol='SZSE.128041', volume=100, side=OrderSide_Buy, order_type=OrderType_Limit, position_effect=PositionEffect_Open, price=340) # 直接获取委托,可以看到相应的可转债委托,普通买卖通过标的体现可转债交易,转股、回售、回售撤销通过order_business字段的枚举值不同来体现。 order_list = get_orders() # 订阅可转债行情。与股票无异 subscribe(symbols='SHSE.113038', frequency='tick', count=2) def on_tick(context, tick): # 打印频率为tick,可转债最新tick print(tick) if __name__ == '__main__': run(strategy_id='strategy_id', filename='main.py', mode=MODE_LIVE, token='token_id', backtest_start_time='2020-12-16 09:00:00', backtest_end_time='2020-12-16 09:15:00', backtest_adjust=ADJUST_PREV, backtest_initial_cash=10000000, backtest_commission_ratio=0.0001, backtest_slippage_ratio=0.0001 ) 复制成功 ``` -------------------------------- ### Example Output for stk_quota_shszhk_infos Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E8%82%A1%E7%A5%A8%E5%A2%9E%E5%80%BC%E6%95%B0%E6%8D%AE%E5%87%BD%E6%95%B0%EF%BC%88%E4%BB%98%E8%B4%B9%EF%BC%89.html This is an example of the output format when retrieving沪深港通 quota data. The keys in the dictionary correspond to the fields described in the function documentation. ```python [ {'type': 'SHHK', 'trade_date': '2024-01-23', 'daily_quota': 420.0, 'day_balance': 433.3, 'day_used': -13.3, 'day_used_rate': -3.167, 'day_buy_amount': 63.4454, 'day_buy_volume': 179494.0, 'day_sell_amount': 86.4077, 'day_sell_volume': 216835.0, 'settle_exrate_buy': 0.9209, 'settle_exrate_sell': 0.9225, 'day_net_amount': -22.9623} ] ``` -------------------------------- ### Example Output of stk_get_fundamentals_cashflow Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E8%82%A1%E7%A5%A8%E8%B4%A2%E5%8A%A1%E6%95%B0%E6%8D%AE%E5%8F%8A%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE%E5%87%BD%E6%95%B0%EF%BC%88%E5%85%8D%E8%B4%B9%EF%BC%89.html This is an example of the output format when `df=True` is used, returning a pandas DataFrame with cash flow data. ```python symbol pub_date rpt_date rpt_type data_type cash_pay_fee 0 SHSE.600000 2022-10-29 2022-09-30 9 101 7261000000.00 ``` -------------------------------- ### Order Percent Return Example - Python Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E4%BA%A4%E6%98%93%E5%87%BD%E6%95%B0.html This example shows the structure of the return object for the order_percent function. It includes details on the order's execution, such as filled volume and value. ```python [] {'strategy_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'account_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'cl_ord_id': '000000000', 'symbol': 'SHSE.600000', 'side': 1, 'position_effect': 1, 'position_side': 1, 'order_type': 1, 'status': 3, 'price': 11.0, 'order_style': 1, 'volume': 18181800, 'value': 200000000.0, 'percent': 0.1, 'target_volume': 18181800, 'target_value': 199999800.0, 'target_percent': 0.0999999, 'filled_volume': 18181800, 'filled_vwap': 11.0011, 'filled_amount': 200019799.98, 'created_at': datetime.datetime(2020, 9, 1, 9, 40, tzinfo=tzfile('PRC')), 'updated_at': datetime.datetime(2020, 9, 1, 9, 40, tzinfo=tzfile('PRC')), 'filled_commission': 20001.979998, 'account_name': '', 'order_id': '', 'ex_ord_id': '', 'algo_order_id': '', 'order_business': 0, 'order_duration': 0, 'order_qualifier': 0, 'order_src': 0, 'position_src': 0, 'ord_rej_reason': 0, 'ord_rej_reason_detail': '', 'stop_price': 0.0} ``` -------------------------------- ### Example Output of Daily Basic Stock Data Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E8%82%A1%E7%A5%A8%E8%B4%A2%E5%8A%A1%E6%95%B0%E6%8D%AE%E5%8F%8A%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE%E5%87%BD%E6%95%B0%EF%BC%88%E5%85%8D%E8%B4%B9%EF%BC%89.html This is an example of the output format when querying daily basic stock data with `df=True`, returning a pandas DataFrame. ```python symbol trade_date turnrate tclose ttl_shr 0 SZSE.000001 2023-06-27 0.2379 11.28 1.9406e+10 1 SZSE.300002 2023-06-27 7.3596 13.44 1.9611e+09 ``` -------------------------------- ### Example Output for Continuous Contracts Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E6%9C%9F%E8%B4%A7%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE%E5%87%BD%E6%95%B0%EF%BC%88%E5%85%8D%E8%B4%B9%EF%BC%89.html This is an example of the output format when querying continuous contracts. Each entry shows the specific contract symbol and the trade date it corresponds to. ```json [{'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-01'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-02'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-05'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-06'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-07'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-08'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-09'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-13'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-14'}, {'symbol': 'SHFE.ni2210', 'trade_date': '2022-09-15'}] ``` -------------------------------- ### fnd_get_share Output Example Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E5%9F%BA%E9%87%91%E5%A2%9E%E5%80%BC%E6%95%B0%E6%8D%AE%E5%87%BD%E6%95%B0%EF%BC%88%E4%BB%98%E8%B4%B9%EF%BC%89.html This is an example of the output returned by the `fnd_get_share` function, showing fund code, trade date, publication date, and current scale. ```python fund trade_date pub_date \ 0 SHSE.510300 2024-11-01T00:00:00+08:00 2024-11-01T00:00:00+08:00 1 SHSE.510300 2024-11-04T00:00:00+08:00 2024-11-04T00:00:00+08:00 2 SHSE.510300 2024-11-05T00:00:00+08:00 2024-11-05T00:00:00+08:00 3 SHSE.510300 2024-11-06T00:00:00+08:00 2024-11-06T00:00:00+08:00 4 SHSE.510300 2024-11-07T00:00:00+08:00 2024-11-07T00:00:00+08:00 5 SHSE.510300 2024-11-08T00:00:00+08:00 2024-11-08T00:00:00+08:00 6 SHSE.510300 2024-11-11T00:00:00+08:00 2024-11-11T00:00:00+08:00 7 SHSE.510300 2024-11-12T00:00:00+08:00 2024-11-12T00:00:00+08:00 8 SHSE.510300 2024-11-13T00:00:00+08:00 2024-11-13T00:00:00+08:00 9 SHSE.510300 2024-11-14T00:00:00+08:00 2024-11-14T00:00:00+08:00 10 SHSE.510300 2024-11-15T00:00:00+08:00 2024-11-15T00:00:00+08:00 11 SHSE.510300 2024-11-18T00:00:00+08:00 2024-11-18T00:00:00+08:00 12 SHSE.510300 2024-11-19T00:00:00+08:00 2024-11-19T00:00:00+08:00 13 SHSE.510300 2024-11-20T00:00:00+08:00 2024-11-20T00:00:00+08:00 14 SHSE.510300 2024-11-21T00:00:00+08:00 2024-11-21T00:00:00+08:00 15 SHSE.510300 2024-11-22T00:00:00+08:00 2024-11-22T00:00:00+08:00 share 0 94878487700.0 1 94926187700.0 2 95349187700.0 3 95259187700.0 4 95871187700.0 5 95310487700.0 6 94261087700.0 7 93306187700.0 8 92872387700.0 9 92568187700.0 10 92709487700.0 11 92480887700.0 12 92370187700.0 13 91457587700.0 14 91029187700.0 15 90434287700.0 ``` -------------------------------- ### Order Return Example - Python Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E4%BA%A4%E6%98%93%E5%87%BD%E6%95%B0.html This is an example of the return object when using the order_value function. It details the order's status, filled quantities, and timestamps. ```python [] {'strategy_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'account_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'cl_ord_id': '000000000', 'symbol': 'SHSE.600000', 'side': 1, 'position_effect': 1, 'position_side': 1, 'order_type': 1, 'status': 3, 'price': 11.0, 'order_style': 1, 'volume': 9000, 'value': 100000.0, 'percent': 5e-05, 'target_volume': 9000, 'target_value': 99000.0, 'target_percent': 4.95e-05, 'filled_volume': 9000, 'filled_vwap': 11.0011, 'filled_amount': 99009.9, 'created_at': datetime.datetime(2020, 9, 1, 9, 40, tzinfo=tzfile('PRC')), 'updated_at': datetime.datetime(2020, 9, 1, 9, 40, tzinfo=tzfile('PRC')), 'filled_commission': 9.90099, 'account_name': '', 'order_id': '', 'ex_ord_id': '', 'algo_order_id': '', 'order_business': 0, 'order_duration': 0, 'order_qualifier': 0, 'order_src': 0, 'position_src': 0, 'ord_rej_reason': 0, 'ord_rej_reason_detail': '', 'stop_price': 0.0} ``` -------------------------------- ### Example Output of stk_hk_inst_holding_info Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E8%82%A1%E7%A5%A8%E5%A2%9E%E5%80%BC%E6%95%B0%E6%8D%AE%E5%87%BD%E6%95%B0%EF%BC%88%E4%BB%98%E8%B4%B9%EF%BC%89.html This is an example of the output format when `df` is set to `False`. Each dictionary in the list represents holding information for a specific stock on a given trade date. ```json [{'symbol': 'SHSE.600008', 'trade_date': '2024-01-25', 'sec_name': '首创环保', 'cum_share_holding': 132319140, 'cum_shares_rate': 1.71}, {'symbol': 'SZSE.000002', 'trade_date': '2024-01-25', 'sec_name': '万科A', 'cum_share_holding': 228964226, 'cum_shares_rate': 2.23}] ``` -------------------------------- ### Python - Batch Order Response Example Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E4%BA%A4%E6%98%93%E5%87%BD%E6%95%B0.html Example of the response structure when submitting a batch of orders. Each item in the list represents a processed order with its execution details. ```python {'strategy_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'account_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'cl_ord_id': '000000000', 'symbol': 'SHSE.600000', 'side': 1, 'position_effect': 1, 'order_type': 2, 'status': 3, 'price': 10.280000686645508, 'order_style': 1, 'volume': 100, 'filled_volume': 100, 'filled_vwap': 10.281028686714173, 'filled_amount': 1028.1028686714174, 'created_at': datetime.datetime(2020, 9, 1, 9, 40, tzinfo=tzfile('PRC')), 'updated_at': datetime.datetime(2020, 9, 1, 9, 40, tzinfo=tzfile('PRC')), 'filled_commission': 0.10281028686714173, 'account_name': '', 'order_id': '', 'ex_ord_id': '', 'algo_order_id': '', 'position_side': 0, 'order_business': 0, 'order_duration': 0, 'order_qualifier': 0, 'order_src': 0, 'position_src': 0, 'ord_rej_reason': 0, 'ord_rej_reason_detail': '', 'stop_price': 0.0, 'value': 0.0, 'percent': 0.0, 'target_volume': 0, 'target_value': 0.0, 'target_percent': 0.0} {'strategy_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'account_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'cl_ord_id': '000000001', 'symbol': 'SHSE.600004', 'side': 1, 'position_effect': 1, 'order_type': 2, 'status': 3, 'price': 15.050000190734863, 'order_style': 1, 'volume': 100, 'filled_volume': 100, 'filled_vwap': 15.051505190753936, 'filled_amount': 1505.1505190753935, 'created_at': datetime.datetime(2020, 9, 1, 9, 40, tzinfo=tzfile('PRC')), 'updated_at': datetime.datetime(2020, 9, 1, 9, 40, tzinfo=tzfile('PRC')), 'filled_commission': 0.15051505190753936, 'account_name': '', 'order_id': '', 'ex_ord_id': '', 'algo_order_id': '', 'position_side': 0, 'order_business': 0, 'order_duration': 0, 'order_qualifier': 0, 'order_src': 0, 'position_src': 0, 'ord_rej_reason': 0, 'ord_rej_reason_detail': '', 'stop_price': 0.0, 'value': 0.0, 'percent': 0.0, 'target_volume': 0, 'target_value': 0.0, 'target_percent': 0.0} {'strategy_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'account_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'cl_ord_id': '000000002', 'symbol': 'SHSE.600000', 'side': 1, 'position_effect': 1, 'order_type': 2, 'status': 3, 'price': 10.180000305175781, 'order_style': 1, 'volume': 100, 'filled_volume': 100, 'filled_vwap': 10.1810183052063, 'filled_amount': 1018.10183052063, 'created_at': datetime.datetime(2020, 9, 2, 9, 40, tzinfo=tzfile('PRC')), 'updated_at': datetime.datetime(2020, 9, 2, 9, 40, tzinfo=tzfile('PRC')), 'filled_commission': 0.101810183052063, 'account_name': '', 'order_id': '', 'ex_ord_id': '', 'algo_order_id': '', 'position_side': 0, 'order_business': 0, 'order_duration': 0, 'order_qualifier': 0, 'order_src': 0, 'position_src': 0, 'ord_rej_reason': 0, 'ord_rej_reason_detail': '', 'stop_price': 0.0, 'value': 0.0, 'percent': 0.0, 'target_volume': 0, 'target_value': 0.0, 'target_percent': 0.0} {'strategy_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'account_id': 'd7443a53-f65b-11ea-bb9d-484d7eaefe55', 'cl_ord_id': '000000003', 'symbol': 'SHSE.600004', 'side': 1, 'position_effect': 1, 'order_type': 2, 'status': 3, 'price': 14.819999694824219, 'order_style': 1, 'volume': 100, 'filled_volume': 100, 'filled_vwap': 14.8214816947937, 'filled_amount': 1482.14816947937, 'created_at': datetime.datetime(2020, 9, 2, 9, 40, tzinfo=tzfile('PRC')), 'updated_at': datetime.datetime(2020, 9, 2, 9, 40, tzinfo=tzfile('PRC')), 'filled_commission': 0.148214816947937, 'account_name': '', 'order_id': '', 'ex_ord_id': '', 'algo_order_id': '', 'position_side': 0, 'order_business': 0, 'order_duration': 0, 'order_qualifier': 0, 'order_src': 0, 'position_src': 0, 'ord_rej_reason': 0, 'ord_rej_reason_detail': '', 'stop_price': 0.0, 'value': 0.0, 'percent': 0.0, 'target_volume': 0, 'target_value': 0.0, 'target_percent': 0.0} ``` -------------------------------- ### Daily Basic Stock Data Output Example Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E8%82%A1%E7%A5%A8%E8%B4%A2%E5%8A%A1%E6%95%B0%E6%8D%AE%E5%8F%8A%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE%E5%87%BD%E6%95%B0%EF%BC%88%E5%85%8D%E8%B4%B9%EF%BC%89.html This is an example output format for the stk_get_daily_basic function when df=True. It includes stock symbol, trade date, and various financial indicators. ```python symbol trade_date turnrate circ_shr ttl_shr tclose 0 SHSE.600000 2023-06-26 0.1159 2.9352e+10 2.9352e+10 7.16 ``` -------------------------------- ### fnd_get_share Example Usage Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E5%9F%BA%E9%87%91%E5%A2%9E%E5%80%BC%E6%95%B0%E6%8D%AE%E5%87%BD%E6%95%B0%EF%BC%88%E4%BB%98%E8%B4%B9%EF%BC%89.html Example of how to call the `fnd_get_share` function to retrieve fund scale data for a specific ETF within a date range. Ensure that `start_date` is less than or equal to `end_date` to avoid errors. ```python fnd_get_share(fund='SHSE.510300', start_date='2024-11-01', end_date='2024-11-24') ``` -------------------------------- ### 初始化策略 (init) Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E5%9F%BA%E6%9C%AC%E5%87%BD%E6%95%B0.html 在策略启动时自动执行,用于初始化配置参数和订阅数据。不支持回测模式下的交易操作。 ```python def init(context): # 订阅bar subscribe(symbols='SHSE.600000,SHSE.600004', frequency='30s', count=5) # 增加对象属性,如:设置一个股票资金占用百分比 context.percentage_stock = 0.8 ``` -------------------------------- ### Example Usage of credit_buying_on_collateral Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E4%B8%A4%E8%9E%8D%E4%BA%A4%E6%98%93%E5%87%BD%E6%95%B0.html Demonstrates how to call the `credit_buying_on_collateral` function with specific parameters for a limit order. ```python credit_buying_on_collateral(symbol='SHSE.600000', volume=100, price=10.67, order_type=OrderType_Limit, order_duration=OrderDuration_Unknown, order_qualifier=OrderQualifier_Unknown, account_id='') ``` -------------------------------- ### Symbol Example: BK.007347 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for a sector or board, such as the Hongmeng concept. ```text BK.007347 ``` -------------------------------- ### Context Mode Return Example Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Shows the output when the script is running in live mode (context.mode == 1). ```python 执行实时模式:1 ``` -------------------------------- ### Symbol Example: SHSE.600000 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for a Shanghai Stock Exchange listed company. ```text SHSE.600000 ``` -------------------------------- ### init - 初始化策略 Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E5%9F%BA%E6%9C%AC%E5%87%BD%E6%95%B0.html 初始化策略,策略启动时自动执行。可以在这里初始化策略配置参数。 ```APIDOC ## init - 初始化策略 ### Description 初始化策略,策略启动时自动执行。可以在这里初始化策略配置参数。 ### Function Signature ```python init(context) ``` ### Parameters * **context** (context) - 上下文,全局变量可存储在这里 ### Example ```python def init(context): # 订阅bar subscribe(symbols='SHSE.600000,SHSE.600004', frequency='30s', count=5) # 增加对象属性,如:设置一个股票资金占用百分比 context.percentage_stock = 0.8 ``` ### Notes 1. 回测模式下init函数里不支持交易操作,仿真模式和实盘模式支持。 2. init只会在策略启动时运行一次,如果不是每天重启策略,每天需要查询更新数据,可以通过设置定时任务执行。 ``` -------------------------------- ### Symbol Example: SZSE.000001 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for a Shenzhen Stock Exchange listed company. ```text SZSE.000001 ``` -------------------------------- ### Context Symbols Return Example Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Shows the expected output of context.symbols after subscribing to specific symbols. ```python {'SHSE.600519', 'SHSE.600419'} ``` -------------------------------- ### Symbol Example: GFEX.lc2405 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for a Guangzhou Futures Exchange (GFEX) futures contract. ```text GFEX.lc2405 ``` -------------------------------- ### Subscribe Symbols Example Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Demonstrates how to subscribe to market data for specific symbols and access the subscribed symbols via context.symbols. ```python subscribe(symbols=['SHSE.600519', 'SHSE.600419'], frequency='60s') context.symbols ``` -------------------------------- ### Symbol Example: CZCE.FG101 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for a Zhengzhou Commodity Exchange (CZCE) futures contract. ```text CZCE.FG101 ``` -------------------------------- ### Query Subscription Data Example Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E8%A1%8C%E6%83%85%E6%95%B0%E6%8D%AE%E6%9F%A5%E8%AF%A2%E5%87%BD%E6%95%B0%EF%BC%88%E5%85%8D%E8%B4%B9%EF%BC%89.html This example shows the structure of data returned by the context.data function after subscribing to market data. Ensure you have subscribed to the data first; otherwise, an error will occur. The 'symbol' parameter supports only one instrument. 'count' must be less than or equal to the count specified in the subscribe function. 'fields' must be within the fields specified in the subscribe function. ```python { 'symbol': 'SHSE.600519', 'price': [1642.0, 1642.0, 1642.0, 1642.0, 1642.0, 1642.0, 1642.0, 1642.0, 1642.0, 0.0], 'bid_p': [1640.0, 1640.0, 1640.0, 1640.0, 1640.0, 1640.0, 1640.0, 1640.0, 1640.0, 0.0], 'created_at': [datetime.datetime(2024, 1, 22, 15, 1, 12, 280000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 22, 15, 1, 21, 277000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 22, 15, 1, 24, 278000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 22, 15, 1, 33, 280000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 22, 15, 1, 36, 282000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 22, 15, 1, 39, 279000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 22, 15, 1, 48, 283000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 22, 15, 1, 51, 286000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 22, 15, 1, 54, 280000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai')), datetime.datetime(2024, 1, 23, 9, 14, 1, 91000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Asia/Shanghai'))] } ``` -------------------------------- ### Symbol Example: DCE.m2011 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for a Dalian Commodity Exchange (DCE) futures contract. ```text DCE.m2011 ``` -------------------------------- ### Live Trading with Dynamic Parameters and KDJ Calculation Source: https://www.myquant.cn/docs2/sdk/python/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B.html Demonstrates live trading with dynamic parameters for KDJ thresholds. Includes KDJ calculation logic and event handlers for parameter changes and account status. ```python # coding=utf-8 from __future__ import print_function, absolute_import, unicode_literals from gm.api import * import numpy as np import pandas as pd '''动态参数,是指在不终止策略的情况下,掘金终端UI界面和策略变量做交互, 通过add_parameter在策略代码里设置动态参数,终端UI界面会显示对应参数 ''' def init(context): # log日志函数,只支持实时模式,在仿真交易和实盘交易界面查看,重启终端log日志会被清除,需要记录到本地可以使用logging库 log(level='info', msg='平安银行信号触发', source='strategy') # 设置k值阀值作为动态参数 context.k_value = 23 # add_parameter设置动态参数函数,只支持实时模式,在仿真交易和实盘交易界面查看,重启终端动态参数会被清除,重新运行策略会重新设置 add_parameter(key='k_value', value=context.k_value, min=0, max=100, name='k值阀值', intro='设置k值阀值', group='1', readonly=False) # 设置d值阀值作为动态参数 context.d_value = 20 add_parameter(key='d_value', value=context.d_value, min=0, max=100, name='d值阀值', intro='设置d值阀值', group='2', readonly=False) print('当前的动态参数有', context.parameters) # 订阅行情 subscribe(symbols='SZSE.002400', frequency='60s', count=120) def on_bar(context, bars): data = context.data(symbol=bars[0]['symbol'], frequency='60s', count=100) kdj = KDJ(data, 9, 3, 3) k_value = kdj['kdj_k'].values d_value = kdj['kdj_d'].values if k_value[-1] > context.k_value and d_value[-1] < context.d_value: order_percent(symbol=bars[0]['symbol'], percent=0.01, side=OrderSide_Buy, order_type=OrderType_Market, position_effect=PositionEffect_Open) print('{}下单买入, k值为{}'.format(bars[0]['symbol'], context.k_value)) # 计算KDJ def KDJ(data, N, M1, M2): lowList= data['low'].rolling(N).min() lowList.fillna(value=data['low'].expanding().min(), inplace=True) highList = data['high'].rolling(N).max() highList.fillna(value=data['high'].expanding().max(), inplace=True) rsv = (data['close'] - lowList) / (highList - lowList) * 100 data['kdj_k'] = rsv.ewm(alpha=1/M1).mean() data['kdj_d'] = data['kdj_k'].ewm(alpha=1/M2).mean() data['kdj_j'] = 3.0 * data['kdj_k'] - 2.0 * data['kdj_d'] return data # 动态参数变更事件 def on_parameter(context, parameter): # print(parameter) if parameter['name'] == 'k值阀值': # 通过全局变量把动态参数值传入别的事件里 context.k_value = parameter['value'] print('{}已经修改为{}'.format(parameter['name'], context.k_value)) if parameter['name'] == 'd值阀值': context.d_value = parameter['value'] print('{}已经修改为{}'.format(parameter['name'], context.d_value)) def on_account_status(context, account): print(account) if __name__ == '__main__': ''' strategy_id策略ID,由系统生成 filename文件名,请与本文件名保持一致 mode实时模式:MODE_LIVE回测模式:MODE_BACKTEST token绑定计算机的ID,可在系统设置-密钥管理中生成 backtest_start_time回测开始时间 backtest_end_time回测结束时间 backtest_adjust股票复权方式不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST backtest_initial_cash回测初始资金 backtest_commission_ratio回测佣金比例 backtest_slippage_ratio回测滑点比例 ''' run(strategy_id='07c08563-a4a8-11ea-a682-7085c223669d', filename='main.py', mode=MODE_LIVE, token='2c4e3c59cde776ebc268bf6d7b4c457f204482b3', backtest_start_time='2020-09-01 08:00:00', backtest_end_time='2020-10-01 16:00:00', backtest_adjust=ADJUST_PREV, backtest_initial_cash=500000, backtest_commission_ratio=0.0001, backtest_slippage_ratio=0.0001) 复制成功 ``` -------------------------------- ### Symbol Example: SHFE.rb2011 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for a Shanghai Futures Exchange (SHFE) futures contract. ```text SHFE.rb2011 ``` -------------------------------- ### Example Return Value of credit_buying_on_collateral Source: https://www.myquant.cn/docs2/sdk/python/API%E4%BB%8B%E7%BB%8D/%E4%B8%A4%E8%9E%8D%E4%BA%A4%E6%98%93%E5%87%BD%E6%95%B0.html Illustrates the structure and fields of the data returned by the `credit_buying_on_collateral` function upon successful execution. ```text strategy_id account_id cl_ord_id symbol order_type status price volume created_at order_business account_name order_id ex_ord_id algo_order_id side position_effect position_side order_duration order_qualifier order_src ord_rej_reason ord_rej_reason_detail stop_price order_style value percent target_volume target_value target_percent filled_volume filled_vwap filled_amount filled_commission updated_at ------------------------------------ ------------------------------------ ------------------------------------ ----------- ---------- ------ ----- ------ ----------------------------------------------------------------------- -------------- ------------ -------- --------- ------------- ---- --------------- ------------- -------------- --------------- --------- -------------- --------------------- ---------- ----------- ----- ------- ------------- ------------ -------------- ------------- ----------- ------------- ----------------- 3af55cb8-a7c5-11ea-b510-309c231d28bd 8f30e83f-a7c5-11ea-b510-309c231d28bd 2b861a31-a7c9-11ea-b510-309c231d28bd SHSE.600000 1 10 10.67 100 datetime.datetime(2020, 6, 6, 15, 41, 44, 869534, tzinfo=tzfile('PRC')) 207 0 0 0 0 0 0 0 0.0 0 0.0 0.0 0 0.0 0.0 0 0.0 0.0 0.0 None ``` -------------------------------- ### Symbol Example: INE.sc2011 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for an INE (Shanghai International Energy Exchange) futures contract. ```text INE.sc2011 ``` -------------------------------- ### Symbol Example: CFFEX.IC2011 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a symbol for a China Financial Futures Exchange (CFFEX) futures contract. ```text CFFEX.IC2011 ``` -------------------------------- ### Virtual Contract Example: SHFE.RB99 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a virtual contract symbol for the weighted index contract of Rebar on SHFE. ```text SHFE.RB99 ``` -------------------------------- ### Live Trading Mode with Data Subscription Source: https://www.myquant.cn/docs2/sdk/python/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B.html This snippet shows how to set up a strategy for live trading. It subscribes to tick data and prints the received bar information. When running in live mode, backtesting parameters are ignored. Ensure 'token' is valid. ```python # coding=utf-8 from __future__ import print_function, absolute_import from gm.api import * def init(context): # 订阅浦发银行的tick subscribe(symbols='SHSE.600000', frequency='60s') def on_bar(context, bars): # 打印当前获取的bar信息 print(bars) if __name__ == '__main__': # 在终端仿真交易和实盘交易的启动策略按钮默认是实时模式,运行回测默认是回测模式,在外部IDE里运行策略需要修改成对应的运行模式 # mode=MODE_LIVE 实时模式, 回测模式的相关参数不生效 # mode=MODE_BACKTEST 回测模式 ''' strategy_id策略ID, 由系统生成 filename文件名, 请与本文件名保持一致 mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST token绑定计算机的ID, 可在系统设置-密钥管理中生成 backtest_start_time回测开始时间 backtest_end_time回测结束时间 backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST backtest_initial_cash回测初始资金 backtest_commission_ratio回测佣金比例 backtest_slippage_ratio回测滑点比例 ''' run(strategy_id='strategy_id', filename='main.py', mode=MODE_LIVE, token='token_id', backtest_start_time='2020-11-01 08:00:00', backtest_end_time='2020-11-10 16:00:00', backtest_adjust=ADJUST_PREV, backtest_initial_cash=10000000, backtest_commission_ratio=0.0001, backtest_slippage_ratio=0.0001) ``` -------------------------------- ### Virtual Contract Example: SHFE.RB Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a virtual contract symbol for the continuous main contract of Rebar on SHFE. ```text SHFE.RB ``` -------------------------------- ### Backtesting Strategy Initialization and Data Subscription Source: https://www.myquant.cn/docs2/sdk/python/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B.html Initializes strategy by fetching historical symbols and subscribing to daily data for backtesting. Stores instrument information in a dictionary for easy access. ```python # coding=utf-8 from __future__ import print_function, absolute_import from gm.api import * def init(context): # 在init中一次性拿到所有需要的instruments信息 instruments = get_history_symbol(symbol='SZSE.000001', start_date=context.backtest_start_time,end_date=context.backtest_end_time) # 将信息按symbol,date作为key存入字典 context.ins_dict = {(i.symbol, i.trade_date.date()): i for i in instruments} subscribe(symbols='SZSE.000001', frequency='1d') def on_bar(context, bars): print(context.ins_dict[(bars[0].symbol, bars[0].eob.date())]) if __name__ == '__main__': ''' strategy_id策略ID, 由系统生成 filename文件名, 请与本文件名保持一致 mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST token绑定计算机的ID, 可在系统设置-密钥管理中生成 backtest_start_time回测开始时间 backtest_end_time回测结束时间 backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST backtest_initial_cash回测初始资金 backtest_commission_ratio回测佣金比例 backtest_slippage_ratio回测滑点比例 ''' run(strategy_id='strategy_id', filename='main.py', mode=MODE_BACKTEST, token='token_id', backtest_start_time='2020-11-01 08:00:00', backtest_end_time='2020-11-10 16:00:00', backtest_adjust=ADJUST_PREV, backtest_initial_cash=10000000, backtest_commission_ratio=0.0001, backtest_slippage_ratio=0.0001) 复制成功 ``` -------------------------------- ### Virtual Contract Example: SHFE.RB03 Source: https://www.myquant.cn/docs2/sdk/python/%E5%8F%98%E9%87%8F%E7%BA%A6%E5%AE%9A.html Example of a virtual contract symbol for the next season continuous contract of Rebar on SHFE. ```text SHFE.RB03 ```