backtrader.parameters module

New Parameter System for Backtrader

This module implements a modern parameter system that replaces the metaclass-based parameter handling with descriptor-based approach. This provides better type safety, validation, and maintainability while maintaining backward compatibility.

Key Components: - ParameterDescriptor: Core descriptor for parameter handling - ParameterManager: Parameter storage and management - ParameterizedBase: Base class for parameterized objects (without metaclass) - Type checking and validation mechanisms - Python 3.6+ __set_name__ support

class backtrader.parameters.ParameterDescriptor[source]

Bases: object

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

__init__(default=None, type_=None, validator=None, doc=None, name=None, required=False)[source]

Initialize parameter descriptor.

Parameters:
  • default (Any) – Default value for the parameter

  • type – Expected type for the parameter (enables type checking)

  • validator (Callable[[Any], bool] | None) – Function to validate parameter values

  • doc (str | None) – Documentation string for the parameter

  • name (str | None) – Parameter name (usually set by __set_name__)

  • required (bool) – Whether this parameter is required (no default allowed)

  • type_ (Type | None)

__set_name__(owner, name)[source]

Called when the descriptor is assigned to a class attribute. This is a Python 3.6+ feature that automatically sets the parameter name.

__get__(obj, objtype=None)[source]

Get parameter value from object instance.

__set__(obj, value)[source]

Set parameter value on object instance with validation.

__delete__(obj)[source]

Delete parameter value, reverting to default.

validate(value)[source]

Validate a value for this parameter.

Parameters:

value (Any) – Value to validate

Returns:

True if value is valid, False otherwise

Return type:

bool

get_type_info()[source]

Get type information for this parameter.

Return type:

Dict[str, Any]

class backtrader.parameters.ParameterManager[source]

Bases: object

Enhanced Parameter storage and management system.

This class manages parameter values for an object, replacing the functionality of AutoInfoClass. It provides efficient storage, inheritance support, batch operations, and advanced features like change tracking, callbacks, and transactional updates.

New Features in Day 32-33: - Parameter change history and tracking - Change callbacks and notifications - Parameter locking mechanism - Parameter groups for organization - Advanced inheritance with conflict resolution - Lazy default value evaluation - Transactional batch updates

__init__(descriptors, initial_values=None, enable_history=True, enable_callbacks=True)[source]

Initialize parameter manager.

Parameters:
  • descriptors (Dict[str, ParameterDescriptor]) – Dictionary of parameter descriptors

  • initial_values (Dict[str, Any] | None) – Initial parameter values

  • enable_history (bool) – Whether to track parameter change history

  • enable_callbacks (bool) – Whether to enable change callbacks

get(name, default=None, _MISSING=<object object>)[source]

Get parameter value with optimized caching and lazy evaluation support.

Parameters:
  • name (str) – Parameter name

  • default (Any) – Default value if parameter not found

Returns:

Parameter value

Return type:

Any

set(name, value, force=False, trigger_callbacks=True, skip_validation=False)[source]

Set parameter value with validation and dependency updates.

Parameters:
  • name (str) – Parameter name

  • value (Any) – Parameter value

  • force (bool) – Force setting even if parameter is locked

  • trigger_callbacks (bool) – Whether to trigger change callbacks

  • skip_validation (bool) – Skip validation (use with caution)

Return type:

None

reset(name, force=False)[source]

Reset parameter to its default value.

Parameters:
  • name (str) – Parameter name

  • force (bool) – Force reset even if parameter is locked

Return type:

None

update(values, force=False, validate_all=True)[source]

Update multiple parameters at once.

Parameters:
  • values (Dict[str, Any] | ParameterManager) – Dictionary of parameter values or another ParameterManager

  • force (bool) – Force update even for locked parameters

  • validate_all (bool) – Validate all parameters before updating any

Return type:

None

to_dict()[source]

Convert parameter manager to dictionary.

Returns:

Dictionary of current parameter values

Return type:

Dict[str, Any]

keys()[source]

Get parameter names.

items()[source]

Get parameter name-value pairs.

values()[source]

Get parameter values.

copy()[source]

