Skip to content

Commit

Permalink
Fix partial fix quantity handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin-Molinero committed Jul 19, 2024
1 parent 9dd02b2 commit 149d6a0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
8 changes: 8 additions & 0 deletions QuantConnect.AlpacaBrokerage.Tests/AlpacaBrokerageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,14 @@ private static IEnumerable<TestCaseData> CryptoOrderParameters
}
}

[Test]
public void PartialCryptoFill()
{
var parameters = new MarketOrderTestParameters(Symbol.Create("BTCUSD", SecurityType.Crypto, Market.USA));

PlaceOrderWaitForStatus(parameters.CreateLongOrder(2), parameters.ExpectedStatus);
}

[Test, TestCaseSource(nameof(EquityOrderParameters))]
public override void CancelOrders(OrderTestParameters parameters)
{
Expand Down
15 changes: 14 additions & 1 deletion QuantConnect.AlpacaBrokerage/AlpacaBrokerage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
using System.Threading.Tasks;
using QuantConnect.Configuration;
using QuantConnect.Brokerages.CrossZero;
using System.Collections.Concurrent;

namespace QuantConnect.Brokerages.Alpaca
{
Expand All @@ -51,6 +52,7 @@ public partial class AlpacaBrokerage : Brokerage

private EventBasedDataQueueHandlerSubscriptionManager _subscriptionManager;

private ConcurrentDictionary<int, decimal> _orderIdToFillQuantity = new();
private BrokerageConcurrentMessageHandler<ITradeUpdate> _messageHandler;
private AlpacaBrokerageSymbolMapper _symbolMapper;

Expand Down Expand Up @@ -404,12 +406,23 @@ private void HandleTradeUpdate(ITradeUpdate obj)

var leanSymbol = _symbolMapper.GetLeanSymbol(obj.Order.AssetClass, obj.Order.Symbol);

// alpaca sends the accumulative filled quantity but we need the partial amount for our event
_orderIdToFillQuantity.TryGetValue(leanOrder.Id, out var previouslyFilledAmount);
var accumulativeFilledQuantity = _orderIdToFillQuantity[leanOrder.Id] =
obj.Order.OrderSide == OrderSide.Buy ? obj.Order.FilledQuantity : decimal.Negate(obj.Order.FilledQuantity);

if (newLeanOrderStatus.IsClosed())
{
// cleanup
_orderIdToFillQuantity.TryRemove(leanOrder.Id, out _);
}

var orderEvent = new OrderEvent(leanOrder, obj.TimestampUtc.HasValue ? obj.TimestampUtc.Value : DateTime.UtcNow,
new OrderFee(new CashAmount(0, Currencies.USD)))
{
Status = newLeanOrderStatus,
FillPrice = obj.Price ?? 0m,
FillQuantity = obj.Order.OrderSide == OrderSide.Buy ? obj.Order.FilledQuantity : decimal.Negate(obj.Order.FilledQuantity),
FillQuantity = accumulativeFilledQuantity - previouslyFilledAmount,
};

// if we filled the order and have another contingent order waiting, submit it
Expand Down

0 comments on commit 149d6a0

Please sign in to comment.