---
title: "Globals and Statics"
description: "It is often convenient to access the QCAlgorithm API in classes outside of the QCAlgorithm class."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/globals-and-statics
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/globals-and-statics.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/01%20Key%20Concepts/12%20Globals%20and%20Statics
modified: 2026-10-30
index: https://www.quantconnect.com/llms.txt
---

# Globals and Statics

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Key Concepts > Globals and Statics

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

It is often convenient to access the QCAlgorithm API in classes outside of the QCAlgorithm class. To achieve this, pass an instance reference or access a global static variable. Whenever possible, we recommend using an instance reference to keep your global namespace clean.

## API Access by Algorithm Instance

You can access the QCAlgorithm API by passing the `self` object into a constructor of your target class. The class constructor receives it as a variable you can use to initialize your algorithm. The following algorithm demonstrates this process:

```python
class CustomPartialFillModelAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)

        # Request SPY data for trading.
        equity = self.add_equity("SPY", Resolution.HOUR)
        self._spy = equity.symbol
        self._holdings = equity.holdings

        # Set the fill model with the algorithm instance.
        equity.set_fill_model(CustomPartialFillModel(self))

    def on_data(self, data: Slice) -> None:
        # To get all SPY open orders, use the transaction manager.
        open_orders = self.transactions.get_open_orders(self._spy)
        if len(open_orders) != 0: return

        # Hold SPY during 10th-20th in each month.
        if self.time.day > 10 and self._holdings.quantity <= 0:
            self.market_order(self._spy, 105, True)
        elif self.time.day > 20 and self._holdings.quantity >= 0:
            self.market_order(self._spy, -100, True)

class CustomPartialFillModel(FillModel):
    def __init__(self, algorithm: QCAlgorithm) -> None:
        self._algorithm = algorithm
        self._absolute_remaining_by_order_id = {}

    def market_fill(self, asset: Security, order: MarketOrder) -> OrderEvent:
        absolute_remaining = self._absolute_remaining_by_order_id.get(order.id, order.absolute_quantity)
        fill = super().market_fill(asset, order)

        # Allow at most 10 shares to be filled at once.
        fill.fill_quantity = np.sign(order.quantity) * 10

        # If the remaining shares are less than or equal to 10, the order will be fully filled.
        if (min(abs(fill.fill_quantity), absolute_remaining) == absolute_remaining):
            fill.fill_quantity = np.sign(order.quantity) * absolute_remaining
            fill.status = OrderStatus.FILLED
            self._absolute_remaining_by_order_id.pop(order.id, None)
        # Otherwise, the order is only partially filled out, and we need to update the remaining quantity.
        else:
            fill.status = OrderStatus.PARTIALLY_FILLED
            self._absolute_remaining_by_order_id[order.id] = absolute_remaining - abs(fill.fill_quantity)
            price = fill.fill_price
            # Use the instance of the algorithm to log the information
            self._algorithm.debug(f"{self._algorithm.time} - Partial Fill - Remaining {self._absolute_remaining_by_order_id[order.id]} Price - {price}")

        return fill
```

## API Access by Global Static Variable

Occasionally, passing the QCAlgorithm object to your class constructor is impossible, so you need to use global static variables to access the API for debugging and initialization purposes. The most common case is [custom data implementations](https://www.quantconnect.com/docs/v2/writing-algorithms/importing-data/streaming-data/key-concepts.md), where the LEAN Engine is creating the objects, and you're unable to specify a custom constructor.

To create a global static variable, assign the reference to the global variable in the algorithm's `initialize` method. This assignment sets the active instance of the variable to the global static. Then, in your custom class, you can access the QCAlgorithm API through the global. The following algorithm demonstrates this process:

```python
class MyAlgorithmInstance(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)

        # Instantiate a custom type as a global variable in the QCAlgorithm instance.
        # Assign self to Static Cape Variable.
        Cape.algorithm = self
        # Request data for trading or signal.
        self._symbol = self.add_data(Cape, "CAPE")

    def on_data(self, data: Slice) -> None:
        cape = data.get(self._symbol)
        if not cape:
            return
        self.plot("CAPE", "Value", cape.value)

class Cape(PythonData):
    def get_source(self, config: SubscriptionDataConfig, date:datetime, isLiveMode: bool) -> SubscriptionDataSource:
        Cape.algorithm.debug("Test Static: GetSource")
        return SubscriptionDataSource("https://raw.githubusercontent.com/QuantConnect/Documentation/master/Resources/datasets/custom-data/CAPE.csv", SubscriptionTransportMedium.REMOTE_FILE)

    def reader(self, config: SubscriptionDataConfig, line: str, date:datetime, isLiveMode: bool) -> BaseData:
        index = Cape()
        index.symbol = config.symbol
        data = [x.strip() for x in line.split(',')]
        if len(data) < 12 or line.startswith('Date'):
            return index

        try:
            # Construct the custom data type with input data entry.
            index.value = float(data[12])
            index.time = datetime.strptime(data[0], "%Y.%m")
        except ValueError:
            Cape.algorithm.debug("Test Static 2: ValueError")
        return index
```
