private async Task ProcessOrdersAsync( Order order, IReliableDictionary <OrderQueueKey, OrderQueue> storage, OrderQueueKey orderQueueKey, OrderQueueKey oppositeOrderQueueKey) { using (var tx = _stateManager.CreateTransaction()) { var orderQueue = await storage.GetOrAddAsync( tx, orderQueueKey, new OrderQueue(order.CurrencyPair, order.Side)); var oppositeOrderQueue = await storage.GetOrAddAsync( tx, oppositeOrderQueueKey, new OrderQueue(order.CurrencyPair, order.Side == Side.Buy ? Side.Sell : Side.Buy)); while (true) { var oppositeOrder = oppositeOrderQueue.Peek(); if (oppositeOrder == null) { break; } var matched = _ordersMatchingRule.IsMatched(order, oppositeOrder); if (matched) { matched = _ordersMatchingRule.IsMatched(order, oppositeOrder); if (matched) { ProcessOrders(order, orderQueue, oppositeOrder, oppositeOrderQueue); } else { // process further if some thread is here continue; } } if (order.IsClosed || !matched || oppositeOrderQueue.IsEmpty) { break; } } await storage.AddOrUpdateAsync(tx, orderQueueKey, orderQueue, (key, old) => orderQueue); await storage.AddOrUpdateAsync(tx, oppositeOrderQueueKey, oppositeOrderQueue, (key, old) => orderQueue); await tx.CommitAsync(); } }
public async Task PlaceAsync(Order order) { var storage = await _stateManager .GetOrAddAsync <IReliableDictionary <OrderQueueKey, OrderQueue> >(OrdersCollectionName); var orderQueueKey = new OrderQueueKey(order.CurrencyPair, order.Side); var oppositeOrderQueueKey = new OrderQueueKey(order.CurrencyPair, order.Side == Side.Buy ? Side.Sell : Side.Buy); await AddOrderAsync(order, storage, orderQueueKey); RaiseOrderOpened(order); await ProcessOrdersAsync(order, storage, orderQueueKey, oppositeOrderQueueKey); }
/// <summary> /// Initializes a new instance of the <see cref="OrderQueue"/> class. /// </summary> /// <param name="currencyPair">The currency pair.</param> /// <param name="side">The side.</param> public OrderQueue(CurrencyPair currencyPair, Side side) { Key = new OrderQueueKey(currencyPair, side); _orders = new SortedList <OrderSortedKey, Order>(); }
private async Task AddOrderAsync(Order order, IReliableDictionary <OrderQueueKey, OrderQueue> storage, OrderQueueKey orderQueueKey) { using (var tx = _stateManager.CreateTransaction()) { var orderQueue = await storage.GetOrAddAsync( tx, orderQueueKey, new OrderQueue(order.CurrencyPair, order.Side)); orderQueue.Add(order); await storage.AddOrUpdateAsync(tx, orderQueueKey, orderQueue, (key, old) => orderQueue); await tx.CommitAsync(); } }