### Initialize and Execute Trading Strategies with MyQuant Python SDK Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Demonstrates how to initialize and run trading strategies using the MyQuant Python SDK. This includes setting up strategy parameters, subscribing to market data, scheduling tasks, and executing orders. The example showcases both backtest and live trading modes with configuration options for initial cash, commission, and slippage. ```python from gm.api import * def init(context): # Initialize strategy - runs once at startup # Subscribe to market data subscribe(symbols='SHSE.600000', frequency='1d', count=50) # Set global variables context.stock_percent = 0.8 # Schedule daily tasks schedule(schedule_func=daily_algo, date_rule='1d', time_rule='14:50:00') def daily_algo(context): # Execute trading logic order_volume(symbol='SHSE.600000', volume=200, side=OrderSide_Buy, order_type=OrderType_Market, position_effect=PositionEffect_Open, price=0) def on_backtest_finished(context, indicator): print(f"Total return: {indicator['pnl_ratio']}") print(f"Sharpe ratio: {indicator['sharpe_ratio']}") if __name__ == '__main__': run(strategy_id='strategy_1', filename='main.py', mode=MODE_BACKTEST, token='your_token_here', 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) ``` -------------------------------- ### Place Orders with Volume, Value, or Percentage Sizing Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Enables placing various types of orders including volume, value, and percentage-based sizing. It supports different order types (Limit, Market) and position effects (Open). Additionally, it allows rebalancing positions to target volume, value, or percentage, and includes an example for market orders with a protection price for Shanghai exchange. ```python from gm.api import * def on_bar(context, bars): symbol = bars[0]['symbol'] # Order by specific volume (shares) order_volume(symbol='SHSE.600000', volume=10000, side=OrderSide_Buy, order_type=OrderType_Limit, position_effect=PositionEffect_Open, price=11.0) # Order by monetary value order_value(symbol='SHSE.600000', value=100000, side=OrderSide_Buy, order_type=OrderType_Limit, position_effect=PositionEffect_Open, price=11.0) # Order by portfolio percentage (10% of NAV) order_percent(symbol='SHSE.600000', percent=0.1, side=OrderSide_Buy, order_type=OrderType_Market, position_effect=PositionEffect_Open) # Rebalance to target position (adjust holdings to 10000 shares) order_target_volume(symbol='SHSE.600000', volume=10000, position_side=PositionSide_Long, order_type=OrderType_Limit, price=13.0) # Rebalance to target value (adjust holdings to 100000 yuan) order_target_value(symbol='SHSE.600000', value=100000, position_side=PositionSide_Long, order_type=OrderType_Limit, price=11.0) # Rebalance to target percentage (10% of portfolio) order_target_percent(symbol='SHSE.600000', percent=0.1, position_side=PositionSide_Long, order_type=OrderType_Limit, price=11.0) # Market order with protection price (required for Shanghai exchange) order_volume(symbol='SHSE.600000', volume=100, side=OrderSide_Buy, order_type=OrderType_Market, position_effect=PositionEffect_Open, price=15.0) # Protection limit price # Batch order submission order_1 = {'symbol': 'SHSE.600000', 'volume': 100, 'price': 11, 'side': OrderSide_Buy, 'order_type': OrderType_Limit, 'position_effect': PositionEffect_Open} order_2 = {'symbol': 'SHSE.600004', 'volume': 100, 'price': 11, 'side': OrderSide_Buy, 'order_type': OrderType_Limit, 'position_effect': PositionEffect_Open} batch_orders = order_batch([order_1, order_2]) ``` -------------------------------- ### Convertible Bond Trading with Conversion and Redemption Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt This snippet demonstrates how to query convertible bond information, retrieve historical data, subscribe to tick data, and place orders. It also includes commented-out examples for performing conversion and redemption operations, which are live trading features. This functionality requires the `gm.api` library. ```python from gm.api import * def init(context): # Query convertible bond information cb_info = get_symbol_infos(sec_type1=1030, sec_type2=103001, symbols='SHSE.113038', df=True) print(cb_info[['symbol', 'sec_name', 'underlying_symbol', 'conversion_start_date', 'listed_date']]) # Query historical data for convertible bonds cb_history = 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) # Subscribe to convertible bond tick data subscribe(symbols='SHSE.113038', frequency='tick') # Place convertible bond order (same as stock trading) order_volume(symbol='SZSE.128041', volume=100, side=OrderSide_Buy, order_type=OrderType_Limit, position_effect=PositionEffect_Open, price=340.0) def on_tick(context, tick): print(f"Convertible bond tick: {tick[0]['symbol']}, Price: {tick[0]['price']}") # Convertible bond conversion operations (live trading only) # Convert 100 bonds to underlying stock # bond_convertible_call('SHSE.110051', 100, 0) # Redeem 100 bonds # bond_convertible_put('SHSE.183350', 100, 0) # Cancel redemption for 100 bonds # bond_convertible_put_cancel('SHSE.183350', 100) ``` -------------------------------- ### Query Historical Market Data with MyQuant Python SDK Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Illustrates how to query historical market data, including daily bars, 1-minute bars, and current market snapshots, using the MyQuant Python SDK. This is essential for backtesting and in-depth market analysis. The examples show how to set the API token, specify date ranges, select fields, and retrieve data in DataFrame format. ```python from gm.api import * # Set token for data access without running strategy set_token('your_token_id') # Query historical daily bars with forward adjustment daily_data = history(symbol='SHSE.600000', frequency='1d', start_time='2020-01-01 09:00:00', end_time='2020-12-31 16:00:00', fields='open,high,low,close,volume,amount', adjust=ADJUST_PREV, adjust_end_time='2020-12-31', df=True) print(daily_data.head()) # Query intraday 1-minute bars minute_data = history(symbol='SZSE.000001', frequency='60s', start_time='2020-11-23 09:30:00', end_time='2020-11-23 15:00:00', df=True) # Query current market snapshot current_data = current(symbols='SHSE.600000,SZSE.000001', fields='symbol,price,open,high,low,quotes') for tick in current_data: print(f"{tick['symbol']}: {tick['price']}") # Query current price only prices = current_price(symbols='SHSE.600000,SZSE.000001') print(prices) ``` -------------------------------- ### Convertible Bond Trading API Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt This section details how to query convertible bond information, access historical data, subscribe to tick data, and place orders. It also includes examples for performing conversion and redemption operations. ```APIDOC ## Convertible Bond Trading ### Description Trade convertible bonds with conversion and redemption operations. ### Functions - **get_symbol_infos**: Query convertible bond information. - **history**: Query historical data for convertible bonds. - **subscribe**: Subscribe to convertible bond tick data. - **order_volume**: Place convertible bond orders. - **bond_convertible_call**: Convert bonds to underlying stock (live trading only). - **bond_convertible_put**: Redeem bonds (live trading only). - **bond_convertible_put_cancel**: Cancel bond redemption (live trading only). ### Example Usage ```python from gm.api import * def init(context): # Query convertible bond information cb_info = get_symbol_infos(sec_type1=1030, sec_type2=103001, symbols='SHSE.113038', df=True) print(cb_info[['symbol', 'sec_name', 'underlying_symbol', 'conversion_start_date', 'listed_date']]) # Query historical data for convertible bonds cb_history = 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) # Subscribe to convertible bond tick data subscribe(symbols='SHSE.113038', frequency='tick') # Place convertible bond order (same as stock trading) order_volume(symbol='SZSE.128041', volume=100, side=OrderSide_Buy, order_type=OrderType_Limit, position_effect=PositionEffect_Open, price=340.0) def on_tick(context, tick): print(f"Convertible bond tick: {tick[0]['symbol']}, Price: {tick[0]['price']}") # Convertible bond conversion operations (live trading only) # Convert 100 bonds to underlying stock # bond_convertible_call('SHSE.110051', 100, 0) # Redeem 100 bonds # bond_convertible_put('SHSE.183350', 100, 0) # Cancel redemption for 100 bonds # bond_convertible_put_cancel('SHSE.183350', 100) ``` ``` -------------------------------- ### Subscribe to Market Data with MyQuant Python SDK Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Shows how to subscribe to real-time market data, including tick and bar data, using the MyQuant Python SDK. It covers subscribing to tick data and 1-minute bars with a sliding window, and demonstrates how to process this data within callback functions like `on_tick` and `on_bar` for trading decisions. ```python from gm.api import * def init(context): # Subscribe to tick data subscribe(symbols='SHSE.600000', frequency='tick') # Subscribe to 1-minute bars with 50-bar sliding window subscribe(symbols='SHSE.600000', frequency='60s', count=50, format='df', fields='symbol,close,open,high,low,volume,eob') def on_tick(context, tick): # Handle real-time tick data print(f"Symbol: {tick[0]['symbol']}, Price: {tick[0]['price']}, " f"Bid: {tick[0]['quotes'][0]['bid_p']}, Ask: {tick[0]['quotes'][0]['ask_p']}") def on_bar(context, bars): # Access sliding window data data = context.data(symbol=bars[0]['symbol'], frequency='60s', count=50, fields='close,eob') # Calculate moving average data['ma5'] = data['close'].rolling(window=5).mean() data['ma20'] = data['close'].rolling(window=20).mean() # Trading logic: golden cross if data['ma5'].iloc[-1] > data['ma20'].iloc[-1] and data['ma5'].iloc[-2] <= data['ma20'].iloc[-2]: order_percent(symbol=bars[0]['symbol'], percent=0.1, side=OrderSide_Buy, order_type=OrderType_Market, position_effect=PositionEffect_Open) print(f"Latest bar: {bars[0]}") if __name__ == '__main__': run(strategy_id='strategy_id', filename='main.py', mode=MODE_LIVE, token='token_id') ``` -------------------------------- ### Python Dynamic Parameters in Live Trading with gm.api Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Configures adjustable parameters that can be modified during live trading without restarting the strategy using the gm.api library. It demonstrates adding dynamic parameters and handling their updates. Dependencies include the gm.api library. ```python from gm.api import * def init(context): # Set dynamic parameters context.k_threshold = 23 add_parameter(key='k_threshold', value=context.k_threshold, min=0, max=100, name='K Value Threshold', intro='KDJ indicator K threshold', group='1', readonly=False) context.d_threshold = 20 add_parameter(key='d_threshold', value=context.d_threshold, min=0, max=100, name='D Value Threshold', intro='KDJ indicator D threshold', group='2', readonly=False) 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 = calculate_kdj(data, 9, 3, 3) # Use dynamic parameters in trading logic if kdj['k'][-1] > context.k_threshold and kdj['d'][-1] < context.d_threshold: order_percent(symbol=bars[0]['symbol'], percent=0.01, side=OrderSide_Buy, order_type=OrderType_Market, position_effect=PositionEffect_Open) def on_parameter(context, parameter): # Handle parameter changes from UI if parameter['name'] == 'K Value Threshold': context.k_threshold = parameter['value'] print(f"K threshold updated to {context.k_threshold}") if parameter['name'] == 'D Value Threshold': context.d_threshold = parameter['value'] print(f"D threshold updated to {context.d_threshold}") def calculate_kdj(data, n, m1, m2): # KDJ indicator calculation low_list = data['low'].rolling(n).min() high_list = data['high'].rolling(n).max() rsv = (data['close'] - low_list) / (high_list - low_list) * 100 k = rsv.ewm(alpha=1/m1).mean() d = k.ewm(alpha=1/m2).mean() j = 3.0 * k - 2.0 * d return {'k': k.values, 'd': d.values, 'j': j.values} ``` -------------------------------- ### Query Orders, Positions, and Execution Reports Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Provides functionalities to query all unfilled orders, and cancel orders older than a specified duration. It also allows querying all orders for the day, execution reports, current positions with details like volume and PnL, and account status including cash, NAV, and total PnL. Includes functions to cancel all unfilled orders and close all open positions. ```python from gm.api import * def on_bar(context, bars): # Query all unfilled orders unfilled_orders = get_unfinished_orders() print(f"Unfilled orders: {len(unfilled_orders)}") # Cancel orders older than 30 seconds for order in unfilled_orders: if (context.now - order['created_at']).seconds > 30: order_cancel([{'cl_ord_id': order['cl_ord_id'], 'account_id': order['account_id']}]) # Query all orders for the day all_orders = get_orders() # Query execution reports exec_reports = get_execution_reports() # Query current positions positions = context.account().positions() for pos in positions: print(f"Symbol: {pos['symbol']}, Volume: {pos['volume']}, " f"Vwap: {pos['vwap']}, PnL: {pos['fpnl']}") # Query account status account = context.account() print(f"Cash: {account.cash}, NAV: {account.nav}, " f"Total PnL: {account.pnl}") # Cancel all unfilled orders order_cancel_all() # Close all positions order_close_all() ``` -------------------------------- ### Python Futures Conditional Orders with gm.api Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Places conditional orders for futures, including stop-loss and take-profit triggers, using the gm.api library. It demonstrates how to open positions and manage existing ones based on specified trigger prices. Dependencies include the gm.api library. ```python from gm.api import * def on_bar(context, bars): # Futures conditional order - open position when trigger price is reached order_volume(symbol='CFFEX.IF2012', volume=1, side=OrderSide_Buy, order_type=OrderType_Limit, position_effect=PositionEffect_Open, price=4800.0, trigger_type=1, # Trigger when last price >= stop_price stop_price=4750.0) # Trigger price # Stop-loss for existing long position order_volume(symbol='CFFEX.IF2012', volume=1, side=OrderSide_Sell, order_type=OrderType_Limit, position_effect=PositionEffect_Close, price=4700.0, trigger_type=2, # Trigger when last price <= stop_price stop_price=4720.0) # Stop-loss price # Take-profit for existing long position order_volume(symbol='CFFEX.IF2012', volume=1, side=OrderSide_Sell, order_type=OrderType_Limit, position_effect=PositionEffect_Close, price=4900.0, trigger_type=1, # Trigger when last price >= stop_price stop_price=4880.0) # Take-profit price ``` -------------------------------- ### Accessing Level 2 Market Data for Tick and Order Book Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt This snippet shows how to access Level 2 market data, including tick-by-tick transactions and order book updates. It covers querying historical L2 data (ticks, bars, transactions, orders) and subscribing to real-time L2 data streams. This functionality is specific to broker-hosted versions and requires the `gm.api` library. ```python from gm.api import * def init(context): # Query historical L2 tick data l2_ticks = get_history_l2ticks('SHSE.600519', '2020-11-23 14:00:00', '2020-11-23 15:00:00', df=False) # Query historical L2 bar data l2_bars = get_history_l2bars('SHSE.600000', '60s', '2020-11-23 14:00:00', '2020-11-23 15:00:00', df=False) # Query historical L2 transactions (tick-by-tick trades) l2_trans = get_history_l2transactions('SHSE.600000', '2020-11-23 14:00:00', '2020-11-23 15:00:00', df=False) # Query historical L2 orders (tick-by-tick order book updates) l2_orders = get_history_l2orders('SZSE.000001', '2020-11-23 14:00:00', '2020-11-23 15:00:00', df=False) # Subscribe to L2 real-time data subscribe(symbols='SHSE.600000', frequency='l2transaction') subscribe(symbols='SZSE.000001', frequency='l2order') def on_l2transaction(context, transaction): # Handle tick-by-tick trade data print(f"L2 Transaction - Symbol: {transaction['symbol']}, " f"Price: {transaction['price']}, Volume: {transaction['volume']}, " f"Side: {transaction['side']}") def on_l2order(context, order): # Handle order book updates print(f"L2 Order - Symbol: {order['symbol']}, " f"Price: {order['price']}, Volume: {order['volume']}, " f"Side: {order['side']}, Type: {order['order_type']}") if __name__ == '__main__': 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') ``` -------------------------------- ### Query Stock Symbol and Instrument Information Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Fetches instrument metadata for various asset types (stocks, ETFs, futures, convertible bonds) and filters them by exchange and listing status. It supports querying specific symbols or all instruments of a certain type, and can also retrieve tradable stocks for a given date, excluding suspended or ST stocks. ```python from gm.api import * set_token('your_token_id') # Query specific stock symbols stock_info = get_symbol_infos(sec_type1=1010, symbols='SHSE.600008,SZSE.000002', df=True) print(stock_info[['symbol', 'sec_name', 'listed_date', 'price_tick', 'trade_n']]) # Query all A-share stocks a_stocks = get_symbol_infos(sec_type1=1010, sec_type2=101001, df=True) print(f"Total A-shares: {len(a_stocks)}") # Query ETFs listed on Shanghai exchange etfs = get_symbol_infos(sec_type1=1020, sec_type2=102001, exchanges='SHSE', df=True) # Query convertible bonds convertibles = get_symbol_infos(sec_type1=1030, sec_type2=103001, df=True) # Query commodity futures on specific exchanges futures = get_symbol_infos(sec_type1=1040, sec_type2=104003, exchanges='CZCE,DCE', df=True) # Get trading symbols for specific date (excludes suspended and ST stocks) trade_symbols = get_symbols(sec_type1=1010, trade_date='2020-11-20', skip_suspended=True, skip_st=True, df=True) print(f"Tradable stocks on 2020-11-20: {len(trade_symbols)}") ``` -------------------------------- ### Python Trading Event Handlers with gm.api Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Handles execution reports, order status updates, and account events using the gm.api library. It defines functions for processing different types of trading events and includes error handling. Dependencies include the gm.api library. ```python from gm.api import * def init(context): subscribe(symbols='SHSE.600000', frequency='60s') def on_execution_report(context, execrpt): # Handle execution reports for filled/rejected orders print(f"Execution Report - Symbol: {execrpt['symbol']}, " f"Side: {execrpt['side']}, Volume: {execrpt['volume']}, " f"Price: {execrpt['price']}, Exec Type: {execrpt['exec_type']}") if execrpt['exec_type'] == 15: # Fully filled print(f"Order fully filled: {execrpt['volume']} shares at {execrpt['price']}") def on_order_status(context, order): # Handle order status changes status_map = {1: 'New', 2: 'PartiallyFilled', 3: 'Filled', 5: 'Cancelled', 8: 'Rejected'} print(f"Order Status Update - {order['symbol']}: {status_map.get(order['status'])}") if order['status'] == 8: # Rejected print(f"Order rejected: {order['ord_rej_reason_detail']}") def on_account_status(context, account): # Handle account status updates print(f"Account Status - Cash: {account['cash']}, " f"Available: {account['cash_available']}, NAV: {account['nav']}") def on_error(context, code, info): # Handle errors print(f"Error {code}: {info}") if __name__ == '__main__': run(strategy_id='strategy_id', filename='main.py', mode=MODE_LIVE, token='token_id') ``` -------------------------------- ### Level 2 Market Data API Source: https://context7.com/wangshengyang2004/myquant_python_docs/llms.txt Access Level 2 tick-by-tick transaction and order book data. This section covers querying historical L2 data and subscribing to real-time L2 data streams. ```APIDOC ## Level 2 Market Data ### Description Access Level 2 tick-by-tick transaction and order book data (broker-hosted version only). ### Functions - **get_history_l2ticks**: Query historical Level 2 tick data. - **get_history_l2bars**: Query historical Level 2 bar data. - **get_history_l2transactions**: Query historical Level 2 transactions (tick-by-tick trades). - **get_history_l2orders**: Query historical Level 2 orders (tick-by-tick order book updates). - **subscribe**: Subscribe to Level 2 real-time data (e.g., 'l2transaction', 'l2order'). ### Callbacks - **on_l2transaction**: Callback function to handle Level 2 transaction data. - **on_l2order**: Callback function to handle Level 2 order book updates. ### Example Usage ```python from gm.api import * def init(context): # Query historical L2 tick data l2_ticks = get_history_l2ticks('SHSE.600519', '2020-11-23 14:00:00', '2020-11-23 15:00:00', df=False) # Query historical L2 bar data l2_bars = get_history_l2bars('SHSE.600000', '60s', '2020-11-23 14:00:00', '2020-11-23 15:00:00', df=False) # Query historical L2 transactions (tick-by-tick trades) l2_trans = get_history_l2transactions('SHSE.600000', '2020-11-23 14:00:00', '2020-11-23 15:00:00', df=False) # Query historical L2 orders (tick-by-tick order book updates) l2_orders = get_history_l2orders('SZSE.000001', '2020-11-23 14:00:00', '2020-11-23 15:00:00', df=False) # Subscribe to L2 real-time data subscribe(symbols='SHSE.600000', frequency='l2transaction') subscribe(symbols='SZSE.000001', frequency='l2order') def on_l2transaction(context, transaction): # Handle tick-by-tick trade data print(f"L2 Transaction - Symbol: {transaction['symbol']}, " f"Price: {transaction['price']}, Volume: {transaction['volume']}, " f"Side: {transaction['side']}") def on_l2order(context, order): # Handle order book updates print(f"L2 Order - Symbol: {order['symbol']}, " f"Price: {order['price']}, Volume: {order['volume']}, " f"Side: {order['side']}, Type: {order['order_type']}") if __name__ == '__main__': 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') ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.