Create a copy of this parameter manager.

Returns:

New ParameterManager instance with same values

Return type:

ParameterManager

inherit_from(parent, strategy='merge', conflict_resolution='parent', selective=None)[source]

Inherit parameters from another ParameterManager.

Parameters:
  • parent (ParameterManager) – Parent ParameterManager to inherit from

  • strategy (str) – Inheritance strategy (‘merge’, ‘replace’, ‘add_only’, ‘selective’)

  • conflict_resolution (str) – How to resolve conflicts (‘parent’, ‘child’, ‘error’, ‘raise’)

  • selective (List[str] | None) – Only inherit specific parameters (list of names)

Return type:

None

get_inheritance_info(name)[source]

Get inheritance information for a parameter.

Parameters:

name (str) – Parameter name

Returns:

Dictionary with inheritance information, or None if not available

Return type:

Dict[str, Any] | None

lock_parameter(name)[source]

Lock a parameter to prevent modification.

Parameters:

name (str)

Return type:

None

unlock_parameter(name)[source]

Unlock a parameter to allow modification.

Parameters:

name (str)

Return type:

None

is_locked(name)[source]

Check if a parameter is locked.

Parameters:

name (str)

Return type:

bool

get_locked_parameters()[source]

Get list of locked parameter names.

Return type:

List[str]

create_group(group_name, param_names)[source]

Create a parameter group.

Parameters:
  • group_name (str) – Name of the group

  • param_names (List[str]) – List of parameter names to include in the group

Return type:

None

get_group(group_name)[source]

Get parameter names in a group.

Parameters:

group_name (str)

Return type:

List[str]

get_parameter_group(param_name)[source]

Get the group name for a parameter.

Parameters:

param_name (str)

Return type:

str | None

set_group(group_name, values)[source]

Set values for all parameters in a group.

Parameters:
Return type:

None

get_group_values(group_name)[source]

Get values for all parameters in a group.

Parameters:

group_name (str)

Return type:

Dict[str, Any]

set_lazy_default(name, lazy_func)[source]

Set a lazy default function for a parameter.

Parameters:
  • name (str) – Parameter name

  • lazy_func (Callable[[], Any]) – Function that returns the default value when called

Return type:

None

clear_lazy_default(name)[source]

Clear lazy default for a parameter.

Parameters:

name (str)

Return type:

None

add_change_callback(callback, param_name=None)[source]

Add a callback function that will be called when parameters change.

Parameters:
  • callback (Callable[[str, Any, Any], None]) – Function to call with (param_name, old_value, new_value)

  • param_name (str | None) – Specific parameter to watch, or None for all parameters

Return type:

None

remove_change_callback(callback, param_name=None)[source]

Remove a change callback.

Parameters:
Return type:

None

get_change_history(name, limit=None)[source]

Get change history for a parameter.

Parameters:
  • name (str) – Parameter name

  • limit (int | None) – Maximum number of history entries to return

Returns:

List of history entries (newest first) in format (old_value, new_value, timestamp)

Return type:

List[tuple]

clear_history(name=None)[source]

Clear change history.

Parameters:

name (str | None) – Specific parameter name, or None to clear all history

Return type:

None

add_dependency(param_name, dependent_param)[source]

Add a dependency relationship between parameters.

Parameters:
  • param_name (str) – Parameter that others depend on

  • dependent_param (str) – Parameter that depends on param_name

Return type:

None

remove_dependency(param_name, dependent_param)[source]

Remove a dependency relationship.

Parameters:
  • param_name (str)

  • dependent_param (str)

Return type:

None

get_dependencies(param_name)[source]

Get list of parameters that depend on the given parameter.

Parameters:

param_name (str)

Return type:

List[str]

get_dependents(param_name)[source]

Get list of parameters that this parameter depends on.

Parameters:

param_name (str)

Return type:

List[str]

begin_transaction()[source]

Begin a parameter transaction.

Return type:

None

commit_transaction()[source]

Commit the current transaction.

Return type:

None

rollback_transaction()[source]

Rollback the current transaction.

Return type:

None

is_in_transaction()[source]

