Files
quantconnect--lean/Common/Orders/GroupOrderExtensions.cs
T
Roman Yavnikov 3f8fd6ac3d
Syntax Tests / build (push) Has been cancelled
Python Virtual Environments / build (push) Has been cancelled
Regression Tests / build (push) Has been cancelled
Report Generator Tests / build (push) Has been cancelled
Research Regression Tests / build (push) Has been cancelled
Build & Test Lean / build (push) Has been cancelled
API Tests / build (push) Has been cancelled
Benchmarks / build (push) Has been cancelled
Feature: support ComboLimit Order type in TastyTrade and refactor BrokerageTests (#9003)
* feat: support new OrderType in TastytradeBrokerageModel

* feat: extension GetGroupQuantity

* refactor: WaitOneAssertFail to return bool

* refactor: GetOpenOrders in BrokerageTests

* feat: display holdings when begin/end test run

* refactor: brokerageTest class to support handle combo order
feat: comboOrderTestParameters
feat: tastytrade option strategy algo

* refactor: Tastytrade Algo BullCallSpread

* feat: Bull/Bear-CallSpread test cases in BrokerageTests
feat: ComboLimitOrderTestParameters

* fix: remove static in ComboLimitOrderTestParameters of ExpectedStatus

* feat: restrict submit combo limit cross zero orders in Tastytrade
test:feat: submit combo limit cross zero test cases in tastytrade

* test:fix: missed test helper to c9907b23

* refactor: GetGroupQuantityByEachLegQuantity
feat: overload GreatestCommonDivisor
test:feat: GetGroupQuantityByEachLegQuantity

* test:feat: extra test cases to GetGroupQuantity to 925c214a

* test:refactor: take out Cancel Status update in HandleEvents()

* feat: prop Direction in Leg

* Revert "feat: prop Direction in Leg"

This reverts commit 4f92f97b630a157d3972c2321473d87c330c26c8.

* refactor: ComboLimitOrderTestParameters

* test:refactor: CancelOrders

* test:feat: add missed xml description

* test:feat: support ModifyUntilFilled Combo orders

* test:feat: Long/Short-Combo unit tests

* test:fix: compare all status if it is combo order type

* test:refactor: applyOrderUpdate in gracefully way in LimitOrderTestParameters

* remover: Tastytrade algo

* test:feat: create new BaseOrderTestParameters with helper methods
test:rename: method in ComboOrderTestParameters
test:remove: duplication
2025-10-06 23:42:30 +03:00

161 lines
7.4 KiB
C#

/*
* 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.
*/
using System;
using System.Linq;
using QuantConnect.Logging;
using QuantConnect.Securities;
using System.Collections.Generic;
namespace QuantConnect.Orders
{
/// <summary>
/// Group (combo) orders extension methods for easiest combo order manipulation
/// </summary>
public static class GroupOrderExtensions
{
/// <summary>
/// Gets the grouped orders (legs) of a group order
/// </summary>
/// <param name="order">Target order, which can be any of the legs of the combo</param>
/// <param name="orderProvider">Order provider to use to access the existing orders</param>
/// <param name="orders">List of orders in the combo</param>
/// <returns>False if any of the orders in the combo is not yet found in the order provider. True otherwise</returns>
/// <remarks>If the target order is not a combo order, the resulting list will contain that single order alone</remarks>
public static bool TryGetGroupOrders(this Order order, Func<int, Order> orderProvider, out List<Order> orders)
{
orders = new List<Order> { order };
if (order.GroupOrderManager != null)
{
lock (order.GroupOrderManager.OrderIds)
{
foreach (var otherOrdersId in order.GroupOrderManager.OrderIds.Where(id => id != order.Id))
{
var otherOrder = orderProvider(otherOrdersId);
if (otherOrder != null)
{
orders.Add(otherOrder);
}
else
{
// this will happen while all the orders haven't arrived yet, we will retry
return false;
}
}
}
if (order.GroupOrderManager.Count != orders.Count)
{
if (Log.DebuggingEnabled)
{
Log.Debug($"GroupOrderExtensions.TryGetGroupOrders(): missing orders of group {order.GroupOrderManager.Id}." +
$" We have {orders.Count}/{order.GroupOrderManager.Count} orders will skip");
}
return false;
}
}
orders.Sort((x, y) => x.Id.CompareTo(y.Id));
return true;
}
/// <summary>
/// Gets the securities corresponding to each order in the group
/// </summary>
/// <param name="orders">List of orders to map</param>
/// <param name="securityProvider">The security provider to use</param>
/// <param name="securities">The resulting map of order to security</param>
/// <returns>True if the mapping is successful, false otherwise.</returns>
public static bool TryGetGroupOrdersSecurities(this List<Order> orders, ISecurityProvider securityProvider, out Dictionary<Order, Security> securities)
{
securities = new(orders.Count);
for (var i = 0; i < orders.Count; i++)
{
var order = orders[i];
var security = securityProvider.GetSecurity(order.Symbol);
if (security == null)
{
return false;
}
securities[order] = security;
}
return true;
}
/// <summary>
/// Returns an error string message saying there is insufficient buying power for the given orders associated with their respective
/// securities
/// </summary>
public static string GetErrorMessage(this Dictionary<Order, Security> securities, HasSufficientBuyingPowerForOrderResult hasSufficientBuyingPowerResult)
{
return Messages.GroupOrderExtensions.InsufficientBuyingPowerForOrders(securities, hasSufficientBuyingPowerResult);
}
/// <summary>
/// Gets the combo order leg group quantity, that is, the total number of shares to be bought/sold from this leg,
/// from its ratio and the group order quantity
/// </summary>
/// <param name="legRatio">The leg ratio</param>
/// <param name="groupOrderManager">The group order manager</param>
/// <returns>The total number of shares to be bought/sold from this leg</returns>
public static decimal GetOrderLegGroupQuantity(this decimal legRatio, GroupOrderManager groupOrderManager)
{
return groupOrderManager != null ? legRatio * groupOrderManager.Quantity : legRatio;
}
/// <summary>
/// Gets the combo order leg ratio from its group quantity and the group order quantity
/// </summary>
/// <param name="legGroupQuantity">
/// The total number of shares to be bought/sold from this leg, that is, the result of the let ratio times the group quantity
/// </param>
/// <param name="groupOrderManager">The group order manager</param>
/// <returns>The ratio of this combo order leg</returns>
public static decimal GetOrderLegRatio(this decimal legGroupQuantity, GroupOrderManager groupOrderManager)
{
return groupOrderManager != null ? legGroupQuantity / groupOrderManager.Quantity : legGroupQuantity;
}
/// <summary>
/// Calculates the greatest common divisor (GCD) of the provided leg quantities
/// and returns it as a signed quantity based on the <see cref="OrderDirection"/>.
/// </summary>
/// <param name="legQuantity">A collection of leg quantities.</param>
/// <param name="orderDirection">
/// Determines the sign of the returned quantity:
/// <see cref="OrderDirection.Buy"/> returns a positive quantity,
/// <see cref="OrderDirection.Sell"/> returns a negative quantity.
/// </param>
/// <returns>
/// The greatest common divisor of the leg quantities, signed according to <paramref name="orderDirection"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="orderDirection"/> has an unsupported value.
/// </exception>
public static decimal GetGroupQuantityByEachLegQuantity(IEnumerable<decimal> legQuantity, OrderDirection orderDirection)
{
var groupQuantity = Extensions.GreatestCommonDivisor(legQuantity.Select(Math.Abs));
return orderDirection switch
{
OrderDirection.Buy => groupQuantity,
OrderDirection.Sell => decimal.Negate(groupQuantity),
_ => throw new ArgumentException($"Unsupported {nameof(OrderDirection)} value: '{orderDirection}'.", nameof(orderDirection))
};
}
}
}