/// <summary> /// Authorizes a Security to be returned to the client. /// </summary> /// <param name="userDataRow">Identifies the current user.</param> /// <param name="securityDataRow">The record to be tested for authorization.</param> /// <returns>true if the record belongs in the user's hierarchy.</returns> public static bool FilterSecurity(DataRow userDataRow, DataRow securityDataRow) { // This will test the record and return true if it belongs to the hierarchies this user is authorized to view. False // if the record should not be included in the user's data model. ServerMarketData.UserRow userRow = (ServerMarketData.UserRow)userDataRow; ServerMarketData.SecurityRow securityRow = (ServerMarketData.SecurityRow)securityDataRow; foreach (ServerMarketData.SourceOrderRow sourceOrderRow in securityRow.GetSourceOrderRowsBySecuritySourceOrderSecurityId()) { if (Hierarchy.IsDescendant(userRow.SystemFolderRow.FolderRow.ObjectRow, sourceOrderRow.WorkingOrderRow.BlotterRow.ObjectRow)) { return(true); } } foreach (ServerMarketData.SourceOrderRow sourceOrderRow in securityRow.GetSourceOrderRowsBySecuritySourceOrderSettlementId()) { if (Hierarchy.IsDescendant(userRow.SystemFolderRow.FolderRow.ObjectRow, sourceOrderRow.WorkingOrderRow.BlotterRow.ObjectRow)) { return(true); } } return(false); }
/// <summary>Inserts a Order record.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit</param> /// <param name="blockOrderId">The value for the BlockOrderId column.</param> /// <param name="accountId">The value for the AccountId column.</param> /// <param name="securityId">The value for the SecurityId column.</param> /// <param name="settlementId">The value for the SettlementId column.</param> /// <param name="brokerId">The value for the BrokerId column.</param> /// <param name="transactionTypeCode">The value for the TransactionTypeCode column.</param> /// <param name="timeInForceCode">The value for the TimeInForceCode column.</param> /// <param name="orderTypeCode">The value for the OrderTypeCode column.</param> /// <param name="conditionCode">The value for the ConditionCode column.</param> /// <param name="rowVersion">The value for the RowVersion column.</param> /// <param name="isAgency">The value for the Agency column.</param> /// <param name="quantity">The value for the Quantity column.</param> /// <param name="price1">The value for the Price1 column.</param> /// <param name="price2">The value for the Price2 column.</param> /// <param name="note">The value for the Note column.</param> /// <param name="createdTime">The value for the CreatedTime column.</param> /// <param name="createdLoginId">The value for the CreatedLoginId column.</param> /// <param name="modifiedTime">The value for the ModifiedTime column.</param> /// <param name="modifiedLoginId">The value for the ModifiedLoginId column.</param> public static int Insert( Transaction transaction, object blockOrderId, object blotterId, int accountId, int securityId, int settlementId, object brokerId, int transactionTypeCode, int timeInForceCode, int orderTypeCode, object conditionCode, ref long rowVersion, object isAgency, System.Decimal quantity, object price1, object price2, object note) { // The rowVersion of the block order is declared here, but it is not passed back to the caller. long rowVersionBlockOrder = long.MinValue; // This will find a block order for the order, or create a block order if one is needed. The order must be associated // with a block at all times. if (blockOrderId == null) { // If the blotter wasn't provided, then find a blotter using the mapping of securities to blotters. if (blotterId == null) { ServerMarketData.SecurityRow securityRow = ServerMarketData.Security.FindBySecurityId(securityId); if (securityRow == null) { throw new Exception(string.Format("Security {0} does not exist", securityId)); } blotterId = TradingSupport.AutoRoute(securityRow, quantity); } // If the order hasn't been associated with a block order yet, then find open one up. The 'Open' method will // either return a block that matches the attributes of the order -- and can still be blocked -- or it will create // a new block based on the attributes of this new order. blockOrderId = Shadows.WebService.Trading.BlockOrder.Open(transaction, (int)blotterId, accountId, securityId, settlementId, brokerId, transactionTypeCode, timeInForceCode, orderTypeCode, conditionCode, ref rowVersionBlockOrder, isAgency, price1, price2); } // These values are provided by the server. int positionTypeCode = Shadows.Quasar.Common.TransactionType.GetPosition(transactionTypeCode); DateTime createdTime = DateTime.Now; int createdLoginId = ServerMarketData.LoginId; // Call the internal method to add the order. return(Shadows.WebService.Core.Order.Insert(transaction, (int)blockOrderId, accountId, securityId, settlementId, brokerId, positionTypeCode, transactionTypeCode, timeInForceCode, orderTypeCode, conditionCode, ref rowVersion, null, null, quantity, price1, price2, note, createdTime, createdLoginId, createdTime, createdLoginId)); }
/// <summary>Archives a Country record.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit</param> /// <param name="RowVersion">The version number of this row.</param> /// <param name="countryId">The value for the CountryId column.</param> /// <param name="archive">true to archive the object, false to unarchive it.</param> public static void Archive(AdoTransaction adoTransaction, SqlTransaction sqlTransaction, long rowVersion, int countryId) { // Accessor for the Country Table. ServerMarketData.CountryDataTable countryTable = ServerMarketData.Country; // Rule #1: Make sure the record exists before updating it. ServerMarketData.CountryRow countryRow = countryTable.FindByCountryId(countryId); if ((countryRow == null)) { throw new Exception(string.Format("The Country table does not have an element identified by {0}", countryId)); } // Rule #2: Optimistic Concurrency Check if ((countryRow.RowVersion != rowVersion)) { throw new System.Exception("This record is busy. Please try again later."); } // Archive the child records. for (int index = 0; (index < countryRow.GetAccountBaseRows().Length); index = (index + 1)) { ServerMarketData.AccountBaseRow childAccountBaseRow = countryRow.GetAccountBaseRows()[index]; AccountBase.ArchiveChildren(adoTransaction, sqlTransaction, childAccountBaseRow.RowVersion, childAccountBaseRow.AccountBaseId); } for (int index = 0; (index < countryRow.GetHolidayRows().Length); index = (index + 1)) { ServerMarketData.HolidayRow childHolidayRow = countryRow.GetHolidayRows()[index]; Holiday.Archive(adoTransaction, sqlTransaction, childHolidayRow.RowVersion, childHolidayRow.HolidayId); } for (int index = 0; (index < countryRow.GetProvinceRows().Length); index = (index + 1)) { ServerMarketData.ProvinceRow childProvinceRow = countryRow.GetProvinceRows()[index]; Province.Archive(adoTransaction, sqlTransaction, childProvinceRow.RowVersion, childProvinceRow.ProvinceId); } for (int index = 0; (index < countryRow.GetSecurityRows().Length); index = (index + 1)) { ServerMarketData.SecurityRow childSecurityRow = countryRow.GetSecurityRows()[index]; Security.ArchiveChildren(adoTransaction, sqlTransaction, childSecurityRow.RowVersion, childSecurityRow.SecurityId); } // Increment the row version rowVersion = ServerMarketData.RowVersion.Increment(); // Delete the record in the ADO database. countryRow[countryTable.RowVersionColumn] = rowVersion; adoTransaction.DataRows.Add(countryRow); countryRow.Delete(); // Archive the record in the SQL database. SqlCommand sqlCommand = new SqlCommand("update \"Country\" set \"IsArchived\" = 1 where \"CountryId\"=@countryId"); sqlCommand.Connection = sqlTransaction.Connection; sqlCommand.Transaction = sqlTransaction; sqlCommand.Parameters.Add(new SqlParameter("@countryId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, countryId)); sqlCommand.ExecuteNonQuery(); }
/// <summary>Updates a Security record using Metadata Parameters.</summary> /// <param name="transaction">Contains the parameters and exceptions for this command.</param> public new static void Update(ParameterList parameters) { // Accessor for the Security Table. ServerMarketData.SecurityDataTable securityTable = ServerMarketData.Security; // Extract the parameters from the command batch. AdoTransaction adoTransaction = parameters["adoTransaction"]; SqlTransaction sqlTransaction = parameters["sqlTransaction"]; object configurationId = parameters["configurationId"].Value; object description = parameters["description"].Value; object groupPermission = parameters["groupPermission"].Value; object hidden = parameters["hidden"].Value; object name = parameters["name"].Value; object owner = parameters["owner"].Value; object ownerPermission = parameters["ownerPermission"].Value; object readOnly = parameters["readOnly"].Value; object worldPermission = parameters["worldPermission"].Value; object averageDailyVolume = parameters["averageDailyVolume"].Value; object externalCountryId = parameters["countryId"].Value; object minimumQuantity = parameters["minimumQuantity"].Value; object marketCapitalization = parameters["marketCapitalization"].Value; object priceFactor = parameters["priceFactor"].Value; object quantityFactor = parameters["quantityFactor"].Value; string externalSecurityId = ((string)(parameters["securityId"])); object symbol = parameters["symbol"].Value; object externalTypeCode = parameters["typeCode"].Value; object logo = parameters["logo"].Value; object externalVolumeCategoryId = parameters["volumeCategoryId"].Value; // The row versioning is largely disabled for external operations. The value is returned to the caller in the // event it's needed for operations within the batch. long rowVersion = long.MinValue; // Resolve External Identifiers object countryId = Country.FindOptionalKey(configurationId, "countryId", externalCountryId); int securityId = Object.FindRequiredKey(configurationId, "securityId", externalSecurityId); object typeCode = Type.FindOptionalKey(configurationId, "typeCode", externalTypeCode); object volumeCategoryId = VolumeCategory.FindOptionalKey(configurationId, "volumeCategoryId", externalVolumeCategoryId); // This disables the concurrency checking logic by finding the current row version and passing it to the // internal method. ServerMarketData.SecurityRow securityRow = securityTable.FindBySecurityId(securityId); rowVersion = ((long)(securityRow[securityTable.RowVersionColumn])); // Call the internal method to complete the operation. MarkThree.Guardian.Core.Security.Update(adoTransaction, sqlTransaction, ref rowVersion, description, null, null, null, null, null, null, null, null, groupPermission, hidden, name, owner, ownerPermission, readOnly, worldPermission, averageDailyVolume, countryId, minimumQuantity, marketCapitalization, priceFactor, quantityFactor, securityId, symbol, typeCode, logo, volumeCategoryId); // Return values. parameters["rowVersion"] = rowVersion; }
/// <summary>Archives a VolumeCategory record.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit</param> /// <param name="RowVersion">The version number of this row.</param> /// <param name="volumeCategoryId">The value for the VolumeCategoryId column.</param> /// <param name="archive">true to archive the object, false to unarchive it.</param> public static void Archive(AdoTransaction adoTransaction, SqlTransaction sqlTransaction, long rowVersion, int volumeCategoryId) { // Accessor for the VolumeCategory Table. ServerMarketData.VolumeCategoryDataTable volumeCategoryTable = ServerMarketData.VolumeCategory; // Rule #1: Make sure the record exists before updating it. ServerMarketData.VolumeCategoryRow volumeCategoryRow = volumeCategoryTable.FindByVolumeCategoryId(volumeCategoryId); if ((volumeCategoryRow == null)) { throw new Exception(string.Format("The VolumeCategory table does not have an element identified by {0}", volumeCategoryId)); } // Rule #2: Optimistic Concurrency Check if ((volumeCategoryRow.RowVersion != rowVersion)) { throw new System.Exception("This record is busy. Please try again later."); } // Archive the child records. for (int index = 0; (index < volumeCategoryRow.GetSecurityRows().Length); index = (index + 1)) { ServerMarketData.SecurityRow childSecurityRow = volumeCategoryRow.GetSecurityRows()[index]; Security.ArchiveChildren(adoTransaction, sqlTransaction, childSecurityRow.RowVersion, childSecurityRow.SecurityId); } for (int index = 0; (index < volumeCategoryRow.GetTraderVolumeSettingRows().Length); index = (index + 1)) { ServerMarketData.TraderVolumeSettingRow childTraderVolumeSettingRow = volumeCategoryRow.GetTraderVolumeSettingRows()[index]; TraderVolumeSetting.Archive(adoTransaction, sqlTransaction, childTraderVolumeSettingRow.RowVersion, childTraderVolumeSettingRow.TraderVolumeSettingId); } // Increment the row version rowVersion = ServerMarketData.RowVersion.Increment(); // Delete the record in the ADO database. volumeCategoryRow[volumeCategoryTable.RowVersionColumn] = rowVersion; adoTransaction.DataRows.Add(volumeCategoryRow); volumeCategoryRow.Delete(); // Archive the record in the SQL database. SqlCommand sqlCommand = new SqlCommand("update \"VolumeCategory\" set \"IsArchived\" = 1 where \"VolumeCategoryId\"=@volumeCate" + "goryId"); sqlCommand.Connection = sqlTransaction.Connection; sqlCommand.Transaction = sqlTransaction; sqlCommand.Parameters.Add(new SqlParameter("@volumeCategoryId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, volumeCategoryId)); sqlCommand.ExecuteNonQuery(); }
/// <summary>Archives a Security record.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit</param> /// <param name="rowVersion">The version number of this row.</param> /// <param name="securityId">The value for the SecurityId column.</param> /// <param name="archive">true to archive the object, false to unarchive it.</param> public new static void Archive(AdoTransaction adoTransaction, SqlTransaction sqlTransaction, long rowVersion, int securityId) { // Accessor for the Security Table. ServerMarketData.SecurityDataTable securityTable = ServerMarketData.Security; // Rule #1: Make sure the record exists before updating it. ServerMarketData.SecurityRow securityRow = securityTable.FindBySecurityId(securityId); if ((securityRow == null)) { throw new Exception(string.Format("The Security table does not have an element identified by {0}", securityId)); } // Rule #2: Optimistic Concurrency Check if ((securityRow.RowVersion != rowVersion)) { throw new System.Exception("This record is busy. Please try again later."); } // Delete the base class record. Note that optimistic concurrency is only used // by the top level type in the hierarchy, it is bypassed after you pass the first test. long baseRowVersion = securityRow.ObjectRow.RowVersion; Object.Archive(adoTransaction, sqlTransaction, baseRowVersion, securityId); }
/// <summary>Archives a Security record using Metadata Parameters.</summary> /// <param name="transaction">Contains the parameters and exceptions for this command.</param> public new static void Archive(ParameterList parameters) { // Accessor for the Security Table. ServerMarketData.SecurityDataTable securityTable = ServerMarketData.Security; // Extract the parameters from the command batch. AdoTransaction adoTransaction = parameters["adoTransaction"]; SqlTransaction sqlTransaction = parameters["sqlTransaction"]; object configurationId = parameters["configurationId"].Value; string externalSecurityId = parameters["securityId"]; // The row versioning is largely disabled for external operations. The value is returned to the caller in the // event it's needed for operations within the batch. long rowVersion = long.MinValue; // Find the internal identifier using the primary key elements. // identifier is used to determine if a record exists with the same key. int securityId = Security.FindRequiredKey(configurationId, "securityId", externalSecurityId); // This disables the concurrency checking logic by finding the current row version and passing it to the // internal method. ServerMarketData.SecurityRow securityRow = securityTable.FindBySecurityId(securityId); rowVersion = ((long)(securityRow[securityTable.RowVersionColumn])); // Call the internal method to complete the operation. MarkThree.Guardian.Core.Security.Archive(adoTransaction, sqlTransaction, rowVersion, securityId); }
/// <summary>Inserts a Security record.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit</param> /// <param name="rowVersion">The version number of the row.</param> /// <param name="description">The value for the Description column.</param> /// <param name="externalId0">The value for the ExternalId0 column.</param> /// <param name="externalId1">The value for the ExternalId1 column.</param> /// <param name="externalId2">The value for the ExternalId2 column.</param> /// <param name="externalId3">The value for the ExternalId3 column.</param> /// <param name="externalId4">The value for the ExternalId4 column.</param> /// <param name="externalId5">The value for the ExternalId5 column.</param> /// <param name="externalId6">The value for the ExternalId6 column.</param> /// <param name="externalId7">The value for the ExternalId7 column.</param> /// <param name="groupPermission">The value for the GroupPermission column.</param> /// <param name="hidden">The value for the Hidden column.</param> /// <param name="name">The value for the Name column.</param> /// <param name="owner">The value for the Owner column.</param> /// <param name="ownerPermission">The value for the OwnerPermission column.</param> /// <param name="readOnly">The value for the ReadOnly column.</param> /// <param name="worldPermission">The value for the WorldPermission column.</param> /// <param name="averageDailyVolume">The value for the AverageDailyVolume column.</param> /// <param name="countryId">The value for the CountryId column.</param> /// <param name="minimumQuantity">The value for the MinimumQuantity column.</param> /// <param name="marketCapitalization">The value for the MarketCapitalization column.</param> /// <param name="priceFactor">The value for the PriceFactor column.</param> /// <param name="quantityFactor">The value for the QuantityFactor column.</param> /// <param name="symbol">The value for the Symbol column.</param> /// <param name="typeCode">The value for the TypeCode column.</param> /// <param name="logo">The value for the Logo column.</param> /// <param name="volumeCategoryId">The value for the VolumeCategoryId column.</param> public static int Insert( AdoTransaction adoTransaction, SqlTransaction sqlTransaction, ref long rowVersion, object description, object externalId0, object externalId1, object externalId2, object externalId3, object externalId4, object externalId5, object externalId6, object externalId7, object groupPermission, object hidden, string name, object owner, object ownerPermission, object readOnly, object worldPermission, object averageDailyVolume, int countryId, object minimumQuantity, object marketCapitalization, decimal priceFactor, decimal quantityFactor, object symbol, object typeCode, object logo, object volumeCategoryId) { // Accessor for the Security Table. ServerMarketData.SecurityDataTable securityTable = ServerMarketData.Security; // Apply Defaults if ((averageDailyVolume == null)) { averageDailyVolume = System.DBNull.Value; } if ((minimumQuantity == null)) { minimumQuantity = System.DBNull.Value; } if ((marketCapitalization == null)) { marketCapitalization = System.DBNull.Value; } if ((symbol == null)) { symbol = System.DBNull.Value; } if ((typeCode == null)) { typeCode = "Security"; } if ((logo == null)) { logo = System.DBNull.Value; } if ((volumeCategoryId == null)) { volumeCategoryId = System.DBNull.Value; } // Insert the base members using the base class. int securityId = Object.Insert(adoTransaction, sqlTransaction, ref rowVersion, description, externalId0, externalId1, externalId2, externalId3, externalId4, externalId5, externalId6, externalId7, groupPermission, hidden, name, owner, ownerPermission, readOnly, typeCode, worldPermission); // Increment the row version rowVersion = ServerMarketData.RowVersion.Increment(); // Insert the record into the ADO database. ServerMarketData.SecurityRow securityRow = securityTable.NewSecurityRow(); securityRow[securityTable.RowVersionColumn] = rowVersion; securityRow[securityTable.AverageDailyVolumeColumn] = averageDailyVolume; securityRow[securityTable.CountryIdColumn] = countryId; securityRow[securityTable.MinimumQuantityColumn] = minimumQuantity; securityRow[securityTable.MarketCapitalizationColumn] = marketCapitalization; securityRow[securityTable.PriceFactorColumn] = priceFactor; securityRow[securityTable.QuantityFactorColumn] = quantityFactor; securityRow[securityTable.SecurityIdColumn] = securityId; securityRow[securityTable.SymbolColumn] = symbol; securityRow[securityTable.LogoColumn] = logo; securityRow[securityTable.VolumeCategoryIdColumn] = volumeCategoryId; securityTable.AddSecurityRow(securityRow); adoTransaction.DataRows.Add(securityRow); // Insert the record into the SQL database. SqlCommand sqlCommand = new SqlCommand(@"insert ""Security"" (""rowVersion"",AverageDailyVolume,CountryId,MinimumQuantity,MarketCapitalization,PriceFactor,QuantityFactor,SecurityId,Symbol,Logo,VolumeCategoryId) values (@rowVersion,@averageDailyVolume,@countryId,@minimumQuantity,@marketCapitalization,@priceFactor,@quantityFactor,@securityId,@symbol,@logo,@volumeCategoryId)"); sqlCommand.Connection = sqlTransaction.Connection; sqlCommand.Transaction = sqlTransaction; sqlCommand.Parameters.Add(new SqlParameter("@rowVersion", SqlDbType.BigInt, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, rowVersion)); sqlCommand.Parameters.Add(new SqlParameter("@averageDailyVolume", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, averageDailyVolume)); sqlCommand.Parameters.Add(new SqlParameter("@countryId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, countryId)); sqlCommand.Parameters.Add(new SqlParameter("@minimumQuantity", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, minimumQuantity)); sqlCommand.Parameters.Add(new SqlParameter("@marketCapitalization", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, marketCapitalization)); sqlCommand.Parameters.Add(new SqlParameter("@priceFactor", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, priceFactor)); sqlCommand.Parameters.Add(new SqlParameter("@quantityFactor", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, quantityFactor)); sqlCommand.Parameters.Add(new SqlParameter("@securityId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, securityId)); sqlCommand.Parameters.Add(new SqlParameter("@symbol", SqlDbType.NVarChar, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, symbol)); sqlCommand.Parameters.Add(new SqlParameter("@logo", SqlDbType.NVarChar, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, logo)); sqlCommand.Parameters.Add(new SqlParameter("@volumeCategoryId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, volumeCategoryId)); sqlCommand.ExecuteNonQuery(); // Return Statements return(securityRow.SecurityId); }
/// <summary>Archives a Object record.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit</param> /// <param name="RowVersion">The version number of this row.</param> /// <param name="objectId">The value for the ObjectId column.</param> /// <param name="archive">true to archive the object, false to unarchive it.</param> public static void Archive(AdoTransaction adoTransaction, SqlTransaction sqlTransaction, long rowVersion, int objectId) { // Accessor for the Object Table. ServerMarketData.ObjectDataTable objectTable = ServerMarketData.Object; // Rule #1: Make sure the record exists before updating it. ServerMarketData.ObjectRow objectRow = objectTable.FindByObjectId(objectId); if ((objectRow == null)) { throw new Exception(string.Format("The Object table does not have an element identified by {0}", objectId)); } // Rule #2: Optimistic Concurrency Check if ((objectRow.RowVersion != rowVersion)) { throw new System.Exception("This record is busy. Please try again later."); } // Archive the child records. for (int index = 0; (index < objectRow.GetAccountBaseRows().Length); index = (index + 1)) { ServerMarketData.AccountBaseRow childAccountBaseRow = objectRow.GetAccountBaseRows()[index]; AccountBase.ArchiveChildren(adoTransaction, sqlTransaction, childAccountBaseRow.RowVersion, childAccountBaseRow.AccountBaseId); } for (int index = 0; (index < objectRow.GetBlotterRows().Length); index = (index + 1)) { ServerMarketData.BlotterRow childBlotterRow = objectRow.GetBlotterRows()[index]; Blotter.ArchiveChildren(adoTransaction, sqlTransaction, childBlotterRow.RowVersion, childBlotterRow.BlotterId); } for (int index = 0; (index < objectRow.GetFolderRows().Length); index = (index + 1)) { ServerMarketData.FolderRow childFolderRow = objectRow.GetFolderRows()[index]; Folder.ArchiveChildren(adoTransaction, sqlTransaction, childFolderRow.RowVersion, childFolderRow.FolderId); } for (int index = 0; (index < objectRow.GetIssuerRows().Length); index = (index + 1)) { ServerMarketData.IssuerRow childIssuerRow = objectRow.GetIssuerRows()[index]; Issuer.ArchiveChildren(adoTransaction, sqlTransaction, childIssuerRow.RowVersion, childIssuerRow.IssuerId); } for (int index = 0; (index < objectRow.GetObjectTreeRowsByObjectObjectTreeChildId().Length); index = (index + 1)) { ServerMarketData.ObjectTreeRow childObjectTreeRow = objectRow.GetObjectTreeRowsByObjectObjectTreeChildId()[index]; ObjectTree.Archive(adoTransaction, sqlTransaction, childObjectTreeRow.RowVersion, childObjectTreeRow.ObjectTreeId); } for (int index = 0; (index < objectRow.GetObjectTreeRowsByObjectObjectTreeParentId().Length); index = (index + 1)) { ServerMarketData.ObjectTreeRow childObjectTreeRow = objectRow.GetObjectTreeRowsByObjectObjectTreeParentId()[index]; ObjectTree.Archive(adoTransaction, sqlTransaction, childObjectTreeRow.RowVersion, childObjectTreeRow.ObjectTreeId); } for (int index = 0; (index < objectRow.GetSecurityRows().Length); index = (index + 1)) { ServerMarketData.SecurityRow childSecurityRow = objectRow.GetSecurityRows()[index]; Security.ArchiveChildren(adoTransaction, sqlTransaction, childSecurityRow.RowVersion, childSecurityRow.SecurityId); } for (int index = 0; (index < objectRow.GetUserRows().Length); index = (index + 1)) { ServerMarketData.UserRow childUserRow = objectRow.GetUserRows()[index]; User.ArchiveChildren(adoTransaction, sqlTransaction, childUserRow.RowVersion, childUserRow.UserId); } // Increment the row version rowVersion = ServerMarketData.RowVersion.Increment(); // Delete the record in the ADO database. objectRow[objectTable.RowVersionColumn] = rowVersion; adoTransaction.DataRows.Add(objectRow); objectRow.Delete(); // Archive the record in the SQL database. SqlCommand sqlCommand = new SqlCommand("update \"Object\" set \"IsArchived\" = 1 where \"ObjectId\"=@objectId"); sqlCommand.Connection = sqlTransaction.Connection; sqlCommand.Transaction = sqlTransaction; sqlCommand.Parameters.Add(new SqlParameter("@objectId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, objectId)); sqlCommand.ExecuteNonQuery(); }
/// <summary>Loads a Security record using Metadata Parameters.</summary> /// <param name="transaction">Contains the parameters and exceptions for this command.</param> public new static void Load(ParameterList parameters) { // Accessor for the Security Table. ServerMarketData.SecurityDataTable securityTable = ServerMarketData.Security; // Extract the parameters from the command batch. AdoTransaction adoTransaction = parameters["adoTransaction"]; SqlTransaction sqlTransaction = parameters["sqlTransaction"]; object configurationId = parameters["configurationId"].Value; object description = parameters["description"].Value; object groupPermission = parameters["groupPermission"].Value; object hidden = parameters["hidden"].Value; string name = parameters["name"]; object owner = parameters["owner"].Value; object ownerPermission = parameters["ownerPermission"].Value; object readOnly = parameters["readOnly"].Value; object worldPermission = parameters["worldPermission"].Value; object averageDailyVolume = parameters["averageDailyVolume"].Value; string externalCountryId = parameters["countryId"]; object minimumQuantity = parameters["minimumQuantity"].Value; object marketCapitalization = parameters["marketCapitalization"].Value; decimal priceFactor = parameters["priceFactor"]; decimal quantityFactor = parameters["quantityFactor"]; string externalSecurityId = parameters["securityId"]; object symbol = parameters["symbol"].Value; object externalTypeCode = parameters["typeCode"].Value; object logo = parameters["logo"].Value; object externalVolumeCategoryId = parameters["volumeCategoryId"].Value; // The row versioning is largely disabled for external operations. The value is returned to the caller in the // event it's needed for operations within the batch. long rowVersion = long.MinValue; // Resolve External Identifiers int countryId = Country.FindRequiredKey(configurationId, "countryId", externalCountryId); int securityId = Object.FindKey(configurationId, "securityId", externalSecurityId); object typeCode = Type.FindOptionalKey(configurationId, "typeCode", externalTypeCode); object volumeCategoryId = VolumeCategory.FindOptionalKey(configurationId, "volumeCategoryId", externalVolumeCategoryId); ServerMarketData.SecurityRow securityRow = securityTable.FindBySecurityId(securityId); // The load operation will create a record if it doesn't exist, or update an existing record. The external // identifier is used to determine if a record exists with the same key. if ((securityRow == null)) { // Populate the 'externalId' varaibles so that the external identifier can be used to find the row when an // external method is called with the same 'configurationId' parameter. int externalKeyIndex = Security.GetExternalKeyIndex(configurationId, "securityId"); object[] externalIdArray = new object[8]; externalIdArray[externalKeyIndex] = externalSecurityId; object externalId0 = externalIdArray[0]; object externalId1 = externalIdArray[1]; object externalId2 = externalIdArray[2]; object externalId3 = externalIdArray[3]; object externalId4 = externalIdArray[4]; object externalId5 = externalIdArray[5]; object externalId6 = externalIdArray[6]; object externalId7 = externalIdArray[7]; // Call the internal method to complete the operation. MarkThree.Guardian.Core.Security.Insert(adoTransaction, sqlTransaction, ref rowVersion, description, externalId0, externalId1, externalId2, externalId3, externalId4, externalId5, externalId6, externalId7, groupPermission, hidden, name, owner, ownerPermission, readOnly, worldPermission, averageDailyVolume, countryId, minimumQuantity, marketCapitalization, priceFactor, quantityFactor, symbol, typeCode, logo, volumeCategoryId); } else { // While the optimistic concurrency checking is disabled for the external methods, the internal methods // still need to perform the check. This ncurrency checking logic by finding the current row version to be // will bypass the coused when the internal method is called. rowVersion = ((long)(securityRow[securityTable.RowVersionColumn])); // Call the internal method to complete the operation. MarkThree.Guardian.Core.Security.Update(adoTransaction, sqlTransaction, ref rowVersion, description, null, null, null, null, null, null, null, null, groupPermission, hidden, name, owner, ownerPermission, readOnly, worldPermission, averageDailyVolume, countryId, minimumQuantity, marketCapitalization, priceFactor, quantityFactor, securityId, symbol, typeCode, logo, volumeCategoryId); } // Return values. parameters["rowVersion"] = rowVersion; }
/// <summary> /// Generates random price movements. /// </summary> private static void MarketThread() { // Keep looping until the thread is terminated. while (true) { try { // Lock the tables. Debug.Assert(!ServerMarketData.AreLocksHeld); ServerMarketData.EquityLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.PriceLock.AcquireWriterLock(Timeout.Infinite); ServerMarketData.SecurityLock.AcquireReaderLock(Timeout.Infinite); // Pick a random security to move from the tax lot tables. This insures us that the ticks we get are // relative to the demo. int index = Random.Next(0, ServerMarketData.Equity.Rows.Count); ServerMarketData.EquityRow equityRow = ServerMarketData.Equity[index]; ServerMarketData.SecurityRow securityRow = equityRow.SecurityRowByFKSecurityEquityEquityId; // Find a price that matches the equity's default settlement. This is the price record that will be updated // with the simulated market conditions. ServerMarketData.PriceRow priceRow = ServerMarketData.Price.FindBySecurityIdCurrencyId(equityRow.EquityId, equityRow.SettlementId); if (priceRow == null) { continue; } // Randomly change the bid, last or asked price. switch (Random.Next(3)) { case 0: // The bid price is moved randomly away from the last price. decimal bidChange = (decimal)(Math.Round(Random.NextDouble() * 0.25, 2)); priceRow.RowVersion = ServerMarketData.RowVersion.Increment(); priceRow.BidPrice = priceRow.LastPrice - bidChange; priceRow.BidSize = (decimal)(Math.Round(Random.NextDouble() * 10.0, 0) * 100.0 + 100); break; case 1: // The price is moved randomly from one to 10 tenths of a percent. decimal randomPercent = (decimal)(Math.Round(Random.NextDouble() * 0.010, 3) - 0.005); priceRow.RowVersion = ServerMarketData.RowVersion.Increment(); priceRow.PriceChange = Math.Round(priceRow.LastPrice * randomPercent, 2); priceRow.LastPrice += priceRow.PriceChange; priceRow.LastSize = (decimal)(Math.Round(Random.NextDouble() * 10.0, 0) * 100.0 + 100); break; case 2: // The ask price is moved randomly away from the last price. decimal askChange = (decimal)(Math.Round(Random.NextDouble(), 2) * 0.25); priceRow.RowVersion = ServerMarketData.RowVersion.Increment(); priceRow.AskPrice = priceRow.LastPrice + askChange; priceRow.AskSize = (decimal)(Math.Round(Random.NextDouble() * 10.0, 0) * 100.0 + 100); break; } } catch (Exception exception) { // Write the error and stack trace out to the debug listener Debug.WriteLine(String.Format("{0}, {1}", exception.Message, exception.StackTrace)); } finally { // Release the global tables. if (ServerMarketData.EquityLock.IsReaderLockHeld) { ServerMarketData.EquityLock.ReleaseReaderLock(); } if (ServerMarketData.PriceLock.IsWriterLockHeld) { ServerMarketData.PriceLock.ReleaseWriterLock(); } if (ServerMarketData.SecurityLock.IsReaderLockHeld) { ServerMarketData.SecurityLock.ReleaseReaderLock(); } Debug.Assert(!ServerMarketData.AreLocksHeld); } // The controls how often the simulator picks another price. Thread.Sleep(Price.Timer); } }
/// <summary>ArchiveChildrens a Security record.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit</param> /// <param name="rowVersion">the version number of this row.</param> /// <param name="securityId">The value for the SecurityId column.</param> /// <param name="archive">true to archive the object, false to unarchive it.</param> internal static void ArchiveChildren(AdoTransaction adoTransaction, SqlTransaction sqlTransaction, long rowVersion, int securityId) { // Accessor for the Security Table. ServerMarketData.SecurityDataTable securityTable = ServerMarketData.Security; // This record can be used to iterate through all the children. ServerMarketData.SecurityRow securityRow = securityTable.FindBySecurityId(securityId); // Archive the child records. for (int index = 0; (index < securityRow.GetAccountBaseRows().Length); index = (index + 1)) { ServerMarketData.AccountBaseRow childAccountBaseRow = securityRow.GetAccountBaseRows()[index]; AccountBase.ArchiveChildren(adoTransaction, sqlTransaction, childAccountBaseRow.RowVersion, childAccountBaseRow.AccountBaseId); } for (int index = 0; (index < securityRow.GetAllocationRowsBySecurityAllocationSecurityId().Length); index = (index + 1)) { ServerMarketData.AllocationRow childAllocationRow = securityRow.GetAllocationRowsBySecurityAllocationSecurityId()[index]; Allocation.Archive(adoTransaction, sqlTransaction, childAllocationRow.RowVersion, childAllocationRow.AllocationId); } for (int index = 0; (index < securityRow.GetAllocationRowsBySecurityAllocationSettlementId().Length); index = (index + 1)) { ServerMarketData.AllocationRow childAllocationRow = securityRow.GetAllocationRowsBySecurityAllocationSettlementId()[index]; Allocation.Archive(adoTransaction, sqlTransaction, childAllocationRow.RowVersion, childAllocationRow.AllocationId); } for (int index = 0; (index < securityRow.GetCurrencyRows().Length); index = (index + 1)) { ServerMarketData.CurrencyRow childCurrencyRow = securityRow.GetCurrencyRows()[index]; Currency.ArchiveChildren(adoTransaction, sqlTransaction, childCurrencyRow.RowVersion, childCurrencyRow.CurrencyId); } for (int index = 0; (index < securityRow.GetDebtRowsBySecurityDebtDebtId().Length); index = (index + 1)) { ServerMarketData.DebtRow childDebtRow = securityRow.GetDebtRowsBySecurityDebtDebtId()[index]; Debt.ArchiveChildren(adoTransaction, sqlTransaction, childDebtRow.RowVersion, childDebtRow.DebtId); } for (int index = 0; (index < securityRow.GetDebtRowsBySecurityDebtSettlementId().Length); index = (index + 1)) { ServerMarketData.DebtRow childDebtRow = securityRow.GetDebtRowsBySecurityDebtSettlementId()[index]; Debt.ArchiveChildren(adoTransaction, sqlTransaction, childDebtRow.RowVersion, childDebtRow.DebtId); } for (int index = 0; (index < securityRow.GetEquityRowsBySecurityEquityEquityId().Length); index = (index + 1)) { ServerMarketData.EquityRow childEquityRow = securityRow.GetEquityRowsBySecurityEquityEquityId()[index]; Equity.ArchiveChildren(adoTransaction, sqlTransaction, childEquityRow.RowVersion, childEquityRow.EquityId); } for (int index = 0; (index < securityRow.GetEquityRowsBySecurityEquitySettlementId().Length); index = (index + 1)) { ServerMarketData.EquityRow childEquityRow = securityRow.GetEquityRowsBySecurityEquitySettlementId()[index]; Equity.ArchiveChildren(adoTransaction, sqlTransaction, childEquityRow.RowVersion, childEquityRow.EquityId); } for (int index = 0; (index < securityRow.GetPositionRows().Length); index = (index + 1)) { ServerMarketData.PositionRow childPositionRow = securityRow.GetPositionRows()[index]; Position.Archive(adoTransaction, sqlTransaction, childPositionRow.RowVersion, childPositionRow.AccountId, childPositionRow.SecurityId, childPositionRow.PositionTypeCode); } for (int index = 0; (index < securityRow.GetPriceRows().Length); index = (index + 1)) { ServerMarketData.PriceRow childPriceRow = securityRow.GetPriceRows()[index]; Price.Archive(adoTransaction, sqlTransaction, childPriceRow.RowVersion, childPriceRow.SecurityId); } for (int index = 0; (index < securityRow.GetSourceOrderRowsBySecuritySourceOrderSecurityId().Length); index = (index + 1)) { ServerMarketData.SourceOrderRow childSourceOrderRow = securityRow.GetSourceOrderRowsBySecuritySourceOrderSecurityId()[index]; SourceOrder.Archive(adoTransaction, sqlTransaction, childSourceOrderRow.RowVersion, childSourceOrderRow.SourceOrderId); } for (int index = 0; (index < securityRow.GetSourceOrderRowsBySecuritySourceOrderSettlementId().Length); index = (index + 1)) { ServerMarketData.SourceOrderRow childSourceOrderRow = securityRow.GetSourceOrderRowsBySecuritySourceOrderSettlementId()[index]; SourceOrder.Archive(adoTransaction, sqlTransaction, childSourceOrderRow.RowVersion, childSourceOrderRow.SourceOrderId); } for (int index = 0; (index < securityRow.GetTaxLotRows().Length); index = (index + 1)) { ServerMarketData.TaxLotRow childTaxLotRow = securityRow.GetTaxLotRows()[index]; TaxLot.Archive(adoTransaction, sqlTransaction, childTaxLotRow.RowVersion, childTaxLotRow.TaxLotId); } for (int index = 0; (index < securityRow.GetWorkingOrderRowsBySecurityWorkingOrderSecurityId().Length); index = (index + 1)) { ServerMarketData.WorkingOrderRow childWorkingOrderRow = securityRow.GetWorkingOrderRowsBySecurityWorkingOrderSecurityId()[index]; WorkingOrder.Archive(adoTransaction, sqlTransaction, childWorkingOrderRow.RowVersion, childWorkingOrderRow.WorkingOrderId); } for (int index = 0; (index < securityRow.GetWorkingOrderRowsBySecurityWorkingOrderSettlementId().Length); index = (index + 1)) { ServerMarketData.WorkingOrderRow childWorkingOrderRow = securityRow.GetWorkingOrderRowsBySecurityWorkingOrderSettlementId()[index]; WorkingOrder.Archive(adoTransaction, sqlTransaction, childWorkingOrderRow.RowVersion, childWorkingOrderRow.WorkingOrderId); } // Increment the row version rowVersion = ServerMarketData.RowVersion.Increment(); // Delete the record in the ADO database. securityRow[securityTable.RowVersionColumn] = rowVersion; adoTransaction.DataRows.Add(securityRow); securityRow.Delete(); // Archive the record in the SQL database. SqlCommand sqlCommand = new SqlCommand("update \"Security\" set \"IsArchived\" = 1 where \"SecurityId\"=@securityId"); sqlCommand.Connection = sqlTransaction.Connection; sqlCommand.Transaction = sqlTransaction; sqlCommand.Parameters.Add(new SqlParameter("@securityId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, securityId)); sqlCommand.ExecuteNonQuery(); }
/// <summary>Updates a Security record.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit</param> /// <param name="rowVersion">The version number of the row</param> /// <param name="description">The value for the Description column.</param> /// <param name="externalId0">The value for the ExternalId0 column.</param> /// <param name="externalId1">The value for the ExternalId1 column.</param> /// <param name="externalId2">The value for the ExternalId2 column.</param> /// <param name="externalId3">The value for the ExternalId3 column.</param> /// <param name="externalId4">The value for the ExternalId4 column.</param> /// <param name="externalId5">The value for the ExternalId5 column.</param> /// <param name="externalId6">The value for the ExternalId6 column.</param> /// <param name="externalId7">The value for the ExternalId7 column.</param> /// <param name="groupPermission">The value for the GroupPermission column.</param> /// <param name="hidden">The value for the Hidden column.</param> /// <param name="name">The value for the Name column.</param> /// <param name="owner">The value for the Owner column.</param> /// <param name="ownerPermission">The value for the OwnerPermission column.</param> /// <param name="readOnly">The value for the ReadOnly column.</param> /// <param name="worldPermission">The value for the WorldPermission column.</param> /// <param name="averageDailyVolume">The value for the AverageDailyVolume column.</param> /// <param name="countryId">The value for the CountryId column.</param> /// <param name="minimumQuantity">The value for the MinimumQuantity column.</param> /// <param name="marketCapitalization">The value for the MarketCapitalization column.</param> /// <param name="priceFactor">The value for the PriceFactor column.</param> /// <param name="quantityFactor">The value for the QuantityFactor column.</param> /// <param name="securityId">The value for the SecurityId column.</param> /// <param name="symbol">The value for the Symbol column.</param> /// <param name="typeCode">The value for the TypeCode column.</param> /// <param name="logo">The value for the Logo column.</param> /// <param name="volumeCategoryId">The value for the VolumeCategoryId column.</param> public static void Update( AdoTransaction adoTransaction, SqlTransaction sqlTransaction, ref long rowVersion, object description, object externalId0, object externalId1, object externalId2, object externalId3, object externalId4, object externalId5, object externalId6, object externalId7, object groupPermission, object hidden, object name, object owner, object ownerPermission, object readOnly, object worldPermission, object averageDailyVolume, object countryId, object minimumQuantity, object marketCapitalization, object priceFactor, object quantityFactor, int securityId, object symbol, object typeCode, object logo, object volumeCategoryId) { // Accessor for the Security Table. ServerMarketData.SecurityDataTable securityTable = ServerMarketData.Security; // Rule #1: Make sure the record exists before updating it. ServerMarketData.SecurityRow securityRow = securityTable.FindBySecurityId(securityId); if ((securityRow == null)) { throw new Exception(string.Format("The Security table does not have an element identified by {0}", securityId)); } // Rule #2: Optimistic Concurrency Check if ((securityRow.RowVersion != rowVersion)) { throw new System.Exception("This record is busy. Please try again later."); } // Apply Defaults if ((averageDailyVolume == null)) { averageDailyVolume = securityRow[securityTable.AverageDailyVolumeColumn]; } if ((countryId == null)) { countryId = securityRow[securityTable.CountryIdColumn]; } if ((minimumQuantity == null)) { minimumQuantity = securityRow[securityTable.MinimumQuantityColumn]; } if ((marketCapitalization == null)) { marketCapitalization = securityRow[securityTable.MarketCapitalizationColumn]; } if ((priceFactor == null)) { priceFactor = securityRow[securityTable.PriceFactorColumn]; } if ((quantityFactor == null)) { quantityFactor = securityRow[securityTable.QuantityFactorColumn]; } if ((symbol == null)) { symbol = securityRow[securityTable.SymbolColumn]; } if ((logo == null)) { logo = securityRow[securityTable.LogoColumn]; } if ((volumeCategoryId == null)) { volumeCategoryId = securityRow[securityTable.VolumeCategoryIdColumn]; } // Insert the base members using the base class. Note that optimistic concurrency is only used // by the top level type in the hierarchy, it is bypassed after you pass the first test. long baseRowVersion = securityRow.ObjectRow.RowVersion; Object.Update(adoTransaction, sqlTransaction, ref baseRowVersion, description, externalId0, externalId1, externalId2, externalId3, externalId4, externalId5, externalId6, externalId7, groupPermission, hidden, name, securityId, owner, ownerPermission, readOnly, typeCode, worldPermission); // Increment the row version rowVersion = ServerMarketData.RowVersion.Increment(); // Update the record in the ADO database. securityRow[securityTable.RowVersionColumn] = rowVersion; securityRow[securityTable.AverageDailyVolumeColumn] = averageDailyVolume; securityRow[securityTable.CountryIdColumn] = countryId; securityRow[securityTable.MinimumQuantityColumn] = minimumQuantity; securityRow[securityTable.MarketCapitalizationColumn] = marketCapitalization; securityRow[securityTable.PriceFactorColumn] = priceFactor; securityRow[securityTable.QuantityFactorColumn] = quantityFactor; securityRow[securityTable.SymbolColumn] = symbol; securityRow[securityTable.LogoColumn] = logo; securityRow[securityTable.VolumeCategoryIdColumn] = volumeCategoryId; adoTransaction.DataRows.Add(securityRow); // Update the record in the SQL database. SqlCommand sqlCommand = new SqlCommand(@"update ""Security"" set ""RowVersion""=@rowVersion,""AverageDailyVolume""=@averageDailyVolume,""CountryId""=@countryId,""MinimumQuantity""=@minimumQuantity,""MarketCapitalization""=@marketCapitalization,""PriceFactor""=@priceFactor,""QuantityFactor""=@quantityFactor,""Symbol""=@symbol,""Logo""=@logo,""VolumeCategoryId""=@volumeCategoryId where ""SecurityId""=@securityId"); sqlCommand.Connection = sqlTransaction.Connection; sqlCommand.Transaction = sqlTransaction; sqlCommand.Parameters.Add(new SqlParameter("@rowVersion", SqlDbType.BigInt, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, rowVersion)); sqlCommand.Parameters.Add(new SqlParameter("@averageDailyVolume", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, averageDailyVolume)); sqlCommand.Parameters.Add(new SqlParameter("@countryId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, countryId)); sqlCommand.Parameters.Add(new SqlParameter("@minimumQuantity", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, minimumQuantity)); sqlCommand.Parameters.Add(new SqlParameter("@marketCapitalization", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, marketCapitalization)); sqlCommand.Parameters.Add(new SqlParameter("@priceFactor", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, priceFactor)); sqlCommand.Parameters.Add(new SqlParameter("@quantityFactor", SqlDbType.Decimal, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, quantityFactor)); sqlCommand.Parameters.Add(new SqlParameter("@securityId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, securityId)); sqlCommand.Parameters.Add(new SqlParameter("@symbol", SqlDbType.NVarChar, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, symbol)); sqlCommand.Parameters.Add(new SqlParameter("@logo", SqlDbType.NVarChar, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, logo)); sqlCommand.Parameters.Add(new SqlParameter("@volumeCategoryId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, volumeCategoryId)); // Update the record in the SQL database. sqlCommand.ExecuteNonQuery(); }
/// <summary>Inserts a SourceOrder record using Metadata Parameters.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit.</param> /// <param name="remoteMethod">Contains the metadata parameters and exceptions for this command.</param> public static void Insert(ParameterList parameters) { // Accessor for the SourceOrder Table. ServerMarketData.SourceOrderDataTable sourceOrderTable = ServerMarketData.SourceOrder; // Extract the parameters from the command batch. AdoTransaction adoTransaction = parameters["adoTransaction"]; SqlTransaction sqlTransaction = parameters["sqlTransaction"]; object blotterId = parameters["blotterId"].Value; object configurationId = parameters["configurationId"].Value; object destinationId = parameters["destinationId"].Value; object externalBlotterId = parameters["blotterId"].Value; object externalSourceOrderId = parameters["sourceOrderId"].Value; object externalDestinationId = parameters["destinationId"].Value; object externalId0 = parameters["externalId0"].Value; object isAdvertised = parameters["isAdvertised"].Value; object isAgencyMatch = parameters["isAgencyMatch"].Value; object isBrokerMatch = parameters["isBrokerMatch"].Value; object isCanceled = parameters["isCanceled"].Value; object isSteppedIn = parameters["isSteppedIn"].Value; object isHedgeMatch = parameters["isHedgeMatch"].Value; object isHeld = parameters["isHeld"].Value; object isInstitutionMatch = parameters["isInstitutionMatch"].Value; object limitPrice = parameters["limitPrice"].Value; object maximumVolatility = parameters["maximumVolatility"].Value; object newsFreeTime = parameters["newsFreeTime"].Value; System.Decimal orderedQuantity = parameters["orderedQuantity"]; int orderTypeCode = parameters["orderTypeCode"]; int priceTypeCode = parameters["priceTypeCode"]; object receivedTime = parameters["receivedTime"].Value; string externalSecurityId = parameters["securityId"]; string externalSettlementId = parameters["settlementId"]; object workingOrderId = parameters["workingOrderId"].Value; object startTime = parameters["startTime"].Value; object stopTime = parameters["stopTime"].Value; object stopPrice = parameters["stopPrice"].Value; object submissionTypeCode = parameters["submissionTypeCode"].Value; object submittedQuantity = parameters["submittedQuantity"].Value; object targetPrice = parameters["targetPrice"].Value; int timeInForceCode = parameters["timeInForceCode"]; object uploadedTime = parameters["uploadedTime"].Value; object externalWorkingOrderId = parameters["workingOrderId"].Value; // Look up the external values. int securityId = External.Security.FindRequiredKey("US TICKER", "securityId", externalSecurityId); int settlementId = External.Security.FindRequiredKey("US TICKER", "settlementId", externalSettlementId); // This will get the row version of the newly added Source Order. long rowVersion = long.MinValue; // Time stamps and user stamps DateTime currentTime = DateTime.Now; int createdUserId = ServerMarketData.UserId; DateTime createdTime = DateTime.Now; int modifiedUserId = ServerMarketData.UserId; DateTime modifiedTime = DateTime.Now; int statusCode = Status.New; // The Trader table contains additional defaults for incoming orders. int traderId = ServerMarketData.UserId; ServerMarketData.TraderRow traderRow = ServerMarketData.Trader.FindByTraderId(traderId); if (isAgencyMatch == null) { isAgencyMatch = traderRow.IsAgencyMatch; } if (isBrokerMatch == null) { isBrokerMatch = traderRow.IsBrokerMatch; } if (isHedgeMatch == null) { isHedgeMatch = traderRow.IsHedgeMatch; } if (isInstitutionMatch == null) { isInstitutionMatch = traderRow.IsInstitutionMatch; } if (maximumVolatility == null && !traderRow.IsMaximumVolatilityDefaultNull()) { maximumVolatility = traderRow.MaximumVolatilityDefault; } if (startTime == null && !traderRow.IsStartTimeDefaultNull()) { startTime = traderRow.StartTimeDefault; } if (stopTime == null && !traderRow.IsStopTimeDefaultNull()) { stopTime = traderRow.StopTimeDefault; } if (newsFreeTime == null && !traderRow.IsNewsFreeTimeDefaultNull()) { newsFreeTime = traderRow.NewsFreeTimeDefault; } // Rule #1 - Blotter must be specified if the working order is not specified. if (blotterId == null && workingOrderId == null) { throw new Exception("Either a blotter or a Working Order must be specified as a location for this Order"); } // If the incoming order specified a submitted quantity, then automatically enter the order into the cross. if (submissionTypeCode == null) { submissionTypeCode = SubmissionType.NeverMatch; } object submittedTime = null; if ((int)submissionTypeCode != SubmissionType.NeverMatch) { submittedTime = DateTime.Now; if (submittedQuantity == null) { submittedQuantity = orderedQuantity; } } // Update the rowversion of the object associated with this trade. ServerMarketData.SecurityRow securityRow = ServerMarketData.Security.FindBySecurityId(securityId); if (securityRow != null) { foreach (ServerMarketData.EquityRow equityRow in securityRow.GetEquityRowsBySecurityEquityEquityId()) { long equityRowVersion = equityRow.RowVersion; Core.Equity.Update(adoTransaction, sqlTransaction, ref equityRowVersion, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, equityRow.EquityId, null, null, null, null, null, null, null); } foreach (ServerMarketData.PriceRow priceRow in securityRow.GetPriceRows()) { long priceRowVersion = priceRow.RowVersion; Core.Price.Update(adoTransaction, sqlTransaction, ref priceRowVersion, null, null, null, null, null, null, null, null, null, null, null, null, priceRow.SecurityId, null, null); } } ServerMarketData.SecurityRow settlementRow = ServerMarketData.Security.FindBySecurityId(settlementId); if (settlementRow != null) { foreach (ServerMarketData.CurrencyRow currencyRow in settlementRow.GetCurrencyRows()) { long currencyRowVersion = currencyRow.RowVersion; Core.Currency.Update(adoTransaction, sqlTransaction, ref currencyRowVersion, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, currencyRow.CurrencyId, null, null, null); } } // An order can be automatically associated with a working order if the working order is specified when the order is // created. if (workingOrderId == null) { long timerRowVersion = long.MinValue; int timerId = Core.Timer.Insert(adoTransaction, sqlTransaction, ref timerRowVersion, currentTime, null, false, currentTime, 0); workingOrderId = Core.WorkingOrder.Insert(adoTransaction, sqlTransaction, ref rowVersion, null, (int)blotterId, createdTime, createdUserId, destinationId, null, isAgencyMatch, null, true, isBrokerMatch, isHedgeMatch, isInstitutionMatch, limitPrice, maximumVolatility, modifiedTime, modifiedUserId, newsFreeTime, orderTypeCode, priceTypeCode, securityId, settlementId, startTime, statusCode, stopPrice, stopTime, (int)submissionTypeCode, submittedQuantity, submittedTime, timeInForceCode, timerId, null); } // Call the internal method to complete the operation. MarkThree.Guardian.Core.SourceOrder.Insert(adoTransaction, sqlTransaction, ref rowVersion, createdTime, createdUserId, destinationId, externalId0, isAdvertised, isHeld, isCanceled, isHeld, isSteppedIn, submissionTypeCode, limitPrice, maximumVolatility, modifiedTime, modifiedUserId, newsFreeTime, orderTypeCode, orderedQuantity, priceTypeCode, receivedTime, securityId, settlementId, startTime, statusCode, stopPrice, stopTime, submittedQuantity, submittedTime, targetPrice, timeInForceCode, (int)workingOrderId); // Return values. parameters["rowVersion"] = rowVersion; }
/// <summary>Inserts a SourceOrder record using Metadata Parameters.</summary> /// <param name="transaction">Commits or rejects a set of commands as a unit.</param> /// <param name="remoteMethod">Contains the metadata parameters and exceptions for this command.</param> public static void InsertFile(ParameterList parameters) { // Accessor for the SourceOrder Table. ServerMarketData.SourceOrderDataTable sourceOrderTable = ServerMarketData.SourceOrder; // Extract the parameters from the command batch. AdoTransaction adoTransaction = parameters["adoTransaction"]; SqlTransaction sqlTransaction = parameters["sqlTransaction"]; object configurationId = parameters["configurationId"].Value; object externalBlotterId = parameters["blotterId"].Value; object externalSourceOrderId = parameters["sourceOrderId"].Value; object externalDestinationId = parameters["destinationId"].Value; object externalId0 = parameters["externalId0"].Value; object isAdvertised = parameters["isAdvertised"].Value; object isCanceled = parameters["isCanceled"].Value; object isSteppedIn = parameters["isSteppedIn"].Value; object limitPrice = parameters["limitPrice"].Value; System.Decimal orderedQuantity = parameters["orderedQuantity"]; string externalOrderTypeCode = parameters["orderTypeCode"]; string externalPriceTypeCode = parameters["priceTypeCode"]; object receivedTime = parameters["receivedTime"].Value; string externalSecurityId = parameters["securityId"]; string externalSettlementId = parameters["settlementId"]; object stopPrice = parameters["stopPrice"].Value; object targetPrice = parameters["targetPrice"].Value; object externalSubmissionTypeCode = parameters["submissionTypeCode"].Value; string externalTimeInForceCode = parameters["timeInForceCode"]; object uploadedTime = parameters["uploadedTime"].Value; object externalWorkingOrderId = parameters["workingOrderId"].Value; // The row versioning is largely disabled for external operations. The value is returned to the caller in the // event it's needed for operations within the batch. long rowVersion = long.MinValue; // Resolve External Identifiers object blotterId = External.Blotter.FindOptionalKey(configurationId, "blotterId", externalBlotterId); int sourceOrderId = External.SourceOrder.FindKey(configurationId, "sourceOrderId", (string)externalSourceOrderId); int orderTypeCode = External.OrderType.FindRequiredKey(configurationId, "orderTypeCode", externalOrderTypeCode); object destinationId = External.Destination.FindOptionalKey(configurationId, "destinationId", externalDestinationId); int priceTypeCode = External.PriceType.FindRequiredKey(configurationId, "priceTypeCode", externalPriceTypeCode); int securityId = External.Security.FindRequiredKey(configurationId, "securityId", externalSecurityId); int settlementId = External.Security.FindRequiredKey(configurationId, "settlementId", externalSettlementId); int timeInForceCode = External.TimeInForce.FindRequiredKey(configurationId, "timeInForceCode", externalTimeInForceCode); object submissionTypeCode = External.SubmissionType.FindOptionalKey(configurationId, "submissionTypeCode", externalSubmissionTypeCode); object workingOrderId = External.WorkingOrder.FindOptionalKey(configurationId, "workingOrderId", externalWorkingOrderId); // Optional Parameters object canceledQuantity = parameters["canceledQuantity"] is MissingParameter ? (object)null : Convert.ToDecimal(parameters["canceledQuantity"].Value); object isAgencyMatch = parameters["isAgencyMatch"] is MissingParameter ? (object)null : Convert.ToBoolean(parameters["isAgencyMatch"].Value); object isBrokerMatch = parameters["isBrokerMatch"] is MissingParameter ? (object)null : Convert.ToBoolean(parameters["isBrokerMatch"].Value); object isHedgeMatch = parameters["isHedgeMatch"] is MissingParameter ? (object)null : Convert.ToBoolean(parameters["isHedgeMatch"].Value); object isHeld = parameters["isHeld"] is MissingParameter ? (object)null : Convert.ToBoolean(parameters["isHeld"].Value); object isInstitutionMatch = parameters["isInstitutionMatch"] is MissingParameter ? (object)null : Convert.ToBoolean(parameters["isInstitutionMatch"].Value); object specifiedLimit = parameters["specifiedLimit"] is MissingParameter ? (object)null : Convert.ToDecimal(parameters["specifiedLimit"].Value); object maximumVolatility = parameters["maximumVolatility"] is MissingParameter ? (object)null : Convert.ToDecimal(parameters["maximumVolatility"].Value); object submittedQuantity = parameters["submittedQuantity"] is MissingParameter ? (object)null : Convert.ToDecimal(parameters["submittedQuantity"].Value); object startTime = parameters["startTime"] is MissingParameter ? (object)null : Convert.ToDateTime(parameters["startTime"].Value); object stopTime = parameters["stopTime"] is MissingParameter ? (object)null : Convert.ToDateTime(parameters["stopTime"].Value); object newsFreeTime = parameters["newsFreeTime"] is MissingParameter ? (object)null : Convert.ToInt32(parameters["newsFreeTime"].Value); // Time stamps and user stamps int createdUserId = ServerMarketData.UserId; DateTime createdTime = DateTime.Now; int modifiedUserId = ServerMarketData.UserId; DateTime modifiedTime = DateTime.Now; int statusCode = Status.New; // The Trader table contains additional defaults for incoming orders. int traderId = ServerMarketData.UserId; ServerMarketData.TraderRow traderRow = ServerMarketData.Trader.FindByTraderId(traderId); if (isAgencyMatch == null) { isAgencyMatch = traderRow.IsAgencyMatch; } if (isBrokerMatch == null) { isBrokerMatch = traderRow.IsBrokerMatch; } if (isHedgeMatch == null) { isHedgeMatch = traderRow.IsHedgeMatch; } if (isInstitutionMatch == null) { isInstitutionMatch = traderRow.IsInstitutionMatch; } if (maximumVolatility == null && !traderRow.IsMaximumVolatilityDefaultNull()) { maximumVolatility = traderRow.MaximumVolatilityDefault; } if (startTime == null && !traderRow.IsStartTimeDefaultNull()) { startTime = traderRow.StartTimeDefault; } if (stopTime == null && !traderRow.IsStopTimeDefaultNull()) { stopTime = traderRow.StopTimeDefault; } if (newsFreeTime == null && !traderRow.IsNewsFreeTimeDefaultNull()) { newsFreeTime = traderRow.NewsFreeTimeDefault; } // Rule #1 - Blotter must be specified if the working order is not specified. if (blotterId == null && workingOrderId == null) { throw new Exception("Either a blotter or a Working Order must be specified as a location for this Order"); } // If the incoming order specified a submitted quantity, then automatically enter the order into the cross. if (submissionTypeCode == null) { submissionTypeCode = SubmissionType.NeverMatch; } object submittedTime = null; if ((int)submissionTypeCode != SubmissionType.NeverMatch) { submittedTime = DateTime.Now; if (submittedQuantity == null) { submittedQuantity = orderedQuantity; } } // Update the rowversion of the object associated with this trade. ServerMarketData.SecurityRow securityRow = ServerMarketData.Security.FindBySecurityId(securityId); if (securityRow != null) { foreach (ServerMarketData.EquityRow equityRow in securityRow.GetEquityRowsBySecurityEquityEquityId()) { long equityRowVersion = equityRow.RowVersion; Core.Equity.Update(adoTransaction, sqlTransaction, ref equityRowVersion, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, equityRow.EquityId, null, null, null, null, null, null, null); } foreach (ServerMarketData.PriceRow priceRow in securityRow.GetPriceRows()) { long priceRowVersion = priceRow.RowVersion; Core.Price.Update(adoTransaction, sqlTransaction, ref priceRowVersion, null, null, null, null, null, null, null, null, null, null, null, null, priceRow.SecurityId, null, null); } } ServerMarketData.SecurityRow settlementRow = ServerMarketData.Security.FindBySecurityId(settlementId); if (settlementRow != null) { foreach (ServerMarketData.CurrencyRow currencyRow in settlementRow.GetCurrencyRows()) { long currencyRowVersion = currencyRow.RowVersion; Core.Currency.Update(adoTransaction, sqlTransaction, ref currencyRowVersion, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, currencyRow.CurrencyId, null, null, null); } } // An order can be automatically associated with a working order if the working order is specified when the order is // created. if (workingOrderId == null) { long timerRowVersion = long.MinValue; DateTime currentTime = DateTime.Now; int timerId = Core.Timer.Insert(adoTransaction, sqlTransaction, ref timerRowVersion, currentTime, null, false, currentTime, 0); workingOrderId = Core.WorkingOrder.Insert(adoTransaction, sqlTransaction, ref rowVersion, null, (int)blotterId, createdTime, createdUserId, destinationId, null, isAgencyMatch, null, true, isBrokerMatch, isHedgeMatch, isInstitutionMatch, limitPrice, maximumVolatility, modifiedTime, modifiedUserId, newsFreeTime, orderTypeCode, priceTypeCode, securityId, settlementId, startTime, statusCode, stopPrice, stopTime, (int)submissionTypeCode, submittedQuantity, submittedTime, timeInForceCode, timerId, null); } // The load operation will create a record if it doesn't exist, or update an existing record. The external // identifier is used to determine if a record exists with the same key. if (sourceOrderId == int.MinValue) { // Populate the 'externalId' varaibles so that the external identifier can be used to find the row when an // external method is called with the same 'configurationId' parameter. int externalKeyIndex = External.SourceOrder.GetExternalKeyIndex(configurationId, "sourceOrderId"); object[] externalIdArray = new object[1]; externalIdArray[externalKeyIndex] = externalSourceOrderId; externalId0 = externalIdArray[0]; // Call the internal method to complete the operation. MarkThree.Guardian.Core.SourceOrder.Insert(adoTransaction, sqlTransaction, ref rowVersion, createdTime, createdUserId, destinationId, externalId0, isAdvertised, isHeld, isCanceled, isHeld, isSteppedIn, submissionTypeCode, limitPrice, maximumVolatility, modifiedTime, modifiedUserId, newsFreeTime, orderTypeCode, orderedQuantity, priceTypeCode, receivedTime, securityId, settlementId, startTime, statusCode, stopPrice, stopTime, submittedQuantity, submittedTime, targetPrice, timeInForceCode, (int)workingOrderId); } else { // While the optimistic concurrency checking is disabled for the external methods, the internal methods // still need to perform the check. This ncurrency checking logic by finding the current row version to be // will bypass the coused when the internal method is called. ServerMarketData.SourceOrderRow sourceOrderRow = sourceOrderTable.FindBySourceOrderId((int)sourceOrderId); rowVersion = ((long)(sourceOrderRow[sourceOrderTable.RowVersionColumn])); // Call the internal method to complete the operation. MarkThree.Guardian.Core.SourceOrder.Update(adoTransaction, sqlTransaction, ref rowVersion, createdTime, createdUserId, (int)sourceOrderId, destinationId, stopTime, externalId0, isAdvertised, isHeld, isCanceled, isHeld, isSteppedIn, submissionTypeCode, limitPrice, maximumVolatility, modifiedTime, modifiedUserId, newsFreeTime, orderTypeCode, orderedQuantity, priceTypeCode, receivedTime, securityId, settlementId, startTime, statusCode, stopPrice, submittedQuantity, submittedTime, targetPrice, timeInForceCode, workingOrderId); } // Return values. parameters["rowVersion"] = rowVersion; }
/// <summary> /// Loads a DataSet from the XML file defined by symbolFilepath. Iterates through each (configurationId, equityId) pair /// and adds the ticker symbol to the eSignal Data Manager watch list. /// </summary> private static void LoadSymbols() { try { // Lock the tables. // Acquire the configuration and object locks for the securityId lookup Debug.Assert(!ServerMarketData.IsLocked); ServerMarketData.SecurityLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.EquityLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.ObjectLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.ConfigurationLock.AcquireReaderLock(Timeout.Infinite); // initialize the dataset from the XMl file DataSet dataSetFromXML = new DataSet("SP500"); dataSetFromXML.ReadXml(symbolFilepath, XmlReadMode.InferSchema); foreach (DataRow dataRow in dataSetFromXML.Tables["method"].Rows) { // extract the configurationId and the externalEquityId from the dataset object configurationId = dataRow["configurationId"]; string externalEquityId = (string)dataRow["equityId"]; try { // look up the equityId int equityId = (int)Security.FindOptionalKey(configurationId, "equityId", externalEquityId); // get the equity row ServerMarketData.EquityRow equityRow = ServerMarketData.Equity.FindByEquityId(equityId); if (equityRow != null) { // Get the security row from the equity row ServerMarketData.SecurityRow securityRow = equityRow.SecurityRowBySecurityEquityEquityId; // attempt to add the symbol to the eSignal data manager if (eSignal.AddRealTimeSymbol(securityRow.Symbol)) { symbolToSecurityIdTable[securityRow.Symbol] = securityRow.SecurityId; } else { MarkThree.EventLog.Warning("Market Data Service has no data for ticker {0}", externalEquityId); } } } catch (Exception exception) { // Write the error to the log. MarkThree.EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } } // Mark the time that the real-time updates started. MarkThree.EventLog.Information("Real Time Symbols Loaded"); } catch (Exception exception) { eSignal = null; // Write the error and stack trace out to the debug listener MarkThree.EventLog.Warning(String.Format("{0}, {1}", exception.Message, exception.StackTrace)); } finally { // Release the global tables. //if (ServerMarketData.PriceLock.IsWriterLockHeld) ServerMarketData.PriceLock.ReleaseWriterLock(); if (ServerMarketData.SecurityLock.IsReaderLockHeld) { ServerMarketData.SecurityLock.ReleaseReaderLock(); } if (ServerMarketData.EquityLock.IsReaderLockHeld) { ServerMarketData.EquityLock.ReleaseReaderLock(); } if (ServerMarketData.ObjectLock.IsReaderLockHeld) { ServerMarketData.ObjectLock.ReleaseReaderLock(); } if (ServerMarketData.ConfigurationLock.IsReaderLockHeld) { ServerMarketData.ConfigurationLock.ReleaseReaderLock(); } Debug.Assert(!ServerMarketData.IsLocked); } }
public static void OnUpdateSymbolDM(object wrapper, DMUpdateSymbolArgs args) { // StockInfo object holding the new symbol data for this update StockInfo stockInfo = args.stockInfo; try { // Lock the tables. Debug.Assert(!ServerMarketData.IsLocked); ServerMarketData.EquityLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.PriceLock.AcquireWriterLock(Timeout.Infinite); ServerMarketData.SecurityLock.AcquireReaderLock(Timeout.Infinite); // make sure the symbol is in the hash table - and that we added it to the data manager if (!symbolToSecurityIdTable.ContainsKey(stockInfo.Symbol)) { throw new Exception("Received update for unknown symbol: " + stockInfo.Symbol); } // get the security id of the symbol int securityID = (int)symbolToSecurityIdTable[stockInfo.Symbol]; // get the security row ServerMarketData.SecurityRow securityRow = ServerMarketData.Security.FindBySecurityId(securityID); if (securityRow == null) { throw new Exception("Warning: Could not find security row for symbol: " + stockInfo.Symbol); } //int equityId = Security.FindRequiredKey(configurationId, "equityId", externalEquityId); // Only Equities are priced by this simulator. All others are ignored. ServerMarketData.EquityRow equityRow = ServerMarketData.Equity.FindByEquityId(securityRow.SecurityId); if (equityRow != null) { // Find a price that matches the equity's default settlement. This is the price record that will be updated // with the simulated market conditions. ServerMarketData.PriceRow priceRow = ServerMarketData.Price.FindBySecurityId(securityRow.SecurityId); if (priceRow == null) { priceRow = ServerMarketData.Price.NewPriceRow(); //priceRow.RowVersion = ServerMarketData.RowVersion.Increment(); priceRow.SecurityId = equityRow.EquityId; priceRow.CurrencyId = equityRow.SettlementId; priceRow.LastPrice = 0.0M; priceRow.AskPrice = 0.0M; priceRow.BidPrice = 0.0M; priceRow.Volume = 0.0M; priceRow.ClosePrice = 0.0M; priceRow.VolumeWeightedAveragePrice = 0.0M; priceRow.HighPrice = 0.0M; priceRow.LowPrice = 0.0M; ServerMarketData.Price.AddPriceRow(priceRow); } // set the new values from the real time event into the price row priceRow.BidSize = stockInfo.BidSize; priceRow.BidPrice = Convert.ToDecimal(stockInfo.BidPrice); priceRow.AskPrice = Convert.ToDecimal(stockInfo.AskPrice); priceRow.AskSize = Convert.ToDecimal(stockInfo.AskSize); priceRow.LastPrice = Convert.ToDecimal(stockInfo.LastPrice); priceRow.LastSize = stockInfo.TradeVolume; priceRow.Volume = Convert.ToDecimal(stockInfo.TotalVolume); priceRow.VolumeWeightedAveragePrice = (Convert.ToDecimal(stockInfo.LastPrice) + Convert.ToDecimal(stockInfo.OpenPrice)) / 2; priceRow.OpenPrice = Convert.ToDecimal(stockInfo.OpenPrice); priceRow.LowPrice = Convert.ToDecimal(stockInfo.LowPrice); priceRow.HighPrice = Convert.ToDecimal(stockInfo.HighPrice); priceRow.ClosePrice = Convert.ToDecimal(stockInfo.PreviousPrice); // increment the RowVersion so the client notices!!! priceRow.RowVersion = ServerMarketData.RowVersion.Increment(); // commit the changes priceRow.AcceptChanges(); } } catch (Exception exception) { String msg = String.Format("{0}, {1}", exception.Message, exception.StackTrace); // Write the error and stack trace out to the debug listener //Debug.WriteLine(msg); MarkThree.EventLog.Warning(msg); } finally { // Release the global tables. if (ServerMarketData.EquityLock.IsReaderLockHeld) { ServerMarketData.EquityLock.ReleaseReaderLock(); } if (ServerMarketData.PriceLock.IsWriterLockHeld) { ServerMarketData.PriceLock.ReleaseWriterLock(); } if (ServerMarketData.SecurityLock.IsReaderLockHeld) { ServerMarketData.SecurityLock.ReleaseReaderLock(); } Debug.Assert(!ServerMarketData.IsLocked); } }
/// <summary> /// Generates random Price movements. /// </summary> private static void ExecutionThread(params object[] argument) { // Extract the thread arguments. The simulator will execute orders placed with this broker. int brokerId = (int)argument[0]; // Continually execute trades from the local order book when they exist. while (true) { // Wait until there is something in the order book to execute. Broker.orderBookEvent.WaitOne(); // These parameters are used to create the filled execution. int blockOrderId = 0; decimal quantity = 0.0M; decimal price = 0.0M; DateTime tradeDate = DateTime.MinValue; DateTime settlementDate = DateTime.MinValue; // This will insure that we survive any single error on a random execution. try { // Lock the Order Book. Broker.orderBookLock.AcquireWriterLock(CommonTimeout.LockWait); // Lock the tables. Debug.Assert(!ServerMarketData.AreLocksHeld); ServerMarketData.DebtLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.ExecutionLock.AcquireWriterLock(Timeout.Infinite); ServerMarketData.EquityLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.HolidayLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.PriceLock.AcquireReaderLock(Timeout.Infinite); ServerMarketData.SecurityLock.AcquireReaderLock(Timeout.Infinite); // Now that the tables are locked, the trade and settlement dates can be calcualted. tradeDate = Trading.TradeDate(0, 0, DateTime.Now); settlementDate = Trading.SettlementDate(0, 0, tradeDate); // Pick a random order to fill. if (Broker.orderBook.Order.Rows.Count > 0) { int orderIndex = Random.Next(0, Broker.orderBook.Order.Rows.Count); OrderBook.OrderRow orderRow = Broker.orderBook.Order[orderIndex]; blockOrderId = orderRow.BlockOrderId; // Find the security associated with this placement. ServerMarketData.SecurityRow securityRow = ServerMarketData.Security.FindBySecurityId(orderRow.SecurityId); if (securityRow == null) { continue; } // A settlement Price is required to find the Price of a security. For many issues, the default can // be found from the defaults. If a settlement currency isn't available, this issue can't be executed. object settlementId = null; foreach (ServerMarketData.DebtRow debtsRow in securityRow.GetDebtRowsByFKSecurityDebtDebtId()) { settlementId = debtsRow.SettlementId; } foreach (ServerMarketData.EquityRow equityRow in securityRow.GetEquityRowsByFKSecurityEquityEquityId()) { settlementId = equityRow.SettlementId; } if (settlementId == null) { continue; } // Simulate an executed quantity for this order. decimal quantityLeaves = orderRow.QuantityOrdered - orderRow.QuantityExecuted; if (quantityLeaves >= 100.0M) { quantity = Random.Next(100, Convert.ToInt32((quantityLeaves > maxExecution) ? maxExecution : quantityLeaves)); quantity = Math.Round(quantity / 100.0M) * 100.0M; } // When the quantity is zero, the order has been filled and can be removed from the local order book. When // the book is empty, then this thread can be paused until a new order is generated from a new placement. // In either event, when there are no shares in the order book, there can be no executions. When there's // nothing to execute, delete the order and go look for another order to fill. if (quantity == 0.0M) { orderRow.Delete(); orderRow.AcceptChanges(); if (orderBook.Order.Rows.Count == 0) { Broker.orderBookEvent.Reset(); } continue; } // Update the amount executed on this order. orderRow.QuantityExecuted += quantity; // Select a Price for the execution. ServerMarketData.PriceRow priceRow = ServerMarketData.Price.FindBySecurityIdCurrencyId(securityRow.SecurityId, (int)settlementId); if (priceRow != null) { price = priceRow.LastPrice; } } } catch (Exception exception) { // Display the error. Debug.WriteLine(exception.Message); } finally { // Release the order book. if (Broker.orderBookLock.IsWriterLockHeld) { Broker.orderBookLock.ReleaseWriterLock(); } // Release the tables. if (ServerMarketData.DebtLock.IsReaderLockHeld) { ServerMarketData.DebtLock.ReleaseReaderLock(); } if (ServerMarketData.EquityLock.IsReaderLockHeld) { ServerMarketData.EquityLock.ReleaseReaderLock(); } if (ServerMarketData.ExecutionLock.IsWriterLockHeld) { ServerMarketData.ExecutionLock.ReleaseWriterLock(); } if (ServerMarketData.HolidayLock.IsReaderLockHeld) { ServerMarketData.HolidayLock.ReleaseReaderLock(); } if (ServerMarketData.PriceLock.IsReaderLockHeld) { ServerMarketData.PriceLock.ReleaseReaderLock(); } if (ServerMarketData.SecurityLock.IsReaderLockHeld) { ServerMarketData.SecurityLock.ReleaseReaderLock(); } Debug.Assert(!ServerMarketData.AreLocksHeld); } // Create an execution record for this fill. Transaction transaction = new Transaction(); Shadows.WebService.Trading.Execution.Insert(transaction); transaction.BeginTransaction(); try { long rowVersion = 0L; Shadows.WebService.Trading.Execution.Insert(transaction, blockOrderId, brokerId, ref rowVersion, quantity, price, null, null, null, null, null, null, tradeDate, settlementDate); transaction.Commit(); } catch { transaction.Rollback(); } transaction.EndTransaction(); // Sleep for a random amount of time between execution. Thread.Sleep(Random.Next(50, 300)); } }