Overall Statistics
Total Orders
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Start Equity
100000
End Equity
100000
Net Profit
0%
Sharpe Ratio
0
Sortino Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
-1.826
Tracking Error
0.108
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
Portfolio Turnover
0%
from AlgorithmImports import *
from System.Drawing import Color

class FuturesChartingDemoAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2021, 1, 1)
        self.set_end_date(2022, 1, 1)
        self.settings.automatic_indicator_warm_up = True

        # List of futures tickers to track (use QC futures symbols)
        self.future_tickers = [Futures.Indices.SP500EMini, Futures.Metals.Gold]  # Add more tickers as needed
        self.contracts = {}  # Store the active contract for each symbol
        self.indicators = {}  # Store EMAs and other indicators for each active contract

        for ticker in self.future_tickers:
            # Add futures and set a filter for the front month contracts
            future = self.add_future(ticker, Resolution.DAILY)
            future.set_filter(timedelta(0), timedelta(182))  # Focus on near-term expirations

            # Initialize dictionary entries for each ticker
            self.indicators[ticker] = {"ema_fast": None, "ema_slow": None}

            # Create "Price" chart for each futures ticker
            price_chart = Chart(f"{ticker} Price")
            self.add_chart(price_chart)
            price_chart.add_series(Series("CROSS UP", SeriesType.SCATTER, "$", Color.Green, ScatterMarkerSymbol.TRIANGLE))
            price_chart.add_series(Series("CROSS DOWN", SeriesType.SCATTER, "$", Color.Red, ScatterMarkerSymbol.TRIANGLE_DOWN))
            price_chart.add_series(Series("EMA FAST", SeriesType.LINE, "$", Color.Orange))
            price_chart.add_series(Series("EMA SLOW", SeriesType.LINE, "$", Color.Blue))

            # Create "Candlestick" chart for each futures ticker
            candlestick_chart = Chart(f"{ticker} Candlestick")
            self.add_chart(candlestick_chart)
            candlestick_chart.add_series(CandlestickSeries(ticker, "$"))

    def on_data(self, slice: Slice) -> None:
        # Iterate through the futures chains in slice.future_chains
        for symbol, chain in slice.future_chains.items():
            ticker = symbol.value  # Use the symbol key from the dictionary

            # Check if there are any contracts in the chain
            if not chain:
                continue

            # Find the front contract (nearest expiry)
            front_contract = sorted(chain, key=lambda contract: contract.expiry)[0]
            self.contracts[ticker] = front_contract

            # Initialize the indicators dictionary for this ticker if not already done
            if ticker not in self.indicators:
                self.indicators[ticker] = {"ema_fast": None, "ema_slow": None}

            # Initialize EMAs for the front contract if not done already
            if self.indicators[ticker]["ema_fast"] is None:
                self.indicators[ticker]["ema_fast"] = self.ema(front_contract.symbol, 10)
                self.indicators[ticker]["ema_slow"] = self.ema(front_contract.symbol, 50)

            # If we have a contract, plot the data
            contract = self.contracts[ticker]
            ema_fast = self.indicators[ticker]["ema_fast"]
            ema_slow = self.indicators[ticker]["ema_slow"]

            # Ensure indicators are warmed up before plotting
            if ema_fast.is_ready and ema_slow.is_ready:
                self.plot(f"{ticker} Price", "EMA FAST", ema_fast.current.value)
                self.plot(f"{ticker} Price", "EMA SLOW", ema_slow.current.value)

                # Get the latest price of the future contract and plot it as a candlestick
                if contract.symbol in self.Securities:
                    latest_price = self.Securities[contract.symbol].Price  # Correct method to get the latest price
                    self.plot(f"{ticker} Candlestick", ticker, latest_price)

                # Plot CROSS UP and CROSS DOWN based on EMA crossover logic
                if (ema_fast.current.value > ema_slow.current.value and 
                    ema_fast[1] < ema_slow[1]):
                    self.plot(f"{ticker} Price", "CROSS UP", self.Securities[contract.symbol].Price)
                elif (ema_fast.current.value < ema_slow.current.value and 
                    ema_fast[1] > ema_slow[1]):
                    self.plot(f"{ticker} Price", "CROSS DOWN", self.Securities[contract.symbol].Price)