Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe 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.735
Tracking Error
0.241
Treynor Ratio
0
Total Fees
$0.00
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Data import *
from QuantConnect.Data.Market import *
from QuantConnect.Data.Consolidators import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from QuantConnect.Securities import *
from QuantConnect.Orders import *
from datetime import datetime
from System.Drawing import Color

import decimal as d
import numpy as np

class Demo(QCAlgorithm):

    def Initialize(self):
        
        # configuration parameters (configurable inputs into the algorithm)
        DEBUG_LOG = str(self.GetParameter("Debug Log")).lower() == "true" or False
        MINUTES_AFTER_OPEN = int(self.GetParameter("MarketOpenDelay")) or 0
        MINUTES_BEFORE_CLOSE = int(self.GetParameter("SellMinutesBeforeClose")) or 1
        SYMBOL = str(self.GetParameter("Symbol"))
        BBLENGTH = int(self.GetParameter("BB Length")) or 20
        BBDEV = int(self.GetParameter("BB Deviation")) or 2
        MATYPE = str(self.GetParameter("BB MA Type")) or Exponential
        
        
        self.ORDER_MAP = ["Market", "Limit", "StopMarket", "StopLimit", "MarketOnOpen", "MarketOnClose", "OptionExercise"]
        
        self.DEBUG = DEBUG_LOG

        # initialization
        self.SetStartDate(2020, 9, 1)
        self.SetEndDate(2020, 9, 30)
        self.SetCash(100000)
        self.stock = self.AddEquity(SYMBOL, Resolution.Second)
        self.SetTimeZone("America/Chicago")
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)

        self.Schedule.On(self.DateRules.EveryDay(self.stock.Symbol), self.TimeRules.AfterMarketOpen(self.stock.Symbol, MINUTES_AFTER_OPEN), self.OnMarketOpen)
        self.Schedule.On(self.DateRules.EveryDay(self.stock.Symbol), self.TimeRules.BeforeMarketClose(self.stock.Symbol, MINUTES_BEFORE_CLOSE), self.OnMarketClose)
        # set the trade flag to False. we'll only start trading when the flag flips to True (after the market open event)
        self.tradeFlag = False
        self.bb = self.BB(SYMBOL, BBLENGTH, 2, MovingAverageType.Exponential, Resolution.Minute)
        
        
        # create the 30-minutes data consolidator
        #fiveMinuteConsolidator = TradeBarConsolidator(timedelta(minutes=5))
        #self.SubscriptionManager.AddConsolidator(SYMBOL, fiveMinuteConsolidator)
        # register the 30-minute consolidated bar data to automatically update the indicator
        #self.RegisterIndicator(SYMBOL, self.bb, fiveMinuteConsolidator)
        #self.RegisterIndicator(SYMBOL, self.bb, timedelta(minutes=5))
        
        self.lastPrice = 0.0
        self.pl = 0.0
        self._lo = None
        
        self.SetWarmUp(120, Resolution.Minute)
        
        self.Consolidate(SYMBOL, timedelta(minutes=5), self.OnStockBarConsolidated)
        
        
    # OnMarketOpen event, callback from our TimeRules.AfterMarketOpen initialization        
    def OnMarketOpen(self):
        # start trading!
        self.tradeFlag = True
        
    # OnMarketClose event, callback from our TimeRules.BeforeMarketClose initialization
    def OnMarketClose(self):
        # liquidate all holdings
        if self.stock.Invested:
            self.Liquidate(self.stock.Symbol, "EOD Liquidate")
        else:
            self.Transactions.CancelOpenOrders()

        # reset trade flag for following day
        self.tradeFlag = False
        
        if self.DEBUG:
            self.Debug("Profit/Loss as of " + str(self.Time) + ": " + str(self.pl) + " | Portfolio Value: " + str(self.Portfolio.TotalPortfolioValue))
        
    def CollectData(self):
        pass
    
    def OnStockBarConsolidated(self, consolidated):
        if self.IsWarmingUp or not self.tradeFlag or not self.bb.IsReady:
            return
        
        open_orders = self.Transactions.GetOpenOrders(self.stock.Symbol)
        
        ub = self.bb.UpperBand.Current.Value
        lb = self.bb.LowerBand.Current.Value
        shares = self.CalculateOrderQuantity(self.stock.Symbol, 0.6)

        self.prevCandle = {
            "Open": consolidated.Open,
            "High": consolidated.High,
            "Low": consolidated.Low,
            "Close": consolidated.Close
        }

    # OnData event provided by QC, provides new dataset on each time slice, based on equity resolution
    def OnData(self, data):
        # if we're not ready to trade, skip this run
        if self.IsWarmingUp or not self.tradeFlag:
            return
        
    def OnOrderEvent(self, OrderEvent):
        if OrderEvent.FillQuantity == 0:
            return
        
        self.lastPrice = float(OrderEvent.FillPrice)

        order = self.Transactions.GetOrderById(OrderEvent.OrderId)
        orderType = order.Type
        self.pl -= order.Value
        
        if "liquid" in (str(order.Tag)).lower():
            if "short" in (str(order.Tag)).lower():
                self.Plot('Stock Plot', 'Liquidate', OrderEvent.FillPrice)
            if "long" in (str(order.Tag)).lower():
                self.Plot('Stock Plot', 'Liquidate', OrderEvent.FillPrice)
        if "buy" in (str(order.Tag)).lower():
            self.Plot('Stock Plot', 'Buy Fill', OrderEvent.FillPrice)
        if "sell" in (str(order.Tag)).lower():
            self.Plot('Stock Plot', 'Sell Fill', OrderEvent.FillPrice)
        if "profit" in (str(order.Tag)).lower():
            self.Plot('Stock Plot', 'Profit', OrderEvent.FillPrice)
        
        
        if self.DEBUG:
            self.Debug("{} was filled. Tag: {}. Symbol: {}. Quantity: {}. Price: {}, Fee: {}, Trade Value: {}. Running Sum: {}. Portfolio: {}"
                      .format(str(self.ORDER_MAP[order.Type]),
                              str(order.Tag),
                              str(OrderEvent.Symbol),
                              str(OrderEvent.FillQuantity),
                              str(OrderEvent.FillPrice),
                              str(OrderEvent.OrderFee),
                              str(order.Value),
                              str(self.pl),
                              str(self.Portfolio.TotalPortfolioValue)))