Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
ffe0aa7
feat: add ADR of OrderType = Bracket
Romazes Jul 13, 2026
efc3380
feat: OCO and Review
Romazes Jul 17, 2026
d67d7ff
feature: add one-cancels-the-other order group support
Romazes Jul 28, 2026
3d81b2b
restore: BrokerageTest file to master
Romazes Jul 29, 2026
b247b36
fix: reduce sibling legs so an oco group cannot over-execute
Romazes Jul 29, 2026
5e14498
test: cover the stop leg winning a one-cancels-the-other group
Romazes Jul 29, 2026
417c950
docs: move order group adrs out of the repo
Romazes Aug 20, 2026
da88773
feature: check alpaca one-cancels-the-other group rules per leg
Romazes Aug 20, 2026
a29b195
rename: combo type to group execution type
Romazes Aug 20, 2026
d5c73bc
refactor: drop manual price rounding in oco regression algorithms
Romazes Aug 20, 2026
5446362
refactor: drop the zero quantity guard from the oco order api
Romazes Aug 20, 2026
1c8a42c
test: update the expected order list hash of the oco regression algor…
Romazes Aug 20, 2026
7c1cdd8
refactor: cancel order group legs one by one in liquidate
Romazes Aug 20, 2026
76d80ea
refactor: drop the order group gate from the brokerage models
Romazes Aug 20, 2026
900ee81
test: update the expected order list hashes of the oco regression alg…
Romazes Aug 20, 2026
9c4d867
feature: add a manual demo algorithm for oco order groups
Romazes Aug 20, 2026
f8572c0
refactor: return the scan flag from the oco group processor
Romazes Aug 20, 2026
aa11b55
test: log order events in the oco partial fill regression algorithm
Romazes Aug 20, 2026
a68ff9e
chore: wrong comments
Romazes Aug 20, 2026
cdfd68c
refactor: drop the composite log handler from this branch
Romazes Aug 20, 2026
cec6427
refactor: shorten the order group comments
Romazes Aug 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 168 additions & 0 deletions Algorithm.CSharp/OneCancelsTheOtherOrderCancelRegressionAlgorithm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* 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.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;

namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm for the cancel path of a one-cancels-the-other (OCO) order group: the group is
/// placed with both legs far from the market, so neither can fill inside the test window, then one of the
/// two tickets is explicitly canceled. Asserts that canceling one leg cancels the whole group, not just
/// the leg that was canceled
/// </summary>
public class OneCancelsTheOtherOrderCancelRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy;
private List<OrderTicket> _tickets;
private bool _canceled;

public override void Initialize()
{
SetStartDate(2019, 1, 1);
SetEndDate(2019, 1, 31);

_spy = AddEquity("SPY", Resolution.Hour).Symbol;
}

public override void OnData(Slice slice)
{
if (!Portfolio.Invested)
{
MarketOrder(_spy, 100);

// both legs sit far from the market: limit sell +30% and stop sell -30% should never be
// reachable in this test window, so only the explicit cancel below can close the group
_tickets = OneCancelsTheOtherOrder(_spy, -100,
limitPrice: Securities[_spy].Price * 1.30m,
stopPrice: Securities[_spy].Price * 0.70m);
}
else if (!_canceled && Time.Day > 5)
{
// cancel only one leg: the whole OCO group must cancel with it
_tickets[0].Cancel();
_canceled = true;
}
}

public override void OnOrderEvent(OrderEvent orderEvent)
{
if (_tickets == null || orderEvent.Status != OrderStatus.Filled)
{
return;
}

// neither OCO leg's price should ever be reachable in this test window; a fill here means the
// regression scenario itself is broken, not just the cancellation behavior being tested
if (_tickets.Any(ticket => ticket.OrderId == orderEvent.OrderId))
{
throw new RegressionTestException(
$"Unexpected fill for OCO leg {orderEvent.OrderId}: prices were set far from the market so the group should only close through the explicit cancel");
}
}

