backtrader.metabase module¶
Base classes and mixins for the Backtrader framework.
This module provides the foundational infrastructure that replaces the original metaclass-based design. It includes parameter management, object factories, and various mixin classes used throughout the framework.
- Key Components:
ObjectFactory: Factory class for creating objects with lifecycle hooks
BaseMixin: Base mixin providing factory-based object creation
ParamsMixin: Mixin for parameter management without metaclasses
AutoInfoClass: Dynamic class for parameter/info storage
ParameterManager: Static utility for handling parameter operations
ItemCollection: Collection class with index and name-based access
- Utility Functions:
findbases: Recursively find base classes of a given type
findowner: Search call stack for owner objects
is_class_type: Cached type checking via MRO inspection
patch_strategy_clk_update: Runtime patch for Strategy clock updates
Example
Creating a class with parameters:
class MyIndicator(ParamsMixin):
params = (('period', 20), ('multiplier', 2.0))
def __init__(self):
print(f"Period: {self.p.period}")
Note
This module was created during the metaclass removal refactoring to provide equivalent functionality using explicit initialization patterns.
- class backtrader.metabase.OwnerContext[source]¶
Bases:
objectContext manager for tracking owner objects during indicator creation.
This class provides an alternative to sys._getframe() based owner lookup by maintaining an explicit owner stack in thread-local storage.
- Usage:
- with OwnerContext.set_owner(strategy):
# All indicators created here will have strategy as their owner sma = SMA(data, period=20)
The owner stack allows nested contexts, so indicators creating sub-indicators will correctly assign ownership.
- static get_current_owner(cls_filter=None)[source]¶
Get the current owner from the context stack.
- Parameters:
cls_filter – Optional class type to filter owners. If provided, only returns an owner that is an instance of this class.
- Returns:
The current owner object, or None if no owner is set or no owner matches the filter.
- static set_owner(owner)[source]¶
Set the current owner for indicator creation.
- Parameters:
owner – The owner object (typically a Strategy or Indicator).
- Yields:
None. The owner is available via get_current_owner() within the context.
- static push_owner(owner)[source]¶
Push an owner onto the stack (non-context-manager version).
- Parameters:
owner – The owner object to push.
- backtrader.metabase.is_class_type(cls, type_name)[source]¶
OPTIMIZED: Check if a class is of a certain type by checking __mro__. Results are cached for better performance.
- Parameters:
cls – The class to check
type_name – The type name to look for (e.g., ‘Strategy’, ‘Indicator’)
- Returns:
True if the class has the type in its MRO
- Return type:
- backtrader.metabase.patch_strategy_clk_update()[source]¶
CRITICAL FIX: Patch the Strategy class’s _clk_update method to prevent the “max() iterable argument is empty” error that occurs when no data sources have any length yet.
- backtrader.metabase.findbases(kls, topclass)[source]¶
Recursively find all base classes that inherit from topclass.
This function traverses the class hierarchy using __bases__ and recursively collects all base classes that are subclasses of the specified topclass.
- Parameters:
kls – The class to search bases for.
topclass – The top-level class to filter by (only bases that are subclasses of this class are included).
- Returns:
- A list of base classes in order from most ancestral to most
immediate parent.
- Return type:
Note
This function uses recursion, but the depth is limited by Python’s recursion limit. In practice, class hierarchies rarely exceed this.
- backtrader.metabase.findowner(owned, cls, startlevel=2, skip=None)[source]¶
Find the owner object in the call stack or context.
This function first checks the OwnerContext for an explicitly set owner, then falls back to traversing the call stack to find an object that: 1. Is an instance of the specified class (cls) 2. Is not the owned object itself 3. Is not the skip object (if provided)
This is commonly used to find parent containers (e.g., Strategy finding its Cerebro, or Indicator finding its Strategy).
- Parameters:
owned – The object looking for its owner.
cls – The class type the owner must be an instance of.
startlevel – Stack frame level to start searching from (default: 2, skips this function and the caller).
skip – Optional object to skip during the search.
- Returns:
The owner object if found, None otherwise.
Note
Uses OwnerContext for explicit owner management. The legacy sys._getframe() based lookup has been removed for better portability and performance.
- class backtrader.metabase.ObjectFactory[source]¶
Bases:
objectFactory class to replace MetaBase functionality.
This class provides a static method for creating objects with lifecycle hooks similar to the original metaclass implementation.
- The creation process follows these steps:
doprenew: Pre-new processing (class modification)
donew: Object creation
dopreinit: Pre-initialization processing
doinit: Main initialization
dopostinit: Post-initialization processing
- class backtrader.metabase.BaseMixin[source]¶
Bases:
objectMixin providing factory-based object creation without metaclass.
This mixin provides default implementations for the lifecycle hooks used by ObjectFactory. Subclasses can override these methods to customize object creation and initialization.
- classmethod doprenew(*args, **kwargs)[source]¶
Called before object creation.
- Parameters:
*args – Positional arguments for object creation.
**kwargs – Keyword arguments for object creation.
- Returns:
(cls, args, kwargs) - Class and arguments to use.
- Return type:
- classmethod donew(*args, **kwargs)[source]¶
Create a new object instance.
- Parameters:
*args – Positional arguments for object creation.
**kwargs – Keyword arguments for object creation.
- Returns:
(_obj, args, kwargs) - New instance and remaining arguments.
- Return type:
- classmethod dopreinit(_obj, *args, **kwargs)[source]¶
Called before __init__ to modify arguments.
- Parameters:
_obj – The object instance.
*args – Positional arguments for __init__.
**kwargs – Keyword arguments for __init__.
- Returns:
(_obj, args, kwargs) - Object and arguments for __init__.
- Return type:
- classmethod doinit(_obj, *args, **kwargs)[source]¶
Call __init__ on the object.
- Parameters:
_obj – The object instance.
*args – Positional arguments for __init__.
**kwargs – Keyword arguments for __init__.
- Returns:
(_obj, args, kwargs) - Object and remaining arguments.
- Return type:
- class backtrader.metabase.AutoInfoClass[source]¶
Bases:
objectDynamic class for storing parameter and info key-value pairs.
This class provides a flexible mechanism for storing and retrieving configuration data (parameters, plot info, etc.) with support for inheritance and derivation.
- Class Methods:
_getpairsbase: Get base class pairs as OrderedDict. _getpairs: Get all pairs (including inherited) as OrderedDict. _getrecurse: Check if recursive derivation is enabled. _derive: Create a derived class with additional parameters. _getkeys: Get all parameter keys. _getdefaults: Get all default values. _getitems: Get all key-value pairs. _gettuple: Get pairs as tuple of tuples.
- Instance Methods:
isdefault: Check if a parameter has its default value. notdefault: Check if a parameter differs from default. get/_get: Get a parameter value with optional default.
- class backtrader.metabase.ParameterManager[source]¶
Bases:
objectManager for handling parameter operations without metaclass.
This class provides static methods for setting up and deriving parameter classes, handling package imports, and managing parameter inheritance.
- class backtrader.metabase.ParamsMixin[source]¶
Bases:
BaseMixinMixin class that provides parameter management capabilities
- static __new__(cls, *args, **kwargs)[source]¶
Create instance and set up parameters before __init__ is called
- property params¶
Instance-level params property for backward compatibility
- property p¶
Provide p property for backward compatibility
- backtrader.metabase.ParamsBase¶
alias of
ParamsMixin
- class backtrader.metabase.ItemCollection[source]¶
Bases:
objectCollection that allows access by both index and name.
This class holds a list of items that can be accessed either by their numeric index or by a string name. Names are set as attributes on the collection instance.
Example
collection = ItemCollection() collection.append(my_strategy, name=’mystrat’) collection[0] # Access by index collection.mystrat # Access by name