### Start Strategy with Logging Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_ctastrategy.html The on_start function is called when the strategy is started. It logs the start event. ```python def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") ``` -------------------------------- ### Example on_start Function for Option Strategy Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy.html The on_start function is called when the strategy is started. It's typically used for logging and setting the strategy's 'trading' status to True, enabling trade signal generation. ```python def on_start(self): """ 策略启动时触发 """ write_log("策略启动") self.trading = True ``` -------------------------------- ### Parameter Optimization Configuration Example Source: https://www.vnpy.com/docs/cn/community/app/cta_backtester.html When configuring parameters for optimization, define the range (start, end) and step for each parameter to be optimized. Fixed parameters can be set by making start and end values identical. ```text Start: 10 End: 20 Step: 2 ``` -------------------------------- ### BacktestingEngine Setup and Execution Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy.html This snippet demonstrates the basic setup and execution of a backtest for an option strategy. It configures the engine, adds a strategy, runs the backtest, calculates results and statistics, and displays a chart. ```python engine = BacktestingEngine() engine.set_parameters( interval=Interval.MINUTE, start=datetime(2023, 1, 1), end=datetime(2023, 11, 30), rate=0, slippage=0, ) engine.add_strategy(IoStrategy, {}) engine.run_backtesting() engine.calculate_result() engine.calculate_statistics() engine.show_chart() ``` -------------------------------- ### Install Ricequant RQData Client Source: https://www.vnpy.com/docs/cn/community/install/mac_install.html Install the RQData client using the specified Ricequant PyPI source. This is necessary for accessing RQData services. ```bash python3 -m pip install rqdatac --index=https://pypi2.ricequant.com/simple ``` -------------------------------- ### Example: CTA Strategy Backtest Notebook Source: https://www.vnpy.com/docs/cn/elite/info/elite_lab.html This example demonstrates loading components and strategy objects, creating a backtest engine, setting parameters, adding the strategy, and running the backtest. Results include daily PnL and statistical indicators. ```python # Load necessary components and strategy objects # Create backtest engine and set parameters # Add strategy object and parameters to the engine # Load data and run backtest # Calculate daily PnL and statistical indicators # Display results via charts ``` -------------------------------- ### Install PyXLL and VN.PY RTD Source: https://www.vnpy.com/docs/cn/community/app/excel_rtd.html Install the PyXLL plugin and the VN.PY RTD component using pip and the pyxll install command. Ensure you place the vnpy_rtd.py file in the correct examples directory. ```bash pip install pyxll pyxll install ``` -------------------------------- ### Start Script Strategy Source: https://www.vnpy.com/docs/cn/community/app/script_trader.html After opening a script strategy file, click the 'Start' button to initiate its execution. Output and status will appear in the interface below. ```python # The interface will output related information upon starting the script strategy. ``` -------------------------------- ### Start Portfolio Strategy (on_start) Source: https://www.vnpy.com/docs/cn/community/app/portfolio_strategy.html This function is called when the strategy is started. It logs the start event. After this function is called, the strategy's 'trading' status becomes True, enabling it to generate trading signals. ```python def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") ``` -------------------------------- ### Start Strategy with on_start Source: https://www.vnpy.com/docs/cn/community/app/cta_strategy.html The on_start function is called when the strategy is started, typically logging the start event. The strategy can generate trading signals after this. ```python def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") ``` -------------------------------- ### Install VeighNa Core Framework and Plugins Source: https://www.vnpy.com/docs/cn/community/install/mac_install.html Install the VeighNa core framework and selected functional modules using the specified index URL. This includes modules for CTA strategy, backtesting, data management, SQLite, and RQData. ```bash python3 -m pip install vnpy --index=https://pypi.doubanio.com/simple python3 -m pip install vnpy_ctastrategy vnpy_ctabacktester vnpy_datamanager vnpy_sqlite vnpy_rqdata --index=https://pypi.doubanio.com/simple ``` -------------------------------- ### MySQL Database Configuration Example Source: https://www.vnpy.com/docs/cn/community/info/database.html Example configuration for connecting to a MySQL database. MySQL is a popular open-source relational database. ```ini database.name = mysql database.host = localhost database.port = 3306 database.database = vnpy database.user = root database.password = ``` -------------------------------- ### PostgreSQL Database Configuration Example Source: https://www.vnpy.com/docs/cn/community/info/database.html Example configuration for connecting to a PostgreSQL database. PostgreSQL is a feature-rich open-source relational database recommended for experienced users. ```ini database.name = postgresql database.host = localhost database.port = 5432 database.database = vnpy database.user = postgres database.password = 123456 ``` -------------------------------- ### Default Strategies Directory on Windows Source: https://www.vnpy.com/docs/cn/community/app/cta_backtester.html For user-developed strategies to be recognized, they must be placed in the 'strategies' directory within the VeighNa Trader runtime directory. This example shows the typical path on a default Windows installation. ```text C:\Users\Administrator\strategies ``` -------------------------------- ### Setting up Breakpoints for Debugging Source: https://www.vnpy.com/docs/cn/community/info/pycharm.html Demonstrates how to set up and start a debugging session for a VeighNa strategy backtest script (backtest.py) in PyCharm. ```Python Create a new file named backtest.py in the project navigation bar (New -> File). Write your strategy backtest code and set breakpoints where needed. Right-click on backtest.py and select "Debug ‘backtest’" to start the debugging session. ``` -------------------------------- ### Log strategy start in on_start Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_spreadtrading.html The on_start callback is executed when the strategy begins running. The default implementation simply logs a 'Strategy started' message. After this callback, the strategy's trading status becomes True, enabling the spread trading algorithm. ```python def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") ``` -------------------------------- ### Load Datafeed Module and Initialize Source: https://www.vnpy.com/docs/cn/community/info/datafeed.html Import necessary modules and get an instance of the datafeed service. This is the first step before querying any data. ```python from datetime import datetime from vnpy.trader.constant import Exchange, Interval from vnpy.trader.datafeed import get_datafeed from vnpy.trader.object import HistoryRequest # Get datafeed instance datafeed = get_datafeed() ``` -------------------------------- ### Check Python Version Source: https://www.vnpy.com/docs/cn/community/install/mac_install.html Verify that the installed Python interpreter is version 3.10. This is a prerequisite for VeighNa installation. ```bash python3 ``` -------------------------------- ### Compile and Install vnpy_ctp Module from Source Source: https://www.vnpy.com/docs/cn/community/install/mac_install.html Clone the vnpy_ctp source code and compile it locally for installation. This is required for the CTP trading interface on Mac due to changes in the API structure. ```bash mkdir github cd github git clone https://github.com/vnpy/vnpy_ctp.git cd vnpy_ctp pip3 install -e . ``` -------------------------------- ### Run VeighNa Elite Lab via Shortcut Source: https://www.vnpy.com/docs/cn/elite/info/elite_lab.html Double-click the VeighNa Elite Lab shortcut on your desktop to launch the application after successful installation. ```bash Click the desktop shortcut to run VeighNa Elite Lab. ``` -------------------------------- ### Install NumPy and TA-Lib Python Libraries Source: https://www.vnpy.com/docs/cn/community/install/mac_install.html Install NumPy and the Python TA-Lib library using the specified index URL to potentially resolve access issues with the official PyPI source. Version pinning for NumPy is included. ```bash python3 -m pip install numpy==1.26.4 --index=https://pypi.doubanio.com/simple python3 -m pip install ta-lib --index=https://pypi.doubanio.com/simple ``` -------------------------------- ### VeighNa Naming Conventions Example Source: https://www.vnpy.com/docs/cn/community/info/contribution.html Illustrates the naming conventions for constants, class attributes, methods, parameters, and variables in VeighNa. ```python DEFAULT_PATH = "/tmp/VeighNa/" class ClassA: def __init__(self, arg_one: int, arg_two: str): if arg_two is None: arg_two = DEFAULT_PATH self.property_one = arg_one variable_one = "some string" ``` -------------------------------- ### Example get_portfolio Function Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy.html The get_portfolio function retrieves the option portfolio data for a specified portfolio name. ```python portfolio = self.get_portfolio(portfolio_name="510050_O") ``` -------------------------------- ### 解决图形驱动问题 Source: https://www.vnpy.com/docs/cn/community/install/ubuntu_install.html 在有图形界面的Ubuntu系统上启动时,如果出现qt.qpa.plugin: Could not load the Qt platform plugin “xcb”的报错,运行此命令安装libxcb-xinerama0尝试解决。 ```bash sudo apt-get install libxcb-xinerama0 ``` -------------------------------- ### Display Contextual Help Source: https://www.vnpy.com/docs/cn/elite/info/elite_lab.html Click the 'Show Contextual Help' icon under 'Other' to open a help window. This window displays documentation for any function when you click on it. ```bash Click the 'Show Contextual Help' icon under 'Other'. ``` -------------------------------- ### Install TA-Lib C++ Development Package Source: https://www.vnpy.com/docs/cn/community/install/mac_install.html Install the TA-Lib C++ development package using Homebrew. This is required for the Python TA-Lib library. ```bash brew install ta-lib ``` -------------------------------- ### SQLite Database Configuration Example Source: https://www.vnpy.com/docs/cn/community/info/database.html Example configuration for using SQLite as the default database in VeighNa Trader. SQLite is a lightweight, embedded database suitable for beginners. ```ini database.name = sqlite database.database = database.db ``` -------------------------------- ### Running the run.py Script Source: https://www.vnpy.com/docs/cn/community/info/pycharm.html Instructions on how to download and run the VeighNa Trader startup script (run.py) within PyCharm. It also covers disabling 'Typo' inspection if needed. ```Python Download run.py from the Github repository and place it in the trader folder. Right-click on run.py in the project navigation bar and select "Run ‘run’". Alternatively, disable 'Typo' inspection under File -> Settings -> Editor -> Inspections -> Proofreading if green wavy lines appear. ``` -------------------------------- ### 启动VeighNa Trader Source: https://www.vnpy.com/docs/cn/community/install/ubuntu_install.html 进入解压的VeighNa源代码目录下的examples/veighna_trader文件夹,运行此命令启动VeighNa Trader。请根据实际需求修改run.py中的启动加载项。 ```bash python run.py ``` -------------------------------- ### Import Necessary Libraries and Get Database Instance Source: https://www.vnpy.com/docs/cn/community/info/database.html Import required modules for data handling and obtain the database instance. Ensure all necessary VeighNa Trader components are imported. ```python from datetime import datetime from typing import List from vnpy.trader.constant import Exchange, Interval from vnpy.trader.database import get_database from vnpy.trader.object import BarData, TickData # 获取数据库实例 database = get_database() ``` -------------------------------- ### get_pricetick Source: https://www.vnpy.com/docs/cn/community/app/cta_strategy.html Get the minimum price tick of the trading contract. ```APIDOC ## get_pricetick ### Description Get the minimum price tick of the trading contract. ### Method `get_pricetick(self)` ### Response - **pricetick** (float) - The minimum price tick of the contract, or None if not available. ``` -------------------------------- ### Example get_today Function Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy.html The get_today function retrieves the current date. ```python today = self.get_today() ``` -------------------------------- ### Data Service Initialization Log (RQData) Source: https://www.vnpy.com/docs/cn/community/app/cta_backtester.html Successful initialization of the data service (e.g., RQData) will log 'Data service initialization successful'. Ensure data services are correctly configured beforehand. ```text Data service initialization successful ``` -------------------------------- ### Get Strategy Engine Type Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_spreadtrading.html Retrieve the type of the strategy engine. ```python def get_engine_type(self): pass ``` -------------------------------- ### Load PortfolioStrategy App via Script Source: https://www.vnpy.com/docs/cn/community/app/portfolio_strategy.html Add the PortfolioStrategyApp to your main engine in the startup script to load the module. ```python # Write at the top from vnpy_portfoliostrategy import PortfolioStrategyApp # Write after creating the main_engine object main_engine.add_app(PortfolioStrategyApp) ``` -------------------------------- ### get_engine_type Source: https://www.vnpy.com/docs/cn/community/app/cta_strategy.html Get the current engine type (backtesting or live trading). ```APIDOC ## get_engine_type ### Description Get the current engine type (backtesting or live trading). ### Method `get_engine_type(self)` ### Response - **engine_type** (EngineType) - The type of the current engine. ### Note Import `EngineType` from `vnpy.trader.engine` to use this function for conditional logic. ``` -------------------------------- ### Get Spread Net Position Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_spreadtrading.html Retrieve the net position data for the spread. ```python def get_spread_pos(self): pass ``` -------------------------------- ### 解决中文编码问题 Source: https://www.vnpy.com/docs/cn/community/install/ubuntu_install.html 当Ubuntu系统语言为英文,连接使用中文的接口时可能出现locale错误。运行此命令安装中文编码。 ```bash sudo locale-gen zh_CN.GB18030 ``` -------------------------------- ### Load CtaStrategyApp via Script Source: https://www.vnpy.com/docs/cn/community/app/cta_strategy.html Add this code to your startup script to load the CtaStrategyApp. Ensure it's placed after the main_engine object is created. ```python # Write at the top from vnpy_ctastrategy import CtaStrategyApp # Write after creating the main_engine object main_engine.add_app(CtaStrategyApp) ``` -------------------------------- ### Get Spread Tick Data Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_spreadtrading.html Fetch the latest Tick data for the spread. ```python def get_spread_tick(self): pass ``` -------------------------------- ### Example load_data Function Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy.html The load_data function loads strategy data from a specified file. ```python self.load_data(file_name="strategy_state.json") ``` -------------------------------- ### Example save_data Function Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy.html The save_data function saves strategy data to a specified file. ```python self.save_data(file_name="strategy_state.json", data=self.get_variables()) ``` -------------------------------- ### Load DataRecorder App via Script Source: https://www.vnpy.com/docs/cn/community/app/data_recorder.html Add the DataRecorderApp to the main engine in your startup script to load the module. ```python # Write at the top from vnpy_datarecorder import DataRecorderApp # Write after creating the main_engine object main_engine.add_app(DataRecorderApp) ``` -------------------------------- ### Create a New Text File Source: https://www.vnpy.com/docs/cn/elite/info/elite_lab.html Click the 'Text File' icon under the 'Other' option in the launcher to create a new blank .txt file. Existing .txt files can also be edited. ```bash Click the 'Text File' icon under 'Other'. ``` -------------------------------- ### Example get_pos Function Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_optionstrategy.html The get_pos function retrieves the current position data for a specific contract. ```python position = self.get_pos(vt_symbol="IF8888.SHFE") ``` -------------------------------- ### Get Specific Leg Tick Data Source: https://www.vnpy.com/docs/cn/elite/strategy/elite_spreadtrading.html Fetch Tick data for a specific contract leg. ```python def get_leg_tick(self, vt_symbol: str): pass ``` -------------------------------- ### start_algo Source: https://www.vnpy.com/docs/cn/community/app/spread_trading.html Internal function to start a new spread trading algorithm. Generally not called directly by users. ```APIDOC ## start_algo ### Description Internal function to start a new spread trading algorithm. Generally not called directly by users. It is invoked by `start_long_algo` and `start_short_algo`. ### Method Signature `start_algo(direction: Direction, price: float, volume: float, payup: int, interval: int, lock: bool, extra: dict) -> str` ### Parameters * **direction** (Direction) - The direction of the trade (LONG or SHORT). * **price** (float) - The target price for the spread trade. * **volume** (float) - The volume of the spread trade. * **payup** (int) - The price tolerance for the trade. * **interval** (int) - The time interval for the trade. * **lock** (bool) - Whether to use lock orders. * **extra** (dict) - Additional parameters for the algorithm. ### Returns * **algoid** (str) - The unique identifier for the started algorithm. ### Note This function can only be called when the strategy's trading status is True. Calling it when trading status is False will return an empty list. ``` -------------------------------- ### Load PortfolioManager App via Script Source: https://www.vnpy.com/docs/cn/community/app/portfolio_manager.html Add the PortfolioManagerApp to your main engine in the startup script. Ensure this code is placed after the main_engine object is created. ```python # Write at the top from vnpy_portfoliomanager import PortfolioManagerApp # Write after creating the main_engine object main_engine.add_app(PortfolioManagerApp) ``` -------------------------------- ### start_short_algo Source: https://www.vnpy.com/docs/cn/community/app/spread_trading.html Starts a short spread trading algorithm. This function is used to initiate a sell-side spread trade. ```APIDOC ## start_short_algo ### Description Starts a short spread trading algorithm. This function is used to initiate a sell-side spread trade. ### Method Signature `start_short_algo(price: float, volume: float, payup: int, interval: int, lock: bool = False, extra: dict = None) -> str` ### Parameters * **price** (float) - The target price for the spread trade. * **volume** (float) - The volume of the spread trade. * **payup** (int) - The price tolerance for the trade. * **interval** (int) - The time interval for the trade. * **lock** (bool) - Optional. Whether to use lock orders. Defaults to False. * **extra** (dict) - Optional. Additional parameters for the algorithm. Defaults to None. ### Returns * **algoid** (str) - The unique identifier for the started algorithm. ``` -------------------------------- ### start_long_algo Source: https://www.vnpy.com/docs/cn/community/app/spread_trading.html Starts a long spread trading algorithm. This function is used to initiate a buy-side spread trade. ```APIDOC ## start_long_algo ### Description Starts a long spread trading algorithm. This function is used to initiate a buy-side spread trade. ### Method Signature `start_long_algo(price: float, volume: float, payup: int, interval: int, lock: bool = False, extra: dict = None) -> str` ### Parameters * **price** (float) - The target price for the spread trade. * **volume** (float) - The volume of the spread trade. * **payup** (int) - The price tolerance for the trade. * **interval** (int) - The time interval for the trade. * **lock** (bool) - Optional. Whether to use lock orders. Defaults to False. * **extra** (dict) - Optional. Additional parameters for the algorithm. Defaults to None. ### Returns * **algoid** (str) - The unique identifier for the started algorithm. ```