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: object

Context 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.

static pop_owner()[source]

Pop the current owner from the stack.

Returns:

The popped owner, or None if the stack was empty.

static clear()[source]

Clear the owner stack (useful for testing).

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:

bool

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:

list

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: object

Factory 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:
  1. doprenew: Pre-new processing (class modification)

  2. donew: Object creation

  3. dopreinit: Pre-initialization processing

  4. doinit: Main initialization

  5. dopostinit: Post-initialization processing

static create(cls, *args, **kwargs)[source]

Create an object with lifecycle hooks.

Parameters:
  • cls – The class to instantiate.

  • *args – Positional arguments for initialization.

  • **kwargs – Keyword arguments for initialization.

Returns:

The created and initialized object.

class backtrader.metabase.BaseMixin[source]

Bases: object

Mixin 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.

doprenew()[source]

Called before object creation (class-level).

donew()[source]

Creates the object instance.

dopreinit()[source]

Called before __init__.

doinit()[source]

Calls __init__ on the object.

dopostinit()[source]

Called after __init__.

create()[source]

Factory method for instance creation.

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:

tuple

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:

tuple

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:

tuple

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:

tuple

classmethod dopostinit(_obj, *args, **kwargs)[source]

Called after __init__ for post-processing.

Parameters:
  • _obj – The object instance.

  • *args – Remaining positional arguments.

  • **kwargs – Remaining keyword arguments.

Returns:

(_obj, args, kwargs) - Object and remaining arguments.

Return type:

tuple

classmethod create(*args, **kwargs)[source]

Factory method to create instances

class backtrader.metabase.AutoInfoClass[source]

Bases: object

Dynamic 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.

isdefault(pname)[source]

Check if a parameter has its default value.

notdefault(pname)[source]

Check if a parameter differs from its default value.

get(name, default=None)[source]

Get a parameter value by name with optional default.

Parameters:
  • name – Name of the parameter to get.

  • default – Default value if parameter is not found.

Returns:

The parameter value or default if not found.

static __new__(cls, *args, **kwargs)[source]

Create a new instance with recursive parameter initialization.

class backtrader.metabase.ParameterManager[source]

Bases: object

Manager 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.

setup_class_params()[source]

Set up parameters for a class.

_derive_params()[source]

Create a derived parameter class.

_handle_packages()[source]

Handle package and module imports.

static setup_class_params(cls, params=(), packages=(), frompackages=())[source]

Set up parameters for a class

class backtrader.metabase.ParamsMixin[source]

Bases: BaseMixin

Mixin class that provides parameter management capabilities

classmethod __init_subclass__(**kwargs)[source]

Set up parameters when a subclass is created

static __new__(cls, *args, **kwargs)[source]

Create instance and set up parameters before __init__ is called

__init__(*args, **kwargs)[source]

Initialize with only non-parameter kwargs

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: object

Collection 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.

items

The underlying list of items.

Type:

list

Example

collection = ItemCollection() collection.append(my_strategy, name=’mystrat’) collection[0] # Access by index collection.mystrat # Access by name

__init__()[source]

Initialize the collection with an empty items list.

__len__()[source]

Return the number of items in the collection.

append(item, name=None)[source]

Add an item to the collection with an optional name.

__getitem__(key)[source]

Get item by index.

getnames()[source]

Get list of all item names.

getitems()[source]

Return list of (name, item) tuples for unpacking.

getbyname(name)[source]

Get item by name.