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
-8.911
Tracking Error
0.223
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
Portfolio Turnover
0%
from AlgorithmImports import *

class CustomBrokerageSideOrderHandlingRegressionAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2013, 10, 7)
        self.SetEndDate(2013, 10, 11)

        self.SetBrokerageMessageHandler(CustomBrokerageMessageHandler(self))

        # This algorithm won't add any securities or place any orders
        self.brokerageSideOrder = None

        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.Every(timedelta(minutes=1)), self.CheckBrokerageSideOrder)

    def CheckBrokerageSideOrder(self):
        if not self.brokerageSideOrder:
            return

        openOrders = self.Transactions.GetOpenOrders()
        brokerageOrder = next((x for x in openOrders if x.BrokerId[0] == self.brokerageSideOrder.BrokerId[0]), None)
        if not brokerageOrder:
            return

        # Also, the security should have been added to the algorithm
        if not self.Securities.ContainsKey(brokerageOrder.Symbol):
            self.Log(f"Security {brokerageOrder.Symbol} not found in algorithm's securities!")
        self.Log(f"{self.Time} :: Brokerage-side order found: {brokerageOrder}")

class CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):
    def __init__(self, algorithm):
        super().__init__(algorithm)
        self._algorithm = algorithm

    def HandleOrder(self, eventArgs):
        order = eventArgs.Order

        try:
            import Newtonsoft.Json as json
            self._algorithm.log(f"CustomBrokerageMessageHandler.HandleOrder(): {self._algorithm.Time} :: New Order:: " + str(json.JsonConvert.serialize_object(order)))
        except:
            # should not happen
            self._algorithm.log(f"CustomBrokerageMessageHandler.HandleOrder(): {self._algorithm.Time} Explosion!")

        self._algorithm.brokerageSideOrder = order

        # Depending on the logic, return true o false to accept or reject the order
        # (e.g. based on the order type if not supported or just orders that you are not interested in handling in the algorithm))

        # Only TerminalLink orders are accepted
        if not isinstance(order.Properties, TerminalLinkOrderProperties):
            self._algorithm.Log(f"CustomBrokerageMessageHandler.HandleOrder(): order properties is not set to expected terminal link type, skipping")
            return False

        # In this case, we are only interested in orders with a custom note "AcceptOrder"
        customNotes1 = order.Properties.CustomNotes1
        result = False
        if customNotes1 and "AcceptOrder" in customNotes1:
            result = True
        self._algorithm.Log(f"CustomBrokerageMessageHandler.HandleOrder(): returning: {result}")
        return result