Hi Francesco Baldisserri,
The above problem is occurring because the cash model will not allow us to have a negative quantity. We have 3 ways to implement this.
Set the Stop Market, handle the take profit manually
Â
crypto = self.Securities[symbol]
quantity = self.CalculateOrderQuantity(symbol, targetSize)
min_notional = crypto.SymbolProperties.MinimumOrderSize
if abs(quantity) * crypto.Price > min_notional:
self.entryTicket = self.MarketOrder(symbol, quantity)
self.StopMarketOrder(symbol, -quantity, stopLossPrice)
self.limit_price = ...
or, set the Limit, handle the stop loss manually
Â
crypto = self.Securities[symbol]
quantity = self.CalculateOrderQuantity(symbol, targetSize)
min_notional = crypto.SymbolProperties.MinimumOrderSize
if abs(quantity) * crypto.Price > min_notional:
self.entryTicket = self.MarketOrder(symbol, quantity)
self.LimitOrder(symbol, -quantity, takeProfirPrice)
self.stop_price = ...
or place only half of quantity for the Stop and Limit
Â
crypto = self.Securities[symbol]
quantity = self.CalculateOrderQuantity(symbol, targetSize / 2)
min_notional = crypto.SymbolProperties.MinimumOrderSize
if abs(quantity * 2) * crypto.Price > min_notional:
self.entryTicket = self.MarketOrder(symbol, quantity * 2)
self.LimitOrder(symbol, -quantity, takeProfirPrice)
self.StopMarketOrder(symbol, -quantity, stopLossPrice)
in this case, call Liquidate whether one or the other is filled, because Liquidate closes the remaining half and cancels the other order. We have created a demo algorithm implementing the above. Refer to the attached backtest.
Best,
Varad Kabade