QuantConnect / Lean

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)
https://lean.io
Apache License 2.0
9.89k stars 3.28k forks source link

Invalid Security Handling in CashBuyingPowerModel #8091

Closed AlexCatarino closed 2 months ago

AlexCatarino commented 5 months ago

Expected Behavior

If CashBuyingPowerModel finds an invalid security, throw an exception.

Actual Behavior

If CashBuyingPowerModel finds an invalid security, throw an exception, the order is invalid and we don't know why: Order Error: id: 1, Error executing margin models: Object reference not set to an instance of an object.

In the syslog, we can read:

2024-06-14T20:53:43.6886306Z ERROR:: BrokerageTransactionHandler.HandleSubmitOrderRequest():  System.NullReferenceException: Object reference not set to an instance of an object.
   at QuantConnect.Securities.CashBuyingPowerModel.GetOpenOrdersReservedQuantity(SecurityPortfolioManager portfolio, Security security, Order order) in /Common/Securities/CashBuyingPowerModel.cs:line 416

It happens because the BaseCurrency of one of the securities is null. For example if the algorithm adds BTGUSDT crypto future:

self.add_crypto_future("BTGUSDT")

it's not in our database, so the base currency is null.

Potential Solution

When we create a CryptoFuture object, we should throw an exception if the baseCurrency parameter is null (CryptoFuture.cs#L76)

Checklist

Martin-Molinero commented 2 months ago

Potential Solution

I think generically, when we create a security in the SecurityService which required base currency and it's null, we should throw a nice exception