Files
quantconnect--lean/Algorithm.CSharp/ComboOrderAlgorithm.cs
T
Jhonathan Abreu b54281b262 Combo orders (#6813)
* Feature combo orders

- Add support for combo orders

* Make fill model wait for all grouped orders to emit fills

* Add ComboFill to model multiple fills for combo orders

* Fill combo limit orders

Add some regression algorithms

* Add fill implementation for combo leg limit orders

* Add IFill as common interface for Fill and ComboFill

* Refactor combo orders removing IGroupOrder interface

Move the group order manager to the base Order class

* Update algorithms

* Handle combo order events atomically

* Refactor brokerage transaction event handler

* Refactor combo fill models

* Process fills in batch

* Combo orders fill model tests

* Combo leg limit orders algorithm

* Regression algorithms cleanup

* Fill and combo fill classes cleanup

* Housekeeping

* Refactor equity fill model to derive from base fill model

* Address review changes request

* Handling the new types of orders in the OrderJsonConverter

* Add regression algorithm to test combo orders update/cancel

* Add regression algorithm to test combo orders update/cancel

* Housekeeping

* Address review changes request

* Minor changes

* Security transaction handler method for setting order request id

* Extend public interface for placing combo orders

* Combo order tickets demo algorithm python version

* Tweaks and updates

* Minor fixes

* Minor changes

* Minor fixes

* Address reviews minor fixes

* Minor fixes

Co-authored-by: Martin-Molinero <martin@quantconnect.com>
2023-01-06 17:58:43 -03:00

140 lines
4.9 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 System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm asserting that combo orders are filled correctly and at the same time
/// </summary>
public abstract class ComboOrderAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _optionSymbol;
protected List<OrderEvent> FillOrderEvents { get; private set; } = new();
protected List<Leg> OrderLegs { get; private set; }
protected int ComboOrderQuantity { get; } = 10;
protected virtual int ExpectedFillCount
{
get
{
return OrderLegs.Count;
}
}
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
SetCash(10000);
var equity = AddEquity("GOOG", leverage: 4, fillDataForward: true);
var option = AddOption(equity.Symbol, fillDataForward: true);
_optionSymbol = option.Symbol;
option.SetFilter(u => u.Strikes(-2, +2)
.Expiration(0, 180));
}
public override void OnData(Slice slice)
{
if (OrderLegs == null)
{
OptionChain chain;
if (IsMarketOpen(_optionSymbol) && slice.OptionChains.TryGetValue(_optionSymbol, out chain))
{
var callContracts = chain.Where(contract => contract.Right == OptionRight.Call)
.GroupBy(x => x.Expiry)
.OrderBy(grouping => grouping.Key)
.First()
.OrderBy(x => x.Strike)
.ToList();
// Let's wait until we have at least three contracts
if (callContracts.Count < 3)
{
return;
}
OrderLegs = new List<Leg>()
{
new Leg() { Symbol = callContracts[0].Symbol, Quantity = 1, OrderPrice = 16.7m },
new Leg() { Symbol = callContracts[1].Symbol, Quantity = -2, OrderPrice = 14.6m },
new Leg() { Symbol = callContracts[2].Symbol, Quantity = 1, OrderPrice = 14.0m},
};
PlaceComboOrder(OrderLegs, ComboOrderQuantity, 45m);
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug($" Order Event: {orderEvent}");
if (orderEvent.Status == OrderStatus.Filled)
{
FillOrderEvents.Add(orderEvent);
}
}
public override void OnEndOfAlgorithm()
{
if (OrderLegs == null)
{
throw new Exception("Combo order legs were not initialized");
}
if (FillOrderEvents.Count != ExpectedFillCount)
{
throw new Exception($"Expected {ExpectedFillCount} fill order events, found {FillOrderEvents.Count}");
}
var fillTimes = FillOrderEvents.Select(x => x.UtcTime).ToHashSet();
if (fillTimes.Count != 1)
{
throw new Exception($"Expected all fill order events to have the same time, found {string.Join(", ", fillTimes)}");
}
if (FillOrderEvents.Zip(OrderLegs).Any(x => x.First.FillQuantity != x.Second.Quantity * ComboOrderQuantity))
{
throw new Exception("Fill quantity does not match expected quantity for at least one order leg");
}
}
protected abstract IEnumerable<OrderTicket> PlaceComboOrder(List<Leg> legs, int quantity, decimal? limitPrice = null);
public abstract bool CanRunLocally { get; }
public abstract Language[] Languages { get; }
public abstract long DataPoints { get; }
public abstract int AlgorithmHistoryDataPoints { get; }
public abstract Dictionary<string, string> ExpectedStatistics { get; }
}
}