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.91
Tracking Error
0.223
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
Portfolio Turnover
0%
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from AlgorithmImports import *

class CustomBrokerageSideOrderHandlingRegressionAlgorithm(QCAlgorithm):
    '''This algorithm handles TerminalLink's brokerage side orders, accepting only those with the string "AcceptOrder" 
    in the order properties' CustomNotes1 field.
    
    After placing one or more orders manually in TerminalLink (after deploying this algorithm) the logs need to be checked
    to see whether the order was received and handled as expected.'''

    def Initialize(self):
        self.SetStartDate(2013, 10, 7)
        self.SetEndDate(2013, 10, 11)
        self.SetCash(100000)

        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):
            raise Exception(f"Security {brokerageOrder.Symbol} not found in algorithm's securities.")

        self.Log(f"{self.Time} :: Brokerage-side order found: {brokerageOrder}")

# To implement custom brokerage messahge handlers, we should be able to derive from DefaultBrokerageMessageHandler,
# but until https://github.com/QuantConnect/Lean/issues/7880 is address, we need to implement IBrokerageMessageHandler
# which requires defining the __namespace__ attribute as shown below in order for the implementation to be picked up.
class CustomBrokerageMessageHandler(IBrokerageMessageHandler):
    __namespace__ = "CustomBrokerageSideOrderHandlingRegressionAlgorithm"

    def __init__(self, algorithm):
        self._algorithm = algorithm

    def HandleOrder(self, eventArgs):
        order = eventArgs.Order
        self._algorithm.Log(f"CustomBrokerageMessageHandler.HandleOrder(): {self._algorithm.Time} :: New Order: {order}")
        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.Propertoes, TerminalLinkOrderProperties):
            return False

        # In this case, we are only interested in orders with a custom note "AcceptOrder"
        customNotes1 = order.Properties.CustomNotes1
        return customNotes1 and customNotes1 == "AcceptOrder"