Ejemplo n.º 1
0
 private void UpdateSpreads(PriceRow row)
 {
     //cout("UPDATE SPREADS: {0}", row.Symbol);
     if (m_updateSpreadRows.ContainsKey(row.Symbol))
     {
         var li = m_updateSpreadRows[row.Symbol];
         foreach (var spreadRow in li)
         {
             spreadRow.SymbolUpdate(row);
             //m_spreadGrid.UpdateRow(spreadRow);
         }
     }
 }
Ejemplo n.º 2
0
 // TODO: WHAT IF WE SUBSCRIBE TO A PRICE FIRST IN THE SPREAD GRID? WE NEED TO CHECK FOR EXISTING m_updatePriceRows ENTRY AND USE IF EXISTS
 private void AddPriceRow(string symbol)
 {
     if (m_updatePriceRows.ContainsKey(symbol))      // if the symbol is already "subscribed"...
     {
         var row = m_updatePriceRows[symbol];        // use the existing PriceRow
         row.AddNotifyGrid(m_priceGrid);            // add m_level1Grid to the grids that should be notified of updates
         m_priceGrid.AddRow(row);                   // display the row in the "Price" grid
     }
     else
     {
         var row = new PriceRow(symbol);             // create a new PriceRow for this symbol
         row.AddNotifyGrid(m_priceGrid);
         m_updatePriceRows[symbol] = row;
         m_priceGrid.AddRow(row);
         //m_prices.SubscribePrices(symbol);
     }
 }
Ejemplo n.º 3
0
        // TODO: WHAT IF WE SUBSCRIBE TO A PRICE FIRST IN THE SPREAD GRID? WE NEED TO CHECK FOR EXISTING m_updatePriceRows ENTRY AND USE IF EXISTS
        private void AddPriceRow(string symbol)
        {
            // Add the priceGrid to the list of grids associated with this symbol
            if (!m_notifyGrids.ContainsKey(symbol)) m_notifyGrids[symbol] = new HashSet<DynamicDisplayGrid>();
            m_notifyGrids[symbol].Add(m_priceGrid);

            // 
            if (m_priceRowForSymbol.ContainsKey(symbol))      // if the symbol is already "subscribed"...
            {
                var row = m_priceRowForSymbol[symbol];        // use the existing PriceRow
                //row.AddNotifyGrid(m_level1Grid);            // add m_level1Grid to the grids that should be notified of updates
                m_priceGrid.AddRow(row);                   // display the row in the "Price" grid
            }
            else
            {
                var row = new PriceRow(symbol);             // create a new PriceRow for this symbol
                //row.AddNotifyGrid(m_level1Grid);
                m_priceRowForSymbol[symbol] = row;
                m_priceGrid.AddRow(row);
                m_prices.SubscribePrices(symbol);
            }
        }
Ejemplo n.º 4
0
        // Reload the SPREADS file into the "Spreads" grid
        private void ReloadSpreads()
        {
            //m_spreadGrid.ClearRows();

            // If our symbols text file exists, then read it and request price updates on the symbols in the file
            var df = dfReadSpreads();
            foreach (var row in df.Rows)
            {
                //string group = row[0];
                string symbol = row[1];
                string formula = row[8];
                var spreadRow = new SpreadRow(symbol, formula);
                //m_spreadGrid.AddRow(spreadRow);

                foreach (var sym in spreadRow.FormulaSymbols)
                {
                    cout("Formula Symbol: {0}", sym);
                    if (m_updatePriceRows.ContainsKey(sym))
                    {
                        var priceRow = m_updatePriceRows[sym];
                        //priceRow.AddNotifyGrid(m_spreadGrid);
                        AddSpreadRow(sym, spreadRow);
                    }
                    else
                    {
                        var priceRow = new PriceRow(sym);
                        //priceRow.AddNotifyGrid(m_spreadGrid);
                        m_updatePriceRows[sym] = priceRow;
                        AddSpreadRow(sym, spreadRow);
                        //m_level1Grid.AddRow(row);
                        StartPublishPriceUpdates(sym);
                    }
                }

                //SubscribePrices(symbol1);
                //SubscribePrices(symbol2);
            }
        }
