Why Strategy Instances Share Class Variables in Python
Summary
The post asks whether two instances of the same VeighNa CTA strategy can mix state when assigned to different contracts. It points to `all_fractals`, a list declared in the strategy class body, and also shows `last_stop_loss_time` declared there. In Python, mutable class attributes are shared by instances unless they are shadowed, so appending to that list in one strategy instance can make its contents visible to the other.
The snippet raises a useful debugging principle: per-instance trading state should be initialized on `self` during construction, while class attributes are appropriate for values intentionally shared across every instance. The post itself does not show the strategy's update logic or a confirmed diagnosis, and it provides no corrected implementation or runtime evidence. The shared-list explanation is plausible from the shown declaration, but whether it causes the observed output depends on how the strategy reads and modifies its state.
Key ideas
- A mutable list declared on a Python class is shared among instances unless an instance attribute replaces it.
- State such as detected fractals and stop-loss timestamps is typically instance-specific when strategies trade separate contracts.
- Initialize per-instance state on `self` in the constructor or another instance setup method.
- The code excerpt suggests a possible cause but does not confirm it without seeing how the list is accessed and changed.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.