Overall Statistics
Total Trades
36
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
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
COMPUSD E3
from AlgorithmImports import *


COINS = ["ROSE", "ZMT", "LUNA", "REQ", "WAVES", "DUSK", "CCD", "COMP", "MANA", "ICP"]

CURRENCY = "USD"
STOPLOSS =  10 # %
WAIT = 10 # Seconds
LIMIT_BUY_LONG = 1.000
LIMIT_SELL_LONG = 1.001
LIMIT_SELL_SHORT = 1.000
LIMIT_BUY_SHORT = 0.999
THRESHOLD = 95 # %
SMA_PERIOD = 90
POSITION = 500
# region imports
from AlgorithmImports import *
import config 
from datetime import *
# endregion

class FatSkyBlueLeopard(QCAlgorithm):

    def Initialize(self):
        # self.SetStartDate(2022, 5, 1)  # Set Start Date
        # self.SetEndDate(2022, 7, 1)
        self.SetStartDate(2022, 7, 4)  # Set Start Date
        self.SetEndDate(2022, 7, 5)
        self.SetCash("USD", 1000) # Binance doesnt have USD pairs, so the account needs to have USDT currency to trade
        # self.SetCash("USDT", 10000) # Set Strategy Cash
        self.SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin)
        # self.SetSecurityInitializer(lambda security: security.SetMarketPrice(self.GetLastKnownPrice(security)))
        self.SetSecurityInitializer(self.CustomSecurityInitializer)
        # self.Portfolio.MarginCallModel = MarginCallModel.Null
        self.DefaultOrderProperties = BitfinexOrderProperties()
        self.DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled
        self.DefaultOrderProperties.PostOnly = False
        self.symbols = []
        self.DataBySymbol = {}
        Pairs = [x + config.CURRENCY for x in config.COINS]
        for Pair in Pairs:
            # self.Debug("HERE")
            try:
                self.symbols.append(self.AddCrypto(Pair, Resolution.Second, Market.Bitfinex).Symbol)
            except:
                if Pair in self.DataBySymbol.keys():
                    symbolData = self.DataBySymbol.pop(Pair, None)
                    self.SubscriptionManager.RemoveConsolidator(Pair, symbolData.Bar_Consolidator)
                    self.SubscriptionManager.RemoveConsolidator(Pair, symbolData.Calculation_Call)
                continue
    
    def CustomSecurityInitializer(self, security):
        # self.Debug(self.Time)
        security.SetMarketPrice(self.GetLastKnownPrice(security))
        security.MarginModel = SecurityMarginModel(3.3)
        security.SetFeeModel(ConstantFeeModel(0))
    
    def OnData(self, data: Slice):
        
        for symbol in self.symbols:
            if not symbol in self.DataBySymbol:
                history = map(lambda x: x[symbol], self.History(timedelta(40), Resolution.Minute))         #self.History(symbol, 40, Resolution.Minute)
                self.DataBySymbol[symbol] = SymbolData(self, symbol, history)
            # if data.ContainsKey(symbol) and self.CurrentSlice.Bars.ContainsKey(symbol):
            #     symbolData = self.DataBySymbol[symbol]
            #     if not self.Portfolio[symbol].Invested:
            #         quantity = 100/self.Securities[symbol].Close
            #         symbolData.ticket = self.MarketOrder(symbol, quantity)

        for symbol in self.DataBySymbol:
            symbolData = self.DataBySymbol[symbol]
            symbolData.OrderHandler(data)

    
    def OnOrderEvent(self, orderEvent: OrderEvent):
        # self.Debug("ORDEREVENT")
        order = self.Transactions.GetOrderById(orderEvent.OrderId)

        for symbol in self.DataBySymbol:
            if orderEvent.Symbol == symbol:
                if orderEvent.Status == OrderStatus.Filled:
                    symbolData = self.DataBySymbol[symbol]
                    symbolData.OnOrderEvent(orderEvent)

        # if orderEvent.Status == OrderStatus.Filled: 
        #     self.Debug("{0}: {1}: {2}".format(self.Time, order.Type, orderEvent))

    # def OnEndOfAlgorithm(self):
    #     for symbol in self.DataBySymbol:
    #         symbolData = self.DataBySymbol[symbol]
    #         self.Debug(f" {symbol} {symbolData.Orders_Sent}")          