public override void OnEndOfAlgorithm()
{
if (!_canceled)
{
throw new RegressionTestException("Expected to have canceled one of the OCO legs before the end of the algorithm");
}

if (_tickets == null || _tickets.Count != 2)
{
throw new RegressionTestException("Expected the OCO group to have exactly 2 legs");
}

foreach (var ticket in _tickets)
{
if (ticket.Status != OrderStatus.Canceled)
{
throw new RegressionTestException(
$"Expected every OCO leg to be Canceled, including the leg that was not explicitly canceled. Leg {ticket.OrderId} has status {ticket.Status}");
}
}

// canceling the OCO exit group must not touch the original market order fill
if (!Portfolio.Invested)
{
throw new RegressionTestException("Expected the algorithm to still be invested: the market order fill is independent from the canceled OCO group");
}
}

/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;

/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python };

/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 302;

/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;

/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;

/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "3"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "29.303%"},
{"Drawdown", "0.700%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "102182.68"},
{"Net Profit", "2.183%"},
{"Sharpe Ratio", "4.501"},
{"Sortino Ratio", "5.158"},
{"Probabilistic Sharpe Ratio", "85.073%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.047"},
{"Beta", "0.24"},
{"Annual Standard Deviation", "0.038"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-6.241"},
{"Tracking Error", "0.117"},
{"Treynor Ratio", "0.708"},
{"Total Fees", "$1.00"},
{"Estimated Strategy Capacity", "$470000000.00"},
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
{"Portfolio Turnover", "0.76%"},
{"Drawdown Recovery", "12"},
{"OrderListHash", "1f0c221acd9f91c1a73a4ea0096eef2f"}
};
}
}
94 changes: 94 additions & 0 deletions Algorithm.CSharp/OneCancelsTheOtherOrderDemoAlgorithm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* 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 QuantConnect.Data;
using QuantConnect.Orders;
using System.Collections.Generic;

namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Demo algorithm for manually testing one-cancels-the-other (OCO) order groups end to end against a live
/// or paper brokerage. Alpaca is the first brokerage to support them.
/// Buys a small position at market, then places a 2-leg OCO exit (take-profit limit above the entry price,
/// stop-loss below it) and logs every order event so the outcome is visible in the live log/console.
/// </summary>
/// <remarks>
/// This is a manual/live testing aid, not part of the automated backtest regression suite - it deliberately
/// does not implement IRegressionAlgorithmDefinition. For the automated backtest version of this scenario,
/// see OneCancelsTheOtherOrderRegressionAlgorithm.
/// </remarks>
public class OneCancelsTheOtherOrderDemoAlgorithm : QCAlgorithm
{
private Symbol _symbol;
private List<OrderTicket> _tickets;

public override void Initialize()
{
// ignored when deployed live; only used if this is run as a quick local backtest sanity check first
SetStartDate(2019, 1, 1);
SetEndDate(2019, 1, 31);
SetCash(100000);

_symbol = AddEquity("AAPL", Resolution.Hour).Symbol;
}

public override void OnData(Slice slice)
{
if (_tickets != null)
{
// the OCO exit group has already been placed, nothing left to do
return;
}

if (!Portfolio.Invested)
{
Debug("Buying 10 AAPL at market to open the position the OCO exit group will close.");
MarketOrder(_symbol, 10);
return;
}

// just went long: place the exit as one OCO group (take profit +1%, stop loss -2% from here).
// Tighten these offsets if you want one leg to trigger quickly for a faster manual test.
var price = Securities[_symbol].Price;
var takeProfitLimitPrice = price * 1.01m;
var stopLossStopPrice = price * 0.98m;

Debug($"Placing OCO exit group on {_symbol}: sell limit {takeProfitLimitPrice} (take profit) / sell stop {stopLossStopPrice} (stop loss)");

_tickets = OneCancelsTheOtherOrder(_symbol, -10, limitPrice: takeProfitLimitPrice, stopPrice: stopLossStopPrice);
}

public override void OnOrderEvent(OrderEvent orderEvent)
{
Debug($"{Time}: {orderEvent}");
}

public override void OnEndOfAlgorithm()
{
if (_tickets == null)
{
Debug("OCO exit group was never placed.");
return;
}

foreach (var ticket in _tickets)
{
Debug($"Final status - Order {ticket.OrderId} ({ticket.OrderType}): {ticket.Status}");
}
}
}
}
Loading
Loading