vn.py is a trading platform commonly used for CTA strategies. For specific installation instructions, you can refer to the previous article "Introduction to CTA Strategies Based on VN.PY". The CTA module in vn.py includes callback functions such as on_init(), on_start(), on_bar(), etc. Most of the time, we focus on the content of the on_bar() function, as it contains the specific strategy logic. However, we should not overlook other callback functions, such as on_init().
The on_init() function may only consist of a few lines of code, but it is not as simple as it seems. Many of us understand it as a function for variable initialization and loading the required historical data through the self.load_bar(10) function (the K-line time series manager calculates and caches relevant indicators during strategy initialization, but does not trigger trading). However, on_init() also has another easily overlooked role, which is to restore the strategy state from the previous exit. Specifically, it reads the strategy parameters, the latest technical indicators, and the position quantity (pos) from .vntrader/cta_strategy_data.json, and restores these values.
Referencing the example below, the content of cta_strategy_data.json is as follows:
{
"rbS": {
"pos": -12,
"initial_sell": 3470,
"initial_cover": 3500,
"step": 20
}
}
In this case, if we restart a CTA strategy and name it rbS, the parameters of the above strategy will be reloaded during initialization, regardless of the new program. The effect is as shown below:
Therefore, if you are planning to restart a CTA strategy, it is advisable to directly delete the cta_strategy_data.json file or remove the relevant parts from it. Otherwise, it may often be inconsistent with the expected initialization.