class SymbolData():

    def OnOrderEvent(self, orderEvent: OrderEvent):
        # self.Debug("ORDEREVENT")
        order = self.Transactions.GetOrderById(orderEvent.OrderId)

    def __init__(self, algorithm, symbol, history):
        self.algorithm = algorithm
        self.symbol = symbol
        # self.data = data
        # self.algorithm.Debug(algorithm.Securities[self.symbol].Price)
        self.sma = SimpleMovingAverage(config.SMA_PERIOD)
        algorithm.WarmUpIndicator(self.symbol, self.sma, timedelta(minutes=1))
        self.count = 0
        # self.OrderHandler(data)
        self.Stop_Loss_Long = (1-(config.STOPLOSS/100))
        self.Stop_Loss_Short = (1+(config.STOPLOSS/100))
        self.Wait_After_Order = config.WAIT
        self.Threshold = config.THRESHOLD/100
        self.Order_Sent_Time = None
        self.Limit_Sell_Time = None
        self.Limit_Buy_Time_Short =None
        self.Current_Order = None
        self.Unfilled_Limit_Buy_Order = False
        self.Unfilled_Limit_Sell_Order = False
        self.Unfilled_Limit_Sell_Order_Short = False
        self.Limit_Price_Buy_Long = None
        self.Limit_Price_Sell_Long = None
        self.Limit_Buy_Long = config.LIMIT_BUY_LONG
        self.Limit_Sell_Long = config.LIMIT_SELL_LONG
        self.Remaining_Quantity_Lmt_Buy_Long = None
        self.Remaining_Quantity_Lmt_Sell_Short = None
        self.Minimum_Order_Size = self.algorithm.Securities[self.symbol].SymbolProperties.MinimumOrderSize
        self.symbol.ticket_LmtBuy = None
        self.symbol.ticket_LmtSell = None
        self.symbol.ticket_Stop_Long = None

        self.symbol.ticket_LmtSell_Short = None
        self.symbol.ticket_LmtBuyShort = None
        self.symbol.ticket_Stop_Short = None
        self.Long_Stop = None
        self.Short_Stop = None
        self.my_quantity = None


        self.Abs_Long_Buy = None
        self.Average_Long_Buy = None
        self.Long_Fill_Distance_LmtBuy = None

        self.Abs_Long_Sell = None
        self.Average_Long_Sell = None
        self.Long_Fill_Distance_LmtSell = None


        self.Abs_Short_Sell = None
        self.Average_Short_Sell = None
        self.Short_Fill_Distance_LmtSell = None

        self.Abs_Short_Cover = None
        self.Average_Short_Cover = None
        self.Short_Fill_Distance_Cover = None

        self.symbol.ticket_switch_short = None
        self.symbol.ticket_switch_long = None

        # self.Order_Status_List = [OrderStatus.New, OrderStatus.]
        self.Limit_Buy_Short= config.LIMIT_BUY_SHORT
        self.Limit_Sell_Short = config.LIMIT_SELL_SHORT
        # self.Order_Quantity = config.ORDER_QUANTITY_IN_USDT

        self.Current_SMA = None
        self.Current_Ask = None
        self.Current_Bid = None

        self.Minimum_Order_Size = None

        self.Orders_Sent = 0

        self.Bar_Consolidator = TradeBarConsolidator(timedelta(minutes=1))
        algorithm.SubscriptionManager.AddConsolidator(symbol, self.Bar_Consolidator)
        self.Bar_Consolidator.DataConsolidated += self.OnDataConsolidated


        

        # for bar in history:
        #     # if symbol == row.Index[0]:
        #     bar = TradeBar(bar.EndTime - timedelta(minutes=1), symbol, bar.Open, bar.High, bar.Low, bar.Close, 10000, bar.Period)
        #     self.Bar_Consolidator.Update(bar)

    # def OnOrderEvent(self, orderEvent: OrderEvent):
    #     self.Debug("ORDEREVENT")
    #     order = self.Transactions.GetOrderById(orderEvent.OrderId)
    #     if orderEvent.Status == OrderStatus.Filled: 
    #         self.Debug("{0}: {1}: {2}".format(self.Time, order.Type, orderEvent))


        self.No_Open_Long_Position = True
        self.No_Open_Long_Sell_Order = True
        self.No_Open_Long_Stop_Order = True
        self.No_Open_Long_Buy_Order = True

        self.symbol.ticket_Stop_Long = None
        self.symbol.ticket_Long_Limit_Sell = None
        self.symbol.ticket_Long_Limit_Buy = None



        self.No_Open_Short_Position = True
        self.No_Open_Short_Buy_Order = True
        self.No_Open_Short_Stop_Order = True
        self.No_Open_Short_Sell_Order = True

        self.symbol.ticket_Stop_Short = None
        self.symbol.ticket_Short_Limit_Buy = None
        self.symbol.ticket_Short_Limit_Sell = None


        if self.symbol == "ROSEUSD":
            self.cash_symbol = "ROSE"
        
        if self.symbol == "ZMTUSD":
            self.cash_symbol = "ZMT"
        
        if self.symbol == "LUNAUSD":
            self.cash_symbol = "LUNA"

        if self.symbol == "REQUSD":
            self.cash_symbol = "REQ"

        if self.symbol == "WAVESUSD":
            self.cash_symbol = "WAVES"
    
        if self.symbol == "DUSKUSD":
            self.cash_symbol = "DUSK"
        
        if self.symbol == "CCDUSD":
            self.cash_symbol = "CCD"

        if self.symbol == "COMPUSD":
            self.cash_symbol = "COMP"

        if self.symbol == "MANAUSD":
            self.cash_symbol = "MANA"
    
        if self.symbol == "ICPUSD":
            self.cash_symbol = "ICP"

        ##########################################################################################


        self.Order_Tag_List = ["LONG BUY", "LONG SELL", "LONG STOP", "SHORT SELL", "SHORT COVER", "SHORT STOP", "UNEXPECTED", "QUANTITY WITHOUT PERMISSION"]
        self.User_Cancelled = False
        self.Entry_Time_Long = None
        self.Entry_Time_Short = None
        self.Interval = timedelta(seconds=config.WAIT)
        self.Long_Stop_Price = None
        self.Order_Permission = True

    def OnDataConsolidated(self, sender, bar):
        self.sma.Update(IndicatorDataPoint(bar.EndTime, bar.Close))
        # self.OrderHandler()
    

    def OrderHandler(self, data):
        
        self.Lot_Size = self.algorithm.Securities[self.symbol].SymbolProperties.LotSize
       
        self.Minimum_Order_Size = (self.algorithm.Securities[self.symbol].SymbolProperties.MinimumOrderSize * self.algorithm.Securities[self.symbol].Price)
        self.Current_SMA = self.sma.Current.Value
        self.Current_Ask = self.algorithm.Securities[self.symbol].AskPrice
        self.Current_Bid = self.algorithm.Securities[self.symbol].BidPrice
        
        self.Minimum_Price_Variation = self.algorithm.Securities[self.symbol].SymbolProperties.MinimumPriceVariation

        # if not self.Order_Permission:
        #     if self.cash_symbol in self.algorithm.Portfolio.CashBook:
                  
        #         quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount
        #         if quantity > 0:
        #             self.algorithm.MarketOrder(self.symbol, -quantity, tag = "QUANTITY WITHOUT PERMISSION")
        #         if quantity < 0:
        #             self.algorithm.MarketOrder(self.symbol, abs(quantity), tag = "QUANTITY WITHOUT PERMISSION")



        if self.algorithm.Securities[self.symbol].Price > self.Current_SMA:
            
            if self.Order_Permission:
             
                if self.cash_symbol in self.algorithm.Portfolio.CashBook:
                   
                  
                    quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount
                    if quantity != 0:
                        self.algorithm.Debug("WTF")
                    if quantity == 0:
                        quantity = config.POSITION / (0.99 *(self.Current_Bid * self.Limit_Buy_Long))

            
                        entry_price = self.Current_Bid * self.Limit_Buy_Long
                        quantity = round(quantity, 3)
                        entry_price = round(entry_price, 5)
                        self.algorithm.Debug("WTF")
                        if quantity * self.algorithm.Securities[self.symbol].Price > (self.Minimum_Order_Size * 1.0001):
                            self.algorithm.LimitOrder(self.symbol, quantity, entry_price, tag = "LONG BUY")
                            self.Order_Permission = False
                            self.Entry_Time_Long = self.algorithm.Time
                else:
                   
                    quantity = config.POSITION / (0.99 *(self.Current_Bid * self.Limit_Buy_Long))

                    
                    entry_price = self.Current_Bid * self.Limit_Buy_Long
                    quantity = round(quantity, 3)
                    entry_price = round(entry_price, 5)
                    self.algorithm.Debug("WTF")
                    if quantity > 0 and (quantity * entry_price) > self.Minimum_Order_Size:
                        
                        self.algorithm.LimitOrder(self.symbol, quantity, entry_price, tag = "LONG BUY")
                        self.Order_Permission = False
                        self.Entry_Time_Long = self.algorithm.Time

        open_orders = self.algorithm.Transactions.GetOpenOrders(self.symbol)
        for Order in open_orders:
            if Order.Tag == "LONG BUY":
                if Order.Status == OrderStatus.Submitted or Order.Status == OrderStatus.PartiallyFilled or Order.Status == OrderStatus.UpdateSubmitted:
                    
                    if Order.Quantity * self.Current_Bid > self.Minimum_Order_Size and Order.Quantity > 0:
                        # self.algorithm.Debug(self.algorithm.Time)
                        if self.algorithm.Time > (self.Entry_Time_Long + self.Interval):
                            order_tickets = self.algorithm.Transactions.GetOpenOrderTickets(self.symbol)
                            for order_ticket in order_tickets:
                                if order_ticket.OrderId == Order.Id:
                                    ticket = order_ticket
                            entry_price = self.Current_Bid * self.Limit_Buy_Long
                            entry_price = round(entry_price, 5)
                            quantity = round(Order.Quantity, 3)
                            Update_Settings = UpdateOrderFields()
                            Update_Settings.LimitPrice= entry_price
                            Update_Settings.Quantity = quantity
                            Update_Settings.Tag = "LONG BUY"
                            Update_Order = order_ticket.Update(Update_Settings)
                            self.Entry_Time_Long = self.algorithm.Time
                            if Update_Order.IsSuccess:
                                pass
                            else:
                                self.Order_Permission = False
                                
                               

        


        if self.Order_Permission:
            if self.cash_symbol in self.algorithm.Portfolio.CashBook:
        
                quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount
                if quantity > 0: 
                    exit_price = self.Current_Ask * self.Limit_Sell_Long
                    self.algorithm.LimitOrder(self.symbol, -quantity, exit_price, tag = "LONG SELL")
                    self.Long_Stop_Price = self.algorithm.Portfolio[self.symbol].AveragePrice * self.Stop_Loss_Long
                    self.Long_Exit_Time = self.algorithm.Time
                    self.Order_Permission = False




        open_orders = self.algorithm.Transactions.GetOpenOrders(self.symbol)
        for Order in open_orders:
            if Order.Tag == "LONG SELL":
                if Order.Status == OrderStatus.Submitted or Order.Status == OrderStatus.PartiallyFilled or Order.Status == OrderStatus.UpdateSubmitted:
                    
                    if ((abs(Order.Quantity)) * self.Current_Ask) > self.Minimum_Order_Size and Order.Quantity < 0:
                        if self.algorithm.Time > (self.Long_Exit_Time + self.Interval):
                            order_tickets = self.algorithm.Transactions.GetOpenOrderTickets(self.symbol)
                            for order_ticket in order_tickets:
                                if order_ticket.OrderId == Order.Id:
                                    ticket = order_ticket
                            entry_price = self.Current_Ask * self.Limit_Sell_Long
                            entry_price = round(entry_price, 5)
                            quantity = round(Order.Quantity, 3)
                            Update_Settings = UpdateOrderFields()
                            Update_Settings.LimitPrice= entry_price
                            Update_Settings.Quantity = quantity
                            Update_Settings.Tag = "LONG SELL"
                            Update_Order = order_ticket.Update(Update_Settings)
                            self.Long_Exit_Time = self.algorithm.Time
                            if Update_Order.IsSuccess:
                                pass
                            else:
                                self.Order_Permission = False
                    
        if self.Long_Stop_Price is not None:
            if self.algorithm.Securities[self.symbol].Price < self.Long_Stop_Price:
                quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount
                self.algorithm.MarketOrder(self.symbol, -quantity, tag = "LONG STOP")
                self.Order_Permission = False

                







    def OnOrderEvent(self, orderEvent):
        order = self.algorithm.Transactions.GetOrderById(orderEvent.OrderId)
        open_orders = self.algorithm.Transactions.GetOpenOrders(self.symbol)
        # cash_book = self.algorithm.Portfolio.CashBook[self.symbol]
        symbol_open_quantity = self.algorithm.Transactions.GetOpenOrdersRemainingQuantity(self.symbol)
   

        if order.Tag == "LONG BUY":
            if order.Status == OrderStatus.PartiallyFilled:
                if (abs(order.AbsoluteFillQuantity * self.Securities[self.symbol].BidPrice)) < self.Minimum_Order_Size:
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
                if self.algorithm.Time > (self.Entry_Time_Long + self.Interval + timedelta(seconds=10)):
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
             


            if order.Status == OrderStatus.Filled:
                if self.cash_symbol in self.algorithm.Portfolio.CashBook:
                    quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount
                   
                    if not quantity > 0:
                        self.Order_Permission = False
                        self.algorithm.Transactions.CancelOpenOrders(self.symbol)
                    if quantity > 0:
                        self.Order_Permission = True
                # if self.cash_symbol not in self.algorithm.Portfolio.CashBook:
                #     if self.algorithm.Portfolio[self.symbol].Quantity == 0:
                #         # self.algorithm.Transactions.CancelOpenOrders(self.symbol)
                #         self.Order_Permission = True

        if order.Tag == "LONG SELL":
            if order.Status == OrderStatus.PartiallyFilled:
                if (abs(order.AbsoluteFillQuantity * self.Securities[self.symbol].AskPrice)) < self.Minimum_Order_Size:
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
                if self.Time > (self.Entry_Time_Long + self.Interval + timedelta(seconds=10)):
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
                

            if order.Status == OrderStatus.Filled:
               
                quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount 
                if quantity > 0:
                    self.Order_Permission = False
                    self.MarketOrder(self.symbol, -quantity, tag = "ERROR")
                if quantity == 0:
                    self.Order_Permission = True

                # if self.cash_symbol not in self.algorithm.Portfolio.CashBook:
                #     if self.algorithm.Portfolio[self.symbol].Quantity == 0:
                #         self.Order_Permission = True
                        # self.algorithm.Transactions.CancelOpenOrders(self.symbol)

        if order.Tag == "LONG STOP":
            if Order.Status == OrderStatus.PartiallyFilled:
                if (abs(order.AbsoluteFillQuantity * self.Securities[self.symbol].BidPrice)) < self.Minimum_Order_Size:
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
                if self.algorithm.Time > (self.Entry_Time_Long + self.Interval + timedelta(seconds=10)):
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
                    
                
            if order.Status == OrderStatus.Filled:
               
                quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount
                if quantity > 0:
                    self.Order_Permission = False
                    self.MarketOrder(self.symbol, -quantity, tag = "ERROR")
                if quantity == 0:
                    self.Order_Permission = True

                # if self.cash_symbol not in self.algorithm.Portfolio.CashBook:
                #     if self.algorithm.Portfolio[self.symbol].Quantity == 0:
                #         self.Order_Permission = True
                        # self.algorithm.Transactions.CancelOpenOrders(self.symbol)

        if order.Tag == "SHORT SELL":
            if Order.Status == OrderStatus.PartiallyFilled:
                if (abs(order.AbsoluteFillQuantity * self.Securities[self.symbol].AskPrice)) < self.Minimum_Order_Size:
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
                if self.Time > (self.Entry_Time_Long + self.Interval + timedelta(seconds=10)):
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True

            if order.Status == OrderStatus.Filled:
              
                quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount 
               
                if not quantity < 0:
                    self.Order_Permission = False
                    self.algorithm.Transactions.CancelOpenOrders(self.symbol)
                if quantity < 0:
                        self.Order_Permission = True
                if self.cash_symbol not in self.algorithm.Portfolio.CashBook:
                    if self.algorithm.Portfolio[self.symbol].Quantity == 0:
                        # self.algorithm.Transactions.CancelOpenOrders(self.symbol)
                        self.Order_Permission = True

        if order.Tag == "SHORT COVER":
            if Order.Status == OrderStatus.PartiallyFilled:
                if (abs(order.AbsoluteFillQuantity * self.Securities[self.symbol].BidPrice)) < self.Minimum_Order_Size:
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
                if self.algorithm.Time > (self.Entry_Time_Long + self.Interval + timedelta(seconds=10)):
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
            if order.Status == OrderStatus.Filled:
        
                quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount 
                if quantity < 0:
                    self.Order_Permission = False
                    self.MarketOrder(self.symbol, abs(quantity), tag = "ERROR")
                if quantity == 0:
                    self.Order_Permission = True
                            
                if self.cash_symbol not in self.algorithm.Portfolio.CashBook:
                    if self.algorithm.Portfolio[self.symbol].Quantity == 0:
                        self.algorithm.Transactions.CancelOpenOrders(self.symbol)
                        self.Order_Permission = True
        if order.Tag == "SHORT STOP":
            if Order.Status == OrderStatus.PartiallyFilled:
                if (abs(order.AbsoluteFillQuantity * self.Securities[self.symbol].BidPrice)) < self.Minimum_Order_Size:
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True
                if self.algorithm.Time > (self.Entry_Time_Long + self.Interval + timedelta(seconds=10)):
                    self.algorithm.Transactions.CancelOrder(order.Id)
                    self.User_Cancelled = True   
            if order.Status == OrderStatus.Filled:
      
                quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount 
                if quantity == 0:
                    self.Order_Permission = True
                if quantity < 0:
                    self.MarketOrder(self.symbol, abs(quantity), tag = "ERROR")

        if order.Status == OrderStatus.Canceled and not self.User_Cancelled:
                for symbol in self.algorithm.Portfolio.CashBook:
                    
                    if symbol == self.cash_symbol:
                        quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount 
                        if quantity > 0:
                            self.MarketOrder(self.symbol, -quantity, tag = "INVALID OR CANCELLED")
                        if quantity < 0:
                            self.MarketOrder(self.symbol, abs(quantity), tag = "INVALID OR CANCELLED")
        
        if order.Status == OrderStatus.Canceled and self.User_Cancelled:
            self.User_Cancelled = False
            self.Order_Permission = True

        if order.Status == OrderStatus.Invalid:
               
            quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount 
            if quantity > 0:
                self.MarketOrder(self.symbol, -quantity, tag = "INVALID OR CANCELLED")
            if quantity < 0:
                self.MarketOrder(self.symbol, abs(quantity), tag = "INVALID OR CANCELLED")

            self.Order_Permission = False

        if order.Status == OrderStatus.CancelPending:
            self.Order_Permission = False
        
        if order.Status == OrderStatus.Submitted:
            self.Order_Permission = False

        if order.Status == OrderStatus.New:
            self.Order_Permission = False

        if order.Tag not in self.Order_Tag_List:
       
            quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount

            if quantity > 0:
                self.algorithm.MarketOrder(self.symbol, -quantity, tag = "UNEXPECTED")
                self.Order_Permission = False
            if quantity < 0:
                self.algorithm.MarketOrder(self.symbol, abs(quantity), tag = "UNEXPECTED")
                self.Order_Permission = False

        if order.Tag == "INVALID OR CANCELLED" or order.Tag == "ERROR" or order.Tag == "UNEXPECTED":
            if order.Status == OrderStatus.Filled:
                for symbol in self.algorithm.Portfolio.CashBook:
                    if symbol == self.cash_symbol:
                        quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount

                        if quantity == 0:
                            self.Order_Permission = True
                        if quantity != 0:
                            self.Order_Permission = False


        if order.Tag == "QUANTITY WITHOUT PERMISSION":
            if order.Status == OrderStatus.Filled:
                if self.cash_symbol in self.algorithm.Portfolio.CashBook:
                    for symbol in self.algorithm.Portfolio.CashBook:
                        if symbol == self.cash_symbol:
                            quantity = self.algorithm.Portfolio.CashBook[self.cash_symbol].Amount

                            if quantity == 0:
                                self.Order_Permission = True
                            if quantity != 0:
                                self.Order_Permission = False
                else:
                    self.Order_Permission = True



    # def OnOrderEvent(self, orderEvent: OrderEvent):
    #     order = self.algorithm.Transactions.GetOrderById(orderEvent.OrderId)
    #     if orderEvent.Status == OrderStatus.Filled: 
    #         self.algorithm.Debug("{0}: {1}: {2}".format(self.algorithm.Time, order.Type, orderEvent))


    


        # self.count = self.count + 1
        # if self.count <= 10:
        #     self.algorithm.Debug(self.algorithm.Portfolio[self.symbol].UnrealizedProfitPercent)
            # self.algorithm.Debug(f" {self.algorithm.Time} {self.algorithm.Securities[self.symbol].Price}")