Check if currently in a transaction.

Return type:

bool

class backtrader.parameters.ParameterAccessor[source]

Bases: object

Parameter accessor that provides dict-like and attribute-like access to parameters.

This class serves as a bridge between the new parameter system and the old MetaParams-style parameter access patterns. It provides backward compatibility by supporting both attribute access (obj.p.param_name) and dict-like access.

__init__(param_manager)[source]

Initialize with a parameter manager.

NOTE: Originally attempted to pre-create instance attributes for performance, but this causes parameter synchronization issues. When parameters are modified through other means (like broker.set_cash()), instance attributes won’t update. Therefore maintain dynamic lookup to ensure latest values are always retrieved.

Parameters:

param_manager (ParameterManager)

__getattr__(name)[source]

Get parameter value via attribute access.

Always get latest value from param_manager to ensure consistency. All parameter accesses are dynamically looked up to guarantee latest values.

__setattr__(name, value)[source]

Set parameter value via attribute access.

__getitem__(name)[source]

Get parameter value via dict-like access.

__setitem__(name, value)[source]

Set parameter value via dict-like access.

__contains__(name)[source]

Check if parameter exists.

__iter__()[source]

Iterate over parameter names.

__len__()[source]

Get number of parameters.

__repr__()[source]

String representation showing parameter values.

class backtrader.parameters.ParameterizedBase[source]

Bases: object

Enhanced base class for objects with parameters - without metaclass.

This class provides the modern parameter system interface while maintaining backward compatibility with the old MetaParams-based system. It uses regular class mechanisms instead of metaclass.

classmethod __init_subclass__(**kwargs)[source]

Called when a class is subclassed. Replaces metaclass functionality.

This method sets up the class for lazy parameter descriptor resolution to avoid inheritance contamination issues.

__init__(**kwargs)[source]

Initialize the parameterized object.

get_param(name, default=None)[source]

Get parameter value with fallback.

Parameters:
  • name (str) – Parameter name

  • default (Any) – Default value if parameter not found

Returns:

Parameter value

Return type:

Any

set_param(name, value, validate=True)[source]

Set parameter value with optional validation.

Parameters:
  • name (str) – Parameter name

  • value (Any) – Parameter value

  • validate (bool) – Whether to perform validation

Raises:
Return type:

None

get_param_info()[source]

Get comprehensive information about all parameters.

Returns:

Dictionary with parameter information

Return type:

Dict[str, Dict[str, Any]]

validate_params()[source]

Validate all parameters and return list of validation errors.

Returns:

List of validation error messages (empty if all valid)

Return type:

List[str]

reset_param(name)[source]

Reset parameter to its default value.

Parameters:

name (str) – Parameter name

Raises:
Return type:

None

reset_all_params()[source]

Reset all parameters to their default values.

Return type:

None

get_modified_params()[source]

Get parameters that have been modified from their defaults.

Returns:

Dictionary of modified parameter names and values

Return type:

Dict[str, Any]

copy_params_from(other, param_names=None, exclude=None)[source]

Copy parameters from another ParameterizedBase instance.

Parameters:
  • other (ParameterizedBase) – Source object to copy parameters from

  • param_names (List[str] | None) – Specific parameter names to copy (None for all)

  • exclude (List[str] | None) – Parameter names to exclude from copying

Return type:

None

__repr__()[source]

Enhanced string representation with parameter information.

Return type:

str

backtrader.parameters.Int(min_val=None, max_val=None)[source]

Create an integer validator function.

Parameters:
  • min_val (int | None) – Minimum allowed value

  • max_val (int | None) – Maximum allowed value

Returns:

Validator function for integer parameters

Return type:

Callable[[Any], bool]

backtrader.parameters.Float(min_val=None, max_val=None)[source]

Create a float validator function.

Parameters:
  • min_val (float | None) – Minimum allowed value

  • max_val (float | None) – Maximum allowed value

Returns:

Validator function for float parameters

Return type:

Callable[[Any], bool]

backtrader.parameters.FloatParam(default=None, min_val=None, max_val=None, doc=None)[source]

