### Starting Live Trading with Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This guide provides instructions on how to connect Poboquant to brokerage accounts for live trading. It covers the necessary steps to enable real-time execution of trading strategies. ```Python from poboquant.api import PoboquantAPI api = PoboquantAPI() # Connect to a specific account type (e.g., futures) api.connect_futures_account(account_id='your_account_id', broker='your_broker') # Start trading... ``` -------------------------------- ### Connecting to SimNow Account in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This guide explains the process of connecting to a SimNow account within the Poboquant framework. SimNow is a simulated trading platform often used for testing and development. ```Python from poboquant.api import PoboquantAPI api = PoboquantAPI() # Connect to SimNow account # api.connect_simnow(username='your_simnow_username', password='your_simnow_password') # Note: Actual connection parameters may vary. ``` -------------------------------- ### Execute Logic on K-Line Events with OnBar Source: https://context7.com/qmhedging/poboquant/llms.txt The OnBar event triggers at the end of each K-line period. This example demonstrates a simple moving average crossover strategy. ```python def OnBar(context, code, bartype): if code != g.code: return dyndata = GetQuote(g.code) MA = GetIndicator("MA", code, params=(5, 10), bar_type=BarType.Min15) MA1, MA2 = MA["MA(5)"], MA["MA(10)"] if len(MA2) < 2: return if MA1[-1] >= MA2[-1] and MA1[-2] < MA2[-2]: QuickInsertOrder(context.myacc, g.code, 'buy', 'open', dyndata.now, 10) elif MA1[-1] <= MA2[-1] and MA1[-2] > MA2[-2]: QuickInsertOrder(context.myacc, g.code, 'sell', 'close', dyndata.now, 10) ``` -------------------------------- ### Writing Python Strategies in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This guide focuses on the process of writing quantitative trading strategies using Python within the Poboquant framework. It covers the fundamental structure and concepts for developing custom strategies. ```Python from poboquant.strategy import Strategy class MyStrategy(Strategy): def __init__(self): super().__init__() self.order_price = None def on_tick(self, tick): if self.order_price is None: self.order_price = tick.last_price self.buy(tick.instrument_id, 100, self.order_price) def on_trade_deal(self, trade_deal): print(f'Trade executed: {trade_deal}') ``` -------------------------------- ### Adjusting Strategies for Live Trading in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This guide discusses the common discrepancies between backtest results and live trading performance ('backtest looks good, live trading is bad') and provides strategies for adjusting trading models in Poboquant to improve live performance. ```Python # Considerations for live trading adjustments: # - Slippage # - Commission costs # - Latency # - Market impact # - Real-time data feed issues # Example: Adjusting stop-loss or take-profit levels based on live conditions ``` -------------------------------- ### Tick-Level Spread Trading Strategy Source: https://context7.com/qmhedging/poboquant/llms.txt A complete strategy example implementing a cross-period spread trading strategy based on tick data and minute K-line analysis. ```python def OnQuote(context, code): dyndataleg1 = GetQuote(g.code1) dyndataleg2 = GetQuote(g.code2) klinedataM1leg1 = GetHisData(g.code1, BarType.Min) klinedataM1leg2 = GetHisData(g.code2, BarType.Min) spread1 = klinedataM1leg1[-2].close - klinedataM1leg2[-2].close spreadt = dyndataleg1.now - dyndataleg2.now if spread1 - 10 >= spreadt: context.myacc.InsertOrder(g.code1, BSType.BuyOpen, dyndataleg1.now, 20) context.myacc.InsertOrder(g.code2, BSType.SellOpen, dyndataleg2.now, 20) ``` -------------------------------- ### Using SmartOrder in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This guide explains how to utilize the SmartOrder functionality in Poboquant for more sophisticated order placement. SmartOrder can help manage order execution logic, such as conditional orders or iceberg orders. ```Python from poboquant.api import PoboquantAPI api = PoboquantAPI() # Example: Placing a limit order using SmartOrder # api.place_smart_order(instrument_id='BTCUSD', order_type='LIMIT', price=30000, volume=100, time_in_force='GTC') # Example: Placing a market order # api.place_smart_order(instrument_id='ETHUSD', order_type='MARKET', volume=50) ``` -------------------------------- ### Understanding Python Objects in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This section explains the concept of object-oriented programming in Python as it applies to Poboquant, using 'bal.CashBalance' as an example. Understanding objects is key to effectively using the framework's components. ```Python # Example demonstrating object usage # Assuming 'account' is an instance of an account object # cash_balance = account.CashBalance # print(f'Current cash balance: {cash_balance.available}') ``` -------------------------------- ### GetContractInfo - Get Contract Information Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves detailed information about a specific futures or options contract. ```APIDOC ## GetContractInfo - Get Contract Information ### Description Retrieves detailed information about a specific futures or options contract, such as last trading day, strike price, etc. ### Method Not specified (function call within a script) ### Endpoint Not applicable (local function) ### Parameters - **contract_code** (string) - Required - The code of the contract (e.g., "rb2001.SHFE", "m2001-C-2800.DCE"). ### Request Example ```python # Example usage within a Python script info1 = GetContractInfo("rb2001.SHFE") ``` ### Response #### Success Response (dictionary) - **dictionary** - A dictionary containing contract details. Keys may include '最后交易日' (Last Trading Day), '行权价格' (Strike Price), '期权标的' (Underlying Asset), '期权种类' (Option Type), '期权类型' (Option Category), '行权到期日' (Exercise Expiry Date). #### Response Example ```python # Example output for a futures contract print("最后交易日: " + str(info1['最后交易日'])) # Example output for an options contract info2 = GetContractInfo("m2001-C-2800.DCE") print("行权价格: " + str(info2['行权价格'])) ``` ``` -------------------------------- ### GetMainContract - Get Main Contract Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves the main contract code for a given exchange and variety, based on trading volume. ```APIDOC ## GetMainContract - Get Main Contract ### Description Retrieves the main contract code for a given exchange and variety, typically based on trading volume. ### Method Not specified (function call within a script) ### Endpoint Not applicable (local function) ### Parameters - **exchange** (string) - Required - The stock exchange code (e.g., 'SHFE', 'DCE', 'CZCE'). - **variety** (string) - Required - The trading variety or symbol (e.g., 'rb', 'm', 'SR'). - **top_percentage** (int) - Required - The percentage of top contracts by volume to consider (e.g., 20 for top 20%). ### Request Example ```python # Example usage within a Python script g.code = GetMainContract('SHFE', 'rb', 20) ``` ### Response #### Success Response (string) - **string** - The contract code of the main contract. #### Response Example ```python # Example output print("螺纹钢主力合约: " + g.code) ``` ``` -------------------------------- ### GetVarieties - Get Exchange Varieties Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves a list of all supported varieties (trading symbols) for a given exchange. ```APIDOC ## GetVarieties - Get Exchange Varieties ### Description Retrieves a list of all supported trading varieties (symbols) for a specified exchange. ### Method Not specified (function call within a script) ### Endpoint Not applicable (local function) ### Parameters - **exchange** (string) - Required - The exchange code (e.g., "SHSE", "SHFE", "DCE"). ### Request Example ```python # Example usage within a Python script varieties_shfe = GetVarieties("SHFE") ``` ### Response #### Success Response (list of strings) - **list of strings** - A list containing the variety codes supported by the exchange. #### Response Example ```python # Example output print("上期所品种: " + str(varieties_shfe)) ``` ``` -------------------------------- ### GetVarieties - Get Exchange Varieties Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves a list of all supported varieties (trading instruments) for a specified exchange. This function is helpful for discovering available trading products on different exchanges. ```python def OnStart(context): # 获取上交所支持的品种 varieties_shse = GetVarieties("SHSE") print("上交所品种: " + str(varieties_shse)) # 获取上期所支持的品种 varieties_shfe = GetVarieties("SHFE") print("上期所品种: " + str(varieties_shfe)) # 获取大商所支持的品种 varieties_dce = GetVarieties("DCE") print("大商所品种: " + str(varieties_dce)) ``` -------------------------------- ### GetAtmOptionContractByPos - Get Option Contract Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves an at-the-money, in-the-money, or out-of-the-money option contract based on the underlying asset. ```APIDOC ## GetAtmOptionContractByPos - Get Option Contract ### Description Retrieves an at-the-money, in-the-money, or out-of-the-money option contract based on the underlying asset and specified parameters. ### Method Not specified (function call within a script) ### Endpoint Not applicable (local function) ### Parameters - **underlying_code** (string) - Required - The code of the underlying asset (e.g., "510050.SHSE", "m2001.DCE"). - **price_type** (string) - Required - Type of price reference (e.g., "now", "open"). - **delta_offset** (int) - Required - Offset from the at-the-money price. - **month_offset** (int) - Required - Offset for the contract month. - **option_type** (int or None) - Optional - Type of option: 0 for Call, 1 for Put. If None, retrieves both. ### Request Example ```python # Example usage within a Python script optioncode = GetAtmOptionContractByPos("510050.SHSE", "now", -1, 0, 1) ``` ### Response #### Success Response (string) - **string** - The contract code of the selected option. #### Response Example ```python # Example output print("50ETF认沽期权: " + optioncode) ``` ``` -------------------------------- ### GetHisDataAsDF - Get Historical Data as DataFrame Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves historical K-line data and returns it as a pandas DataFrame. ```APIDOC ## GetHisDataAsDF - Get Historical Data as DataFrame ### Description Retrieves historical K-line data and returns it as a pandas DataFrame. ### Method Not specified (function call within a script) ### Endpoint Not applicable (local function) ### Parameters - **code** (string) - Required - The contract code (e.g., 'rb2001.SHFE'). - **bar_type** (BarType enum) - Required - The type of bar (e.g., BarType.Min). - **start_date** (datetime or None) - Optional - The start date for the data. - **end_date** (datetime) - Required - The end date for the data. - **count** (int) - Required - The number of bars to retrieve. - **weight_type** (int) - Optional - Weighting type for data aggregation. ### Request Example ```python # Example usage within a Python script df = GetHisDataAsDF(code='rb2001.SHFE', bar_type=BarType.Min, count=10, weight_type=0) ``` ### Response #### Success Response (DataFrame) - **DataFrame** - A pandas DataFrame containing historical K-line data with columns like open, high, low, close, volume, etc. #### Response Example ```python # Example DataFrame output print(df) print(df.columns) print(df.head(2)) print(df.close) print(df.close[0:5]) ``` ``` -------------------------------- ### Controlling Trade Flow with OnTradeDeal in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This guide explains the use of the `OnTradeDeal` function in Poboquant for fine-grained control over trade execution. It allows developers to react to specific trade events and implement custom logic. ```Python from poboquant.strategy import Strategy class MyStrategy(Strategy): def on_trade_deal(self, trade_deal): # Custom logic when a trade is executed print(f'Trade executed: {trade_deal.instrument_id}, Price: {trade_deal.price}, Volume: {trade_deal.volume}') if trade_deal.direction == 'BUY': # Perform actions for buy trades pass else: # Perform actions for sell trades pass ``` -------------------------------- ### Get HisDataAsDF - Fetch Historical Data as DataFrame Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves historical K-line data and returns it as a pandas DataFrame. Useful for time-series analysis and backtesting. Requires specifying the contract code, bar type, and optionally start/end dates or count. ```python def OnAlarm(context, alarmid): code = 'rb2001.SHFE' # 获取DataFrame格式的K线数据 df = GetHisDataAsDF(code, bar_type=BarType.Min, start_date=None, end_date=GetCurrentTime(), count=10, weight_type=0) print(df) print(df.columns) print(df.head(2)) print(df.close) print(df.close[0:5]) ``` -------------------------------- ### Implement Strategy Initialization with OnStart Source: https://context7.com/qmhedging/poboquant/llms.txt The OnStart function is the entry point for strategy initialization. It is used to subscribe to market data, set timers, and log into trading accounts. ```python def OnStart(context): print("策略开始运行...") g.code = "rb2001.SHFE" SubscribeQuote(g.code) SubscribeBar(g.code, BarType.Day) context.MyAlarm1 = SetAlarm(datetime.time(9, 30)) context.myacc = None if "回测期货" in context.accounts: if context.accounts["回测期货"].Login(): context.myacc = context.accounts["回测期货"] ``` -------------------------------- ### GetIndicator - Get Technical Indicator Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves the calculated results for a built-in technical indicator. ```APIDOC ## GetIndicator - Get Technical Indicator ### Description Retrieves the calculated results for a built-in technical indicator for a specified contract and bar type. ### Method Not specified (function call within a script) ### Endpoint Not applicable (local function) ### Parameters - **indicator_name** (string) - Required - The name of the technical indicator (e.g., "MA"). - **contract_code** (string) - Required - The code of the contract for which to calculate the indicator. - **params** (tuple) - Required - The parameters for the indicator (e.g., (5, 10) for a 5-period and 10-period MA). - **bar_type** (BarType enum) - Required - The type of bar period (e.g., BarType.Min15). ### Request Example ```python # Example usage within a Python script MA = GetIndicator("MA", g.code, params=(5, 10), bar_type=BarType.Min15) ``` ### Response #### Success Response (dictionary) - **dictionary** - A dictionary where keys are indicator names (e.g., "MA(5)") and values are lists of calculated indicator values. #### Response Example ```python # Example output MA5 = MA["MA(5)"] print("MA5最新值: " + str(MA5[-1])) ``` ``` -------------------------------- ### Quick Order Execution Source: https://context7.com/qmhedging/poboquant/llms.txt A simplified interface for order placement using string-based parameters to specify action and side. ```python def OnBar(context, code, bartype): dyndata = GetQuote(g.code) QuickInsertOrder(context.myacc, g.code, 'buy', 'open', dyndata.now, 10) QuickInsertOrder(context.myacc, g.code, 'sell', 'close', dyndata.now, 10, True) ``` -------------------------------- ### Handle Market Quotation Initialization Source: https://context7.com/qmhedging/poboquant/llms.txt The OnMarketQuotationInitialEx event triggers when exchange data is ready. It allows for dynamic contract selection and subscription management. ```python def OnMarketQuotationInitialEx(context, exchange, daynight): if exchange != 'SHFE': return g.code = GetMainContract('SHFE', 'rb', 20) UnsubscribeAllBar() SubscribeBar(g.code, BarType.Min15) SubscribeQuote(g.code) ``` -------------------------------- ### Backtesting on Tick Level with Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This snippet demonstrates how to perform backtesting on a tick-by-tick basis using the Poboquant framework. It is essential for strategies requiring high-frequency data analysis. ```Python from poboquant.backtester import TickBacktester # Assuming you have tick data loaded into a pandas DataFrame tick_data = ... backtester = TickBacktester(tick_data) results = backtester.run() ``` -------------------------------- ### Importing and Reading CSV Files in Python Source: https://github.com/qmhedging/poboquant/wiki/Poboquant如何引入外部文件 Demonstrates how to import the necessary CSV library and read an uploaded file. Ensure the filename is 8 characters or less and do not include file paths when referencing the file. ```python import csv # Open the uploaded file directly by name with open('data.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row) ``` -------------------------------- ### InsertSmartOrder - Advanced Order Placement (Python) Source: https://context7.com/qmhedging/poboquant/llms.txt Implements advanced order placement functionalities including order splitting and reordering. It requires multiple parameter objects for order details, splitting logic, reordering strategy, and final cancellation timeout. Dependencies: context, GetQuote, OrderParam, SplitOrderParam, ReorderParam, CancelOrderParam, BSType, PbPriceType. Outputs: UID of the smart order if successful. ```python def TestSmartOrder(context, code): dyndata = GetQuote(code) # 生成委托参数对象 OrderParam1 = OrderParam() OrderParam1.Code = code OrderParam1.BSType = BSType.BuyOpen # 设置价格类型 from copy import deepcopy aPriceType = deepcopy(PbPriceType.Limit) aPriceType.LimitPriceType = 2 # 最新价 aPriceType.LimitPriceOffset = 10 # 超价10个tick OrderParam1.PyPriceType = aPriceType OrderParam1.Volume = 12 # 拆单参数 SplitOrderParam1 = SplitOrderParam() SplitOrderParam1.Mode = 2 # 0=不拆单, 1=固定拆单, 2=随机拆单 SplitOrderParam1.TimeSpan = 100 # 下单间隔时间(毫秒) SplitOrderParam1.RandomSplit.Threshold = 10 # 阈值: 大于10手才拆单 SplitOrderParam1.RandomSplit.LowerLimit = 3 # 每次委托下限数量 SplitOrderParam1.RandomSplit.UpperLimit = 6 # 每次委托上限数量 # 追单参数 ReorderParam1 = ReorderParam() ReorderParam1.PriceType = '2' # 限价 ReorderParam1.LimitPriceType = 16 # 对手价 ReorderParam1.LimitPriceOffset = 2 # 超价 ReorderParam1.RepeatTotal = 3 # 追价总次数 ReorderParam1.MaxaPriceOffset = 100 # 最大价差 ReorderParam1.TimeOut = 800 # 超时撤单时间(ms) # 最后撤单参数 CancelOrderParam1 = CancelOrderParam() CancelOrderParam1.TimeOut = 1500 # 最后超时撤单时间(ms) # 执行智能下单 ret = context.myacc.InsertSmartOrder(OrderParam1, SplitOrderParam1, ReorderParam1, CancelOrderParam1) if ret and ret.UID: g.SmartOrderUID = ret.UID # 记录智能单ID print("智能单提交成功,UID: " + str(ret.UID)) ``` -------------------------------- ### Debugging Techniques in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This section offers various tips and techniques for debugging trading strategies and the Poboquant framework itself. It covers common error scenarios and debugging workflows. ```Python # Using print statements for debugging print(f'Variable value: {my_variable}') # Using a debugger (e.g., pdb) import pdb pdb.set_trace() ``` -------------------------------- ### Introduction to High-Frequency Trading Strategies in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This section provides an overview of common high-frequency trading (HFT) strategies that can be implemented using Poboquant. It covers the principles and characteristics of HFT. ```Python # Common HFT strategies: # - Market Making # - Arbitrage # - Statistical Arbitrage # - Event-Driven Trading # Implementation would involve low-latency data handling and order execution. ``` -------------------------------- ### GetPositions - Query Account Holdings (Python) Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves the current holdings for a given account. It can fetch all positions or filter for specific contracts and buy/sell types. Dependencies include context and PBObj. Outputs are position details like contract, volume, and open average price. ```python def OnBar(context, code, bartype): # 查询所有持仓 positions = context.myacc.GetPositions() print("持仓数量: " + str(len(positions))) for pos in positions: print("合约: " + str(pos.contract)) print("持仓数量: " + str(pos.volume)) print("可用数量: " + str(pos.availvolume)) print("开仓均价: " + str(pos.openavgprice)) print("买卖方向: " + str(pos.bstype.BuySellFlag)) # 0=多头, 1=空头 print("----------------") # 查询指定合约的多头持仓 option = PBObj() option.contract = g.code option.buysellflag = '0' # 0=多头, 1=空头 long_positions = context.myacc.GetPositions(option) ``` -------------------------------- ### Choosing Between Python and C++ for Quant Strategies in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This discussion compares the use of Python and C++ for developing quantitative trading strategies within Poboquant. It helps users decide which language is more suitable based on performance, development speed, and complexity requirements. ```Python # Python example (simpler development) # C++ example (higher performance, more complex integration) ``` -------------------------------- ### Execute Trade Orders Source: https://context7.com/qmhedging/poboquant/llms.txt Demonstrates how to send buy and sell orders for futures and stocks using the account's InsertOrder method. ```python def OnBar(context, code, bartype): dyndata = GetQuote(g.code) context.myacc.InsertOrder(g.code, BSType.BuyOpen, dyndata.now + 5, 10) context.myacc.InsertOrder(g.code, BSType.SellClose, dyndata.now - 5, 10) context.myacc.InsertOrder("600519.SHSE", BSType.Buy, dyndata.now, 100) ``` -------------------------------- ### GetOrders - Query Account Orders (Python) Source: https://context7.com/qmhedging/poboquant/llms.txt Fetches all outstanding orders for an account. It iterates through the orders to display details such as order ID, volume, price, status, and whether the order is cancellable. Requires context object. Outputs include order status and cancellation eligibility. ```python def OnAlarm(context, alarmid): # 查询所有委托 orders = context.myacc.GetOrders() print("委托数量: " + str(len(orders))) for order in orders: print('委托编号: ' + str(order.id)) print('委托数量: ' + str(order.volume)) print('委托价格: ' + str(order.price)) print('委托状态: ' + str(order.status)) print('是否可撤: ' + str(order.IsCanCancel())) print("----------------") ``` -------------------------------- ### Retrieve Historical Market Data Source: https://context7.com/qmhedging/poboquant/llms.txt Demonstrates various ways to fetch historical K-line data, including full objects, simplified counts, and specific fields. ```python # Fetching with options klinedata = GetHisData(g.code, BarType.Day) # Simplified fetching kline = GetHisData2(code, bar_type=BarType.Min, count=10) # Fetching specific fields close_list = GetHisDataByField(g.code, BarType.Day, "close", option) ``` -------------------------------- ### Importing External Files into Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This section covers the methods for importing various external data files into the Poboquant framework. This is crucial for loading historical data, parameters, or other necessary information for strategy execution. ```Python from poboquant.data import DataLoader data_loader = DataLoader() # Example: Loading CSV data price_data = data_loader.load_csv('path/to/your/data.csv') # Example: Loading Excel data (requires pandas and openpyxl) excel_data = data_loader.load_excel('path/to/your/data.xlsx') ``` -------------------------------- ### Process Real-time Tick Data with OnQuote Source: https://context7.com/qmhedging/poboquant/llms.txt The OnQuote event triggers on every new tick. It is used for high-frequency monitoring and accessing the latest market price. ```python def OnQuote(context, code): if code != g.code: return dyndata = GetQuote(g.code) if dyndata: log.info("最新价: " + str(dyndata.now)) ``` -------------------------------- ### Manage Strategy Timers Source: https://context7.com/qmhedging/poboquant/llms.txt Demonstrates setting and killing a timer within a strategy. The timer triggers a callback function periodically until a specific condition is met. ```python def OnStart(context): g.TimerID = SetTimer(60) context.counter = 0 def OnTimer(context, timerid): context.counter += 1 if context.counter >= 5: KillTimer(g.TimerID) ``` -------------------------------- ### AccountBalance - Query Account Financial Status (Python) Source: https://context7.com/qmhedging/poboquant/llms.txt Fetches the financial status of an account, including assets balance, dynamic net assets, and market value of holdings. This function accesses the AccountBalance object from the context. Outputs are key financial metrics of the account. ```python def OnBar(context, code, bartype): # 获取账户余额对象 bal = context.myacc.AccountBalance # 资产余额 print("资产余额: " + str(bal.AssetsBalance)) # 动态权益 print("动态权益: " + str(bal.DynamicNetAssets)) # 持仓市值 print("持仓市值: " + str(bal.MarketValue)) ``` -------------------------------- ### Schedule Tasks with OnAlarm Source: https://context7.com/qmhedging/poboquant/llms.txt The OnAlarm function handles events triggered by pre-set timers, useful for market opening or closing routines. ```python def OnAlarm(context, alarmid): if alarmid == context.MyAlarm1: print("执行9:30开盘操作...") elif alarmid == context.MyAlarm2: print("执行14:50收盘前操作...") ``` -------------------------------- ### Sending Email Notifications for Trading Signals and Trades in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This functionality allows users to set up email alerts for trading signals and trade execution information within Poboquant. It requires configuration of email sending parameters. ```Python from poboquant.notifier import EmailNotifier notifier = EmailNotifier(smtp_server='smtp.example.com', port=587, username='user@example.com', password='password') # To send a notification notifier.send_notification('Trading Signal', 'Buy BTCUSD at 30000') ``` -------------------------------- ### InsertAbsStopLossPosition Source: https://context7.com/qmhedging/poboquant/llms.txt Sets an absolute price stop-loss order for a specific position. ```APIDOC ## POST /InsertAbsStopLossPosition ### Description Sets an absolute price stop-loss order for a given account and instrument. ### Method POST ### Endpoint InsertAbsStopLossPosition(context.myacc, code, direction, price, volume) ### Parameters #### Path Parameters - **context.myacc** (Object) - Required - The account object. - **code** (String) - Required - The instrument code. - **direction** (String) - Required - 'buy' for long or 'sell' for short. - **price** (Float) - Required - The absolute price trigger. - **volume** (Integer) - Required - The volume to close. ### Request Example InsertAbsStopLossPosition(context.myacc, "MA905.CZCE", "buy", 2500.0, 10) ``` -------------------------------- ### Handling Common Errors and Debugging in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This section addresses common error messages encountered while using Poboquant and outlines the debugging process. It aims to help users resolve issues efficiently. ```Python # Example of error handling try: # Code that might raise an error result = 10 / 0 except ZeroDivisionError as e: print(f'An error occurred: {e}') # Log the error or take corrective action ``` -------------------------------- ### CreateIndicator - Create and Calculate Custom Indicator Source: https://context7.com/qmhedging/poboquant/llms.txt Allows the creation of indicator objects, setting custom parameters, and attaching them to specific codes and bar types for calculation. This provides flexibility in using and analyzing various technical indicators like MACD. It includes logic for generating buy/sell signals based on indicator crossovers. ```python def OnBar(context, code, bartype): # 创建MACD指标对象 MACDindi = CreateIndicator("MACD") # 设定参数 param = {"SHORT": 12, "LONG": 26, "M": 9} MACDindi.SetParameter(param) # 设定要计算的品种和K线周期 MACDindi.Attach(g.code, BarType.Day) # 开始计算 MACDindi.Calc() # 获取计算结果 diff = MACDindi.GetValue("DIF") dea = MACDindi.GetValue("DEA") if len(diff) < 2: return # MACD金叉买入 if diff[-1] > 0 and dea[-1] > 0 and diff[-1] > dea[-1] and diff[-2] <= dea[-2]: print("MACD金叉,买入信号") context.myacc.InsertOrder(g.code, BSType.BuyOpen, dyndata.now + 5, 10) # MACD死叉卖出 elif diff[-1] < 0 and dea[-1] < 0 and diff[-1] < dea[-1] and diff[-2] >= dea[-2]: print("MACD死叉,卖出信号") context.myacc.InsertOrder(g.code, BSType.SellClose, dyndata.now - 5, 10) ``` -------------------------------- ### Black-Scholes Option Pricing Model Source: https://context7.com/qmhedging/poboquant/llms.txt Utilizes the Black-Scholes model to calculate theoretical option prices and Greeks based on provided market parameters like asset price, strike price, and volatility. ```python def OnQuote(context, code): CalOBJ = CreateCalcObj() OptDirection = 0 AssetType = 1 AssetPrice = 2.65 StrikePrice = 2.6 HisVola = 0.20 InterestRate = 0.045 ExpireinYear = 0.1 OptionPrice = 0.08 BSPrice = CalOBJ.GetOptionBSPrice(OptDirection, AssetType, AssetPrice, StrikePrice, HisVola, InterestRate, ExpireinYear) print("BS理论价格: " + str(BSPrice)) OptDelta = CalOBJ.GetOptionDelta(OptDirection, AssetType, AssetPrice, StrikePrice, HisVola, InterestRate, ExpireinYear) print("Delta: " + str(OptDelta)) ``` -------------------------------- ### Retrieve Time and Trading Date Information Source: https://context7.com/qmhedging/poboquant/llms.txt Functions to access the current system time, current trading date for specific exchanges, and lists of trading dates within a range. ```python def OnBar(context, code, bartype): cutime = GetCurrentTime() cur_trade_day = GetCurrentTradingDate('SHFE') trade_dates = GetTradingDates('SHFE', 20190801, 20190930) pre_trade_day = GetPreviousTradingDate('SHFE', cur_trade_day) next_trade_day = GetNextTradingDate('SHFE', cur_trade_day) ``` -------------------------------- ### Product Codes of Exchanges in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This resource lists the product codes for various exchanges supported by Poboquant, along with their corresponding contract codes. This information is essential for correctly identifying and trading financial instruments. ```N/A # Example format: # Exchange: SSE, Product Code: 510300, Contract Code: 510300.SSE # Exchange: CME, Product Code: ES, Contract Code: ESZ3.CME ``` -------------------------------- ### Optimizing Tick Data Processing with Numpy and Deque in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This snippet highlights techniques for efficient processing of tick-level data in Poboquant, emphasizing the use of Numpy for numerical operations and collections.deque for fast append/pop operations, crucial for high-frequency trading. ```Python import numpy as np from collections import deque # Example: Using deque for recent prices price_deque = deque(maxlen=100) # Example: Using numpy for calculations on tick data def calculate_vwap(ticks): prices = np.array([t.last_price for t in ticks]) volumes = np.array([t.volume for t in ticks]) return np.sum(prices * volumes) / np.sum(volumes) ``` -------------------------------- ### GetAtmOptionContractByPos - Fetch ATM/OTM/ITM Option Contracts Source: https://context7.com/qmhedging/poboquant/llms.txt Fetches option contract codes based on the underlying asset, price type (e.g., 'now', 'open'), and position relative to the strike price (e.g., 'atm', 'otm', 'itm'). It can also filter by month and option type (call/put). Useful for option strategy implementation. ```python def OnAlarm(context, alarmid): # 获取50ETF股票期权合约 # 参数: 标的代码, 价格类型, 档位偏移, 月份偏移, 期权类型(0=认购,1=认沽) optioncode = GetAtmOptionContractByPos("510050.SHSE", "now", -1, 0, 1) print("50ETF认沽期权: " + optioncode) # 获取豆粕期货期权合约 optioncode2 = GetAtmOptionContractByPos("m2001.DCE", "open", 0, 0, None) print("豆粕平值期权: " + optioncode2) # 获取期权K线数据 kline = GetHisData2(optioncode2, bar_type=BarType.Min, count=10) ``` -------------------------------- ### OnOrderChange - Order Status Change Event (Python) Source: https://context7.com/qmhedging/poboquant/llms.txt This is an event handler that is triggered whenever an order's status changes. It logs details about the order, including its ID, account name, volume, price, status, buy/sell type, and cancellation eligibility. It requires context, account name, and order objects. ```python def OnOrderChange(context, AccountName, order): print("委托编号: " + order.id + " 账号名称: " + AccountName) print("委托数量: " + str(order.volume)) print("委托价格: " + str(order.price)) print("委托状态: " + str(order.status)) print("买卖方向: " + str(order.bstype.BuySellFlag)) print("是否可撤: " + str(order.IsCanCancel())) ``` -------------------------------- ### Timer Management Source: https://context7.com/qmhedging/poboquant/llms.txt Functions to handle periodic execution via timers. ```APIDOC ## POST /TimerManagement ### Description Set and kill timers within the strategy lifecycle. ### Methods - **SetTimer(seconds)**: Starts a timer that triggers OnTimer every N seconds. - **KillTimer(timerid)**: Stops a running timer. ### Request Example g.TimerID = SetTimer(60) KillTimer(g.TimerID) ``` -------------------------------- ### CreateIndicator - Create Indicator Object Source: https://context7.com/qmhedging/poboquant/llms.txt Creates an indicator object and allows for custom parameter calculation. ```APIDOC ## CreateIndicator - Create Indicator Object ### Description Creates an indicator object, sets its parameters, attaches it to a contract and bar type, and then calculates and retrieves its values. ### Method Not specified (function call within a script) ### Endpoint Not applicable (local function) ### Parameters - **indicator_name** (string) - Required - The name of the indicator to create (e.g., "MACD", "ATR"). ### Methods on Indicator Object: - **SetParameter(params: dict)**: Sets the parameters for the indicator. - **Attach(contract_code: str, bar_type: BarType)**: Attaches the indicator to a specific contract and bar type. - **Calc()**: Performs the indicator calculation. - **GetValue(value_name: str)**: Retrieves the calculated values (e.g., "DIF", "DEA", "ATR"). ### Request Example ```python # Example usage for MACD MACDindi = CreateIndicator("MACD") param = {"SHORT": 12, "LONG": 26, "M": 9} MACDindi.SetParameter(param) MACDindi.Attach(g.code, BarType.Day) MACDindi.Calc() diff = MACDindi.GetValue("DIF") ``` ### Response #### Success Response (object) - **Indicator Object** - An object representing the created and configured technical indicator. #### Response Example ```python # Example output print("MACD金叉,买入信号") ``` ``` -------------------------------- ### Uploading and Reading Excel Attachments in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This functionality covers how to upload Excel files as strategy attachments in Poboquant and subsequently read their content within the strategy code. This is useful for loading configuration or parameters from external files. ```Python from poboquant.data import DataLoader data_loader = DataLoader() # Assuming 'strategy_context' has access to attachment paths # attachment_path = strategy_context.get_attachment_path('my_parameters.xlsx') # parameters = data_loader.load_excel(attachment_path) # Example of reading data from an Excel file # df = pd.read_excel('my_parameters.xlsx') # print(df) ``` -------------------------------- ### Time and Trading Date APIs Source: https://context7.com/qmhedging/poboquant/llms.txt Functions to retrieve system time, current trading dates, and manage trading date ranges. ```APIDOC ## GET /TimeAndTradingDate ### Description Utilities for retrieving current time, trading dates for specific exchanges, and calculating relative trading days. ### Methods - **GetCurrentTime()**: Returns current system/backtest time. - **GetCurrentTradingDate(exchange)**: Returns current trading date for the exchange. - **GetTradingDates(exchange, start, end)**: Returns a list of trading dates. - **GetPreviousTradingDate(exchange, date)**: Returns the previous trading date. - **GetNextTradingDate(exchange, date)**: Returns the next trading date. ### Parameters - **exchange** (String) - Required - Exchange code (e.g., 'SHFE'). - **start/end** (Integer) - Required - Date in YYYYMMDD format. ``` -------------------------------- ### Option Greeks Calculation Source: https://context7.com/qmhedging/poboquant/llms.txt Provides methods to calculate Greeks (Delta, Theta, Gamma, Vega, Rho) for options. ```APIDOC ## GET /api/calc/GetOptionGreeks ### Description Retrieves the Greeks for a specific option contract based on historical data window and pricing type. ### Method GET ### Endpoint /api/calc/GetOptionGreeks ### Parameters #### Query Parameters - **code** (string) - Required - Option contract code - **window** (int) - Required - Lookback window for calculation - **pricetype** (string) - Optional - Pricing type (default: "now") - **r** (float) - Optional - Risk-free rate ### Response #### Success Response (200) - **delta** (float) - Delta value - **theta** (float) - Theta value - **gamma** (float) - Gamma value - **vega** (float) - Vega value - **rho** (float) - Rho value ``` -------------------------------- ### InsertOrder - Place Trade Order Source: https://context7.com/qmhedging/poboquant/llms.txt Executes a trade order (buy/sell/open/close) for stocks or futures. ```APIDOC ## POST /api/trade/InsertOrder ### Description Submits a trade order to the account for execution. ### Method POST ### Endpoint /api/trade/InsertOrder ### Parameters #### Request Body - **code** (string) - Required - Asset code - **direction** (enum) - Required - BSType (BuyOpen, SellClose, SellOpen, BuyClose, Buy, Sell) - **price** (float) - Required - Order price - **volume** (int) - Required - Order quantity ### Response #### Success Response (200) - **status** (string) - Order submission status ``` -------------------------------- ### Canceling Orders in Poboquant Source: https://github.com/qmhedging/poboquant/wiki/_Footer This functionality details how to cancel existing orders in Poboquant. It is crucial for risk management and adjusting positions during live trading. ```Python from poboquant.api import PoboquantAPI api = PoboquantAPI() # Assuming 'order_id' is the ID of the order to cancel api.cancel_order(order_id=12345) ``` -------------------------------- ### GetMainContract - Fetch Main Contract Code Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves the main contract code for a given exchange and variety, typically based on trading volume. This is useful for focusing on the most actively traded contract. It takes exchange, variety, and a percentage threshold as input. ```python def OnMarketQuotationInitialEx(context, exchange, daynight): if exchange != 'SHFE': return # 获取上期所螺纹钢主力合约(成交量排名前20%) g.code = GetMainContract('SHFE', 'rb', 20) print("螺纹钢主力合约: " + g.code) # 获取大商所豆粕主力合约 soybean_main = GetMainContract('DCE', 'm', 20) print("豆粕主力合约: " + soybean_main) # 获取郑商所白糖主力合约 sugar_main = GetMainContract('CZCE', 'SR', 20) print("白糖主力合约: " + sugar_main) ``` -------------------------------- ### GetContractInfo - Fetch Contract Details Source: https://context7.com/qmhedging/poboquant/llms.txt Retrieves detailed information for a specific futures or options contract, including expiry dates, strike prices, and underlying assets. This function is essential for understanding contract specifications and performing date-based calculations. ```python def OnAlarm(context, alarmid): # 获取期货合约信息 info1 = GetContractInfo("rb2001.SHFE") print("最后交易日: " + str(info1['最后交易日'])) # 获取期权合约信息 info2 = GetContractInfo("m2001-C-2800.DCE") print("最后交易日: " + str(info2['最后交易日'])) print("行权价格: " + str(info2['行权价格'])) print("期权标的: " + str(info2['期权标的'])) print("期权种类: " + str(info2['期权种类'])) print("期权类型: " + str(info2['期权类型'])) print("行权到期日: " + str(info2['行权到期日'])) # 计算距离到期日天数 cutime = GetCurrentTime().date() n = (info2['最后交易日'] - cutime).days print("距到期日: " + str(n) + "天") ``` -------------------------------- ### Send Email Notifications in PoboQuant Source: https://github.com/qmhedging/poboquant/wiki/如何用poboquant发送邮件提醒交易信号、成交信息 This function utilizes Python's standard email libraries to construct and send SMTP messages. It is designed to be called within a trading strategy after a signal is triggered or a trade is executed. ```python from email.header import Header import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(subject, content, sender, password, receiver, smtp_server): msg = MIMEMultipart() msg['Subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = receiver msg.attach(MIMEText(content, 'plain', 'utf-8')) server = smtplib.SMTP_SSL(smtp_server, 465) server.login(sender, password) server.sendmail(sender, [receiver], msg.as_string()) server.quit() ```