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

示例

Creating a class with parameters:

class MyIndicator(ParamsMixin):
    params = (('period', 20), ('multiplier', 2.0))

    def __init__(self):
        print(f"Period: {self.p.period}")

备注

This module was created during the metaclass removal refactoring to provide equivalent functionality using explicit initialization patterns.

class backtrader.metabase.OwnerContext[源代码]

基类: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)[源代码]

Get the current owner from the context stack.

参数:

cls_filter -- Optional class type to filter owners. If provided, only returns an owner that is an instance of this class.

返回:

The current owner object, or None if no owner is set or no owner matches the filter.

static set_owner(owner)[源代码]

Set the current owner for indicator creation.

参数:

owner -- The owner object (typically a Strategy or Indicator).

生成器:

None. The owner is available via get_current_owner() within the context.

static push_owner(owner)[源代码]

Push an owner onto the stack (non-context-manager version).

参数:

owner -- The owner object to push.

static pop_owner()[源代码]

Pop the current owner from the stack.

返回:

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

static clear()[源代码]

Clear the owner stack (useful for testing).

backtrader.metabase.is_class_type(cls, type_name)[源代码]

OPTIMIZED: Check if a class is of a certain type by checking __mro__. Results are cached for better performance.

参数:
  • cls -- The class to check

  • type_name -- The type name to look for (e.g., 'Strategy', 'Indicator')

返回:

True if the class has the type in its MRO

返回类型:

bool

backtrader.metabase.patch_strategy_clk_update()[源代码]

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)[源代码]

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.

参数:
  • 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).

返回:

A list of base classes in order from most ancestral to most

immediate parent.

返回类型:

list

备注

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)[源代码]

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

参数:
  • 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.

返回:

The owner object if found, None otherwise.

备注

Uses OwnerContext for explicit owner management. The legacy sys._getframe() based lookup has been removed for better portability and performance.

class backtrader.metabase.ObjectFactory[源代码]

基类: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)[源代码]

Create an object with lifecycle hooks.

参数:
  • cls -- The class to instantiate.

  • *args -- Positional arguments for initialization.

  • **kwargs -- Keyword arguments for initialization.

返回:

The created and initialized object.

class backtrader.metabase.BaseMixin[源代码]

基类: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()[源代码]

Called before object creation (class-level).

donew()[源代码]

Creates the object instance.

dopreinit()[源代码]

Called before __init__.

doinit()[源代码]

Calls __init__ on the object.

dopostinit()[源代码]

Called after __init__.

create()[源代码]

Factory method for instance creation.

classmethod doprenew(*args, **kwargs)[源代码]

Called before object creation.

参数:
  • *args -- Positional arguments for object creation.

  • **kwargs -- Keyword arguments for object creation.

返回:

(cls, args, kwargs) - Class and arguments to use.

返回类型:

tuple

classmethod donew(*args, **kwargs)[源代码]

Create a new object instance.

参数:
  • *args -- Positional arguments for object creation.

  • **kwargs -- Keyword arguments for object creation.

返回:

(_obj, args, kwargs) - New instance and remaining arguments.

返回类型:

tuple

classmethod dopreinit(_obj, *args, **kwargs)[源代码]

Called before __init__ to modify arguments.

参数:
  • _obj -- The object instance.

  • *args -- Positional arguments for __init__.

  • **kwargs -- Keyword arguments for __init__.

返回:

(_obj, args, kwargs) - Object and arguments for __init__.

返回类型:

tuple

classmethod doinit(_obj, *args, **kwargs)[源代码]

Call __init__ on the object.

参数:
  • _obj -- The object instance.

  • *args -- Positional arguments for __init__.

  • **kwargs -- Keyword arguments for __init__.

返回:

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

返回类型:

tuple

classmethod dopostinit(_obj, *args, **kwargs)[源代码]

Called after __init__ for post-processing.

参数:
  • _obj -- The object instance.

  • *args -- Remaining positional arguments.

  • **kwargs -- Remaining keyword arguments.

返回:

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

返回类型:

tuple

classmethod create(*args, **kwargs)[源代码]

Factory method to create instances

class backtrader.metabase.AutoInfoClass[源代码]

基类: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)[源代码]

Check if a parameter has its default value.

notdefault(pname)[源代码]

Check if a parameter differs from its default value.

get(name, default=None)[源代码]

Get a parameter value by name with optional default.

参数:
  • name -- Name of the parameter to get.

  • default -- Default value if parameter is not found.

返回:

The parameter value or default if not found.

static __new__(cls, *args, **kwargs)[源代码]

Create a new instance with recursive parameter initialization.

class backtrader.metabase.ParameterManager[源代码]

基类: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()[源代码]

Set up parameters for a class.

_derive_params()[源代码]

Create a derived parameter class.

_handle_packages()[源代码]

Handle package and module imports.

static setup_class_params(cls, params=(), packages=(), frompackages=())[源代码]

Set up parameters for a class

class backtrader.metabase.ParamsMixin[源代码]

基类:BaseMixin

Mixin class that provides parameter management capabilities

classmethod __init_subclass__(**kwargs)[源代码]

Set up parameters when a subclass is created

static __new__(cls, *args, **kwargs)[源代码]

Create instance and set up parameters before __init__ is called

__init__(*args, **kwargs)[源代码]

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

ParamsMixin 的别名

class backtrader.metabase.ItemCollection[源代码]

基类: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

示例

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

__init__()[源代码]

Initialize the collection with an empty items list.

__len__()[源代码]

Return the number of items in the collection.

append(item, name=None)[源代码]

Add an item to the collection with an optional name.

__getitem__(key)[源代码]

Get item by index.

getnames()[源代码]

Get list of all item names.

getitems()[源代码]

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

getbyname(name)[源代码]

Get item by name.