Ejemplo n.º 5
0
        internal static void Accept(Guid matchId, Int64 rowVersion)
        {
            DataModel dataModel = new DataModel();

            try
            {
                DataModel.DataLock.EnterReadLock();

                MatchRow matchRow = DataModel.Match.MatchKey.Find(matchId);
                if (matchRow != null)
                {
                    // Time stamps and user stamps
                    Guid     createdUserId  = TradingSupport.UserId;
                    DateTime createdTime    = DateTime.UtcNow;
                    Guid     modifiedUserId = createdUserId;
                    DateTime modifiedTime   = createdTime;

                    // Call the internal method to complete the operation.
                    dataModel.UpdateMatch(null, null, null, null, null, null, null, new Object[] { matchRow.MatchId }, rowVersion, StatusMap.FromCode(Status.Accepted), null);

                    // This is the working order associated with the match.
                    WorkingOrderRow workingOrderRow = matchRow.WorkingOrderRow;

                    // This will find the contra order.
                    MatchRow contraMatchRow = DataModel.Match.MatchKeyWorkingOrderIdContraOrderId.Find(
                        matchRow.ContraOrderId,
                        matchRow.WorkingOrderId);
                    if (contraMatchRow == null)
                    {
                        throw new Exception(string.Format("Corruption: the match record for {0}, {1} can't be found", matchRow.ContraOrderId, matchRow.WorkingOrderId));
                    }

                    // When both sides have agreed to the match, the Destination Orders are generated.
                    if (contraMatchRow.StatusId != StatusMap.FromCode(Status.Accepted))
                    {
                        return;
                    }

                    // At this point, both sides have agreed to a trade.  This is the working order of the contra side of the trade.
                    WorkingOrderRow contraOrderRow = contraMatchRow.WorkingOrderRow;

                    // The quantity of this transaction is the lesser of the two sides of the trade.
                    decimal quantity = workingOrderRow.SubmittedQuantity < contraOrderRow.SubmittedQuantity ?
                                       workingOrderRow.SubmittedQuantity :
                                       contraOrderRow.SubmittedQuantity;

                    PriceRow priceRow = DataModel.Price.PriceKey.Find(workingOrderRow.SecurityId, workingOrderRow.SettlementId);
                    if (priceRow == null)
                    {
                        throw new Exception("The price of this trade can't be determined.");
                    }

                    Guid destinationOrderId = Guid.NewGuid();
                    dataModel.CreateDestinationOrder(
                        workingOrderRow.BlotterId,
                        null,
                        null,
                        createdTime,
                        createdUserId,
                        Match.destinationId,
                        destinationOrderId,
                        null,
                        null,
                        false,
                        false,
                        workingOrderRow[DataModel.WorkingOrder.LimitPriceColumn],
                        modifiedTime,
                        modifiedUserId,
                        quantity,
                        workingOrderRow.OrderTypeId,
                        workingOrderRow.SecurityId,
                        createdTime,
                        workingOrderRow.SettlementId,
                        workingOrderRow.SideId,
                        StateMap.FromCode(State.Acknowledged),
                        StatusMap.FromCode(Status.New),
                        workingOrderRow[DataModel.WorkingOrder.StopPriceColumn],
                        workingOrderRow.TimeInForceId,
                        createdTime,
                        createdUserId,
                        workingOrderRow.WorkingOrderId);

                    Guid executionId = Guid.NewGuid();
                    dataModel.CreateExecution(
                        0.0m,
                        workingOrderRow.BlotterId,
                        null,
                        null,
                        0.0m,
                        createdTime,
                        createdUserId,
                        destinationOrderId,
                        StateMap.FromCode(State.Acknowledged),
                        executionId,
                        priceRow.LastPrice,
                        quantity,
                        null,
                        null,
                        false,
                        modifiedTime,
                        modifiedUserId,
                        null,
                        null,
                        null,
                        null,
                        StateMap.FromCode(State.Sent),
                        null,
                        null,
                        null,
                        null);

                    dataModel.UpdateMatch(null, null, null, null, null, null, null, new Object[] { matchId }, matchRow.RowVersion, StatusMap.FromCode(Status.Accepted), null);

                    Guid contraDestinationOrderId = Guid.NewGuid();
                    dataModel.CreateDestinationOrder(
                        contraOrderRow.BlotterId,
                        0.0m,
                        null,
                        createdTime,
                        createdUserId,
                        Match.destinationId,
                        contraDestinationOrderId,
                        null,
                        null,
                        false,
                        false,
                        contraOrderRow[DataModel.WorkingOrder.LimitPriceColumn],
                        modifiedTime,
                        modifiedUserId,
                        quantity,
                        contraOrderRow.OrderTypeId,
                        contraOrderRow.SecurityId,
                        createdTime,
                        contraOrderRow.SettlementId,
                        contraOrderRow.SideId,
                        StateMap.FromCode(State.Acknowledged),
                        StatusMap.FromCode(Status.New),
                        contraOrderRow[DataModel.WorkingOrder.StopPriceColumn],
                        contraOrderRow.TimeInForceId,
                        createdTime,
                        createdUserId,
                        contraOrderRow.WorkingOrderId);

                    Guid contraExecutionId = Guid.NewGuid();
                    dataModel.CreateExecution(
                        0.0m,
                        contraOrderRow.BlotterId,
                        null,
                        null,
                        0.0m,
                        createdTime,
                        createdUserId,
                        contraDestinationOrderId,
                        StateMap.FromCode(State.Acknowledged),
                        contraExecutionId,
                        priceRow.LastPrice,
                        quantity,
                        null,
                        null,
                        false,
                        modifiedTime,
                        modifiedUserId,
                        null,
                        null,
                        null,
                        null,
                        StateMap.FromCode(State.Sent),
                        0.0m,
                        0.0m,
                        0.0m,
                        0.0m);
                }
            }
            finally
            {
                // Release the tables.
                DataModel.DataLock.ExitReadLock();
            }
        }
