public void TestMultipleArgumentBooleanExpressions() { // expression tests // - empty multi-AND = true { IExpression[] args = new IExpression[] { }; Assert.IsTrue(Expr.CastTo <bool>(Expr.BoolAND(args).Evaluate(null), false)); } // - multi-AND true { IExpression[] args = new IExpression[] { Expr.Const(true), null, null, Expr.Const(true) }; Assert.IsTrue(Expr.CastTo <bool>(Expr.BoolAND(args).Evaluate(null), false)); } // multi-AND false { IExpression[] args = new IExpression[] { Expr.Const(true), null, null, Expr.Const(false) }; Assert.IsFalse(Expr.CastTo <bool>(Expr.BoolAND(args).Evaluate(null), false)); } // - empty multi-OR = false { IExpression[] args = new IExpression[] { }; Assert.IsFalse(Expr.CastTo <bool>(Expr.BoolOR(args).Evaluate(null), false)); } // - multi-OR false { IExpression[] args = new IExpression[] { Expr.Const(false), null, null, Expr.Const(false) }; Assert.IsFalse(Expr.CastTo <bool>(Expr.BoolOR(args).Evaluate(null), false)); } // multi-OR true { IExpression[] args = new IExpression[] { Expr.Const(false), null, null, Expr.Const(true) }; Assert.IsTrue(Expr.CastTo <bool>(Expr.BoolOR(args).Evaluate(null), false)); } }
private void BuildFilter() { var tempFilterArgs = new List <IExpression>(); _dataTypeName = null; if (chkProp1.Checked) { _dataTypeName = cbDataTypeValues.Text; } if (chkPropItemName.Checked) { tempFilterArgs.Add(Expr.StartsWith(Expr.SysPropItemName, txtPropItemNameValue.Text)); } IExpression[] filterArgs = tempFilterArgs.ToArray(); if (filterArgs.Length > 1) { _filter = Expr.BoolAND(filterArgs); } else if (filterArgs.Length == 1) { _filter = filterArgs[0]; } else { _filter = Expr.ALL; } _loggerRef.Target.LogDebug("Filter: {0} and (DataType is {1})", _filter.DisplayString(), _dataTypeName ?? "(any)"); }
/// <summary> /// Makes a rule filter. /// </summary> /// <param name="envAbbr">The (optional) name of the application processing the rules.</param> /// <param name="hostName">The (optional) name of the computer running the rules processor.</param> /// <param name="userName">The (optional) name of the user account hosting the rules processor.</param> /// <param name="instance">The (optional) instance name for the rule processor.</param> /// <param name="nameSpace">The (optional) instance namespace for the rule processor.</param> /// <returns></returns> public static IExpression MakeRuleFilter( string envAbbr, // optional environment short name string hostName, // optional name of computer string instance, // optional instance name string userName, string nameSpace) // optional name of the user { var clauses = new List <IExpression>(); if (envAbbr != null) { clauses.Add(Expr.BoolOR(Expr.IsNull(HostEnvName), Expr.IsEQU(HostEnvName, envAbbr))); } if (hostName != null) { clauses.Add(Expr.BoolOR(Expr.IsNull(HostComputer), Expr.IsEQU(HostComputer, hostName))); } clauses.Add(instance != null ? Expr.IsEQU(HostInstance, instance) : Expr.IsNull(HostInstance)); if (userName != null) { clauses.Add(Expr.BoolOR(Expr.IsNull(HostUserName), Expr.IsEQU(HostUserName, userName))); } if (nameSpace != null) { clauses.Add(Expr.BoolOR(Expr.IsNull(HostNameSpace), Expr.IsEQU(HostNameSpace, nameSpace))); } return(Expr.BoolAND(clauses.ToArray())); }
/// <summary> /// Makes the fx curve scenario rule. /// </summary> /// <param name="scenarioId">The scenario id.</param> /// <param name="priority">The priority.</param> /// <param name="currency">currency.</param> /// <param name="stressId">The stress id.</param> /// <param name="description">The description.</param> /// <returns></returns> private static ScenarioRule MakeFxCurveScenarioRule(string scenarioId, int priority, string currency, string stressId, string description) { // currency1 is mandatory, currency2 = USD if (currency == null) { throw new ArgumentNullException(nameof(currency)); } return(new ScenarioRule { ScenarioId = scenarioId, Category = ScenarioConst.FxPrefix, RuleId = "1", Disabled = false, Priority = priority, // base curve filter FilterExpr = Expr.BoolAND( Expr.IsEQU(CurveProp.PricingStructureType, "FxCurve"), Expr.IsEQU(CurveProp.Currency1, currency)) .Serialise(), // output RuleDesc = description, StressId = stressId }); }
protected override void OnFirstCallback() { _WorkerResponseCache = _IntClient.Target.CreateCache(); _WorkerResponseCache.Subscribe <WorkerResponse>( Expr.BoolAND( Expr.IsEQU(RequestBase.Prop.WorkerHostComputer, Environment.MachineName), (HostInstance == null) ? Expr.IsNull(RequestBase.Prop.WorkerHostInstance) : Expr.IsEQU(RequestBase.Prop.WorkerHostInstance, HostInstance)), (subs, item) => { _EventQueue.Dispatch(null); }, null); _CancellationsCache = _IntClient.Target.CreateCache(); _CancellationsCache.Subscribe <CancellationRequest>(Expr.ALL, (subs, item) => { _EventQueue.Dispatch(null); }, null); _AssignedRequestsCache = _IntClient.Target.CreateCache(); _AssignedRequestsCache.Subscribe <AssignedWorkflowRequest>( Expr.BoolAND( Expr.IsEQU(RequestBase.Prop.WorkerHostComputer, Environment.MachineName), (HostInstance == null) ? Expr.IsNull(RequestBase.Prop.WorkerHostInstance) : Expr.IsEQU(RequestBase.Prop.WorkerHostInstance, HostInstance)), (subs, item) => { _EventQueue.Dispatch(null); }, null); _HousekeepTimer = new Timer(HousekeepTimeout, null, HousekeepInterval, HousekeepInterval); _EventQueue.Dispatch(null); }
private void BtnAutoCurveBuilderClick(object sender, EventArgs e) { var ccy = listBoxCurrencies.SelectedItems; IExpression query1 = ccy.Cast <object>().Aggregate <object, IExpression>(null, (current, cc) => Expr.BoolOR(current, Expr.IsEQU(CurveProp.Currency1, cc))); var pst = listBoxCurves.SelectedItems; var query2 = pst.Cast <object>().Aggregate <object, IExpression>(null, (current, ps) => Expr.BoolOR(current, Expr.IsEQU(CurveProp.PricingStructureType, ps))); var marketName = txtBoxMarket.Text; var query3 = Expr.IsEQU(CurveProp.Market, marketName); query2 = Expr.BoolAND(query1, query2, query3, Expr.IsEQU(EnvironmentProp.NameSpace, NameSpace), Expr.IsEQU(EnvironmentProp.Function, FunctionProp.QuotedAssetSet)); ISubscription newSubscription = _clientRef.Target.CreateSubscription <QuotedAssetSet>(query2); newSubscription.UserCallback = delegate(ISubscription subscription, ICoreItem item) { // note: this is running on a thread pool thread // add the item to the queue and post a callback _queuedItems.Locked(queue => queue.Enqueue(item)); _loggerRef.Target.LogDebug("Queued Item {0} created at {1}", item.Name, item.Created.ToString()); int count = Interlocked.Increment(ref _queuedCalls); //if (count % 10000 == 0) _loggerRef.Target.LogDebug("SubscribeCallback: Queued calls posted: {0}", count); _syncContext.Post(ReceiveNewItem, item); //changed from null }; newSubscription.Start(); _loggerRef.Target.LogDebug("Subscription started."); }
public void TestDateFunctions() { DateTimeOffset dtoNow = DateTimeOffset.Now; DateTime dtNow = dtoNow.DateTime; DateTime dtToday = dtNow.Date; NamedValueSet props = new NamedValueSet(); props.Set("dtoNow", dtoNow); props.Set("dtNow", dtNow); props.Set("dtToday", dtToday); // check DayOfWeek() { IExpression expr = Expr.Create(Expr.BoolAND( Expr.IsGEQ(Expr.DayOfWeek(Expr.Prop("dtoNow")), Expr.Const(DayOfWeek.Sunday)), Expr.IsLEQ(Expr.DayOfWeek(Expr.Prop("dtoNow")), Expr.Const(DayOfWeek.Saturday)) ).Serialise()); string disp = expr.DisplayString(); object result = expr.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual <Type>(typeof(bool), result.GetType()); Assert.AreEqual <bool>(true, (bool)result); } // check FuncTODAY { IExpression expr = Expr.IsEQU(Expr.Prop("dtToday"), Expr.FuncToday()); object result = expr.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual <Type>(typeof(bool), result.GetType()); Assert.AreEqual <bool>(true, (bool)result); } // test DateTimeOffset/DateTime comparisons { IExpression expr = Expr.IsEQU(Expr.Prop("dtNow"), Expr.Prop("dtoNow")); object result = expr.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual <Type>(typeof(bool), result.GetType()); Assert.AreEqual <bool>(true, (bool)result); } { IExpression expr = Expr.IsLSS(Expr.Prop("dtToday"), Expr.Prop("dtNow")); object result = expr.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual <Type>(typeof(bool), result.GetType()); Assert.AreEqual <bool>(true, (bool)result); } { IExpression expr = Expr.IsLSS(Expr.Prop("dtToday"), Expr.Prop("dtoNow")); object result = expr.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual <Type>(typeof(bool), result.GetType()); Assert.AreEqual <bool>(true, (bool)result); } }
public void IsNotNullTest() { // Set up conditions that Name must exist and be not empty IExpression expression = Expr.IsNEQ("Name", ""); Assert.IsNotNull(expression); IExpression conditions = expression; expression = Expr.IsNotNull("Name"); Assert.IsNotNull(expression); conditions = Expr.BoolAND(expression, conditions); Assert.IsNotNull(conditions); // Test that if there is Name that it passes NamedValueSet props = new NamedValueSet(); props.Set("Name", "Test"); object result = conditions.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual(typeof(bool), result.GetType()); Assert.IsTrue((bool)result); // And if there isn't it fails props = new NamedValueSet(); props.Set("NoName", "Test"); result = conditions.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual(typeof(bool), result.GetType()); Assert.IsFalse((bool)result); // Test serialization string serialized = conditions.Serialise(); Assert.IsTrue(!string.IsNullOrEmpty(serialized)); // And deserialization IExpression deserializedConditions = Expr.Deserialise(serialized); // Test that if there is Name that it passes props = new NamedValueSet(); props.Set("Name", "Test"); result = deserializedConditions.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual(typeof(bool), result.GetType()); Assert.IsTrue((bool)result); // And if there isn't it fails props = new NamedValueSet(); props.Set("NoName", "Test"); result = deserializedConditions.Evaluate(props); Assert.IsNotNull(result); Assert.AreEqual(typeof(bool), result.GetType()); Assert.IsFalse((bool)result); }
public static void Load(ILogger logger, ICoreCache targetClient, string nameSpace) { logger.LogDebug("Loading alert rules..."); // defaults // - check constraint: time of day is between 2am and 11pm 7 days a week IExpression defaultCheckConstraint = Expr.BoolAND( Expr.IsGEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Monday)), Expr.IsLEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Friday)), Expr.IsGEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(4, 30, 0))), Expr.IsLEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(20, 30, 0)))); // - monitor period: every minute TimeSpan defaultMonitorPeriod = TimeSpan.FromMinutes(1); // - publish period: hourly TimeSpan defaultPublishPeriod = TimeSpan.FromHours(1); // build rules var alertRules = new List <AlertRule>(); alertRules.AddRange(CreateDevRules(defaultCheckConstraint, defaultMonitorPeriod, defaultPublishPeriod)); alertRules.AddRange(CreateSitRules(defaultCheckConstraint, defaultMonitorPeriod, defaultPublishPeriod)); alertRules.AddRange(CreateStgRules(defaultCheckConstraint, defaultMonitorPeriod, defaultPublishPeriod)); alertRules.AddRange(CreateLegacyRules(defaultCheckConstraint, defaultMonitorPeriod, defaultPublishPeriod)); // save Import rules foreach (AlertRule rule in alertRules) { logger.LogDebug(" Loading {0}.{1}.{2} ({3})...", rule.EnvName, rule.Instance, rule.RuleName, rule.Disabled ? "Disabled" : "Enabled"); rule.NameSpace = nameSpace; TimeSpan lifetime = rule.Disabled ? TimeSpan.FromDays(30) : TimeSpan.MaxValue; targetClient.SaveObject(rule, lifetime); } logger.LogDebug("Loaded {0} alert rules.", alertRules.Count); // load from embedded xml //const string Prefix = "Orion.Configuration.AlertRules"; //Dictionary<string, string> chosenFiles = ResourceHelper.GetResources(assembly, Prefix, "xml"); //if (chosenFiles.Count == 0) // throw new InvalidOperationException("Missing alert rules!"); //foreach (KeyValuePair<string, string> file in chosenFiles) //{ // AlertRule rule = XmlSerializerHelper.DeserializeFromString<AlertRule>(file.Value); // logger.LogDebug(" Loading {0} ({1})...", // file.Key, // rule.Disabled ? "Disabled" : "Enabled"); // TimeSpan lifetime = rule.Disabled ? TimeSpan.FromDays(30) : TimeSpan.MaxValue; // LoadConfigDataHelper.AsyncSaveObject<AlertRule>( // rule, rule.UniqueKeyNetwork, rule.Properties, lifetime, false, targetClient, completions); //} //logger.LogDebug("Loaded {0} alert rules.", chosenFiles.Count); }
private static IEnumerable <ICoreItem> GetStressedItems(string tenor) { IExpression expr1 = Expr.IsEQU(Expr.Prop(CurveProp.MarketAndDate), Expr.Const("GlobalIB_EOD")); IExpression expr2 = string.IsNullOrEmpty(tenor) ? Expr.IsEQU(Expr.Prop(CurveProp.PricingStructureType), Expr.Const("XccySpreadCurve")) : Expr.IsEQU(Expr.Prop(CurveProp.IndexTenor), Expr.Const(tenor)); IExpression expr3 = Expr.IsNotNull(Expr.Prop(CurveProp.StressName)); IExpression expr = Expr.BoolAND(expr1, expr2, expr3); List <ICoreItem> stressedItems = Engine.Cache.LoadItems <Market>(expr); Assert.AreEqual(13, stressedItems.Count); return(stressedItems); }
public void TestNamedValueSetConstructors() { NamedValueSet props = new NamedValueSet(); props.Set("prop1", 123); props.Set("prop2", 234); int[] choiceSet = new int[] { 456, 567, 678 }; props.Set("prop3", choiceSet); IExpression expr1 = Expr.BoolAND(props); Assert.AreEqual <bool>(false, expr1.HasErrors()); string text1 = expr1.Serialise(); string disp1 = expr1.DisplayString(); }
public void TestSerialisationFailures() { var props = new NamedValueSet(); props.Set("prop1", 123); props.Set("prop2", 456); IExpression expr1 = Expr.BoolAND(props); Assert.AreEqual <bool>(false, expr1.HasErrors()); string text1 = expr1.Serialise(); Assert.AreEqual <string>( "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + "<QuerySpec xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://tempuri.org/ExprFormat.xsd\">\r\n" + " <version>1</version>\r\n" + " <v1QueryExpr node=\"EXPR\" name=\"AND\">\r\n" + " <args node=\"EXPR\" name=\"EQU\">\r\n" + " <args node=\"FIELD\" name=\"prop1\" />\r\n" + " <args node=\"CONST\" name=\"Int32\" value=\"123\" />\r\n" + " </args>\r\n" + " <args node=\"EXPR\" name=\"EQU\">\r\n" + " <args node=\"FIELD\" name=\"prop2\" />\r\n" + " <args node=\"CONST\" name=\"Int32\" value=\"456\" />\r\n" + " </args>\r\n" + " </v1QueryExpr>\r\n" + "</QuerySpec>", text1); string text2a = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + "<QuerySpec xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://tempuri.org/ExprFormat.xsd\">\r\n" + " <version>1</version>\r\n" + " <v1QueryExpr node=\"EXPR\" name=\"AND\">\r\n" + " <args node=\"EXPR\" name=\"EQU\">\r\n" + " <args node=\"FIELD\" name=\"prop1\" />\r\n" + " <args node=\"CONSTqq\" name=\"Int32\" value=\"123\" />\r\n" + " </args>\r\n" + " <args node=\"EXPR\" name=\"EQU\">\r\n" + " <args node=\"FIELD\" name=\"prop2\" />\r\n" + " <args node=\"CONST\" name=\"Int32\" value=\"456\" />\r\n" + " </args>\r\n" + " </v1QueryExpr>\r\n" + "</QuerySpec>"; // deserialisation should succeed, but with errors IExpression expr2 = Expr.Create(text2a); Assert.AreEqual <bool>(true, expr2.HasErrors()); // evaluation should fail UnitTestHelper.AssertThrows <InvalidOperationException>( () => expr2.Evaluate(props)); }
private static void AssertValuation(HandlerResponse result) { // Load valuationItems for the current request Id List <ICoreItem> rawValuationItems = Engine.Cache.LoadItems <ValuationReport>(Expr.BoolAND(Expr.IsNull(ValueProp.Aggregation), Expr.IsEQU(RequestBase.Prop.RequestId, Guid.Parse(result.RequestId)))); foreach (ICoreItem valuationItem in rawValuationItems) { // Extract the valuation report var valuation = (ValuationReport)valuationItem.Data; // Check that the valuation returned successfully var excpName = valuationItem.AppProps.GetValue <string>(WFPropName.ExcpName, null); if (excpName != null) { // valuation failed - log details var excpText = valuationItem.AppProps.GetValue <string>(WFPropName.ExcpText, null); UTE.Logger.LogError( "Valuation failed:" + "{0} UniqueId : {1}" + "{0} Exception: {2}: '{3}'", Environment.NewLine, valuationItem.Name, excpName, excpText); Assert.Fail(excpName, $"Workflow error ({excpName})"); } // check for errors var tradeSource = valuationItem.AppProps.GetValue <string>(TradeProp.TradeSource); var tradeId = valuationItem.AppProps.GetValue <string>(TradeProp.TradeId); var marketName = valuationItem.AppProps.GetValue <string>(CurveProp.Market); var key = $"{tradeSource}_{tradeId}_{marketName}_{InstrumentMetrics.NPV}".ToLower(); // Assert expected value has been supplied Assert.IsTrue(ExpectedValues.ContainsKey(key), $"ExpectedValue for key:({key}) is missing."); ExpectedValue expectedValue = ExpectedValues[key]; Quotation quote = valuation.GetFirstQuotationForMetricName(InstrumentMetrics.NPV.ToString()); Assert.IsNotNull(quote, $"CalculatedValue for key:({key}) is missing."); Assert.IsTrue(quote.valueSpecified, $"CalculatedValue for key:({key}) is missing."); decimal calculatedNPV = quote.value; decimal differenceNPV = expectedValue.OutputNPV - calculatedNPV; Assert.IsFalse(System.Math.Abs(differenceNPV) > ToleranceNPV, $"ToleranceExceeded(|{differenceNPV:F0}| > {ToleranceNPV:F0})"); } }
private RequestBase CreateCurveGenRequest() { // get curve identifiers IExpression curveDefFilter = Expr.BoolAND( Expr.IsEQU(CurveProp.Function, "Configuration"), Expr.IsEQU(CurveProp.Market, CurveConst.QR_LIVE), Expr.IsNull(CurveProp.MarketDate)); DateTime dtNow = DateTime.Now; // - hack get reference curves 1st List <string> curveItemNames = new List <string>(); List <CurveSelection> referenceCurveSelectors = new List <CurveSelection>(); List <CurveSelection> remainingCurveSelectors = new List <CurveSelection>(); List <ICoreItem> curveDefItems = _ClientRef.Target.LoadItems <Market>(curveDefFilter); foreach (ICoreItem curveDefItem in curveDefItems) { string marketName = curveDefItem.AppProps.GetValue <string>(CurveProp.Market, true); string curveType = curveDefItem.AppProps.GetValue <string>(CurveProp.PricingStructureType, true); string curveName = curveDefItem.AppProps.GetValue <string>(CurveProp.CurveName, true); string refCurveName = curveDefItem.AppProps.GetValue <string>(CurveProp.ReferenceCurveName, null); ((refCurveName == null) ? referenceCurveSelectors : remainingCurveSelectors).Add(new CurveSelection() { MarketName = marketName, CurveType = curveType, CurveName = curveName }); } List <CurveSelection> curveSelectors = new List <CurveSelection>(referenceCurveSelectors); curveSelectors.AddRange(remainingCurveSelectors); OrdinaryCurveGenRequest request = new OrdinaryCurveGenRequest() { RequestId = Guid.NewGuid().ToString(), RequesterId = new UserIdentity() { Name = _ClientRef.Target.ClientInfo.Name, DisplayName = "Grid Test Harness" }, SubmitTime = DateTimeOffset.Now.ToString("o"), BaseDate = dtNow.Date, SaveMarketData = false, UseSavedMarketData = false, ForceGenerateEODCurves = false, CurveSelector = curveSelectors.ToArray() }; _ClientRef.Target.SaveObject <OrdinaryCurveGenRequest>(request); return(request); }
public void TidyUpMarkets(IEnumerable <string> uniqueIds) { try { foreach (string uniqueId in uniqueIds) { IExpression expression = Expr.BoolAND(Expr.IsEQU("UniqueIdentifier", uniqueId), Expr.IsEQU(EnvironmentProp.NameSpace, NameSpace)); Cache.DeleteObjects <Market>(expression); } } catch (System.Exception ex) { throw new System.Exception("Failed to remove from object store", ex); } }
protected override void OnFirstCallback() { base.OnFirstCallback(); // initialise workflow _workflow.Initialise(_workContext); // subscribe to curve definitions _curveSubs = IntClient.Target.Subscribe <QuotedAssetSet>( Expr.BoolAND( Expr.IsEQU(CurveProp.Function, FunctionProp.QuotedAssetSet.ToString()), Expr.IsEQU(CurveProp.Market, CurveConst.QR_LIVE), Expr.IsNull(CurveProp.MarketDate)), (subscription, item) => { MainThreadQueue?.Dispatch(item, BaseCurveCallback); }, null); }
private static void PrintValuation(HandlerResponse result) { // Load valuationItems for the current request Id List <ICoreItem> rawValuationItems = Engine.Cache.LoadItems <ValuationReport>(Expr.BoolAND(Expr.IsNull(ValueProp.Aggregation), Expr.IsEQU(RequestBase.Prop.RequestId, Guid.Parse(result.RequestId)))); foreach (ICoreItem valuationItem in rawValuationItems) { Debug.Print(XmlSerializerHelper.SerializeToString(valuationItem.AppProps.Serialise())); // Extract the valuation report var valuation = (ValuationReport)valuationItem.Data; XmlSerializerHelper.SerializeToFile(valuation, valuationItem.Name); //Debug.Print(valuationItem.Text); } }
private void BtnDebugLoadAlertRulesClick(object sender, EventArgs e) { using (Reference <ILogger> loggerRef = Reference <ILogger> .Create(new TextBoxLogger(txtDebugLog))) { loggerRef.Target.LogDebug("Loading alert rules..."); using (ICoreClient client = new CoreClientFactory(loggerRef).SetEnv(BuildConst.BuildEnv).Create()) { // load test user details //client.SaveObject<UserDetail>(MakeUserDetail(User_MLim2, "Mark Lim", "*****@*****.**")); //client.SaveObject<UserDetail>(MakeUserDetail(User_SDudley, "Simon Dudley", "*****@*****.**")); client.SaveObject(MakeUserDetail(AlertRule.UserDefaultReplyTo, "Default ReplyTo User", "*****@*****.**")); client.SaveObject(MakeUserGroup(AlertRule.GroupDefaultMailTo, "Default MailTo Group", new[] { AlertRule.UserDefaultReplyTo }, null)); //client.SaveObject<UserGroup>(MakeUserGroup(Group_QDS_Developers, "QDS Developers Group", new string[] { User_SDudley, User_MLim2 }, null)); //client.SaveObject<UserGroup>(MakeUserGroup(Group_QDS_Developers, "QDS Developers Group", new string[] { User_SDudley }, null)); // defaults // - check constraint: time of day is between 4:30am and 8:30pm 7 days a week IExpression defaultCheckConstraint = Expr.BoolAND( Expr.IsGEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Monday)), Expr.IsLEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Friday)), Expr.IsGEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(4, 30, 0))), Expr.IsLEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(20, 30, 0)))); // - monitor period: every minute TimeSpan defaultMonitorPeriod = TimeSpan.FromMinutes(1); // - publish period: hourly TimeSpan defaultPublishPeriod = TimeSpan.FromHours(1); // build rules var alertRules = new List <AlertRule>(); alertRules.AddRange(CreateDevRules(defaultCheckConstraint, defaultMonitorPeriod, defaultPublishPeriod)); //alertRules.AddRange(CreateSitRules(defaultCheckConstraint, defaultMonitorPeriod, defaultPublishPeriod)); //alertRules.AddRange(CreateStgRules(defaultCheckConstraint, defaultMonitorPeriod, defaultPublishPeriod)); //alertRules.AddRange(CreateLegacyRules(defaultCheckConstraint, defaultMonitorPeriod, defaultPublishPeriod)); // save Import rules foreach (AlertRule rule in alertRules) { loggerRef.Target.LogDebug(" Loading AlertRule: {0}.{1}.{2} ({3})...", rule.HostEnvAbbr, rule.HostInstance, rule.RuleUniqueId, rule.Disabled ? "Disabled" : "Enabled"); TimeSpan lifetime = rule.Disabled ? TimeSpan.FromDays(30) : TimeSpan.MaxValue; client.SaveObject(rule, lifetime); } loggerRef.Target.LogDebug("Loaded {0} alert rules.", alertRules.Count); } } }
private IExpression BuildExpression(out string dataTypeName) { dataTypeName = null; if (chkProp1.Checked) { dataTypeName = cbDataTypeValues.Text; } var tempQueryArgs = new List <IExpression>(); if (chkProp2.Checked) { tempQueryArgs.Add(Expr.IsEQU(txtProp2Name.Text, txtProp2Value.Text)); } if (chkProp3.Checked) { tempQueryArgs.Add(Expr.IsEQU(txtProp3Name.Text, txtProp3Value.Text)); } if (chkProp4.Checked) { tempQueryArgs.Add(Expr.IsEQU(txtProp4Name.Text, txtProp4Value.Text)); } if (chkPropItemName.Checked) { tempQueryArgs.Add(Expr.StartsWith(Expr.SysPropItemName, txtPropItemNameValue.Text)); } IExpression[] queryArgs = tempQueryArgs.ToArray(); IExpression query = null; if (queryArgs.Length > 0) { query = Expr.BoolAND(queryArgs); } if (chkDebugRequests.Checked) { _loggerRef.Target.LogDebug("DataType: {0}", dataTypeName ?? "(any)"); _loggerRef.Target.LogDebug("Where : {0}", (query != null) ? query.DisplayString() : "(all)"); } return(query ?? Expr.ALL); }
protected override void OnFirstCallback() { // initialise workflow _workflow.Initialise(_workContext); // subscribe to all base curves _baseCurveSubs = IntClient.Target.Subscribe <Market>( Expr.BoolAND( //Expr.BoolOR( Expr.IsEQU(CurveProp.Market, CurveConst.QR_LIVE), //Expr.IsEQU(CurveProp.Market, CurveConst.QR_EOD), //Expr.IsEQU(CurveProp.Market, CurveConst.NAB_EOD)), Expr.IsEQU(EnvironmentProp.Function, FunctionProp.Market.ToString()), Expr.IsNull(CurveProp.MarketDate), Expr.IsNull(CurveProp.StressName) //Expr.StartsWith(Expr.SysPropItemName, "Highlander.Market.") ), (subscription, item) => { MainThreadQueue?.Dispatch(item, BaseCurveCallback); }, null); }
private static Market GetCurve(ILogger logger, ICoreCache cache, string nameSpace, object[][] rateCurveFiltersRange) { NamedValueSet rateCurveFilters = rateCurveFiltersRange.ToNamedValueSet(); IExpression queryExpr = Expr.BoolAND(rateCurveFilters); List <ICoreItem> loadedCurves = cache.LoadItems <Market>(queryExpr); if (loadedCurves.Count == 0) { throw new InvalidOperationException("Requested curve is not available."); } if (loadedCurves.Count > 1) { throw new InvalidOperationException("More than 1 curve found for supplied filters."); } var loadedCurve = loadedCurves.Single(); var market = (Market)loadedCurve.Data; var yieldCurveValuation = (YieldCurveValuation)market.Items1[0]; DateTime baseDate = yieldCurveValuation.baseDate.Value; string currency = PropertyHelper.ExtractCurrency(loadedCurve.AppProps); yieldCurveValuation.discountFactorCurve = ConstructDiscountFactors(logger, cache, nameSpace, yieldCurveValuation.discountFactorCurve, baseDate, currency); return(market); }
protected override MDSResult <QuotedAssetSet> OnRequestPricingStructure( IModuleInfo clientInfo, Guid requestId, MDSRequestType requestType, NamedValueSet requestParams, DateTimeOffset subsExpires, NamedValueSet structureParams) { var combinedResult = new QuotedAssetSet(); var debugRequest = requestParams.GetValue <bool>("DebugRequest", false); Client.DebugRequests = debugRequest; IExpression query = Expr.BoolAND(structureParams); List <QuotedAssetSet> providerResults = Client.LoadObjects <QuotedAssetSet>(query); Client.DebugRequests = false; // merge multiple results combinedResult = providerResults.Aggregate(combinedResult, (current, providerResult) => current.Merge(providerResult, false, true, true)); return(new MDSResult <QuotedAssetSet> { Result = combinedResult }); }
private static ScenarioRule MakeIrCurveScenarioRule(string scenarioId, int priority, string currency, string indexName, string indexTenor, string stressId, string description) { return(new ScenarioRule { ScenarioId = scenarioId, Category = ScenarioConst.IrPrefix, RuleId = "1", Disabled = false, Priority = priority, // base curve filter FilterExpr = Expr.BoolAND( Expr.BoolOR( Expr.IsEQU(CurveProp.PricingStructureType, "RateCurve"), Expr.IsEQU(CurveProp.PricingStructureType, "RateBasisCurve"), Expr.IsEQU(CurveProp.PricingStructureType, "RateSpreadCurve"), Expr.IsEQU(CurveProp.PricingStructureType, "DiscountCurve")), ((indexName != null) ? Expr.Contains(CurveProp.IndexName, indexName) : null), ((indexTenor != null) ? Expr.IsEQU(CurveProp.IndexTenor, indexTenor) : null), ((currency != null) ? Expr.IsEQU(CurveProp.Currency1, currency) : null)).Serialise(), // output RuleDesc = description, StressId = stressId }); }
public static void Load(ILogger logger, ICoreCache targetClient) { logger.LogDebug("Loading file import rules..."); // generate import rules var ImportRules = new List <FileImportRule>(); { // defaults // - monitor period: check rules every 5 minutes TimeSpan defaultMonitorPeriod = TimeSpan.FromMinutes(5); // - check constraint: time of day is between 2am and 11pm IExpression defaultCheckConstraint = Expr.BoolAND( //Expr.IsGEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Monday)), //Expr.IsLEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Friday)), Expr.IsGEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(2, 0, 0))), Expr.IsLEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(23, 59, 59)))); // - effective date: last import date plus 1 day IExpression defaultEffectiveDate = Expr.NumADD(Expr.FuncDatePart(Expr.Prop(RuleConst.LastImportDateTime)), Expr.Const(TimeSpan.FromDays(1))); // - import delay: 26 hours IExpression importDelayDefault = Expr.Const(TimeSpan.FromHours(2)); IExpression importDelayCalypso = Expr.Const(TimeSpan.FromHours(26)); IExpression importDelayMurex = Expr.Const(TimeSpan.FromHours(26)); // - import condition: (current date - effective date) >= import delay IExpression defaultImportCondition = Expr.IsGEQ(Expr.NumSUB(Expr.FuncNow(), Expr.Prop(RuleConst.EffectiveDateTime)), Expr.Prop(RuleConst.ImportDelay)); // - next import date = effective date, or today IExpression nextImportDateIncrement = Expr.Prop(RuleConst.EffectiveDateTime); IExpression nextImportDateUseLatest = Expr.FuncToday(); // build rules // -------------------- Calyspo IR trades ImportRules.Add(MakeImportRule("CalypsoFRAs", false, // rule enabled true, // debugging on defaultMonitorPeriod, defaultCheckConstraint, defaultEffectiveDate, importDelayCalypso, defaultImportCondition, nextImportDateIncrement, null, // other properties "Calypso", @"\\melfiler02\marketrisk\mrtdata\AU\MEL", @"C:\_qrsc\Imported\Calypso\{yyyy}\{MM}_{MMM}\{dd}_{ddd}", "FraCalypso.{yyyy}{MM}{dd}.gz", RuleConst.FileContent_GWML_6_5, false // always copy )); ImportRules.Add(MakeImportRule("CalypsoSwaps", false, // rule enabled false, // debugging off defaultMonitorPeriod, defaultCheckConstraint, defaultEffectiveDate, importDelayCalypso, defaultImportCondition, nextImportDateIncrement, null, // other properties "Calypso", @"\\melfiler02\marketrisk\mrtdata\AU\MEL", @"C:\_qrsc\Imported\Calypso\{yyyy}\{MM}_{MMM}\{dd}_{ddd}", "SwCalypso.{yyyy}{MM}{dd}.gz", RuleConst.FileContent_GWML_6_5, false // always copy )); // -------------------- Murex FX trades ImportRules.Add(MakeImportRule("Murex", false, // rule enabled false, // debugging off defaultMonitorPeriod, defaultCheckConstraint, defaultEffectiveDate, importDelayMurex, defaultImportCondition, nextImportDateIncrement, null, // other properties "Murex", @"\\melfiler02\marketrisk\mrtdata\AU\GBL", @"C:\_qrsc\Imported\Murex\{yyyy}\{MM}_{MMM}\{dd}_{ddd}", "FxMurex.{yyyy}{MM}{dd}.gz;FxoMurex.{yyyy}{MM}{dd}.gz", RuleConst.FileContent_GWML_6_5, false // always copy )); // -------------------- Cartoo EOD curves ImportRules.Add(MakeImportRule("Cartoo", true, // rule disabled - access is denied to svc_qrbuild account - need to use svc_qrdev false, // debugging off defaultMonitorPeriod, defaultCheckConstraint, defaultEffectiveDate, importDelayDefault, defaultImportCondition, nextImportDateIncrement, null, // other properties "Cartoo", @"\\melfiler02\xferdata\Cartoo\Out\MELB", //@"C:\_qrsc\Imported\Cartoo\{yyyy}\{MM}_{MMM}\{dd}_{ddd}", @"C:\_qrsc\Imported\Cartoo\Output", "*.xls", RuleConst.FileContent_GenericText, //false // always copy true // only copy if newer )); // -------------------- Credient output (Sungard) files ImportRules.Add(MakeImportRule("CredientDetail", false, // rule enabled false, // debugging off defaultMonitorPeriod, defaultCheckConstraint, defaultEffectiveDate, importDelayDefault, defaultImportCondition, nextImportDateUseLatest, null, // other properties "Credient", @"\\tmelf001\sentry\API\Credient\Output", @"C:\_qrsc\Imported\Credient\Output", "*.xml", RuleConst.FileContent_GenericXML, true // only copy if newer )); // -------------------- Credient snapshot files ImportRules.Add(MakeImportRule("CredientSnapshot", false, // rule enabled false, // debugging off defaultMonitorPeriod, defaultCheckConstraint, defaultEffectiveDate, importDelayDefault, defaultImportCondition, nextImportDateUseLatest, null, // other properties "Credient", @"\\tmelf001\sentry\API\Credient", @"C:\_qrsc\Imported\Credient\Snapshot", "*.txt", RuleConst.FileContent_GenericText, false // always copy )); } // save Import rules foreach (FileImportRule rule in ImportRules) { logger.LogDebug(" Loading {0} ...", rule.RuleName); TimeSpan lifetime = rule.Disabled ? TimeSpan.FromDays(30) : TimeSpan.MaxValue; targetClient.SaveObject <FileImportRule>(rule, lifetime); } logger.LogDebug("Loaded {0} file import rules.", ImportRules.Count); }
private static IEnumerable <AlertRule> CreateStgRules(IExpression defaultCheckConstraint, TimeSpan defaultMonitorPeriod, TimeSpan defaultPublishPeriod) { const string env = "STG"; var alertRules = new List <AlertRule> { MakeAlertRule( "CartooEODCurves", false, env, "AlertServer", defaultCheckConstraint, Expr.IsGTR(Expr.NumSUB(Expr.FuncNow(), Expr.Prop(Expr.SysPropItemCreated)), Expr.Const(TimeSpan.FromHours(31))), typeof(Market), Expr.IsEQU(Expr.SysPropItemName, "Market.EOD.RateCurve.AUD-ZERO-BANK-3M"), new NamedValueSet(new[] { new NamedValue("BaseDate", new DateTime(2000, 1, 1)) }), defaultMonitorPeriod, defaultPublishPeriod, $"Cartoo EOD curves ({env}) have not been published today." ), MakeAlertRule( "Trader Curves (TraderMid)", false, env, "AlertServer", Expr.BoolAND( Expr.IsGEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Monday)), Expr.IsLEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Friday)), Expr.IsGEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(8, 30, 0))), Expr.IsLEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(16, 30, 0)))), Expr.IsGTR(Expr.NumSUB(Expr.FuncNow(), Expr.Prop(Expr.SysPropItemCreated)), Expr.Const(TimeSpan.FromMinutes(10))), typeof(Market), Expr.IsEQU(Expr.SysPropItemName, "Market.TraderMid.RateCurve.AUD-LIBOR-BBA-6M"), new NamedValueSet(new[] { new NamedValue("BaseDate", new DateTime(2000, 1, 1)), new NamedValue("MailTo", new[] { AWatt }) }), defaultMonitorPeriod, defaultPublishPeriod, string.Format("TraderMid ({0}) curve is out of date.", env) ), MakeAlertRule( "Trader Curves (LpmCapFloor)", false, env, "AlertServer", Expr.BoolAND( Expr.IsGEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Monday)), Expr.IsLEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Friday)), Expr.IsGEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(8, 30, 0))), Expr.IsLEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(16, 30, 0)))), Expr.IsGTR(Expr.NumSUB(Expr.FuncNow(), Expr.Prop(Expr.SysPropItemCreated)), Expr.Const(TimeSpan.FromMinutes(10))), typeof(Market), Expr.BoolAND( Expr.IsEQU(Expr.Prop("PricingStructureType"), Expr.Const("LpmCapFloorCurve")), Expr.IsGTR(Expr.Prop(Expr.SysPropItemCreated), Expr.FuncToday())), new NamedValueSet(new[] { new NamedValue("BaseDate", new DateTime(2000, 1, 1)), new NamedValue("MailTo", new[] { AWatt }) }), defaultMonitorPeriod, defaultPublishPeriod, $"LpmCapFloor curve ({env}) is out of date." ), MakeAlertRule( "Trader Curves (LPMSwaption)", false, env, "AlertServer", Expr.BoolAND( Expr.IsGEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Monday)), Expr.IsLEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Friday)), Expr.IsGEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(8, 30, 0))), Expr.IsLEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(16, 30, 0)))), Expr.IsGTR(Expr.NumSUB(Expr.FuncNow(), Expr.Prop(Expr.SysPropItemCreated)), Expr.Const(TimeSpan.FromMinutes(10))), typeof(Market), Expr.BoolAND( Expr.IsEQU(Expr.Prop("PricingStructureType"), Expr.Const("LPMSwaptionCurve")), Expr.IsGTR(Expr.Prop(Expr.SysPropItemCreated), Expr.FuncToday())), new NamedValueSet(new[] { new NamedValue("BaseDate", new DateTime(2000, 1, 1)), new NamedValue("MailTo", new[] { AWatt }) }), defaultMonitorPeriod, defaultPublishPeriod, $"LPMSwaption curve ({env}) is out of date." ), MakeAlertRule( "Trader Curves (Swaption)", false, env, "AlertServer", Expr.BoolAND( Expr.IsGEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Monday)), Expr.IsLEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Friday)), Expr.IsGEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(8, 30, 0))), Expr.IsLEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(16, 30, 0)))), Expr.IsGTR(Expr.NumSUB(Expr.FuncNow(), Expr.Prop(Expr.SysPropItemCreated)), Expr.Const(TimeSpan.FromMinutes(10))), typeof(Market), Expr.IsEQU(Expr.SysPropItemName, "Market.Live.RateATMVolatilityMatrix.AUD-LIBOR-BBA-Swaption"), new NamedValueSet(new[] { new NamedValue("BaseDate", new DateTime(2000, 1, 1)), new NamedValue("MailTo", new[] { AWatt }) }), defaultMonitorPeriod, defaultPublishPeriod, $"Swaption ({env}) curve is out of date." ), MakeAlertRule( "Trader Curves (CapFloor)", false, env, "AlertServer", Expr.BoolAND( Expr.IsGEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Monday)), Expr.IsLEQ(Expr.DayOfWeek(Expr.FuncToday()), Expr.Const(DayOfWeek.Friday)), Expr.IsGEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(8, 30, 0))), Expr.IsLEQ(Expr.FuncTimeOfDay(), Expr.Const(new TimeSpan(16, 30, 0)))), Expr.IsGTR(Expr.NumSUB(Expr.FuncNow(), Expr.Prop(Expr.SysPropItemCreated)), Expr.Const(TimeSpan.FromMinutes(10))), typeof(Market), Expr.IsEQU(Expr.SysPropItemName, "Market.Live.RateVolatilityMatrix.AUD-LIBOR-BBA-CapFloor"), new NamedValueSet(new[] { new NamedValue("BaseDate", new DateTime(2000, 1, 1)), new NamedValue("MailTo", new[] { AWatt }) }), defaultMonitorPeriod, defaultPublishPeriod, $"CapFloor ({env}) curve is out of date." ), MakeAlertRule( "Calendar", false, env, "AlertServer", defaultCheckConstraint, Expr.IsGTR( Expr.NumSUB(Expr.FuncNow(), Expr.Prop(Expr.SysPropItemCreated)), Expr.Const(TimeSpan.FromDays(8))), typeof(LocationCalendarYear), Expr.IsEQU(Expr.SysPropItemName, "Orion.ReferenceData.RDMHolidays.ZAJO.2060"), new NamedValueSet(new[] { new NamedValue("BaseDate", new DateTime(2000, 1, 1)), new NamedValue("MailHost", "sydwatqur01:2525"), new NamedValue("MailTo", new[] { AWatt }) }), defaultMonitorPeriod, defaultPublishPeriod, $"Holiday calendars ({env}) have not been downloaded in the past week." ), // Check that a rule has been updated in the past 2 minutes, // this rule is updated every minute MakeAlertRule( "Heartbeat", false, env, "AlertServer", defaultCheckConstraint, Expr.IsGTR( Expr.NumSUB(Expr.FuncNow(), Expr.Prop(Expr.SysPropItemCreated)), Expr.Const(TimeSpan.FromMinutes(2))), typeof(AlertSignal), Expr.IsEQU(Expr.Prop("RuleName"), Expr.Const("Heartbeat")), new NamedValueSet(new[] { new NamedValue("MailHost", "sydwatqur01:2525"), new NamedValue("MailTo", new[] { AWatt }) }), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), "No rule status has been updated in the past 2 minutes.") }; return(alertRules); }
/// <summary> /// Returns the header information for all trades matching the query properties. /// </summary> /// <param name="query">The query properties. A 2-column array of names and values.</param> /// <returns></returns> public object[,] QueryTradeIds(object[,] query) { //try //{ int rowMin = query.GetLowerBound(0); int rowMax = query.GetUpperBound(0); int colMin = query.GetLowerBound(1); int colMax = query.GetUpperBound(1); if (colMax - colMin + 1 != 3) { throw new ApplicationException("Input parameters must be 3 columns (name/op/value)!"); } IExpression whereExpr = null; for (int row = rowMin; row <= rowMax; row++) { int colName = colMin + 0; int colOp = colMin + 1; int colValue = colMin + 2; var name = query[row, colName] == null ? null : query[row, colName].ToString(); var op = query[row, colOp] == null ? null : query[row, colOp].ToString(); object value = query[row, colValue]; if (name != null && (op != null) && (value != null)) { op = op.ToLower().Trim(); if (op == "equ" || op == "==") { whereExpr = Expr.BoolAND(Expr.IsEQU(name, value), whereExpr); } else if (op == "neq" || op == "!=") { whereExpr = Expr.BoolAND(Expr.IsNEQ(name, value), whereExpr); } else if (op == "geq" || op == ">=") { whereExpr = Expr.BoolAND(Expr.IsGEQ(name, value), whereExpr); } else if (op == "leq" || op == "<=") { whereExpr = Expr.BoolAND(Expr.IsLEQ(name, value), whereExpr); } else if (op == "gtr" || op == ">") { whereExpr = Expr.BoolAND(Expr.IsGTR(name, value), whereExpr); } else if (op == "lss" || op == "<") { whereExpr = Expr.BoolAND(Expr.IsLSS(name, value), whereExpr); } else if (op == "starts") { whereExpr = Expr.BoolAND(Expr.StartsWith(name, value.ToString()), whereExpr); } else if (op == "ends") { whereExpr = Expr.BoolAND(Expr.EndsWith(name, value.ToString()), whereExpr); } else if (op == "contains") { whereExpr = Expr.BoolAND(Expr.Contains(name, value.ToString()), whereExpr); } else { throw new ApplicationException("Unknown Operator: '" + op + "'"); } } } List <ICoreItem> items = _cache.LoadItems(typeof(Trade), whereExpr); //TODO what about confirmation? var result = new object[items.Count + 1, 17]; // add heading row result[0, 0] = TradeProp.ProductType; result[0, 1] = TradeProp.TradeId; result[0, 2] = TradeProp.TradeDate; result[0, 3] = TradeProp.MaturityDate; result[0, 4] = TradeProp.EffectiveDate; result[0, 5] = TradeProp.TradeState; result[0, 6] = TradeProp.RequiredCurrencies; result[0, 7] = TradeProp.RequiredPricingStructures; result[0, 8] = TradeProp.ProductTaxonomy; result[0, 9] = TradeProp.AsAtDate; result[0, 10] = EnvironmentProp.SourceSystem; result[0, 11] = TradeProp.TradingBookId; result[0, 12] = TradeProp.TradingBookName; result[0, 13] = TradeProp.BaseParty; result[0, 14] = TradeProp.Party1; result[0, 15] = TradeProp.CounterPartyName; result[0, 16] = TradeProp.Party2; // now add data rows int tradeNum = 1; foreach (ICoreItem item in items) { try { //var fpmlTrade = (Trade)item.Data; result[tradeNum, 0] = item.AppProps.GetValue <string>(TradeProp.ProductType); result[tradeNum, 1] = item.AppProps.GetValue <string>(TradeProp.TradeId); result[tradeNum, 2] = item.AppProps.GetValue <DateTime>(TradeProp.TradeDate).ToShortDateString(); result[tradeNum, 3] = item.AppProps.GetValue <DateTime>(TradeProp.MaturityDate).ToShortDateString(); result[tradeNum, 4] = item.AppProps.GetValue <DateTime>(TradeProp.EffectiveDate).ToShortDateString(); result[tradeNum, 5] = item.AppProps.GetValue <string>(TradeProp.TradeState); result[tradeNum, 6] = String.Join(";", item.AppProps.GetArray <string>(TradeProp.RequiredCurrencies)); result[tradeNum, 7] = String.Join(";", item.AppProps.GetArray <string>(TradeProp.RequiredPricingStructures)); result[tradeNum, 8] = item.AppProps.GetValue <string>(TradeProp.ProductTaxonomy, null); result[tradeNum, 9] = item.AppProps.GetValue <DateTime>(TradeProp.AsAtDate).ToShortDateString(); result[tradeNum, 10] = item.AppProps.GetValue <string>(EnvironmentProp.SourceSystem); result[tradeNum, 11] = item.AppProps.GetValue <string>(TradeProp.TradingBookId); result[tradeNum, 12] = item.AppProps.GetValue <string>(TradeProp.TradingBookName); result[tradeNum, 13] = item.AppProps.GetValue <string>(TradeProp.BaseParty); result[tradeNum, 14] = item.AppProps.GetValue <string>(TradeProp.Party1); result[tradeNum, 15] = item.AppProps.GetValue <string>(TradeProp.CounterPartyName); result[tradeNum, 16] = item.AppProps.GetValue <string>(TradeProp.OriginatingPartyName); tradeNum++; } catch (Exception e) { Debug.Print("TradeStoreExcelApi.QueryTrades: Exception: {0}", e); } } //} //catch (Exception e) //{ // Debug.Print("TradeStoreExcelApi.QueryTrades: Exception: {0}", e); //} //finally //{ // Debug.Print("TradeStoreExcelApi.QueryTrades: Leave"); //} return(result); }
public void ProcessRequest(RequestBase request, HandlerResponse response) { if (request == null) { throw new ArgumentNullException(nameof(request)); } var tradeValRequest = request as TradeValuationRequest; if (tradeValRequest == null) { throw new InvalidCastException( $"{typeof(RequestBase).Name} is not a {typeof(TradeValuationRequest).Name}"); } DateTime lastStatusPublishedAt = DateTime.Now; var nameSpace = tradeValRequest.NameSpace; // common properties string reportingCurrency = tradeValRequest.ReportingCurrency; string market = tradeValRequest.MarketName; // build a single trade portfolio var tradeItemInfos = new Dictionary <string, ICoreItemInfo>(); ICoreItemInfo tradeItemInfo = Context.Cache.LoadItemInfo <Trade>(tradeValRequest.TradeItemName); if (tradeItemInfo != null) { tradeItemInfos[tradeValRequest.TradeItemName] = tradeItemInfo; } // define scenario loops // - always include un-stressed scenario (null) var irScenarios = new List <string> { null }; if (tradeValRequest.IRScenarioNames != null) { irScenarios.AddRange(tradeValRequest.IRScenarioNames); } string[] irScenarioNames = irScenarios.Distinct().ToArray(); var fxScenarios = new List <string> { null }; if (tradeValRequest.FXScenarioNames != null) { fxScenarios.AddRange(tradeValRequest.FXScenarioNames); } string[] fxScenarioNames = fxScenarios.Distinct().ToArray(); // update progress status response.ItemCount = irScenarios.Count * fxScenarios.Count * tradeItemInfos.Count; response.Status = RequestStatusEnum.InProgress; Context.Cache.SaveObject(response); // preload *all* curves into the cache // note: this is required to optimise all subsequent curve queries Context.Cache.LoadItems <Market>(Expr.ALL); // load and sort scenario definition rules var clauses = new List <IExpression> { Expr.IsEQU(EnvironmentProp.NameSpace, nameSpace) }; var scenarioRules = Context.Cache.LoadObjects <ScenarioRule>(Expr.BoolAND(clauses.ToArray())); var sortedScenarioRules = new List <CachedScenarioRule>(); { sortedScenarioRules.AddRange(from scenarioRule in scenarioRules where !scenarioRule.Disabled select new CachedScenarioRule(scenarioRule.ScenarioId, scenarioRule.RuleId, scenarioRule.Priority, (scenarioRule.FilterExpr != null) ? Expr.Create(scenarioRule.FilterExpr) : Expr.ALL, scenarioRule.StressId)); } sortedScenarioRules.Sort(); // build distinct lists of curve names and currencies required by the Trade var curvenamesList = new List <string>(); var currenciesList = new List <string>(); foreach (var item in tradeItemInfos.Values) { curvenamesList.AddRange(item.AppProps.GetArray <string>(TradeProp.RequiredPricingStructures)); currenciesList.AddRange(item.AppProps.GetArray <string>(TradeProp.RequiredCurrencies)); } curvenamesList = new List <string>(curvenamesList.Distinct().Where(x => !String.IsNullOrEmpty(x))); currenciesList = new List <string>(currenciesList.Distinct().Where(x => !String.IsNullOrEmpty(x))); IEnumerable <string> metrics = GetSwapMetrics(); // run the scenario rules ONCE for each IR and FX scenario to determine which // stressed curves to use when pricing. var resolvedCurveProps = new Dictionary <string, NamedValueSet>(); // IR loop var irScenarioCurveMap = new List <CurveStressPair> [irScenarioNames.Length]; for (int i = 0; i < irScenarioNames.Length; i++) { string irScenario = irScenarioNames[i]; irScenarioCurveMap[i] = new List <CurveStressPair>(); foreach (string curveName in curvenamesList) { string curveSignature = CurveLoader.IrCurveSignature(market, curveName, null); NamedValueSet curveProperties; if (!resolvedCurveProps.TryGetValue(curveSignature, out curveProperties)) { // not cached - resolve and cache curveProperties = PricingStructureFactory.GetInterestRateCurveProperties(Context.Logger, Context.Cache, request.NameSpace, market, curveName, null); resolvedCurveProps[curveSignature] = curveProperties; } string stressName = CachedScenarioRule.RunScenarioRules(sortedScenarioRules, irScenario, curveProperties); irScenarioCurveMap[i].Add(new CurveStressPair(curveName, stressName)); } } // FX loop var fxScenarioCurveMap = new List <CurveStressPair> [fxScenarioNames.Length]; for (int j = 0; j < fxScenarioNames.Length; j++) { string fxScenario = fxScenarioNames[j]; fxScenarioCurveMap[j] = new List <CurveStressPair>(); foreach (string currency in currenciesList) { string curveSignature = CurveLoader.FxCurveSignature(market, currency, reportingCurrency, null); NamedValueSet curveProperties; if (!resolvedCurveProps.TryGetValue(curveSignature, out curveProperties)) { // not cached - resolve and cache curveProperties = PricingStructureFactory.GetFxCurveProperties(Context.Logger, Context.Cache, request.NameSpace, market, currency, reportingCurrency); resolvedCurveProps[curveSignature] = curveProperties; } string stressName = CachedScenarioRule.RunScenarioRules(sortedScenarioRules, fxScenario, curveProperties); fxScenarioCurveMap[j].Add(new CurveStressPair(currency, stressName)); } } // iterate the scenario loops var resolvedCurveCache = new Dictionary <string, ICurve>(); var reportNameCache = new Dictionary <string, string>(); for (int i = 0; i < irScenarioNames.Length; i++) { string irScenario = irScenarioNames[i]; for (int j = 0; j < fxScenarioNames.Length; j++) { string fxScenario = fxScenarioNames[j]; // check for workflow cancellation (user abort, server shutdown etc.) if (Cancelled) { throw new OperationCanceledException(CancelReason); } // initialise the pricer with the IR/FX scenario curve maps var pricer = new PortfolioPricer(irScenarioCurveMap[i], fxScenarioCurveMap[j]); // now price the Trade if (metrics != null) { var enumerable = metrics.ToArray(); pricer.PriceAndPublish( Context.Logger, Context.Cache, resolvedCurveCache, reportNameCache, response, tradeItemInfos.Keys, tradeValRequest, irScenario, fxScenario, reportingCurrency, tradeValRequest.BaseParty, enumerable, false); } // export to valuation database //foreach (var valuationItem in valuationItems) //{ // ExportValuation(valuationItem); //} DateTime dtNow = DateTime.Now; if ((dtNow - lastStatusPublishedAt) > TimeSpan.FromSeconds(5)) { lastStatusPublishedAt = dtNow; response.Status = RequestStatusEnum.InProgress; Context.Cache.SaveObject(response); } } // foreach ir scenario } // foreach fx scenario // success response.Status = RequestStatusEnum.Completed; }
public void ProcessItems() { int count = Interlocked.Decrement(ref _queuedCalls); // exit if there are more callbacks following us //if (count % 10000 == 0) _loggerRef.Target.LogDebug("ProcessItems: Queued calls remaining: {0}", count); if (count != 0) { return; } ICoreItem item = null; _queuedItems.Locked(queue => { if (queue.Count > 0) { item = queue.Dequeue(); } }); while (item != null) { var qas = item.Data as QuotedAssetSet; if (qas != null) { // 1. Get the property values that uniquely identify the curves to refresh. // This is the process for the workflow request. Alternatively, a direct build of the curve can occur. // var nameSpace = item.AppProps.GetValue <string>(EnvironmentProp.NameSpace); var market = item.AppProps.GetValue <string>(CurveProp.Market);//For real time use Market and not MarketAndDate var curveType = item.AppProps.GetValue <string>(CurveProp.PricingStructureType); var curveName = item.AppProps.GetValue <string>(CurveProp.CurveName); var configIdentifier = FunctionProp.Configuration + ".PricingStructures." + market + "." + curveType + "." + curveName; var identifier = FunctionProp.Market + "." + market + "." + curveType + "." + curveName; List <ICoreItem> items = null; // 2.Check if the dependent curves should be refreshed // if (chkBoxDependentCurves.Checked) { //Find all the QAS's where the ReferenceCurveName is equal to the curveType.curveName! var requestProperties = new NamedValueSet(); requestProperties.Set(EnvironmentProp.NameSpace, NameSpace); requestProperties.Set(CurveProp.Market, market); requestProperties.Set(EnvironmentProp.Function, FunctionProp.Configuration); requestProperties.Set(CurveProp.ReferenceCurveName, curveType + '.' + curveName); IExpression queryExpr = Expr.BoolAND(requestProperties); _loggerRef.Target.LogDebug("Dependent curve property request set at {0}", DateTime.Now.ToLongTimeString()); items = _cache.LoadItems <Market>(queryExpr); } // 3. If the build is a local build then use the curve engine. // if (!chkBoxWorkflow.Checked) { _loggerRef.Target.LogDebug("Request to build base curve {0} locally at : {1}", identifier, DateTime.Now.ToLongTimeString()); var curve = CurveEngine.RefreshPricingStructureFromConfiguration(_loggerRef.Target, _cache, nameSpace, configIdentifier, identifier, qas, DateTime.Now, DateTime.Now); _loggerRef.Target.LogDebug("Built the base curve {0} locally at : {1}", curve, DateTime.Now.ToLongTimeString()); if (items != null) { foreach (var dataItem in items) { var spreadCurve = dataItem.Data as Market; if (spreadCurve == null) { continue; } //var bootstrap = dataItem.AppProps.GetValue<bool>(CurveProp.BootStrap, false); //if (!bootstrap) { dataItem.AppProps.Set(CurveProp.BootStrap, true); } try { var curveId = spreadCurve.id; if (String.IsNullOrEmpty(curveId)) { curveId = spreadCurve.Items[0].id; //use yieldCurve.id, CurveGen 1.X compatible } dataItem.AppProps.Set(CurveProp.BaseDate, DateTime.Now); dataItem.AppProps.Set(CurveProp.BuildDateTime, DateTime.Now); var marketData = new Pair <PricingStructure, PricingStructureValuation>(spreadCurve.Items[0], spreadCurve.Items1[0]); var ps = PricingStructureFactory.Create(_loggerRef.Target, _cache, nameSpace, null, null, marketData, dataItem.AppProps); if (ps != null) { CurveEngine.SaveCurve(_cache, nameSpace, ps); } _loggerRef.Target.LogDebug("Built the spread curve {0} locally at : {1}", curveId, DateTime.Now.ToLongTimeString()); } catch (Exception e) { _loggerRef.Target.LogDebug(e.ToString()); } } } } else { // 4. Set the parameters for the work request. // var curveGenRequest = new OrdinaryCurveGenRequest { NameSpace = nameSpace, BaseDate = DateTime.Now, RequestId = Guid.NewGuid().ToString(), RequesterId = new UserIdentity { Name = _cache.ClientInfo.Name, DisplayName = _cache.ClientInfo.UserFullName //Name = _clientRef.Target.ClientInfo.Name, //DisplayName = _clientRef.Target.ClientInfo.UserFullName }, UseSavedMarketData = true, ForceGenerateEODCurves = true }; // 5. Set the base curve in the curve selection for the work request. // var curveSelector = new List <CurveSelection> { new CurveSelection { NameSpace = nameSpace, MarketName = market, CurveType = curveType, CurveName = curveName } }; // 6.Include all other dependent curvenames i.e. spread curves. // if (items != null) { curveSelector.AddRange(from childCurve in items let spreadCurveType = childCurve.AppProps.GetValue <string>( CurveProp.PricingStructureType) let spreadCurveName = childCurve.AppProps.GetValue <string>(CurveProp.CurveName) select new CurveSelection { NameSpace = nameSpace, MarketName = market, CurveType = spreadCurveType, CurveName = spreadCurveName }); } curveGenRequest.CurveSelector = curveSelector.ToArray(); // 7. Set the actual work request. // IWorkContext context = new WorkContext(_loggerRef.Target, _cache, "DEV"); //IWorkContext context = new WorkContext(_loggerRef.Target, _clientRef.Target, "DEV"); _loggerRef.Target.LogDebug("WorkContext set at {0}", DateTime.Now.ToLongTimeString()); using (var workflow = new WFGenerateOrdinaryCurve()) { workflow.Initialise(context); WorkflowOutput <HandlerResponse> output = workflow.Execute(curveGenRequest); WorkflowHelper.ThrowErrors(output.Errors); foreach (var error in output.Errors) { _loggerRef.Target.LogInfo("WorkFlow error: {0} at {1}", error.Message, DateTime.Now.ToLongTimeString()); } } _loggerRef.Target.LogDebug("WorkFlow executed at {0}", DateTime.Now.ToLongTimeString()); //item = null; //_queuedItems.Locked(queue => // { // if (queue.Count > 0) // item = queue.Dequeue(); // }); } } } }
public void ProcessRequest(RequestBase baseRequest, HandlerResponse response) { if (baseRequest == null) { throw new ArgumentNullException(nameof(baseRequest)); } if (!(baseRequest is PortfolioValuationRequest request)) { throw new InvalidCastException( $"{typeof(RequestBase).Name} is not a {typeof(PortfolioValuationRequest).Name}"); } DateTime lastStatusPublishedAt = DateTime.Now; // common properties var nameSpace = request.NameSpace; // resolve portfolio valuation request var identifier = (new PortfolioSpecification(request.PortfolioId, request.NameSpace)).NetworkKey; var portfolio = Context.Cache.LoadObject <PortfolioSpecification>(identifier); if (portfolio == null) { throw new ArgumentException($"Unknown portfolio id: '{request.PortfolioId}'"); } // build trade query from portfolio definition var tradeItemInfos = new Dictionary <string, ICoreItemInfo>(); if (portfolio.PortfolioSubqueries != null) { foreach (var subQuery in portfolio.PortfolioSubqueries.OrderBy(x => x.SequenceOrder)) { var clauses = new List <IExpression> { Expr.IsEQU(EnvironmentProp.NameSpace, nameSpace) }; if (subQuery.CounterpartyId != null) { clauses.Add(Expr.IsEQU(TradeProp.CounterPartyId, subQuery.CounterpartyId)); } if (subQuery.TradingBookId != null) { clauses.Add(Expr.IsEQU(TradeProp.TradingBookId, subQuery.TradingBookId)); } // load trades defined by the query if (clauses.Count <= 0) { continue; } List <ICoreItemInfo> subQueryItems = Context.Cache.LoadItemInfos <Trade>(Expr.BoolAND(clauses.ToArray())); //TODO again have to handle confirmation foreach (var tradeItemInfo in subQueryItems) { if (subQuery.ExcludeItems) { tradeItemInfos.Remove(tradeItemInfo.Name); } else { tradeItemInfos[tradeItemInfo.Name] = tradeItemInfo; } } } } // process included/excluded trades ids if (portfolio.ExcludeOverridesInclude) { // add included names if (portfolio.IncludedTradeItemNames != null) { foreach (var name in portfolio.IncludedTradeItemNames) { var tradeItemInfo = name.Contains(FpML5R10NameSpaces.Confirmation) ? Context.Cache.LoadItemInfo <FpML.V5r10.Confirmation.Trade>(name) : Context.Cache.LoadItemInfo <Trade>(name); if (tradeItemInfo != null) { tradeItemInfos[name] = tradeItemInfo; } } } } // remove excluded names if (portfolio.ExcludedTradeItemNames != null) { foreach (var name in portfolio.ExcludedTradeItemNames) { tradeItemInfos.Remove(name); } } if (!portfolio.ExcludeOverridesInclude) { // add included names if (portfolio.IncludedTradeItemNames != null) { foreach (var name in portfolio.IncludedTradeItemNames) { var tradeItemInfo = name.Contains(FpML5R10NameSpaces.Confirmation) ? Context.Cache.LoadItemInfo <FpML.V5r10.Confirmation.Trade>(name) : Context.Cache.LoadItemInfo <Trade>(name); if (tradeItemInfo != null) { tradeItemInfos[name] = tradeItemInfo; } } } } // define scenario loops // - always include un-stressed scenario (null) var marketScenarios = new List <DateTime>(); if (request.DateScenarios != null) { marketScenarios.AddRange(request.DateScenarios); } // update progress status response.ItemCount = marketScenarios.Count * tradeItemInfos.Count; response.Status = RequestStatusEnum.InProgress; Context.Cache.SaveObject(response); // preload *all* curves into the cache // note: this is required to optimise all subsequent curve queries var markets = new List <IExpression> { Expr.IsEQU(EnvironmentProp.NameSpace, nameSpace) }; Context.Cache.LoadItems <Market>(Expr.BoolAND(markets.ToArray())); // build distinct lists of curve names and currencies required by the portfolio var curvenamesList = new List <string>(); var currenciesList = new List <string>(); foreach (var item in tradeItemInfos.Values) { curvenamesList.AddRange(item.AppProps.GetArray <string>(TradeProp.RequiredPricingStructures)); currenciesList.AddRange(item.AppProps.GetArray <string>(TradeProp.RequiredCurrencies)); } curvenamesList = new List <string>(curvenamesList.Distinct().Where(x => !String.IsNullOrEmpty(x))); currenciesList = new List <string>(currenciesList.Distinct().Where(x => !String.IsNullOrEmpty(x))); var metrics = GetSwapMetrics(); // check for workflow cancellation (user abort, server shutdown etc.) if (Cancelled) { throw new OperationCanceledException(CancelReason); } // initialise the pricer with the IR/FX scenario curve maps var portfolioPricer = new PortfolioPricer(); var keyList = tradeItemInfos.Keys.ToList(); // now price the portfolio portfolioPricer.PriceAndPublish( Context.Logger, Context.Cache, response, curvenamesList, currenciesList, keyList, request, metrics, false); var dtNow = DateTime.Now; if ((dtNow - lastStatusPublishedAt) > TimeSpan.FromSeconds(5)) { //lastStatusPublishedAt = dtNow; response.Status = RequestStatusEnum.InProgress; Context.Cache.SaveObject(response); } // success response.Status = RequestStatusEnum.Completed; }
public void TestFailingExpressions() { // tests expressions that fail to evaluate on the server using (Reference <ILogger> loggerRef = Reference <ILogger> .Create(new TraceLogger(true))) { NamedValueSet serverSettings = new NamedValueSet(); serverSettings.Set(CfgPropName.NodeType, (int)NodeType.Router); serverSettings.Set(CfgPropName.EnvName, "UTT"); using (CoreServer server = new CoreServer(loggerRef, serverSettings)) { server.Start(); // save using (ICoreClient client1 = new CoreClientFactory(loggerRef).SetEnv("UTT").Create()) { client1.SaveObject(new TestData(), "AllValuesNotNull", new NamedValueSet("StrValue/String=A|NumValue/Int32=0"), TimeSpan.MaxValue); client1.SaveObject(new TestData(), "NumValueIsNull", new NamedValueSet("StrValue/String=A"), TimeSpan.MaxValue); client1.SaveObject(new TestData(), "StrValueIsNull", new NamedValueSet("NumValue/Int32=0"), TimeSpan.MaxValue); client1.SaveObject(new TestData(), "AllValuesAreNull", null, TimeSpan.MaxValue); } // load using expression using (ICoreClient client2 = new CoreClientFactory(loggerRef).SetEnv("UTT").Create()) { client2.DebugRequests = true; { var items = client2.LoadObjects <TestData>(Expr.BoolAND(Expr.IsEQU("StrValue", "A"), Expr.IsEQU("NumValue", 0))); Assert.AreEqual(1, items.Count); } { var items = client2.LoadObjects <TestData>(Expr.BoolOR(Expr.IsEQU("StrValue", "A"), Expr.IsEQU("NumValue", 0))); Assert.AreEqual(3, items.Count); } { // unknown/missing string property var items = client2.LoadObjects <TestData>(Expr.BoolOR(Expr.IsEQU("StrValue", "A"), Expr.IsEQU("XValue", "X"))); Assert.AreEqual(2, items.Count); } { // unknown/missing non-string property var items = client2.LoadObjects <TestData>(Expr.BoolOR(Expr.IsEQU("StrValue", "A"), Expr.IsEQU("YValue", 1))); Assert.AreEqual(2, items.Count); } { // property missing var items = client2.LoadObjects <TestData>(Expr.IsNull("StrValue")); Assert.AreEqual(2, items.Count); } { // property has value var items = client2.LoadObjects <TestData>(Expr.IsNotNull("StrValue")); Assert.AreEqual(2, items.Count); } { var items = client2.LoadObjects <TestData>(Expr.StartsWith("StrValue", "A")); Assert.AreEqual(2, items.Count); } { var items = client2.LoadObjects <TestData>(Expr.BoolOR(Expr.StartsWith("StrValue", "A"), Expr.IsEQU("NumValue", 0))); Assert.AreEqual(3, items.Count); } } } } }