Create a float parameter descriptor with validation.

Parameters:
Return type:

ParameterDescriptor

backtrader.parameters.BoolParam(default=None, doc=None)[source]

Create a boolean parameter descriptor.

Parameters:

doc (str)

Return type:

ParameterDescriptor

backtrader.parameters.StringParam(default=None, min_length=None, max_length=None, doc=None)[source]

Create a string parameter descriptor with length validation.

Parameters:
  • min_length (int | None)

  • max_length (int | None)

  • doc (str)

Return type:

ParameterDescriptor

backtrader.parameters.String(min_length=None, max_length=None)[source]

Create a string validator function.

Parameters:
  • min_length (int | None) – Minimum allowed string length

  • max_length (int | None) – Maximum allowed string length

Returns:

Validator function for string parameters

Return type:

Callable[[Any], bool]

backtrader.parameters.Bool()[source]

Create a boolean validator function.

Returns:

Validator function for boolean parameters

Return type:

Callable[[Any], bool]

backtrader.parameters.OneOf(*choices)[source]

Create a validator that checks if value is one of the given choices.

Parameters:

*choices – Allowed values

Returns:

Validator function

Return type:

Callable[[Any], bool]

backtrader.parameters.create_param_descriptor(name, default=None, doc=None)[source]

Create a basic parameter descriptor.

Parameters:
  • name (str) – Parameter name

  • default (Any) – Default value

  • doc (str) – Documentation string

Returns:

ParameterDescriptor instance

Return type:

ParameterDescriptor

backtrader.parameters.derive_params(base_params, new_params, other_base_params=None)[source]

Derive parameters by combining base parameters with new ones.

Parameters:
  • base_params – Base parameter descriptors or tuples

  • new_params – New parameter descriptors or tuples

  • other_base_params – Additional base parameters

Returns:

Dictionary of combined parameter descriptors

class backtrader.parameters.ParamsBridge[source]

Bases: object

Bridge class for transitioning from MetaParams to new parameter system.

This class provides utilities for converting between the old MetaParams system and the new descriptor-based system during the migration period.

static extract_params_from_metaparams_class(cls)[source]

Extract parameter descriptors from a MetaParams-based class.

Parameters:

cls – Class with MetaParams-based parameters

Returns:

Dictionary of parameter descriptors

Return type:

Dict[str, ParameterDescriptor]

static convert_legacy_params_tuple(params_tuple)[source]

Convert legacy params tuple to parameter descriptors.

Parameters:

params_tuple – Legacy params tuple like ((‘param1’, 10), (‘param2’, ‘value’))

Returns:

Dictionary of parameter descriptors

Return type:

Dict[str, ParameterDescriptor]

static create_compatibility_wrapper(metaparams_class)[source]

Create a compatibility wrapper for MetaParams-based classes.

Parameters:

metaparams_class – Original MetaParams-based class

Returns:

New class that uses the modern parameter system

exception backtrader.parameters.ParameterValidationError[source]

Bases: ValueError

Specific exception for parameter validation errors.

__init__(parameter_name, value, expected_type=None, additional_info='')[source]

Initialize a parameter validation error.

Parameters:
  • parameter_name (str) – Name of the parameter that failed validation.

  • value (Any) – The invalid value that was provided.

  • expected_type (Type | None) – Expected type for the parameter (optional).

  • additional_info (str) – Additional error information (optional).

exception backtrader.parameters.ParameterAccessError[source]

Bases: AttributeError

Specific exception for parameter access errors.

__init__(parameter_name, class_name, available_params)[source]

Initialize a parameter access error.

Parameters:
  • parameter_name (str) – Name of the parameter that was not found.

  • class_name (str) – Name of the class where access was attempted.

  • available_params (List[str]) – List of available parameter names.

backtrader.parameters.validate_parameter_compatibility(old_class, new_class)[source]

Validate compatibility between old MetaParams class and new descriptor-based class.

Parameters:
  • old_class – Original MetaParams-based class

  • new_class – New descriptor-based class

Returns:

Dictionary with compatibility analysis results

Return type:

Dict[str, Any]