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.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)

        self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))

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

        self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(minutes=1)), self.check_brokerage_side_order)

    def check_brokerage_side_order(self):
        if not self.brokerage_side_order:
            return

        open_orders = self.transactions.get_open_orders()
        brokerage_order = next((x for x in open_orders if x.broker_id[0] == self.brokerage_side_order.broker_id[0]), None)
        if not brokerage_order:
            return

        # Also, the security should have been added to the algorithm
        if not self.securities.contains_key(brokerage_order.symbol):
            self.log(f"Security {brokerage_order.symbol} not found in algorithm's securities!")
        self.log(f"{self.time} :: Brokerage-side order found: {brokerage_order}")

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

    def handle_order(self, eventArgs):
        order = eventArgs.order

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

        self._algorithm.brokerage_side_order = 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.handle_order(): 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"
        custom_notes1 = order.properties.custom_notes1
        result = False
        if custom_notes1 and "AcceptOrder" in custom_notes1:
            result = True
        self._algorithm.log(f"CustomBrokerageMessageHandler.handle_order(): returning: {result}")
        return result