Ejemplo n.º 6
0
        /// <summary>Inserts a Negotiation record using Metadata Parameters.</summary>
        internal static void Offer(Guid matchId, Decimal quantity)
        {
            Guid      negotiationId = Guid.Empty;
            DataModel dataModel     = new DataModel();

            try
            {
                DataModel.DataLock.EnterReadLock();

                MatchRow matchRow = DataModel.Match.MatchKey.Find(matchId);
                if (matchRow != null)
                {
                    // Rule #1: Insure that there are no pending offers.
                    foreach (NegotiationRow innerNegotiationRow in matchRow.GetNegotiationRows())
                    {
                        if (innerNegotiationRow.StatusId == StatusMap.FromCode(Status.Pending))
                        {
                            throw new Exception("There is already an offer pending.");
                        }

                        if (innerNegotiationRow.StatusId == StatusMap.FromCode(Status.Declined))
                        {
                            throw new Exception("This offer has previously been declined.");
                        }
                    }

                    // Time stamps and user stamps
                    Guid     createdUserId  = TradingSupport.UserId;
                    DateTime createdTime    = DateTime.UtcNow;
                    Guid     modifiedUserId = TradingSupport.UserId;
                    DateTime modifiedTime   = createdTime;

                    // This will find the contra matching record.
                    MatchRow contraMatchRow = DataModel.Match.MatchKeyWorkingOrderIdContraOrderId.Find(
                        new Object[] { matchRow.ContraOrderId, matchRow.WorkingOrderId });
                    if (contraMatchRow == null)
                    {
                        throw new Exception(
                                  string.Format("Corruption: the match record for {0}, {1} can't be found", matchRow.ContraOrderId, matchRow.WorkingOrderId));
                    }

                    // This is the order on the other side of the match.
                    WorkingOrderRow contraWorkingOrderRow = contraMatchRow.WorkingOrderRow;

                    // When both sides have agreed to the Negotiation, the Destination Orders are generated.
                    NegotiationRow contraNegotiationRow = null;
                    foreach (NegotiationRow innerNegotiationRow in contraMatchRow.GetNegotiationRows())
                    {
                        if (innerNegotiationRow.StatusId == StatusMap.FromCode(Status.Pending))
                        {
                            contraNegotiationRow = innerNegotiationRow;
                            break;
                        }
                    }

                    // This means that there's an offer on the other side.
                    if (contraNegotiationRow == null)
                    {
                        // There is no opposite side of this transaction yet.  It will be placed in the negotation table and wait there
                        // until it times out, or the other side accepts the offer.
                        negotiationId = Guid.NewGuid();
                        dataModel.CreateNegotiation(
                            contraWorkingOrderRow.BlotterId,
                            null,
                            false,
                            contraMatchRow.MatchId,
                            negotiationId,
                            quantity,
                            StatusMap.FromCode(Status.Pending));
                    }
                    else
                    {
                        // At this point, there is an offer on both sides of the match for a follow-on order.  We'll create orders and
                        // executions for both sides of the trade for the minimum agreed upon quantity.
                        WorkingOrderRow workingOrderRow = matchRow.WorkingOrderRow;
                        WorkingOrderRow contraOrderRow  = contraNegotiationRow.MatchRow.WorkingOrderRow;

                        // The quantity of this negotiation will be the minimum of the two offers.
                        decimal matchedQuantity = quantity < contraNegotiationRow.Quantity ? quantity : contraNegotiationRow.Quantity;

                        // Create the order on this side of the trade.
                        Guid destinationOrderId = Guid.NewGuid();
                        dataModel.CreateDestinationOrder(
                            workingOrderRow.BlotterId,
                            null,
                            null,
                            createdTime,
                            createdUserId,
                            destinationId,
                            destinationOrderId,
                            null,
                            null,
                            null,
                            null,
                            workingOrderRow[DataModel.WorkingOrder.LimitPriceColumn],
                            modifiedTime,
                            modifiedUserId,
                            matchedQuantity,
                            workingOrderRow.OrderTypeId,
                            workingOrderRow.SecurityId,
                            modifiedTime,
                            workingOrderRow.SettlementId,
                            workingOrderRow.SideId,
                            StateMap.FromCode(State.Acknowledged),
                            StatusMap.FromCode(Status.New),
                            workingOrderRow[DataModel.WorkingOrder.StopPriceColumn],
                            workingOrderRow.TimeInForceId,
                            modifiedTime,
                            null,
                            workingOrderRow.WorkingOrderId);

                        // The the trade is executed at the current price.
                        PriceRow priceRow = DataModel.Price.PriceKey.Find(workingOrderRow.SecurityId, workingOrderRow.SettlementId);

                        // Create the Execution for this side of the trade.
                        Guid executionId = Guid.NewGuid();
                        dataModel.CreateExecution(
                            null,
                            workingOrderRow.BlotterId,
                            null,
                            null,
                            null,
                            createdTime,
                            createdUserId,
                            destinationOrderId,
                            StateMap.FromCode(State.Acknowledged),
                            executionId,
                            priceRow.LastPrice,
                            matchedQuantity,
                            null,
                            null,
                            null,
                            modifiedTime,
                            modifiedUserId,
                            null,
                            null,
                            null,
                            null,
                            StateMap.FromCode(State.Sent),
                            null,
                            null,
                            null,
                            null);

                        // There is no opposite side of this transaction yet.  It will be placed in the negotation table and wait there
                        // until it times out, or the other side accepts the offer.
                        negotiationId = Guid.NewGuid();
                        dataModel.CreateNegotiation(
                            workingOrderRow.BlotterId,
                            executionId,
                            false,
                            matchId,
                            negotiationId,
                            quantity,
                            StatusMap.FromCode(Status.Accepted));

                        // Create an order for the agreed upon quantity.
                        // Create the order on this side of the trade.
                        Guid contraDestinationOrderId = Guid.NewGuid();
                        dataModel.CreateDestinationOrder(
                            contraWorkingOrderRow.BlotterId,
                            null,
                            null,
                            createdTime,
                            createdUserId,
                            destinationId,
                            contraDestinationOrderId,
                            null,
                            null,
                            null,
                            null,
                            contraWorkingOrderRow[DataModel.WorkingOrder.LimitPriceColumn],
                            modifiedTime,
                            modifiedUserId,
                            matchedQuantity,
                            contraWorkingOrderRow.OrderTypeId,
                            contraWorkingOrderRow.SecurityId,
                            modifiedTime,
                            contraWorkingOrderRow.SettlementId,
                            contraWorkingOrderRow.SideId,
                            StateMap.FromCode(State.Acknowledged),
                            StatusMap.FromCode(Status.New),
                            contraWorkingOrderRow[DataModel.WorkingOrder.StopPriceColumn],
                            contraWorkingOrderRow.TimeInForceId,
                            modifiedTime,
                            null,
                            contraWorkingOrderRow.WorkingOrderId);

                        // Create the Execution for this side of the trade.
                        Guid contraExecutionId = Guid.NewGuid();
                        dataModel.CreateExecution(
                            null,
                            contraWorkingOrderRow.BlotterId,
                            null,
                            null,
                            null,
                            createdTime,
                            createdUserId,
                            contraDestinationOrderId,
                            StateMap.FromCode(State.Acknowledged),
                            contraExecutionId,
                            priceRow.LastPrice,
                            matchedQuantity,
                            null,
                            null,
                            null,
                            modifiedTime,
                            modifiedUserId,
                            null,
                            null,
                            null,
                            null,
                            StateMap.FromCode(State.Sent),
                            null,
                            null,
                            null,
                            null);

                        // Update the contra offer.
                        dataModel.UpdateNegotiation(
                            contraWorkingOrderRow.BlotterId,
                            contraExecutionId,
                            false,
                            null,
                            null,
                            new Object[] { contraNegotiationRow.NegotiationId },
                            null,
                            contraNegotiationRow.RowVersion,
                            StatusMap.FromCode(Status.Accepted));
                    }
                }
            }
            finally
            {
                // Release the tables.
                DataModel.DataLock.ExitReadLock();
            }
        }
