### Run PyQtGraph Examples in VeighNa Studio Source: https://www.vnpy.com/docs/cn/community/install/windows_install This code snippet demonstrates how to run the built-in examples for the pyqtgraph library within the VeighNa Studio Python environment. It imports the examples module and calls the run() function to launch the example viewer. This is useful for testing and exploring the capabilities of pyqtgraph. ```python from pyqtgraph import examples examples.run() ``` -------------------------------- ### Configure CTP Interface Connection (SimNow Example) Source: https://www.vnpy.com/docs/cn/community/info/veighna_trader This example demonstrates the configuration parameters required to connect to the CTP trading interface using the SimNow simulation. It includes details for username, password, broker ID, trading and market servers, product name, and authorization code. Proper configuration is crucial for successful market data access and trade execution. ```text 用户名:xxxxxx (6位纯数字账号) 密码:xxxxxx (需要修改一次密码用于盘后测试) 经纪商代码:9999 (SimNow默认经纪商编号) 交易服务器:182.254.243.31:30001 (盘中测试) 行情服务器:182.254.243.31:30011 (盘中测试) 产品名称:simnow_client_test 授权编码:0000000000000000 (16个0) ``` -------------------------------- ### Launch VeighNa Trader Application Source: https://www.vnpy.com/docs/cn/community/install/windows_install This command initiates the VeighNa Trader application by running the 'run.py' script located in the 'examples/veighna_trader' directory. Users can customize the script to include specific trading interfaces and application modules based on their operating system and trading requirements. It's recommended to uncomment the desired interface loading lines. ```shell python run.py ``` -------------------------------- ### Install VeighNa via install.bat Script Source: https://www.vnpy.com/docs/cn/community/install/windows_install This command executes a batch script to automate the installation of VeighNa and its dependencies, including the ta-lib library. It's designed for users who have manually prepared their Python environment. The script performs a two-step installation process: first installing ta-lib, then VeighNa itself. ```shell install.bat ``` -------------------------------- ### Implement on_start Callback in Python Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_ctastrategy The on_start function is executed when a strategy is started. It logs the strategy startup and sets the strategy's 'trading' status to True, enabling it to send trading signals. ```python def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") ``` -------------------------------- ### Installing VN.PY Package Source: https://www.vnpy.com/docs/cn/community/info/i18n This command installs the VN.PY package using pip. Ensure that your `MANIFEST.in` file includes `*.mo` to package the compiled translation files correctly. ```shell pip install . ``` -------------------------------- ### Creating Language Directories and Copying .po Files Source: https://www.vnpy.com/docs/cn/community/info/i18n This command sequence illustrates how to create the necessary directory structure for individual language files and copy the template .po file into the appropriate language-specific location. This prepares the files for translation. ```shell mkdir -p vnpy/trader/locale/{en, es}/LC_MESSAGES cp vnpy/trader/locale/vnpy.pot vnpy/trader/locale/en/LC_MESSAGES/vnpy.po cp vnpy/trader/locale/vnpy.pot vnpy/trader/locale/es/LC_MESSAGES/vnpy.po ``` -------------------------------- ### Install PyXLL and ExcelRtd Module Source: https://www.vnpy.com/docs/cn/community/app/excel_rtd Commands to install the PyXLL plugin and integrate the vnpy_rtd.py file into the PyXLL examples directory. This is a prerequisite for using the ExcelRtd module. ```bash pip install pyxll pyxll install ``` -------------------------------- ### CTA策略回调函数:on_start (Python) Source: https://www.vnpy.com/docs/cn/community/app/cta_strategy on_start是策略启动时调用的回调函数。用于输出启动日志。调用此函数后,策略的trading状态变为True,可以开始发出交易信号。 ```python def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") ``` -------------------------------- ### Translating Messages in .po Files Source: https://www.vnpy.com/docs/cn/community/info/i18n This example demonstrates how to translate messages within a Portable Object (.po) file. It shows the structure of a .po file, including `msgid` (the original string) and `msgstr` (the translated string). Ensure the `charset` is set to UTF-8 and pay attention to language-specific punctuation. ```po #: vnpy/trader/optimize.py:62 msgid "范围参数添加成功,数量{}" msgstr "" ``` ```po #: vnpy/trader/optimize.py:62 msgid "范围参数添加成功,数量{}" msgstr "Range parameter added successfully, quantity {}" ``` ```po #: vnpy/trader/optimize.py:45 msgid "固定参数添加成功" msgstr "" ``` ```po #: vnpy/trader/optimize.py:48 msgid "参数优化起始点必须小于终止点" msgstr "" ``` ```po #: vnpy/trader/optimize.py:45 msgid "固定参数添加成功" msgstr "Fixed parameters added successfully" ``` ```po #: vnpy/trader/optimize.py:62 msgid "范围参数添加成功,数量{}" msgstr "Range parameter added successfully, quantity {}" ``` -------------------------------- ### 初始化多合约组合策略类 Source: https://www.vnpy.com/docs/cn/community/app/portfolio_strategy 策略类的__init__函数是其构造函数,负责初始化策略实例。它需要继承自StrategyTemplate,并接收策略引擎、策略名称、交易合约列表和设置字典作为参数。初始化过程包括调用父类构造函数、创建存储策略变量的字典,以及配置K线生成器。 ```python def __init__( self, strategy_engine: StrategyEngine, strategy_name: str, vt_symbols: List[str], setting: dict ): """ """ super().__init__(strategy_engine, strategy_name, vt_symbols, setting) self.boll_up: Dict[str, float] = {} self.boll_down: Dict[str, float] = {} self.cci_value: Dict[str, float] = {} self.atr_value: Dict[str, float] = {} self.intra_trade_high: Dict[str, float] = {} self.intra_trade_low: Dict[str, float] = {} self.targets: Dict[str, int] = {} self.last_tick_time: datetime = None self.ams: Dict[str, ArrayManager] = {} for vt_symbol in self.vt_symbols: self.ams[vt_symbol] = ArrayManager() self.targets[vt_symbol] = 0 self.pbg = PortfolioBarGenerator(self.on_bars, 2, self.on_2hour_bars, Interval.HOUR) ``` -------------------------------- ### 解决图形驱动问题 - Ubuntu Source: https://www.vnpy.com/docs/cn/community/install/ubuntu_install 如果在Ubuntu图形界面下启动时遇到Qt平台插件加载错误,可以尝试安装libxcb-xinerama0库来解决图形驱动的依赖问题。 ```bash sudo apt-get install libxcb-xinerama0 ``` -------------------------------- ### BacktestingEngine Setup and Execution Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy This section covers the core functions for setting up and running a backtest using the BacktestingEngine. ```APIDOC ## BacktestingEngine API ### Description Provides functions to configure, run, and analyze backtesting for trading strategies. ### Methods #### `set_parameters` ##### Description Sets the external parameters for the BacktestingEngine instance. ##### Parameters - **interval** (Interval) - Required - The time interval for backtesting (e.g., MINUTE, HOUR). - **start** (datetime) - Required - The start date for the backtest. - **end** (datetime) - Required - The end date for the backtest. - **rate** (float) - Required - The trading commission rate. - **slippage** (float) - Required - The trading slippage. - **capital** (int) - Optional - The initial trading capital. Defaults to 1,000,000. - **cache** (str) - Optional - The name for data caching. Defaults to "". - **memory** (bool) - Optional - Whether to use in-memory cache. Defaults to False. ##### Response - None #### `add_strategy` ##### Description Adds an option strategy instance and its settings to the BacktestingEngine instance. ##### Parameters - **strategy_class** (Type[StrategyTemplate]) - Required - The class of the strategy to add. - **setting** (dict) - Required - A dictionary containing the strategy's specific settings. ##### Response - None #### `run_backtesting` ##### Description Executes the backtesting task day by day. The engine replays historical data and simulates trading conditions, re-initializing the strategy object daily. ##### Parameters - **disable_tqdm** (bool) - Optional - Whether to disable the progress bar. Defaults to False. ##### Response - None ##### Detailed Process - **Intraday Backtesting:** Loads yesterday's closing positions and price data, updates daily statistics. Initializes a new strategy instance, restores positions, and executes initialization. Loads historical data based on subscriptions (all subscribed contracts). Executes strategy startup and data replay (handling order matching and historical data push). Executes strategy stop, retrieves closing positions, and updates closing data to statistics. #### `calculate_result` ##### Description Calculates the daily mark-to-market profit and loss for the strategy instance. ##### Parameters - None ##### Response - None #### `calculate_statistics` ##### Description Calculates and outputs statistical indicators based on the strategy instance's daily mark-to-market profit and loss. ##### Parameters - **df** (DataFrame) - Optional - A DataFrame containing the daily P&L. If None, uses the engine's internal results. Defaults to None. - **output** (bool) - Optional - Whether to print the statistics. Defaults to True. ##### Response - None #### `show_chart` ##### Description Displays charts based on the backtesting results of the strategy instance. ##### Parameters - **df** (DataFrame) - Optional - A DataFrame containing the backtesting results. If None, uses the engine's internal results. Defaults to None. ##### Response - None ### Request Example ```python from vnpy.app.cta_strategy import BacktestingEngine, Interval from datetime import datetime engine = BacktestingEngine() engine.set_parameters( interval=Interval.MINUTE, start=datetime(2023, 1, 1), end=datetime(2023, 11, 30), rate=0.0001, slippage=0.0002, capital=1000000, ) # Assuming IoStrategy is defined elsewhere # engine.add_strategy(IoStrategy, {}) # engine.run_backtesting() # engine.calculate_result() # engine.calculate_statistics() # engine.show_chart() ``` ``` -------------------------------- ### Python: K线数据处理与交易信号生成 Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_ctastrategy 该函数在接收到最新的K线数据后被调用,用于计算技术指标(如均线、均线差值),生成交易信号(如金叉、死叉),并根据策略逻辑(持仓时间、止损、开仓/平仓信号)设置新的交易目标。最后执行交易并更新UI。 ```Python def on_history(self, hm: HistoryManager) -> None: """K线推送""" # 计算均线数组 fast_array: ndarray = sma(hm.close, self.fast_window) slow_array: ndarray = wma(hm.close, self.slow_window) # 计算均线差值 diff_array: ndarray = fast_array - slow_array rumi_array: ndarray = sma(diff_array, self.rumi_window) self.rumi_0 = rumi_array[-1] self.rumi_1 = rumi_array[-2] # 判断上下穿 long_signal: bool = cross_over(rumi_array, 0) short_signal: bool = cross_below(rumi_array, 0) # 计算交易数量 self.trading_size = self.calculate_volume(self.risk_capital, self.risk_window, 1000, 1) # 获取当前目标 last_target: int = self.get_target() # 初始化新一轮目标(默认不变) new_target: int = last_target # 执行开仓信号 if long_signal: new_target = self.trading_size elif short_signal: new_target = -self.trading_size # 持仓时间平仓 if self.bar_since_entry() >= self.max_holding: new_target = 0 # 保护止损平仓 close_price = hm.close[-1] if last_target > 0: stop_price: float = self.long_average_price() * (1 - self.stop_percent) if close_price <= stop_price: new_target = 0 elif last_target < 0: stop_price: float = self.short_average_price() * (1 + self.stop_percent) if close_price >= stop_price: new_target = 0 # 设置新一轮目标 self.set_target(new_target) # 执行目标交易 self.execute_trading(self.price_add) # 推送UI更新 self.put_event() ``` -------------------------------- ### Strategy Lifecycle and State Management Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy Functions for initializing, starting, and stopping trading strategies, and managing their states. ```APIDOC ## Strategy Lifecycle Callbacks ### on_init * **Description**: Initializes the strategy, subscribes to market data, and sets up global cache variables. * **Method**: Callback * **Parameters**: * Path Parameters: None * Query Parameters: None * Request Body: None * **Response**: * Success Response (None): * **Example**: ```python def on_init(self): self.write_log("策略初始化") self.subscribe_options("510050_O") # Example subscription self.inited = True self.trading = False ``` ### on_start * **Description**: Starts the strategy, enabling it to send trading signals. * **Method**: Callback * **Parameters**: * Path Parameters: None * Query Parameters: None * Request Body: None * **Response**: * Success Response (None): * **Example**: ```python def on_start(self): self.write_log("策略启动") self.trading = True ``` ### on_stop * **Description**: Stops the strategy, disabling it from sending trading signals. * **Method**: Callback * **Parameters**: * Path Parameters: None * Query Parameters: None * Request Body: None * **Response**: * Success Response (None): * **Example**: ```python def on_stop(self): self.write_log("策略停止") self.trading = False ``` ``` -------------------------------- ### Python: 计算风险调整后的委托数量 Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_ctastrategy 此函数根据风险资本、K线周期窗口、最大和最小委托量来计算风险调整后的委托数量。注意,risk_window的长度不能超过HistoryManager的bar_buffer长度。 ```Python def calculate_volume(self, risk_capital: float, risk_window: int, max_volume = 0, min_volume: int = 0) -> int: """计算风险调整后的委托数量""" pass ``` -------------------------------- ### Get Pricetick (Python) Source: https://www.vnpy.com/docs/cn/community/app/cta_strategy Fetches the minimum price fluctuation (tick size) for the currently traded contract. This information is vital for accurate order placement and calculations. Returns None if the pricetick cannot be determined. ```python def get_pricetick(self) -> float: """ Get the pricetick of the contract. """ # ... implementation details ... pass ``` -------------------------------- ### Configure Contract Parameters for Data Operations Source: https://www.vnpy.com/docs/cn/community/info/database Sets up specific parameters for a financial contract to be used in database operations. This includes symbol, exchange, start and end dates, and the time interval for historical data. ```python # 合约代码,888为米筐的连续合约,仅用于示范,具体合约代码请根据需求自行更改 symbol = "cu888" # 交易所,目标合约的交易所 exchange = Exchange.SHFE # 历史数据开始时间,精确到日 start = datetime(2019, 1, 1) # 历史数据结束时间,精确到日 end = datetime(2021, 1, 20) # 数据的时间粒度,这里示例采用日级别 interval = Interval.DAILY ``` -------------------------------- ### 获取特定合约目标仓位 (Python) Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy 在策略中调用get_target函数,可以获取已设定的特定合约目标仓位。策略的目标仓位状态会在sync_data时自动持久化到硬盘文件,并在策略重启后恢复。入参为合约标识符,出参为整数目标仓位。 ```python get_target(vt_symbol: str) -> int ``` -------------------------------- ### Get Engine Type (Python) Source: https://www.vnpy.com/docs/cn/community/app/cta_strategy Retrieves the type of the current trading engine (e.g., backtesting or live trading). This is useful for implementing conditional logic that differs between backtesting and live environments. Requires importing EngineType. ```python def get_engine_type(self) -> EngineType: """ Get the type of the current engine. """ # ... implementation details ... pass ``` -------------------------------- ### Access Real-Time Data in Excel using rtd_tick_data Source: https://www.vnpy.com/docs/cn/community/app/excel_rtd Example of using the rtd_tick_data function in Excel to fetch real-time tick data for a specific contract. It demonstrates how to specify the vt_symbol and TickData attributes. ```excel =rtd_tick_data("yf2205", "bid_price_1") =rtd_tick_data("yf2205", "high_price") =rtd_tick_data("yf2205", "low_price") =rtd_tick_data("yf2205", "last_price") ``` -------------------------------- ### 策略初始化 (on_init) - Python Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_spreadtrading on_init函数在策略初始化时被调用。它用于设置BarGenerator、ArrayManager,配置交易模式(AlgoType, AlgoOffset),并加载历史数据。ArrayManager的size参数应大于指标周期长度。此函数完成后,策略的inited状态变为True。 ```python def on_init(self): """ Callback when strategy is inited. """ self.bg = BarGenerator(self.on_spread_bar) self.am = ArrayManager(self.ma_window + 10) # 价差算法交易模式配置 self.algo_type: AlgoType = AlgoType.TAKER self.algo_offset: AlgoOffset = AlgoOffset.NET self.write_log("策略初始化") self.load_bar(10) ``` -------------------------------- ### 基于目标仓位执行调仓交易 (Python) Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy 在策略中调用execute_trading函数,可以基于设定的特定合约目标仓位执行调仓交易。该函数接管委托下单和撤单操作。它会先撤销所有活动委托,然后根据目标仓位和持仓仓差进行委托。仅当price_data中包含切片合约时,该合约才会参与交易执行。入参为价格数据字典和百分比增量。 ```python execute_trading(price_data: Dict[str, float], percent_add: float) ``` -------------------------------- ### Load RpcServiceApp in VN.PY Script Source: https://www.vnpy.com/docs/cn/community/app/rpc_service This code snippet demonstrates how to add the RpcServiceApp to the main engine in a VN.PY startup script. Ensure this is done after the main_engine object is created and before starting other modules. This is essential for enabling RPC server functionality. ```python # Write at the top from vnpy_rpcservice import RpcServiceApp # Write after creating the main_engine object main_engine.add_app(RpcServiceApp) ``` -------------------------------- ### Generating .pot Translation Template Files with xgettext Source: https://www.vnpy.com/docs/cn/community/info/i18n This command-line instruction uses `xgettext` to extract translatable strings from Python files into a Portable Object Template (.pot) file. This is an alternative method to `pygettext.py` for generating the template. ```shell xgettext -o vnpy/trader/locale/base.pot `find ./vnpy -name "*.py"` ``` -------------------------------- ### 处理 K 线数据并合成更长周期 K 线 (Python) Source: https://www.vnpy.com/docs/cn/community/app/portfolio_strategy 当策略收到最新的 K 线数据时,on_bars 函数会被调用。对于多合约组合策略,它一次性接收该时间点上所有合约的 K 线数据。若策略需要基于这些 K 线合成更长时间周期的 K 线,则在 on_bars 中调用 PortfolioBarGenerator 的 update_bars 函数。 ```python def on_bars(self, bars: Dict[str, BarData]): """ Callback of new bars data update. """ self.pbg.update_bars(bars) ``` -------------------------------- ### 加载PortfolioStrategy模块 (Python) Source: https://www.vnpy.com/docs/cn/community/app/portfolio_strategy 在VN.PY脚本中加载PortfolioStrategyApp。此代码应在创建main_engine对象后添加,以将该应用模块集成到VN.PY交易系统中。 ```python # 写在顶部 from vnpy_portfoliostrategy import PortfolioStrategyApp # 写在创建main_engine对象后 main_engine.add_app(PortfolioStrategyApp) ```