Ejemplo n.º 7
0
        private void OnMarketDepthUpdate(object sender, Data.MarketDepthEventArgs e)
        {
            if (justConnected)
            {
                if (SuperDom.Account == null)
                {
                    return;
                }
                // Get the orders already open and assign APQ values to them
                lock (SuperDom.Account.Orders)
                    foreach (Cbi.Order order in SuperDom.Account.Orders)
                    {
                        GetInitialOrderApq(order, order.OrderState, order.LimitPrice);
                    }

                justConnected = false;
                return;
            }

            lock (SuperDom.Rows)
            {
                if (SuperDom.MarketDepth != null)
                {
                    if (SuperDom.MarketDepth.Bids != null)
                    {
                        foreach (LadderRow bid in SuperDom.MarketDepth.Bids)
                        {
                            PriceRow row = SuperDom.Rows.FirstOrDefault(r => r.Price == bid.Price);
                            if (row == null)
                            {
                                continue;
                            }

                            long currentApqValue;
                            bool gotCurrentApq = priceApqValues.TryGetValue(bid.Price, out currentApqValue);

                            if ((!gotCurrentApq || bid.Volume < currentApqValue - 1) && bid.Volume >= 1)
                            {
                                // If the current volume has dropped below the previous value, update APQ value
                                if (row.BuyOrders.Count(o => o.IsLimit) > 0)
                                {
                                    long newVal = priceApqValues.AddOrUpdate(bid.Price, bid.Volume + 1,
                                                                             (key, oldValue) => oldValue > 1 ?
                                                                             oldValue - (currentApqValue - bid.Volume) >= 1 ?
                                                                             oldValue - (currentApqValue - bid.Volume) : 1 : oldValue);

                                    ConcurrentDictionary <Cbi.Order, long> ordersThisPrice;
                                    if (priceToOrderApqMap.TryGetValue(bid.Price, out ordersThisPrice))
                                    {
                                        foreach (Cbi.Order key in ordersThisPrice.Keys)
                                        {
                                            if (newVal < ordersThisPrice[key])
                                            {
                                                ordersThisPrice.TryUpdate(key, newVal, ordersThisPrice[key]);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    long oldDepth;
                                    priceApqValues.TryRemove(bid.Price, out oldDepth);
                                }
                            }
                        }
                    }

                    if (SuperDom.MarketDepth.Asks != null)
                    {
                        foreach (LadderRow ask in SuperDom.MarketDepth.Asks)
                        {
                            PriceRow row = SuperDom.Rows.FirstOrDefault(r => r.Price == ask.Price);
                            if (row == null)
                            {
                                continue;
                            }

                            long currentApqValue;
                            bool gotCurrentApq = priceApqValues.TryGetValue(ask.Price, out currentApqValue);

                            if ((!gotCurrentApq || ask.Volume < currentApqValue - 1) && ask.Volume >= 1)
                            {
                                // If the current volume has dropped below the previous value, update APQ value
                                if (row.SellOrders.Count(o => o.IsLimit) > 0)
                                {
                                    long newVal = priceApqValues.AddOrUpdate(ask.Price, ask.Volume + 1,
                                                                             (key, oldValue) => oldValue > 1 ?
                                                                             oldValue - (currentApqValue - ask.Volume) >= 1 ?
                                                                             oldValue - (currentApqValue - ask.Volume) : 1 : oldValue);

                                    ConcurrentDictionary <Cbi.Order, long> ordersThisPrice;
                                    // Are there any orders at this price?
                                    if (priceToOrderApqMap.TryGetValue(ask.Price, out ordersThisPrice))
                                    {
                                        foreach (Cbi.Order key in ordersThisPrice.Keys)
                                        {
                                            if (newVal < ordersThisPrice[key])
                                            {
                                                ordersThisPrice.TryUpdate(key, newVal, ordersThisPrice[key]);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    long oldDepth;
                                    priceApqValues.TryRemove(ask.Price, out oldDepth);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 8
0
        protected override void OnMarketData(Data.MarketDataEventArgs marketUpdate)
        {
            if (marketUpdate.MarketDataType != Data.MarketDataType.Last)
            {
                return;
            }

            Data.MarketDataEventArgs mu = marketUpdate;                 // Access to modified closure
            if (justConnected)
            {
                if (SuperDom.Account == null)
                {
                    return;
                }
                // Get the orders already open and assign APQ values to them
                lock (SuperDom.Account.Orders)
                    foreach (Cbi.Order order in SuperDom.Account.Orders)
                    {
                        GetInitialOrderApq(order, order.OrderState, order.LimitPrice);
                    }

                justConnected = false;
                return;
            }

            long currentApqValue;

            if (priceApqValues.TryGetValue(mu.Price, out currentApqValue))
            {
                // If the current volume has dropped below the previous value, update APQ value
                lock (SuperDom.Rows)
                {
                    PriceRow row = SuperDom.Rows.FirstOrDefault(r => r.Price == mu.Price);
                    if (row != null)
                    {
                        if (row.BuyOrders.Count > 0)
                        {
                            long newVal = currentApqValue - mu.Volume;
                            if (currentApqValue != 0 && newVal < currentApqValue)
                            {
                                priceApqValues.TryUpdate(mu.Price,                                                                                                              // Key
                                                         currentApqValue > 1 ? (newVal >= 1 ? newVal : 1) : currentApqValue,                                                    // New value
                                                         currentApqValue);                                                                                                      // Comparison value

                                ConcurrentDictionary <Cbi.Order, long> ordersThisPrice;
                                if (priceToOrderApqMap.TryGetValue(mu.Price, out ordersThisPrice))
                                {
                                    foreach (Cbi.Order key in ordersThisPrice.Keys)
                                    {
                                        if (newVal < ordersThisPrice[key])
                                        {
                                            ordersThisPrice.TryUpdate(key, newVal, ordersThisPrice[key]);
                                        }
                                    }
                                }
                            }
                        }
                        else if (row.SellOrders.Count == 0)
                        {
                            long oldDepth;
                            priceApqValues.TryRemove(mu.Price, out oldDepth);
                        }
                    }
                }
            }

            if (priceApqValues.TryGetValue(mu.Price, out currentApqValue))
            {
                // If the current volume has dropped below the previous value, update APQ value
                lock (SuperDom.Rows)
                {
                    PriceRow row = SuperDom.Rows.FirstOrDefault(r => r.Price == mu.Price);
                    if (row != null)
                    {
                        if (row.SellOrders.Count > 0)
                        {
                            long newVal = currentApqValue - mu.Volume;
                            if (currentApqValue != 0 && newVal < currentApqValue)
                            {
                                priceApqValues.TryUpdate(mu.Price,                                                                              // Key
                                                         currentApqValue > 1 ? (newVal >= 1 ? newVal : 1) : currentApqValue,                    // New value
                                                         currentApqValue);                                                                      // Comparison value

                                ConcurrentDictionary <Cbi.Order, long> ordersThisPrice;
                                if (priceToOrderApqMap.TryGetValue(mu.Price, out ordersThisPrice))
                                {
                                    foreach (Cbi.Order key in ordersThisPrice.Keys)
                                    {
                                        if (newVal < ordersThisPrice[key])
                                        {
                                            ordersThisPrice.TryUpdate(key, newVal, ordersThisPrice[key]);
                                        }
                                    }
                                }
                            }
                        }
                        else if (row.BuyOrders.Count == 0)
                        {
                            long oldDepth;
                            priceApqValues.TryRemove(mu.Price, out oldDepth);
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Create working orders.
        /// </summary>
        /// <param name="sender">The generic thread initialization parameter.</param>
        public static void CreateOrders(object state)
        {
            GenerateTradeInfo generateTradeInfo = state as GenerateTradeInfo;

            // Create a random number generator with about as random a number as possible.
            Random random = new Random(DateTime.Now.TimeOfDay.Milliseconds);

            XDocument xDocument = new XDocument();

            lock (DataModel.SyncRoot)
            {
                // This is the selected blotter for the orders.
                BlotterRow blotterRow = DataModel.Blotter.BlotterKey.Find(generateTradeInfo.BlotterId);
                if (blotterRow == null)
                {
                    throw new Exception(String.Format("Blotter {0} not found", generateTradeInfo.BlotterId));
                }

                // This is the current user creating the orders.
                UserRow userRow = DataModel.User.UserKey.Find(Information.UserId);
                if (userRow == null)
                {
                    throw new Exception("The current user isn't mapped to a database user.");
                }

                CountryRow countryRow = DataModel.Country.CountryKeyExternalId0.Find("US");
                if (countryRow == null)
                {
                    throw new Exception("The country isn't part of the database.");
                }

                //<script name="Automatically Generated Orders">
                XElement elementRoot = new XElement("script", new XAttribute("name", "Automatically Generated Orders"));
                xDocument.Add(elementRoot);

                //  <client name="DataModelClient" type="DataModelClient, Client Data Model" endpoint="TcpDataModelEndpoint" />
                elementRoot.Add(
                    new XElement("client",
                                 new XAttribute("name", "DataModelClient"),
                                 new XAttribute("type", "DataModelClient, Client Data Model"),
                                 new XAttribute("endpoint", "TcpDataModelEndpoint")));

                for (int index = 0; index < generateTradeInfo.OrderCount; index++)
                {
                    //  <transaction>
                    XElement elementTransaction = new XElement("transaction");
                    elementRoot.Add(elementTransaction);

                    // Generate a working order identifier.
                    Guid workingOrderId = Guid.NewGuid();

                    // Generate the status of the new order.
                    StatusRow statusRow = DataModel.Status.StatusKeyStatusCode.Find(Status.New);

                    // Generate a random US Fixed Income Instrument.
                    SecurityRow securityRow           = null;
                    SecurityRow settlementCurrencyRow = null;
                    while (true)
                    {
                        // Select a random equity.
                        DebtRow debtRow = DataModel.Debt[random.Next(DataModel.Debt.Count - 1)];
                        securityRow = debtRow.SecurityRowByFK_Security_Debt_DebtId;

                        // Generate the settlement currency
                        EntityRow usdEntityRow = DataModel.Entity.EntityKeyExternalId0.Find("USD");
                        settlementCurrencyRow = DataModel.Security.SecurityKey.Find(usdEntityRow.EntityId);

                        PriceRow priceRow = DataModel.Price.PriceKey.Find(securityRow.SecurityId, settlementCurrencyRow.SecurityId);
                        if (priceRow != null)
                        {
                            break;
                        }
                    }

                    // Generate the side for the order.
                    Side    side    = random.Next(2) == 0 ? Side.Buy : Side.Sell;
                    SideRow sideRow = DataModel.Side.SideKeySideCode.Find(side);

                    // Generate the time in force for this order.
                    TimeInForceRow timeInForceRow = DataModel.TimeInForce.TimeInForceKeyTimeInForceCode.Find(TimeInForce.GoodTillCancel);

                    // Generate trade and settlement dates.
                    DateTime tradeDate      = DateTime.Now;
                    DateTime settlementDate = DateTime.Now;
                    for (int dayIndex = 0; dayIndex < 3; dayIndex++)
                    {
                        settlementDate += TimeSpan.FromDays(1.0);
                        if (settlementDate.DayOfWeek == DayOfWeek.Saturday)
                        {
                            settlementDate += TimeSpan.FromDays(1.0);
                        }
                        if (settlementDate.DayOfWeek == DayOfWeek.Sunday)
                        {
                            settlementDate += TimeSpan.FromDays(1.0);
                        }
                    }

                    // Generate matching selections.
                    Boolean isBrokerMatch      = random.Next(10) == 0;
                    Boolean isHedgeMatch       = random.Next(5) == 0;
                    Boolean isInstitutionMatch = true;
                    if (random.Next(5) == 0)
                    {
                        isBrokerMatch      = true;
                        isHedgeMatch       = true;
                        isInstitutionMatch = true;
                    }
                    if (random.Next(10) == 0)
                    {
                        isBrokerMatch      = false;
                        isHedgeMatch       = false;
                        isInstitutionMatch = false;
                    }

                    // Generate a submission type for crossing.
                    Crossing    crossing    = Crossing.NeverMatch;
                    CrossingRow crossingRow = DataModel.Crossing.CrossingKeyCrossingCode.Find(crossing);

                    //    <method name="CreateWorkingOrderEx" client="DataModelClient">
                    XElement elementWorkingOrder = new XElement(
                        "method",
                        new XAttribute("name", "CreateWorkingOrderEx"),
                        new XAttribute("client", "DataModelClient"));
                    elementTransaction.Add(elementWorkingOrder);

                    //      <parameter name="blotterKey" value="TONY DE SILVA BLOTTER" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "blotterKey"),
                                     new XAttribute("value", blotterRow.EntityRow.ExternalId0)));

                    //      <parameter name="configurationId" value="CUSIP" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "configurationId"),
                                     new XAttribute("value", "CUSIP")));

                    //      <parameter name="createdTime" value="5/26/2006 11:57:19 AM" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "createdTime"),
                                     new XAttribute("value", DateTime.Now.ToString("G"))));

                    //      <parameter name="crossingKey" value="ALWAYS" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "crossingKey"),
                                     new XAttribute("value", crossingRow.ExternalId0)));

                    //      <parameter name="externalId0" value="{fed508fb-b2a9-44df-8aa9-760f43a5d768}" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "externalId0"),
                                     new XAttribute("value", workingOrderId.ToString("B"))));

                    //      <parameter name="isBrokerMatch" value="True" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "isBrokerMatch"),
                                     new XAttribute("value", isBrokerMatch)));

                    //      <parameter name="isHedgeMatch" value="True" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "isHedgeMatch"),
                                     new XAttribute("value", isHedgeMatch)));

                    //      <parameter name="isInstitutionMatch" value="True" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "isInstitutionMatch"),
                                     new XAttribute("value", isInstitutionMatch)));

                    //      <parameter name="modifiedTime" value="5/26/2006 11:57:19 AM" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "modifiedTime"),
                                     new XAttribute("value", DateTime.Now.ToString("G"))));

                    //      <parameter name="orderTypeKey" value="MKT" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "orderTypeKey"),
                                     new XAttribute("value", "MKT")));

                    //      <parameter name="securityKeyBySecurityId" value="LMT" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "securityKeyBySecurityId"),
                                     new XAttribute("value", securityRow.EntityRow.ExternalId4)));

                    //      <parameter name="securityKeyBySettlementId" value="USD" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "securityKeyBySettlementId"),
                                     new XAttribute("value", settlementCurrencyRow.EntityRow.ExternalId0)));

                    //		<parameter name="settlementDate" value="3/31/2008 10:00:00 AM" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "settlementDate"),
                                     new XAttribute("value", settlementDate.ToString("G"))));

                    //      <parameter name="sideKey" value="BUY" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "sideKey"),
                                     new XAttribute("value", sideRow.ExternalId0)));

                    //      <parameter name="statusKey" value="PARTIALFILL" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "statusKey"),
                                     new XAttribute("value", statusRow.ExternalId0)));

                    //      <parameter name="timeInForceKey" value="DAY" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "timeInForceKey"),
                                     new XAttribute("value", timeInForceRow.ExternalId0)));

                    //		<parameter name="tradeDate" value="3/28/2008 10:00:00 AM" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "tradeDate"),
                                     new XAttribute("value", tradeDate.ToString("G"))));

                    //      <parameter name="userKeyByCreatedUserId" value="TONY DE SILVA" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "userKeyByCreatedUserId"),
                                     new XAttribute("value", userRow.EntityRow.ExternalId0)));

                    //      <parameter name="userKeyByModifiedUserId" value="TONY DE SILVA" />
                    elementWorkingOrder.Add(
                        new XElement("parameter",
                                     new XAttribute("name", "userKeyByModifiedUserId"),
                                     new XAttribute("value", userRow.EntityRow.ExternalId0)));

                    // Most working orders have only a single source order but occationally they are blocked together and
                    // allocated as a single ticket.
                    Int32 sourceOrderCount = random.Next(6) == 0 ? random.Next(4) + 1 : 1;
                    for (int sourceOrderIndex = 0; sourceOrderIndex < sourceOrderCount; sourceOrderIndex++)
                    {
                        // Generate the source order identifier.
                        Guid sourceOrderId = Guid.NewGuid();

                        // Generate the quantity of this order.
                        Decimal orderedQuantity = Convert.ToDecimal(random.Next(1, 100)) * 100.0M;
                        if (orderedQuantity == 0.0M)
                        {
                            throw new Exception("The Quantity is zero!!");
                        }

                        //    <method name="CreateSourceOrderEx" client="DataModelClient">
                        XElement elementSourceOrder = new XElement(
                            "method",
                            new XAttribute("name", "CreateSourceOrderEx"),
                            new XAttribute("client", "DataModelClient"));
                        elementTransaction.Add(elementSourceOrder);

                        //      <parameter name="blotterKey" value="TONY DE SILVA BLOTTER" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "blotterKey"),
                                         new XAttribute("value", blotterRow.EntityRow.ExternalId0)));

                        //      <parameter name="configurationId" value="CUSIP" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "configurationId"),
                                         new XAttribute("value", "CUSIP")));

                        //      <parameter name="createdTime" value="5/26/2006 11:57:19 AM" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "createdTime"),
                                         new XAttribute("value", DateTime.Now)));

                        //      <parameter name="externalId0" value="{3d289495-9c66-4582-b50f-3548c8c260f1}" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "externalId0"),
                                         new XAttribute("value", sourceOrderId.ToString("B"))));

                        //      <parameter name="modifiedTime" value="5/26/2006 11:57:19 AM" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "modifiedTime"),
                                         new XAttribute("value", DateTime.Now.ToString("G"))));

                        //      <parameter name="orderedQuantity" value="4300.0000000" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "orderedQuantity"),
                                         new XAttribute("value", orderedQuantity)));

                        //      <parameter name="orderTypeKey" value="MKT" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "orderTypeKey"),
                                         new XAttribute("value", "MKT")));

                        //      <parameter name="securityKeyBySecurityId" value="LMT" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "securityKeyBySecurityId"),
                                         new XAttribute("value", securityRow.EntityRow.ExternalId4)));

                        //      <parameter name="securityKeyBySettlementId" value="USD" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "securityKeyBySettlementId"),
                                         new XAttribute("value", settlementCurrencyRow.EntityRow.ExternalId0)));

                        //		<parameter name="settlementDate" value="3/31/2008 10:00:00 AM" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "settlementDate"),
                                         new XAttribute("value", settlementDate)));

                        //      <parameter name="sideKey" value="BUY" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "sideKey"),
                                         new XAttribute("value", sideRow.ExternalId0)));

                        //      <parameter name="statusKey" value="PARTIALFILL" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "statusKey"),
                                         new XAttribute("value", statusRow.ExternalId0)));
                        //      <parameter name="timeInForceKey" value="DAY" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "timeInForceKey"),
                                         new XAttribute("value", timeInForceRow.ExternalId0)));

                        //		<parameter name="tradeDate" value="3/28/2008 10:00:00 AM" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "tradeDate"),
                                         new XAttribute("value", tradeDate.ToString("G"))));

                        //      <parameter name="userKeyByCreatedUserId" value="TONY DE SILVA" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "userKeyByCreatedUserId"),
                                         new XAttribute("value", userRow.EntityRow.ExternalId0)));

                        //      <parameter name="userKeyByModifiedUserId" value="TONY DE SILVA" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "userKeyByModifiedUserId"),
                                         new XAttribute("value", userRow.EntityRow.ExternalId0)));

                        //      <parameter name="workingOrderKey" value="{fed508fb-b2a9-44df-8aa9-760f43a5d768}" />
                        elementSourceOrder.Add(
                            new XElement("parameter",
                                         new XAttribute("name", "workingOrderKey"),
                                         new XAttribute("value", workingOrderId.ToString("B"))));
                    }
                }

                // Fill out the file name with a default directory and an extension if they are required before saving the
                // generated orders.
                String fileName = generateTradeInfo.FileName;
                if (!Path.IsPathRooted(fileName))
                {
                    fileName = Path.Combine(Environment.ExpandEnvironmentVariables(FixedIncomeOrders.DefaultDirectory), fileName);
                }
                if (!Path.HasExtension(fileName))
                {
                    fileName = Path.ChangeExtension(fileName, FixedIncomeOrders.DefaultFileExtension);
                }
                xDocument.Save(fileName);
            }
        }