public void Swap(Swap swap) { var from = new Point(swap.From.X, swap.From.Y); var to = new Point(swap.To.X, swap.To.Y); _animals[from.X, from.Y] = swap.To; swap.To.MoveTo(from.X, from.Y); _animals[to.X, to.Y] = swap.From; swap.From.MoveTo(to.X, to.Y); }
public bool Equals(Swap obj) { if (obj == null) return false; return (this == obj); }
public void SwapEnsureCanAssignAcceptSwapStatus() { Swap swapping = new Swap(); swapping.AcceptSwap = true; bool expected = true; bool actual = swapping.AcceptSwap; Assert.AreEqual(expected, actual); }
public void SwapEnsureICanAssignBeerNameAvailable() { Swap swapping = new Swap(); swapping.BeerName = "Pale Ale"; string expected = "Pale Ale"; string actual = swapping.BeerName; Assert.AreEqual(expected, actual); }
public void SwapEnsureICanAssignBeerNameOffered() { Swap swapping = new Swap(); swapping.BeerOffered = "Dos Perros"; string expected = "Dos Perros"; string actual = swapping.BeerOffered; Assert.AreEqual(expected, actual); }
public void SwapEnsureICanAssignQtyAvailable() { Swap swapping = new Swap(); swapping.QtyOffered = 3; int expected = 3; int actual = swapping.QtyOffered; Assert.AreEqual(expected, actual); }
public void SwapEnsureICanAssignQtyWanted() { Swap swapping = new Swap(); swapping.QtyWanted = 2; int expected = 2; int actual = swapping.QtyWanted; Assert.AreEqual(expected, actual); }
public Swap CreateSwap(string _specificUser) { Swap make_swap = new Swap { OfferUserId = _specificUser }; context.Swaps.Add(make_swap); context.SaveChanges(); return make_swap; }
public bool AddSwap(int _beerpostid, Swap haveSwap) { var query = from p in context.BeerPostings where p.BeerPostingID == _beerpostid select p; BeerPosting foundPosting = null; bool result = true; try { foundPosting = query.Single<BeerPosting>(); foundPosting.Swaps.Add(haveSwap); context.SaveChanges(); } catch (InvalidOperationException) { result = false; } catch(ArgumentNullException) { result = false; } return result; }
public void testDecomposition() { // Testing collared coupon against its decomposition... CommonVars vars= new CommonVars(); double tolerance = 1e-10; double npvVanilla,npvCappedLeg,npvFlooredLeg,npvCollaredLeg,npvCap,npvFloor,npvCollar; double error; double floorstrike = 0.05; double capstrike = 0.10; InitializedList<double> caps = new InitializedList<double>(vars.length,capstrike); List<double> caps0 = new List<double>(); InitializedList<double> floors = new InitializedList<double>(vars.length,floorstrike); List<double> floors0 = new List<double>(); double gearing_p = 0.5; double spread_p = 0.002; double gearing_n = -1.5; double spread_n = 0.12; // fixed leg with zero rate List<CashFlow> fixedLeg = vars.makeFixedLeg(vars.startDate,vars.length); // floating leg with gearing=1 and spread=0 List<CashFlow> floatLeg = vars.makeYoYLeg(vars.startDate,vars.length); // floating leg with positive gearing (gearing_p) and spread<>0 List<CashFlow> floatLeg_p = vars.makeYoYLeg(vars.startDate,vars.length,gearing_p,spread_p); // floating leg with negative gearing (gearing_n) and spread<>0 List<CashFlow> floatLeg_n = vars.makeYoYLeg(vars.startDate,vars.length,gearing_n,spread_n); // Swap with null fixed leg and floating leg with gearing=1 and spread=0 Swap vanillaLeg = new Swap(fixedLeg,floatLeg); // Swap with null fixed leg and floating leg with positive gearing and spread<>0 Swap vanillaLeg_p = new Swap(fixedLeg,floatLeg_p); // Swap with null fixed leg and floating leg with negative gearing and spread<>0 Swap vanillaLeg_n = new Swap(fixedLeg,floatLeg_n); IPricingEngine engine = new DiscountingSwapEngine(vars.nominalTS); vanillaLeg.setPricingEngine(engine); // here use the autoset feature vanillaLeg_p.setPricingEngine(engine); vanillaLeg_n.setPricingEngine(engine); // CAPPED coupon - Decomposition of payoff // Payoff = Nom * Min(rate,strike) * accrualperiod = // = Nom * [rate + Min(0,strike-rate)] * accrualperiod = // = Nom * rate * accrualperiod - Nom * Max(rate-strike,0) * accrualperiod = // = VanillaFloatingLeg - Call // int whichPricer = 0; // Case gearing = 1 and spread = 0 List<CashFlow> cappedLeg = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length, caps,floors0,vars.volatility); Swap capLeg = new Swap(fixedLeg,cappedLeg); capLeg.setPricingEngine(engine); YoYInflationCap cap = new YoYInflationCap(floatLeg, new List<double>(){capstrike}); cap.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvVanilla = vanillaLeg.NPV(); npvCappedLeg = capLeg.NPV(); npvCap = cap.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla-npvCap)); if (error>tolerance) { Assert.Fail("\nYoY Capped Leg: gearing=1, spread=0%, strike=" + capstrike*100 + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" + " Diff: " + error ); } // gearing = 1 and spread = 0 // FLOORED coupon - Decomposition of payoff // Payoff = Nom * Max(rate,strike) * accrualperiod = // = Nom * [rate + Max(0,strike-rate)] * accrualperiod = // = Nom * rate * accrualperiod + Nom * Max(strike-rate,0) * accrualperiod = // = VanillaFloatingLeg + Put // List<CashFlow> flooredLeg = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length, caps0,floors,vars.volatility); Swap floorLeg = new Swap(fixedLeg,flooredLeg); floorLeg.setPricingEngine(engine); YoYInflationFloor floor= new YoYInflationFloor(floatLeg, new List<double>(){floorstrike}); floor.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvFlooredLeg = floorLeg.NPV(); npvFloor = floor.NPV(); error = Math.Abs(npvFlooredLeg-(npvVanilla + npvFloor)); if (error>tolerance) { Assert.Fail("YoY Floored Leg: gearing=1, spread=0%, strike=" + floorstrike *100 + "%\n" + " Floored Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor) + "\n" + " Diff: " + error ); } // gearing = 1 and spread = 0 // COLLARED coupon - Decomposition of payoff // Payoff = Nom * Min(strikem,Max(rate,strikeM)) * accrualperiod = // = VanillaFloatingLeg - Collar // List<CashFlow> collaredLeg = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length, caps,floors,vars.volatility); Swap collarLeg = new Swap(fixedLeg,collaredLeg); collarLeg.setPricingEngine(engine); YoYInflationCollar collar = new YoYInflationCollar(floatLeg, new List<double>(){capstrike}, new List<double>(){floorstrike}); collar.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvCollaredLeg = collarLeg.NPV(); npvCollar = collar.NPV(); error = Math.Abs(npvCollaredLeg -(npvVanilla - npvCollar)); if (error>tolerance) { Assert.Fail("\nYoY Collared Leg: gearing=1, spread=0%, strike=" + floorstrike*100 + "% and " + capstrike*100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar) + "\n" + " Diff: " + error ); } // gearing = a and spread = b // CAPPED coupon - Decomposition of payoff // Payoff // = Nom * Min(a*rate+b,strike) * accrualperiod = // = Nom * [a*rate+b + Min(0,strike-a*rate-b)] * accrualperiod = // = Nom * a*rate+b * accrualperiod + Nom * Min(strike-b-a*rate,0) * accrualperiod // --> If a>0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg - Call(a*rate+b,strike) // --> If a<0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg + Nom * Min(strike-b+|a|*rate+,0) * accrualperiod = // = VanillaFloatingLeg + Put(|a|*rate+b,strike) // // Positive gearing List<CashFlow> cappedLeg_p = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps,floors0, vars.volatility,gearing_p,spread_p); Swap capLeg_p = new Swap(fixedLeg,cappedLeg_p); capLeg_p.setPricingEngine(engine); YoYInflationCap cap_p = new YoYInflationCap(floatLeg_p,new List<double>(){capstrike}); cap_p.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvVanilla = vanillaLeg_p.NPV(); npvCappedLeg = capLeg_p.NPV(); npvCap = cap_p.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla-npvCap)); if (error>tolerance) { Assert.Fail("\nYoY Capped Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p *100 + "%, strike=" + capstrike*100 + "%, " + "effective strike= " + (capstrike-spread_p)/gearing_p*100 + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " Vanilla Leg NPV: " + npvVanilla + "\n" + " Cap NPV: " + npvCap + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" + " Diff: " + error ); } // Negative gearing List<CashFlow> cappedLeg_n = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps,floors0, vars.volatility,gearing_n,spread_n); Swap capLeg_n = new Swap(fixedLeg,cappedLeg_n); capLeg_n.setPricingEngine(engine); YoYInflationFloor floor_n = new YoYInflationFloor(floatLeg,new List<double>(){(capstrike-spread_n)/gearing_n}); floor_n.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvVanilla = vanillaLeg_n.NPV(); npvCappedLeg = capLeg_n.NPV(); npvFloor = floor_n.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla+ gearing_n*npvFloor)); if (error>tolerance) { Assert.Fail("\nYoY Capped Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n *100 + "%, strike=" + capstrike*100 + "%, " + "effective strike= " + ((capstrike-spread_n)/gearing_n*100) + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " npv Vanilla: " + npvVanilla + "\n" + " npvFloor: " + npvFloor + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla + gearing_n*npvFloor) + "\n" + " Diff: " + error ); } // gearing = a and spread = b // FLOORED coupon - Decomposition of payoff // Payoff // = Nom * Max(a*rate+b,strike) * accrualperiod = // = Nom * [a*rate+b + Max(0,strike-a*rate-b)] * accrualperiod = // = Nom * a*rate+b * accrualperiod + Nom * Max(strike-b-a*rate,0) * accrualperiod // --> If a>0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg + Put(a*rate+b,strike) // --> If a<0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg + Nom * Max(strike-b+|a|*rate+,0) * accrualperiod = // = VanillaFloatingLeg - Call(|a|*rate+b,strike) // // Positive gearing List<CashFlow> flooredLeg_p1 = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps0,floors, vars.volatility,gearing_p,spread_p); Swap floorLeg_p1 = new Swap(fixedLeg,flooredLeg_p1); floorLeg_p1.setPricingEngine(engine); YoYInflationFloor floor_p1 = new YoYInflationFloor(floatLeg_p,new List<double>(){floorstrike}); floor_p1.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvVanilla = vanillaLeg_p.NPV(); npvFlooredLeg = floorLeg_p1.NPV(); npvFloor = floor_p1.NPV(); error = Math.Abs(npvFlooredLeg - (npvVanilla+npvFloor)); if (error>tolerance) { Assert.Fail("\nYoY Floored Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p *100+ "%, strike=" + floorstrike *100 + "%, " + "effective strike= " + (floorstrike-spread_p)/gearing_p*100 + "%\n" + " Floored Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor) + "\n" + " Diff: " + error ); } // Negative gearing List<CashFlow> flooredLeg_n = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps0,floors, vars.volatility,gearing_n,spread_n); Swap floorLeg_n = new Swap(fixedLeg,flooredLeg_n); floorLeg_n.setPricingEngine(engine); YoYInflationCap cap_n = new YoYInflationCap(floatLeg,new List<double>(){(floorstrike-spread_n)/gearing_n}); cap_n.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvVanilla = vanillaLeg_n.NPV(); npvFlooredLeg = floorLeg_n.NPV(); npvCap = cap_n.NPV(); error = Math.Abs(npvFlooredLeg - (npvVanilla - gearing_n*npvCap)); if (error>tolerance) { Assert.Fail("\nYoY Capped Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n *100 + "%, strike=" + floorstrike*100 + "%, " + "effective strike= " + (floorstrike-spread_n)/gearing_n*100 + "%\n" + " Capped Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - gearing_n*npvCap) + "\n" + " Diff: " + error ); } // gearing = a and spread = b // COLLARED coupon - Decomposition of payoff // Payoff = Nom * Min(caprate,Max(a*rate+b,floorrate)) * accrualperiod // --> If a>0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg - Collar(a*rate+b, floorrate, caprate) // --> If a<0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg + Collar(|a|*rate+b, caprate, floorrate) // // Positive gearing List<CashFlow> collaredLeg_p = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps,floors, vars.volatility,gearing_p,spread_p); Swap collarLeg_p1 = new Swap(fixedLeg,collaredLeg_p); collarLeg_p1.setPricingEngine(engine); YoYInflationCollar collar_p = new YoYInflationCollar(floatLeg_p, new List<double>(){capstrike}, new List<double>(){floorstrike}); collar_p.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvVanilla = vanillaLeg_p.NPV(); npvCollaredLeg = collarLeg_p1.NPV(); npvCollar = collar_p.NPV(); error = Math.Abs(npvCollaredLeg - (npvVanilla - npvCollar)); if (error>tolerance) { Assert.Fail("\nYoY Collared Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p*100 + "%, strike=" + floorstrike*100 + "% and " + capstrike*100 + "%, " + "effective strike=" + (floorstrike-spread_p)/gearing_p*100 + "% and " + (capstrike-spread_p)/gearing_p*100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar) + "\n" + " Diff: " + error ); } // Negative gearing List<CashFlow> collaredLeg_n = vars.makeYoYCapFlooredLeg(whichPricer,vars.startDate,vars.length,caps,floors, vars.volatility,gearing_n,spread_n); Swap collarLeg_n1 = new Swap(fixedLeg,collaredLeg_n); collarLeg_n1.setPricingEngine(engine); YoYInflationCollar collar_n = new YoYInflationCollar(floatLeg, new List<double>(){(floorstrike-spread_n)/gearing_n}, new List<double>(){(capstrike-spread_n)/gearing_n}); collar_n.setPricingEngine(vars.makeEngine(vars.volatility,whichPricer)); npvVanilla = vanillaLeg_n.NPV(); npvCollaredLeg = collarLeg_n1.NPV(); npvCollar = collar_n.NPV(); error = Math.Abs(npvCollaredLeg - (npvVanilla - gearing_n*npvCollar)); if (error>tolerance) { Assert.Fail("\nYoY Collared Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n*100 + "%, strike=" + floorstrike*100 + "% and " + capstrike*100 + "%, " + "effective strike=" + (floorstrike-spread_n)/gearing_n*100 + "% and " + (capstrike-spread_n)/gearing_n*100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - gearing_n*npvCollar) + "\n" + " Diff: " + error ); } // remove circular refernce vars.hy.linkTo(new YoYInflationTermStructure()); }
public bool IsPossibleSwap(Swap swap) => _possibleSwaps.Contains(swap);
public Task <bool> AddSwapAsync(Swap swap) => DataRepository.AddSwapAsync(swap);
public Trade(XmlNode xmlNode) { XmlNodeList tradeHeaderNodeList = xmlNode.SelectNodes("tradeHeader"); if (tradeHeaderNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in tradeHeaderNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { tradeHeaderIDRef = item.Attributes["id"].Name; TradeHeader ob = TradeHeader(); IDManager.SetID(tradeHeaderIDRef, ob); } else if (item.Attributes.ToString() == "href") { tradeHeaderIDRef = item.Attributes["href"].Name; } else { tradeHeader = new TradeHeader(item); } } } XmlNodeList productNodeList = xmlNode.SelectNodes("product"); if (productNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in productNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { productIDRef = item.Attributes["id"].Name; Product ob = Product(); IDManager.SetID(productIDRef, ob); } else if (item.Attributes.ToString() == "href") { productIDRef = item.Attributes["href"].Name; } else { product = new Product(item); } } } XmlNodeList forwardNodeList = xmlNode.SelectNodes("forward"); if (forwardNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in forwardNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { forwardIDRef = item.Attributes["id"].Name; ForwardSale ob = ForwardSale(); IDManager.SetID(forwardIDRef, ob); } else if (item.Attributes.ToString() == "href") { forwardIDRef = item.Attributes["href"].Name; } else { forward = new ForwardSale(item); } } } XmlNodeList bondOptionNodeList = xmlNode.SelectNodes("bondOption"); if (bondOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in bondOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { bondOptionIDRef = item.Attributes["id"].Name; BondOption ob = BondOption(); IDManager.SetID(bondOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { bondOptionIDRef = item.Attributes["href"].Name; } else { bondOption = new BondOption(item); } } } XmlNodeList creditDefaultSwapNodeList = xmlNode.SelectNodes("creditDefaultSwap"); if (creditDefaultSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in creditDefaultSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { creditDefaultSwapIDRef = item.Attributes["id"].Name; CreditDefaultSwap ob = CreditDefaultSwap(); IDManager.SetID(creditDefaultSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { creditDefaultSwapIDRef = item.Attributes["href"].Name; } else { creditDefaultSwap = new CreditDefaultSwap(item); } } } XmlNodeList creditDefaultSwapOptionNodeList = xmlNode.SelectNodes("creditDefaultSwapOption"); if (creditDefaultSwapOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in creditDefaultSwapOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { creditDefaultSwapOptionIDRef = item.Attributes["id"].Name; CreditDefaultSwapOption ob = CreditDefaultSwapOption(); IDManager.SetID(creditDefaultSwapOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { creditDefaultSwapOptionIDRef = item.Attributes["href"].Name; } else { creditDefaultSwapOption = new CreditDefaultSwapOption(item); } } } XmlNodeList commodityForwardNodeList = xmlNode.SelectNodes("commodityForward"); if (commodityForwardNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in commodityForwardNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { commodityForwardIDRef = item.Attributes["id"].Name; CommodityForward ob = CommodityForward(); IDManager.SetID(commodityForwardIDRef, ob); } else if (item.Attributes.ToString() == "href") { commodityForwardIDRef = item.Attributes["href"].Name; } else { commodityForward = new CommodityForward(item); } } } XmlNodeList commodityOptionNodeList = xmlNode.SelectNodes("commodityOption"); if (commodityOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in commodityOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { commodityOptionIDRef = item.Attributes["id"].Name; CommodityOption ob = CommodityOption(); IDManager.SetID(commodityOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { commodityOptionIDRef = item.Attributes["href"].Name; } else { commodityOption = new CommodityOption(item); } } } XmlNodeList commoditySwapNodeList = xmlNode.SelectNodes("commoditySwap"); if (commoditySwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in commoditySwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { commoditySwapIDRef = item.Attributes["id"].Name; CommoditySwap ob = CommoditySwap(); IDManager.SetID(commoditySwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { commoditySwapIDRef = item.Attributes["href"].Name; } else { commoditySwap = new CommoditySwap(item); } } } XmlNodeList commoditySwaptionNodeList = xmlNode.SelectNodes("commoditySwaption"); if (commoditySwaptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in commoditySwaptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { commoditySwaptionIDRef = item.Attributes["id"].Name; CommoditySwaption ob = CommoditySwaption(); IDManager.SetID(commoditySwaptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { commoditySwaptionIDRef = item.Attributes["href"].Name; } else { commoditySwaption = new CommoditySwaption(item); } } } XmlNodeList correlationSwapNodeList = xmlNode.SelectNodes("correlationSwap"); if (correlationSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in correlationSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { correlationSwapIDRef = item.Attributes["id"].Name; CorrelationSwap ob = CorrelationSwap(); IDManager.SetID(correlationSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { correlationSwapIDRef = item.Attributes["href"].Name; } else { correlationSwap = new CorrelationSwap(item); } } } XmlNodeList dividendSwapOptionTransactionSupplementNodeList = xmlNode.SelectNodes("dividendSwapOptionTransactionSupplement"); if (dividendSwapOptionTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in dividendSwapOptionTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { dividendSwapOptionTransactionSupplementIDRef = item.Attributes["id"].Name; DividendSwapOptionTransactionSupplement ob = DividendSwapOptionTransactionSupplement(); IDManager.SetID(dividendSwapOptionTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { dividendSwapOptionTransactionSupplementIDRef = item.Attributes["href"].Name; } else { dividendSwapOptionTransactionSupplement = new DividendSwapOptionTransactionSupplement(item); } } } XmlNodeList dividendSwapTransactionSupplementNodeList = xmlNode.SelectNodes("dividendSwapTransactionSupplement"); if (dividendSwapTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in dividendSwapTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { dividendSwapTransactionSupplementIDRef = item.Attributes["id"].Name; DividendSwapTransactionSupplement ob = DividendSwapTransactionSupplement(); IDManager.SetID(dividendSwapTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { dividendSwapTransactionSupplementIDRef = item.Attributes["href"].Name; } else { dividendSwapTransactionSupplement = new DividendSwapTransactionSupplement(item); } } } XmlNodeList instrumentTradeDetailsNodeList = xmlNode.SelectNodes("instrumentTradeDetails"); if (instrumentTradeDetailsNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in instrumentTradeDetailsNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { instrumentTradeDetailsIDRef = item.Attributes["id"].Name; InstrumentTradeDetails ob = InstrumentTradeDetails(); IDManager.SetID(instrumentTradeDetailsIDRef, ob); } else if (item.Attributes.ToString() == "href") { instrumentTradeDetailsIDRef = item.Attributes["href"].Name; } else { instrumentTradeDetails = new InstrumentTradeDetails(item); } } } XmlNodeList strategyNodeList = xmlNode.SelectNodes("strategy"); if (strategyNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in strategyNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { strategyIDRef = item.Attributes["id"].Name; Strategy ob = Strategy(); IDManager.SetID(strategyIDRef, ob); } else if (item.Attributes.ToString() == "href") { strategyIDRef = item.Attributes["href"].Name; } else { strategy = new Strategy(item); } } } XmlNodeList returnSwapNodeList = xmlNode.SelectNodes("returnSwap"); if (returnSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in returnSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { returnSwapIDRef = item.Attributes["id"].Name; ReturnSwap ob = ReturnSwap(); IDManager.SetID(returnSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { returnSwapIDRef = item.Attributes["href"].Name; } else { returnSwap = new ReturnSwap(item); } } } XmlNodeList brokerEquityOptionNodeList = xmlNode.SelectNodes("brokerEquityOption"); if (brokerEquityOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in brokerEquityOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { brokerEquityOptionIDRef = item.Attributes["id"].Name; BrokerEquityOption ob = BrokerEquityOption(); IDManager.SetID(brokerEquityOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { brokerEquityOptionIDRef = item.Attributes["href"].Name; } else { brokerEquityOption = new BrokerEquityOption(item); } } } XmlNodeList equityForwardNodeList = xmlNode.SelectNodes("equityForward"); if (equityForwardNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in equityForwardNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { equityForwardIDRef = item.Attributes["id"].Name; EquityForward ob = EquityForward(); IDManager.SetID(equityForwardIDRef, ob); } else if (item.Attributes.ToString() == "href") { equityForwardIDRef = item.Attributes["href"].Name; } else { equityForward = new EquityForward(item); } } } XmlNodeList equityOptionNodeList = xmlNode.SelectNodes("equityOption"); if (equityOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in equityOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { equityOptionIDRef = item.Attributes["id"].Name; EquityOption ob = EquityOption(); IDManager.SetID(equityOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { equityOptionIDRef = item.Attributes["href"].Name; } else { equityOption = new EquityOption(item); } } } XmlNodeList equityOptionTransactionSupplementNodeList = xmlNode.SelectNodes("equityOptionTransactionSupplement"); if (equityOptionTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in equityOptionTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { equityOptionTransactionSupplementIDRef = item.Attributes["id"].Name; EquityOptionTransactionSupplement ob = EquityOptionTransactionSupplement(); IDManager.SetID(equityOptionTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { equityOptionTransactionSupplementIDRef = item.Attributes["href"].Name; } else { equityOptionTransactionSupplement = new EquityOptionTransactionSupplement(item); } } } XmlNodeList fxSingleLegNodeList = xmlNode.SelectNodes("fxSingleLeg"); if (fxSingleLegNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fxSingleLegNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fxSingleLegIDRef = item.Attributes["id"].Name; FxSingleLeg ob = FxSingleLeg(); IDManager.SetID(fxSingleLegIDRef, ob); } else if (item.Attributes.ToString() == "href") { fxSingleLegIDRef = item.Attributes["href"].Name; } else { fxSingleLeg = new FxSingleLeg(item); } } } XmlNodeList fxSwapNodeList = xmlNode.SelectNodes("fxSwap"); if (fxSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fxSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fxSwapIDRef = item.Attributes["id"].Name; FxSwap ob = FxSwap(); IDManager.SetID(fxSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { fxSwapIDRef = item.Attributes["href"].Name; } else { fxSwap = new FxSwap(item); } } } XmlNodeList fxOptionNodeList = xmlNode.SelectNodes("fxOption"); if (fxOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fxOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fxOptionIDRef = item.Attributes["id"].Name; FxOption ob = FxOption(); IDManager.SetID(fxOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { fxOptionIDRef = item.Attributes["href"].Name; } else { fxOption = new FxOption(item); } } } XmlNodeList fxDigitalOptionNodeList = xmlNode.SelectNodes("fxDigitalOption"); if (fxDigitalOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fxDigitalOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fxDigitalOptionIDRef = item.Attributes["id"].Name; FxDigitalOption ob = FxDigitalOption(); IDManager.SetID(fxDigitalOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { fxDigitalOptionIDRef = item.Attributes["href"].Name; } else { fxDigitalOption = new FxDigitalOption(item); } } } XmlNodeList termDepositNodeList = xmlNode.SelectNodes("termDeposit"); if (termDepositNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in termDepositNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { termDepositIDRef = item.Attributes["id"].Name; TermDeposit ob = TermDeposit(); IDManager.SetID(termDepositIDRef, ob); } else if (item.Attributes.ToString() == "href") { termDepositIDRef = item.Attributes["href"].Name; } else { termDeposit = new TermDeposit(item); } } } XmlNodeList genericProductNodeList = xmlNode.SelectNodes("genericProduct"); if (genericProductNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in genericProductNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { genericProductIDRef = item.Attributes["id"].Name; GenericProduct ob = GenericProduct(); IDManager.SetID(genericProductIDRef, ob); } else if (item.Attributes.ToString() == "href") { genericProductIDRef = item.Attributes["href"].Name; } else { genericProduct = new GenericProduct(item); } } } XmlNodeList nonSchemaProductNodeList = xmlNode.SelectNodes("nonSchemaProduct"); if (nonSchemaProductNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in nonSchemaProductNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { nonSchemaProductIDRef = item.Attributes["id"].Name; GenericProduct ob = GenericProduct(); IDManager.SetID(nonSchemaProductIDRef, ob); } else if (item.Attributes.ToString() == "href") { nonSchemaProductIDRef = item.Attributes["href"].Name; } else { nonSchemaProduct = new GenericProduct(item); } } } XmlNodeList bulletPaymentNodeList = xmlNode.SelectNodes("bulletPayment"); if (bulletPaymentNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in bulletPaymentNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { bulletPaymentIDRef = item.Attributes["id"].Name; BulletPayment ob = BulletPayment(); IDManager.SetID(bulletPaymentIDRef, ob); } else if (item.Attributes.ToString() == "href") { bulletPaymentIDRef = item.Attributes["href"].Name; } else { bulletPayment = new BulletPayment(item); } } } XmlNodeList capFloorNodeList = xmlNode.SelectNodes("capFloor"); if (capFloorNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in capFloorNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { capFloorIDRef = item.Attributes["id"].Name; CapFloor ob = CapFloor(); IDManager.SetID(capFloorIDRef, ob); } else if (item.Attributes.ToString() == "href") { capFloorIDRef = item.Attributes["href"].Name; } else { capFloor = new CapFloor(item); } } } XmlNodeList fraNodeList = xmlNode.SelectNodes("fra"); if (fraNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fraNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fraIDRef = item.Attributes["id"].Name; Fra ob = Fra(); IDManager.SetID(fraIDRef, ob); } else if (item.Attributes.ToString() == "href") { fraIDRef = item.Attributes["href"].Name; } else { fra = new Fra(item); } } } XmlNodeList swapNodeList = xmlNode.SelectNodes("swap"); if (swapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in swapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { swapIDRef = item.Attributes["id"].Name; Swap ob = Swap(); IDManager.SetID(swapIDRef, ob); } else if (item.Attributes.ToString() == "href") { swapIDRef = item.Attributes["href"].Name; } else { swap = new Swap(item); } } } XmlNodeList swaptionNodeList = xmlNode.SelectNodes("swaption"); if (swaptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in swaptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { swaptionIDRef = item.Attributes["id"].Name; Swaption ob = Swaption(); IDManager.SetID(swaptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { swaptionIDRef = item.Attributes["href"].Name; } else { swaption = new Swaption(item); } } } XmlNodeList equitySwapTransactionSupplementNodeList = xmlNode.SelectNodes("equitySwapTransactionSupplement"); if (equitySwapTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in equitySwapTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { equitySwapTransactionSupplementIDRef = item.Attributes["id"].Name; EquitySwapTransactionSupplement ob = EquitySwapTransactionSupplement(); IDManager.SetID(equitySwapTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { equitySwapTransactionSupplementIDRef = item.Attributes["href"].Name; } else { equitySwapTransactionSupplement = new EquitySwapTransactionSupplement(item); } } } XmlNodeList standardProductNodeList = xmlNode.SelectNodes("standardProduct"); if (standardProductNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in standardProductNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { standardProductIDRef = item.Attributes["id"].Name; StandardProduct ob = StandardProduct(); IDManager.SetID(standardProductIDRef, ob); } else if (item.Attributes.ToString() == "href") { standardProductIDRef = item.Attributes["href"].Name; } else { standardProduct = new StandardProduct(item); } } } XmlNodeList varianceOptionTransactionSupplementNodeList = xmlNode.SelectNodes("varianceOptionTransactionSupplement"); if (varianceOptionTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in varianceOptionTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { varianceOptionTransactionSupplementIDRef = item.Attributes["id"].Name; VarianceOptionTransactionSupplement ob = VarianceOptionTransactionSupplement(); IDManager.SetID(varianceOptionTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { varianceOptionTransactionSupplementIDRef = item.Attributes["href"].Name; } else { varianceOptionTransactionSupplement = new VarianceOptionTransactionSupplement(item); } } } XmlNodeList varianceSwapNodeList = xmlNode.SelectNodes("varianceSwap"); if (varianceSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in varianceSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { varianceSwapIDRef = item.Attributes["id"].Name; VarianceSwap ob = VarianceSwap(); IDManager.SetID(varianceSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { varianceSwapIDRef = item.Attributes["href"].Name; } else { varianceSwap = new VarianceSwap(item); } } } XmlNodeList varianceSwapTransactionSupplementNodeList = xmlNode.SelectNodes("varianceSwapTransactionSupplement"); if (varianceSwapTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in varianceSwapTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { varianceSwapTransactionSupplementIDRef = item.Attributes["id"].Name; VarianceSwapTransactionSupplement ob = VarianceSwapTransactionSupplement(); IDManager.SetID(varianceSwapTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { varianceSwapTransactionSupplementIDRef = item.Attributes["href"].Name; } else { varianceSwapTransactionSupplement = new VarianceSwapTransactionSupplement(item); } } } XmlNodeList otherPartyPaymentNodeList = xmlNode.SelectNodes("otherPartyPayment"); foreach (XmlNode item in otherPartyPaymentNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { otherPartyPaymentIDRef = item.Attributes["id"].Name; List<Payment> ob = new List<Payment>(); ob.Add(new Payment(item)); IDManager.SetID(otherPartyPaymentIDRef, ob); } else if (item.Attributes.ToString() == "href") { otherPartyPaymentIDRef = item.Attributes["href"].Name; } else { otherPartyPayment.Add(new Payment(item)); } } } XmlNodeList brokerPartyReferenceNodeList = xmlNode.SelectNodes("brokerPartyReference"); foreach (XmlNode item in brokerPartyReferenceNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { brokerPartyReferenceIDRef = item.Attributes["id"].Name; List<PartyReference> ob = new List<PartyReference>(); ob.Add(new PartyReference(item)); IDManager.SetID(brokerPartyReferenceIDRef, ob); } else if (item.Attributes.ToString() == "href") { brokerPartyReferenceIDRef = item.Attributes["href"].Name; } else { brokerPartyReference.Add(new PartyReference(item)); } } } XmlNodeList calculationAgentNodeList = xmlNode.SelectNodes("calculationAgent"); if (calculationAgentNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in calculationAgentNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { calculationAgentIDRef = item.Attributes["id"].Name; CalculationAgent ob = CalculationAgent(); IDManager.SetID(calculationAgentIDRef, ob); } else if (item.Attributes.ToString() == "href") { calculationAgentIDRef = item.Attributes["href"].Name; } else { calculationAgent = new CalculationAgent(item); } } } XmlNodeList calculationAgentBusinessCenterNodeList = xmlNode.SelectNodes("calculationAgentBusinessCenter"); if (calculationAgentBusinessCenterNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in calculationAgentBusinessCenterNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { calculationAgentBusinessCenterIDRef = item.Attributes["id"].Name; BusinessCenter ob = BusinessCenter(); IDManager.SetID(calculationAgentBusinessCenterIDRef, ob); } else if (item.Attributes.ToString() == "href") { calculationAgentBusinessCenterIDRef = item.Attributes["href"].Name; } else { calculationAgentBusinessCenter = new BusinessCenter(item); } } } XmlNodeList determiningPartyNodeList = xmlNode.SelectNodes("determiningParty"); foreach (XmlNode item in determiningPartyNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { determiningPartyIDRef = item.Attributes["id"].Name; List<PartyReference> ob = new List<PartyReference>(); ob.Add(new PartyReference(item)); IDManager.SetID(determiningPartyIDRef, ob); } else if (item.Attributes.ToString() == "href") { determiningPartyIDRef = item.Attributes["href"].Name; } else { determiningParty.Add(new PartyReference(item)); } } } XmlNodeList hedgingPartyNodeList = xmlNode.SelectNodes("hedgingParty"); foreach (XmlNode item in hedgingPartyNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { hedgingPartyIDRef = item.Attributes["id"].Name; List<PartyReference> ob = new List<PartyReference>(); ob.Add(new PartyReference(item)); IDManager.SetID(hedgingPartyIDRef, ob); } else if (item.Attributes.ToString() == "href") { hedgingPartyIDRef = item.Attributes["href"].Name; } else { hedgingParty.Add(new PartyReference(item)); } } } XmlNodeList collateralNodeList = xmlNode.SelectNodes("collateral"); if (collateralNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in collateralNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { collateralIDRef = item.Attributes["id"].Name; Collateral ob = Collateral(); IDManager.SetID(collateralIDRef, ob); } else if (item.Attributes.ToString() == "href") { collateralIDRef = item.Attributes["href"].Name; } else { collateral = new Collateral(item); } } } XmlNodeList documentationNodeList = xmlNode.SelectNodes("documentation"); if (documentationNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in documentationNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { documentationIDRef = item.Attributes["id"].Name; Documentation ob = Documentation(); IDManager.SetID(documentationIDRef, ob); } else if (item.Attributes.ToString() == "href") { documentationIDRef = item.Attributes["href"].Name; } else { documentation = new Documentation(item); } } } XmlNodeList governingLawNodeList = xmlNode.SelectNodes("governingLaw"); if (governingLawNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in governingLawNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { governingLawIDRef = item.Attributes["id"].Name; GoverningLaw ob = GoverningLaw(); IDManager.SetID(governingLawIDRef, ob); } else if (item.Attributes.ToString() == "href") { governingLawIDRef = item.Attributes["href"].Name; } else { governingLaw = new GoverningLaw(item); } } } XmlNodeList allocationsNodeList = xmlNode.SelectNodes("allocations"); if (allocationsNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in allocationsNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { allocationsIDRef = item.Attributes["id"].Name; Allocations ob = Allocations(); IDManager.SetID(allocationsIDRef, ob); } else if (item.Attributes.ToString() == "href") { allocationsIDRef = item.Attributes["href"].Name; } else { allocations = new Allocations(item); } } } }
void Start() { _endBox = GameObject.Find("EndBox"); _endBox.SetActive(false); _blockCount = 0; _blockMemoryInt = -1; _level.Level = _level.GetLevelSelected(); _level.Section = _level.GetSectionSelected(); _textures = _level.GetLevelBlocks(); _size = _level.GetLevelDimensions(); _swap = SwapFactory.CreateSwap(_level.GetLevelDimensions(), SpriteArray, CreateGrid()); var titleFieldText = GameObject.Find("Title").GetComponent<Text>(); titleFieldText.text = _level.GetTitle(); _movesLeftText = GameObject.Find("Moves").GetComponent<Text>(); _movesLeftText.text = _level.GetMoves().ToString(); _movesCountInt = _level.GetMoves(); _movesLeftFontSize = _movesLeftText.fontSize; _fontSizeTemp = _movesLeftFontSize; _levelEndCompletitionText = _endBox.transform.FindChild("Finished").GetComponent<Text>(); _medal = _endBox.transform.FindChild("MedalImage").GetComponent<Image>(); _medalText = _endBox.transform.FindChild("MedalName").GetComponent<Text>(); _timeBar = GameObject.Find("Progress").GetComponent<TimeBar>(); _timeBar.TotalTime = _level.GetTime(); }
private bool IsAccept(Swap swap, Swap receivedSwap) { return(swap.IsStatusSet(receivedSwap.Status, SwapStatus.Accepted)); }
public abstract Task StartPartyPaymentControlAsync( Swap swap, CancellationToken cancellationToken = default);
public Swaption(XmlNode xmlNode) : base(xmlNode) { XmlNodeList buyerPartyReferenceNodeList = xmlNode.SelectNodes("buyerPartyReference"); if (buyerPartyReferenceNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in buyerPartyReferenceNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { buyerPartyReferenceIDRef = item.Attributes["id"].Name; PartyReference ob = PartyReference(); IDManager.SetID(buyerPartyReferenceIDRef, ob); } else if (item.Attributes.ToString() == "href") { buyerPartyReferenceIDRef = item.Attributes["href"].Name; } else { buyerPartyReference = new PartyReference(item); } } } XmlNodeList buyerAccountReferenceNodeList = xmlNode.SelectNodes("buyerAccountReference"); if (buyerAccountReferenceNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in buyerAccountReferenceNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { buyerAccountReferenceIDRef = item.Attributes["id"].Name; AccountReference ob = AccountReference(); IDManager.SetID(buyerAccountReferenceIDRef, ob); } else if (item.Attributes.ToString() == "href") { buyerAccountReferenceIDRef = item.Attributes["href"].Name; } else { buyerAccountReference = new AccountReference(item); } } } XmlNodeList sellerPartyReferenceNodeList = xmlNode.SelectNodes("sellerPartyReference"); if (sellerPartyReferenceNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in sellerPartyReferenceNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { sellerPartyReferenceIDRef = item.Attributes["id"].Name; PartyReference ob = PartyReference(); IDManager.SetID(sellerPartyReferenceIDRef, ob); } else if (item.Attributes.ToString() == "href") { sellerPartyReferenceIDRef = item.Attributes["href"].Name; } else { sellerPartyReference = new PartyReference(item); } } } XmlNodeList sellerAccountReferenceNodeList = xmlNode.SelectNodes("sellerAccountReference"); if (sellerAccountReferenceNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in sellerAccountReferenceNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { sellerAccountReferenceIDRef = item.Attributes["id"].Name; AccountReference ob = AccountReference(); IDManager.SetID(sellerAccountReferenceIDRef, ob); } else if (item.Attributes.ToString() == "href") { sellerAccountReferenceIDRef = item.Attributes["href"].Name; } else { sellerAccountReference = new AccountReference(item); } } } XmlNodeList premiumNodeList = xmlNode.SelectNodes("premium"); foreach (XmlNode item in premiumNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { premiumIDRef = item.Attributes["id"].Name; List<Payment> ob = new List<Payment>(); ob.Add(new Payment(item)); IDManager.SetID(premiumIDRef, ob); } else if (item.Attributes.ToString() == "href") { premiumIDRef = item.Attributes["href"].Name; } else { premium.Add(new Payment(item)); } } } XmlNodeList exerciseNodeList = xmlNode.SelectNodes("exercise"); if (exerciseNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in exerciseNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { exerciseIDRef = item.Attributes["id"].Name; Exercise ob = Exercise(); IDManager.SetID(exerciseIDRef, ob); } else if (item.Attributes.ToString() == "href") { exerciseIDRef = item.Attributes["href"].Name; } else { exercise = new Exercise(item); } } } XmlNodeList americanExerciseNodeList = xmlNode.SelectNodes("americanExercise"); if (americanExerciseNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in americanExerciseNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { americanExerciseIDRef = item.Attributes["id"].Name; AmericanExercise ob = AmericanExercise(); IDManager.SetID(americanExerciseIDRef, ob); } else if (item.Attributes.ToString() == "href") { americanExerciseIDRef = item.Attributes["href"].Name; } else { americanExercise = new AmericanExercise(item); } } } XmlNodeList bermudaExerciseNodeList = xmlNode.SelectNodes("bermudaExercise"); if (bermudaExerciseNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in bermudaExerciseNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { bermudaExerciseIDRef = item.Attributes["id"].Name; BermudaExercise ob = BermudaExercise(); IDManager.SetID(bermudaExerciseIDRef, ob); } else if (item.Attributes.ToString() == "href") { bermudaExerciseIDRef = item.Attributes["href"].Name; } else { bermudaExercise = new BermudaExercise(item); } } } XmlNodeList europeanExerciseNodeList = xmlNode.SelectNodes("europeanExercise"); if (europeanExerciseNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in europeanExerciseNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { europeanExerciseIDRef = item.Attributes["id"].Name; EuropeanExercise ob = EuropeanExercise(); IDManager.SetID(europeanExerciseIDRef, ob); } else if (item.Attributes.ToString() == "href") { europeanExerciseIDRef = item.Attributes["href"].Name; } else { europeanExercise = new EuropeanExercise(item); } } } XmlNodeList exerciseProcedureNodeList = xmlNode.SelectNodes("exerciseProcedure"); if (exerciseProcedureNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in exerciseProcedureNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { exerciseProcedureIDRef = item.Attributes["id"].Name; ExerciseProcedure ob = ExerciseProcedure(); IDManager.SetID(exerciseProcedureIDRef, ob); } else if (item.Attributes.ToString() == "href") { exerciseProcedureIDRef = item.Attributes["href"].Name; } else { exerciseProcedure = new ExerciseProcedure(item); } } } XmlNodeList calculationAgentNodeList = xmlNode.SelectNodes("calculationAgent"); if (calculationAgentNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in calculationAgentNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { calculationAgentIDRef = item.Attributes["id"].Name; CalculationAgent ob = CalculationAgent(); IDManager.SetID(calculationAgentIDRef, ob); } else if (item.Attributes.ToString() == "href") { calculationAgentIDRef = item.Attributes["href"].Name; } else { calculationAgent = new CalculationAgent(item); } } } XmlNodeList cashSettlementNodeList = xmlNode.SelectNodes("cashSettlement"); if (cashSettlementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in cashSettlementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { cashSettlementIDRef = item.Attributes["id"].Name; CashSettlement ob = CashSettlement(); IDManager.SetID(cashSettlementIDRef, ob); } else if (item.Attributes.ToString() == "href") { cashSettlementIDRef = item.Attributes["href"].Name; } else { cashSettlement = new CashSettlement(item); } } } XmlNodeList physicalSettlementNodeList = xmlNode.SelectNodes("physicalSettlement"); if (physicalSettlementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in physicalSettlementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { physicalSettlementIDRef = item.Attributes["id"].Name; SwaptionPhysicalSettlement ob = SwaptionPhysicalSettlement(); IDManager.SetID(physicalSettlementIDRef, ob); } else if (item.Attributes.ToString() == "href") { physicalSettlementIDRef = item.Attributes["href"].Name; } else { physicalSettlement = new SwaptionPhysicalSettlement(item); } } } XmlNodeList swaptionStraddleNodeList = xmlNode.SelectNodes("swaptionStraddle"); if (swaptionStraddleNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in swaptionStraddleNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { swaptionStraddleIDRef = item.Attributes["id"].Name; XsdTypeBoolean ob = XsdTypeBoolean(); IDManager.SetID(swaptionStraddleIDRef, ob); } else if (item.Attributes.ToString() == "href") { swaptionStraddleIDRef = item.Attributes["href"].Name; } else { swaptionStraddle = new XsdTypeBoolean(item); } } } XmlNodeList swaptionAdjustedDatesNodeList = xmlNode.SelectNodes("swaptionAdjustedDates"); if (swaptionAdjustedDatesNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in swaptionAdjustedDatesNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { swaptionAdjustedDatesIDRef = item.Attributes["id"].Name; SwaptionAdjustedDates ob = SwaptionAdjustedDates(); IDManager.SetID(swaptionAdjustedDatesIDRef, ob); } else if (item.Attributes.ToString() == "href") { swaptionAdjustedDatesIDRef = item.Attributes["href"].Name; } else { swaptionAdjustedDates = new SwaptionAdjustedDates(item); } } } XmlNodeList swapNodeList = xmlNode.SelectNodes("swap"); if (swapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in swapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { swapIDRef = item.Attributes["id"].Name; Swap ob = Swap(); IDManager.SetID(swapIDRef, ob); } else if (item.Attributes.ToString() == "href") { swapIDRef = item.Attributes["href"].Name; } else { swap = new Swap(item); } } } }
protected Task UpdateSwapAsync( Swap swap, SwapStateFlags changedFlag, CancellationToken cancellationToken = default) => SwapUpdated?.Invoke(this, new SwapEventArgs(swap, changedFlag), cancellationToken);
protected abstract Task RefundTimeReachedHandler( Swap swap, CancellationToken cancellationToken = default);
private void RaiseSwapUpdated(Swap swap, SwapStateFlags changedFlag) { SwapUpdatedHandler(this, new SwapEventArgs(swap, changedFlag)); }
private async Task RestoreSwapAsync( Swap swap, CancellationToken cancellationToken = default) { if (swap.StateFlags.HasFlag(SwapStateFlags.IsPaymentBroadcast)) { bool confirmed = true; if (!swap.StateFlags.HasFlag(SwapStateFlags.IsPaymentConfirmed) && DateTime.UtcNow > swap.TimeStamp.ToUniversalTime() + DefaultMaxPaymentTimeout) { var result = await swap.PaymentTx .IsTransactionConfirmed( cancellationToken : cancellationToken) .ConfigureAwait(false); if (result.HasError || !result.Value.IsConfirmed) { confirmed = false; Log.Debug("Swap {@id} canceled in RestoreSwapAsync. Timeout reached.", swap.Id); swap.Cancel(); RaiseSwapUpdated(swap, SwapStateFlags.IsCanceled); } } if (confirmed) { await GetCurrencySwap(swap.SoldCurrency) .StartWaitForRedeemAsync(swap, cancellationToken) .ConfigureAwait(false); if (swap.IsInitiator) { // check acceptor payment confirmation await GetCurrencySwap(swap.PurchasedCurrency) .StartPartyPaymentControlAsync(swap, cancellationToken) .ConfigureAwait(false); } } } else { if (DateTime.UtcNow < swap.TimeStamp.ToUniversalTime() + DefaultMaxSwapTimeout) { if (swap.IsInitiator) { // todo: reinitiate swap } else { // todo: reaccept swap } } else { swap.Cancel(); RaiseSwapUpdated(swap, SwapStateFlags.IsCanceled); } } }
private async Task HandleInitiateAsync(Swap swap, Swap receivedSwap) { if (DateTime.UtcNow > swap.TimeStamp.ToUniversalTime() + DefaultCredentialsExchangeTimeout) { Log.Error("Handle initiate after swap {@swap} timeout", swap.Id); swap.Cancel(); RaiseSwapUpdated(swap, SwapStateFlags.IsCanceled); return; } if (swap.SecretHash != null) { if (!swap.SecretHash.SequenceEqual(receivedSwap.SecretHash)) { throw new InternalException( code: Errors.InvalidSecretHash, description: $"Secret hash does not match the one already received for swap {swap.Id}"); } return; } if (receivedSwap.SecretHash == null || receivedSwap.SecretHash.Length != CurrencySwap.DefaultSecretHashSize) { throw new InternalException( code: Errors.InvalidSecretHash, description: $"Incorrect secret hash length for swap {swap.Id}"); } Log.Debug("Secret hash {@hash} successfully received", receivedSwap.SecretHash.ToHexString()); swap.SecretHash = receivedSwap.SecretHash; RaiseSwapUpdated(swap, SwapStateFlags.HasSecretHash); // check party requisites if (receivedSwap.PartyAddress == null) { throw new InternalException( code: Errors.InvalidWallets, description: $"Incorrect party address for swap {swap.Id}"); } //if (IsCriminal(clientSwap.PartyAddress)) // throw new InternalException( // code: Errors.IsCriminalWallet, // description: $"Party wallet is criminal for swap {swap.Id}"); if (receivedSwap.RewardForRedeem < 0) { throw new InternalException( code: Errors.InvalidRewardForRedeem, description: $"Incorrect reward for redeem for swap {swap.Id}"); } swap.PartyAddress = receivedSwap.PartyAddress; swap.PartyRewardForRedeem = receivedSwap.PartyRewardForRedeem; // create self requisites var walletToAddress = (await _account .GetRedeemAddressAsync(swap.PurchasedCurrency) .ConfigureAwait(false)); swap.ToAddress = walletToAddress.Address; swap.RewardForRedeem = await GetRewardForRedeemAsync(walletToAddress) .ConfigureAwait(false); RaiseSwapUpdated(swap, SwapStateFlags.Empty); // send "accept" to other side _swapClient.SwapAcceptAsync(swap); await GetCurrencySwap(swap.PurchasedCurrency) .StartPartyPaymentControlAsync(swap) .ConfigureAwait(false); }
public void testInArrears() { //("Testing in-arrears swap calculation..."); CommonVars vars = new CommonVars(); /* See Hull, 4th ed., page 550 Note: the calculation in the book is wrong (work out the adjustment and you'll get 0.05 + 0.000115 T1) */ Date maturity = vars.today + new Period(5, TimeUnit.Years); Calendar calendar = new NullCalendar(); Schedule schedule = new Schedule(vars.today, maturity, new Period(Frequency.Annual), calendar, BusinessDayConvention.Following, BusinessDayConvention.Following, DateGeneration.Rule.Forward, false); DayCounter dayCounter = new SimpleDayCounter(); List<double> nominals = new List<double>() { 100000000.0 }; IborIndex index = new IborIndex("dummy", new Period(1, TimeUnit.Years), 0, new EURCurrency(), calendar, BusinessDayConvention.Following, false, dayCounter, vars.termStructure); double oneYear = 0.05; double r = Math.Log(1.0 + oneYear); vars.termStructure.linkTo(Utilities.flatRate(vars.today, r, dayCounter)); List<double> coupons = new List<double>() { oneYear }; List<CashFlow> fixedLeg = new FixedRateLeg(schedule) .withCouponRates(coupons, dayCounter) .withNotionals(nominals); List<double> gearings = new List<double>(); List<double> spreads = new List<double>(); int fixingDays = 0; double capletVolatility = 0.22; var vol = new Handle<OptionletVolatilityStructure>( new ConstantOptionletVolatility(vars.today, new NullCalendar(), BusinessDayConvention.Following, capletVolatility, dayCounter)); IborCouponPricer pricer = new BlackIborCouponPricer(vol); List<CashFlow> floatingLeg = new IborLeg(schedule, index) .withPaymentDayCounter(dayCounter) .withFixingDays(fixingDays) .withGearings(gearings) .withSpreads(spreads) .inArrears() .withNotionals(nominals); Utils.setCouponPricer(floatingLeg, pricer); Swap swap = new Swap(floatingLeg, fixedLeg); swap.setPricingEngine(new DiscountingSwapEngine(vars.termStructure)); double storedValue = -144813.0; double tolerance = 1.0; if (Math.Abs(swap.NPV() - storedValue) > tolerance) Assert.Fail("Wrong NPV calculation:\n" + " expected: " + storedValue + "\n" + " calculated: " + swap.NPV()); }
public abstract Task RedeemForPartyAsync( Swap swap, CancellationToken cancellationToken = default);
public override async Task RefundAsync( Swap swap, CancellationToken cancellationToken = default) { var erc20 = Erc20; if (swap.StateFlags.HasFlag(SwapStateFlags.IsRefundBroadcast)) { TrackTransactionConfirmationAsync( swap: swap, currency: erc20, txId: swap.RefundTx.Id, confirmationHandler: RefundConfirmedEventHandler, cancellationToken: cancellationToken) .FireAndForget(); return; } Log.Debug("Create refund for swap {@swap}", swap.Id); var walletAddress = (await Erc20Account .GetUnspentAddressesAsync( toAddress: null, // get refund address amount: 0, fee: 0, feePrice: 0, feeUsagePolicy: FeeUsagePolicy.EstimatedFee, addressUsagePolicy: AddressUsagePolicy.UseOnlyOneAddress, transactionType: BlockchainTransactionType.SwapRefund, cancellationToken: cancellationToken) .ConfigureAwait(false)) .FirstOrDefault(); if (walletAddress == null) { Log.Error("Insufficient funds for refund"); return; } var nonceResult = await EthereumNonceManager.Instance .GetNonceAsync(erc20, walletAddress.Address) .ConfigureAwait(false); if (nonceResult.HasError) { Log.Error("Nonce getting error with code {@code} and description {@description}", nonceResult.Error.Code, nonceResult.Error.Description); return; } var message = new ERC20RefundFunctionMessage { FromAddress = walletAddress.Address, HashedSecret = swap.SecretHash, GasPrice = Atomex.Ethereum.GweiToWei(erc20.GasPriceInGwei), Nonce = nonceResult.Value, }; message.Gas = await EstimateGasAsync(message, new BigInteger(erc20.RefundGasLimit)) .ConfigureAwait(false); var txInput = message.CreateTransactionInput(erc20.SwapContractAddress); var refundTx = new EthereumTransaction(erc20, txInput) { Type = BlockchainTransactionType.Output | BlockchainTransactionType.SwapRefund }; var signResult = await SignTransactionAsync(refundTx, cancellationToken) .ConfigureAwait(false); if (!signResult) { Log.Error("Transaction signing error"); return; } swap.RefundTx = refundTx; swap.StateFlags |= SwapStateFlags.IsRefundSigned; RaiseSwapUpdated(swap, SwapStateFlags.IsRefundSigned); await BroadcastTxAsync(swap, refundTx, cancellationToken) .ConfigureAwait(false); swap.RefundTx = refundTx; swap.StateFlags |= SwapStateFlags.IsRefundBroadcast; RaiseSwapUpdated(swap, SwapStateFlags.IsRefundBroadcast); TrackTransactionConfirmationAsync( swap: swap, currency: erc20, txId: refundTx.Id, confirmationHandler: RefundConfirmedEventHandler, cancellationToken: cancellationToken) .FireAndForget(); }
public abstract Task RefundAsync( Swap swap, CancellationToken cancellationToken = default);
public void SwapEnsureICanCreateInstance() { Swap swapping = new Swap(); Assert.IsNotNull(swapping); }
public abstract Task StartWaitForRedeemBySomeoneAsync( Swap swap, CancellationToken cancellationToken = default);
public CapHelper(Period length, Handle<Quote> volatility, IborIndex index, // data for ATM swap-rate calculation Frequency fixedLegFrequency, DayCounter fixedLegDayCounter, bool includeFirstSwaplet, Handle<YieldTermStructure> termStructure, bool calibrateVolatility /*= false*/) : base(volatility, termStructure, calibrateVolatility) { Period indexTenor = index.tenor(); double fixedRate = 0.04; // dummy value Date startDate, maturity; if (includeFirstSwaplet) { startDate = termStructure.link.referenceDate(); maturity = termStructure.link.referenceDate() + length; } else { startDate = termStructure.link.referenceDate() + indexTenor; maturity = termStructure.link.referenceDate() + length; } IborIndex dummyIndex=new IborIndex("dummy", indexTenor, index.fixingDays(), index.currency(), index.fixingCalendar(), index.businessDayConvention(), index.endOfMonth(), termStructure.link.dayCounter(), termStructure); List<double> nominals = new InitializedList<double>(1,1.0); Schedule floatSchedule=new Schedule(startDate, maturity, index.tenor(), index.fixingCalendar(), index.businessDayConvention(), index.businessDayConvention(), DateGeneration.Rule.Forward, false); List<CashFlow> floatingLeg; IborLeg iborLeg = (IborLeg) new IborLeg(floatSchedule, index) .withFixingDays(0) .withNotionals(nominals) .withPaymentAdjustment(index.businessDayConvention()); floatingLeg = iborLeg.value(); Schedule fixedSchedule=new Schedule(startDate, maturity, new Period(fixedLegFrequency), index.fixingCalendar(), BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Forward, false); List<CashFlow> fixedLeg = new FixedRateLeg(fixedSchedule) .withCouponRates(fixedRate, fixedLegDayCounter) .withNotionals(nominals) .withPaymentAdjustment(index.businessDayConvention()); Swap swap = new Swap(floatingLeg, fixedLeg); swap.setPricingEngine(new DiscountingSwapEngine(termStructure)); double bp = 1.0e-4; double fairRate = fixedRate - (double)(swap.NPV()/(swap.legBPS(1) / bp)); List<double> exerciceRate = new InitializedList<double>(1,fairRate); cap_ = new Cap(floatingLeg, exerciceRate); marketValue_ = blackPrice(volatility_.link.value()); }
public abstract Task <Result <IBlockchainTransaction> > TryToFindPaymentAsync( Swap swap, CancellationToken cancellationToken = default);
public static List <TextChunk> GetEmbeddedText(string pdf_filename, string page_numbers, string password, ProcessPriorityClass priority_class) { WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread(); string process_parameters = String.Format( "" + " " + "-tt " + " " + (String.IsNullOrEmpty(password) ? "" : "-p " + password) + " " + '"' + pdf_filename + '"' + " " + page_numbers ); var execResult = ReadEntireStandardOutput("pdfdraw.exe", process_parameters, binary_output: false, priority_class); using (MemoryStream ms = execResult.stdoutStream) { ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr_lines = new StreamReader(ms)) { List <TextChunk> text_chunks = new List <TextChunk>(); int page = 0; double page_x0 = 0; double page_y0 = 0; double page_x1 = 0; double page_y1 = 0; double page_rotation = 0; string current_font_name = ""; double current_font_size = 0; string line; while (null != (line = sr_lines.ReadLine())) { // Look for a character element (note that even a " can be the character in the then malformed XML) { Match match = Regex.Match(line, "char ucs=\"(.*)\" bbox=\"\\[(\\S*) (\\S*) (\\S*) (\\S*)\\]"); if (Match.Empty != match) { string text = match.Groups[1].Value; double word_x0 = Convert.ToDouble(match.Groups[2].Value, Internationalization.DEFAULT_CULTURE); double word_y0 = Convert.ToDouble(match.Groups[3].Value, Internationalization.DEFAULT_CULTURE); double word_x1 = Convert.ToDouble(match.Groups[4].Value, Internationalization.DEFAULT_CULTURE); double word_y1 = Convert.ToDouble(match.Groups[5].Value, Internationalization.DEFAULT_CULTURE); ResolveRotation(page_rotation, ref word_x0, ref word_y0, ref word_x1, ref word_y1); // safety measure: discard zero-width and zero-height "words" as those only cause trouble down the line: if (word_x0 == word_x1 || word_y0 == word_y1) { Logging.Warn("Zero-width/height bounding box for text chunk: ignoring this 'word' @ {0}.", line); continue; } // Position this little grubber TextChunk text_chunk = new TextChunk(); text_chunk.text = text; text_chunk.font_name = current_font_name; text_chunk.font_size = current_font_size; text_chunk.page = page; text_chunk.x0 = (word_x0 - page_x0) / (page_x1 - page_x0); text_chunk.y0 = 1 - (word_y0 - page_y0) / (page_y1 - page_y0); text_chunk.x1 = (word_x1 - page_x0) / (page_x1 - page_x0); text_chunk.y1 = 1 - (word_y1 - page_y0) / (page_y1 - page_y0); // Cater for the rotation if (0 != page_rotation) { text_chunk.y0 = 1 - text_chunk.y0; text_chunk.y1 = 1 - text_chunk.y1; } // Make sure the bounding box is TL-BR if (text_chunk.x1 < text_chunk.x0) { Swap.swap(ref text_chunk.x0, ref text_chunk.x1); } if (text_chunk.y1 < text_chunk.y0) { Swap.swap(ref text_chunk.y0, ref text_chunk.y1); } if (text_chunk.x1 <= text_chunk.x0 || text_chunk.y1 <= text_chunk.y0) { Logging.Warn("Bad bounding box for text chunk ({0})", process_parameters); } // And add him to the result list text_chunks.Add(text_chunk); continue; } } // Look for a change in font name { Match match = Regex.Match(line, " font=\"(\\S*)\" size=\"(\\S*)\" "); if (Match.Empty != match) { current_font_name = match.Groups[1].Value; current_font_size = Convert.ToDouble(match.Groups[2].Value, Internationalization.DEFAULT_CULTURE); continue; } } // Look for the page header with dimensions { Match match = Regex.Match(line, @"\[Page (.+) X0 (\S+) Y0 (\S+) X1 (\S+) Y1 (\S+) R (\S+)\]"); if (Match.Empty != match) { page = Convert.ToInt32(match.Groups[1].Value, Internationalization.DEFAULT_CULTURE); page_x0 = Convert.ToDouble(match.Groups[2].Value, Internationalization.DEFAULT_CULTURE); page_y0 = Convert.ToDouble(match.Groups[3].Value, Internationalization.DEFAULT_CULTURE); page_x1 = Convert.ToDouble(match.Groups[4].Value, Internationalization.DEFAULT_CULTURE); page_y1 = Convert.ToDouble(match.Groups[5].Value, Internationalization.DEFAULT_CULTURE); page_rotation = Convert.ToDouble(match.Groups[6].Value, Internationalization.DEFAULT_CULTURE); ResolveRotation(page_rotation, ref page_x0, ref page_y0, ref page_x1, ref page_y1); continue; } } } text_chunks = AggregateOverlappingTextChunks(text_chunks, process_parameters); return(text_chunks); } } }
protected Task RaiseAcceptorPaymentConfirmed( Swap swap, CancellationToken cancellationToken = default) => AcceptorPaymentConfirmed?.Invoke(this, new SwapEventArgs(swap), cancellationToken);
public double calculateImpl(DateTime calcDate, FP_Parameter fp_parameter) { List<QLNet.CashFlow> ql_fixedCFList = new List<QLNet.CashFlow>(); List<QLNet.CashFlow> ql_floatingCFList = new List<QLNet.CashFlow>(); foreach (FP_CashFlow fixed_cf in this.FixedLegInfo_.FP_CashFlowList_) { ql_fixedCFList.Add(fixed_cf.build_ql_cf(fp_parameter)); } foreach (FP_CashFlow floating_cf in this.FloatingLegInfo_.FP_CashFlowList_) { ql_floatingCFList.Add(floating_cf.build_ql_cf(fp_parameter)); } Swap ql_swap = new Swap(ql_fixedCFList, ql_floatingCFList); //QLNet.DiscountingBasisSwapEngine Handle<YieldTermStructure> ql_discount_ts //= new QLNet.Handle<YieldTermStructure>(fp_parameter.DiscountCurveMap_["KRW"]); = new QLNet.Handle<YieldTermStructure>(fp_parameter.getDiscountCurve("KRW")); QLNet.DiscountingSwapEngine engine = new DiscountingSwapEngine(ql_discount_ts); ql_swap.setPricingEngine(engine); #region Result Price/Greek //clsHITM_FP_GREEKRESULT_TB clstb_greekresult = new clsHITM_FP_GREEKRESULT_TB(); //clsHDAT_MARKETDATA_TB clstb_market = new clsHDAT_MARKETDATA_TB(); //clstb_market.REF_DT = calcDate.ToString("yyyyMMdd"); double swap_price = ql_swap.NPV(); #region Comment //foreach (var item in index_cdList) //{ // clstb_market.INDEX_CD = item; // clstb_market.SelectOwn(); // clstb_greekresult.FP_GREEKRESULT_ID = ""; // clstb_greekresult.CALC_DT = calcDate.ToString("yyyyMMdd"); // clstb_greekresult.INSTRUMENT_ID = this.SwapDAO_.INSTRUMENT_ID; // clstb_greekresult.INSTRUMENT_TYP = 0; // clstb_greekresult.UNDERLYING_ID = item; // clstb_greekresult.UNDERLYING_VALUE = clstb_market.LAST; // clstb_greekresult.SEQ = count; // clstb_greekresult.DELTA = 0.0; // clstb_greekresult.GAMMA = 0.0; // clstb_greekresult.VEGA = 0.0; // if (count == 1) { clstb_greekresult.CALC_PRICE = swap_price; } // else { clstb_greekresult.CALC_PRICE = 0.0; } // clstb_greekresult.CALCULATED_FLAG = 1; // clstb_greekresult.CALCULATED_TIME = DateTime.Now.ToString("HHmmss"); // clstb_greekresult.CALCULATE_TYP = 1; // 패러럴 쉬푸투 or 그냥 구한거 머 등등.. // clstb_greekresult.Insert(); // count += 1; //} #endregion #endregion for (int i = 0; i < this.FixedLegInfo_.FP_CashFlowList_.Count; i++) { this.FixedLegInfo_.FP_CashFlowList_[i].CashFlowAmount_ = ql_fixedCFList[i].amount(); this.FixedLegInfo_.FP_CashFlowList_[i].DiscountFactor_ = ql_discount_ts.currentLink().discount(this.FixedLegInfo_.FP_CashFlowList_[i].PaymentDate_); } for (int j = 0; j < this.FloatingLegInfo_.FP_CashFlowList_.Count; j++) { this.FloatingLegInfo_.FP_CashFlowList_[j].CashFlowAmount_ = ql_floatingCFList[j].amount(); this.FloatingLegInfo_.FP_CashFlowList_[j].DiscountFactor_ = ql_discount_ts.currentLink().discount(this.FloatingLegInfo_.FP_CashFlowList_[j].PaymentDate_); } return swap_price; //#endregion }
public void testInArrears() { //("Testing in-arrears swap calculation..."); CommonVars vars = new CommonVars(); /* See Hull, 4th ed., page 550 * Note: the calculation in the book is wrong (work out the adjustment and you'll get 0.05 + 0.000115 T1) */ Date maturity = vars.today + new Period(5, TimeUnit.Years); Calendar calendar = new NullCalendar(); Schedule schedule = new Schedule(vars.today, maturity, new Period(Frequency.Annual), calendar, BusinessDayConvention.Following, BusinessDayConvention.Following, DateGeneration.Rule.Forward, false); DayCounter dayCounter = new SimpleDayCounter(); List <double> nominals = new List <double>() { 100000000.0 }; IborIndex index = new IborIndex("dummy", new Period(1, TimeUnit.Years), 0, new EURCurrency(), calendar, BusinessDayConvention.Following, false, dayCounter, vars.termStructure); double oneYear = 0.05; double r = Math.Log(1.0 + oneYear); vars.termStructure.linkTo(Utilities.flatRate(vars.today, r, dayCounter)); List <double> coupons = new List <double>() { oneYear }; List <CashFlow> fixedLeg = new FixedRateLeg(schedule) .withCouponRates(coupons, dayCounter) .withNotionals(nominals); List <double> gearings = new List <double>(); List <double> spreads = new List <double>(); int fixingDays = 0; double capletVolatility = 0.22; var vol = new Handle <OptionletVolatilityStructure>( new ConstantOptionletVolatility(vars.today, new NullCalendar(), BusinessDayConvention.Following, capletVolatility, dayCounter)); IborCouponPricer pricer = new BlackIborCouponPricer(vol); List <CashFlow> floatingLeg = new IborLeg(schedule, index) .withPaymentDayCounter(dayCounter) .withFixingDays(fixingDays) .withGearings(gearings) .withSpreads(spreads) .inArrears() .withNotionals(nominals); Utils.setCouponPricer(floatingLeg, pricer); Swap swap = new Swap(floatingLeg, fixedLeg); swap.setPricingEngine(new DiscountingSwapEngine(vars.termStructure)); double storedValue = -144813.0; double tolerance = 1.0; if (Math.Abs(swap.NPV() - storedValue) > tolerance) { Assert.Fail("Wrong NPV calculation:\n" + " expected: " + storedValue + "\n" + " calculated: " + swap.NPV()); } }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Swap obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; }
public void testDecomposition() { // Testing collared coupon against its decomposition... CommonVars vars = new CommonVars(); double tolerance = 1e-10; double npvVanilla, npvCappedLeg, npvFlooredLeg, npvCollaredLeg, npvCap, npvFloor, npvCollar; double error; double floorstrike = 0.05; double capstrike = 0.10; List <double?> caps = new InitializedList <double?>(vars.length, capstrike); List <double?> caps0 = new List <double?>(); List <double?> floors = new InitializedList <double?>(vars.length, floorstrike); List <double?> floors0 = new List <double?>(); double gearing_p = 0.5; double spread_p = 0.002; double gearing_n = -1.5; double spread_n = 0.12; // fixed leg with zero rate List <CashFlow> fixedLeg = vars.makeFixedLeg(vars.startDate, vars.length); // floating leg with gearing=1 and spread=0 List <CashFlow> floatLeg = vars.makeYoYLeg(vars.startDate, vars.length); // floating leg with positive gearing (gearing_p) and spread<>0 List <CashFlow> floatLeg_p = vars.makeYoYLeg(vars.startDate, vars.length, gearing_p, spread_p); // floating leg with negative gearing (gearing_n) and spread<>0 List <CashFlow> floatLeg_n = vars.makeYoYLeg(vars.startDate, vars.length, gearing_n, spread_n); // Swap with null fixed leg and floating leg with gearing=1 and spread=0 Swap vanillaLeg = new Swap(fixedLeg, floatLeg); // Swap with null fixed leg and floating leg with positive gearing and spread<>0 Swap vanillaLeg_p = new Swap(fixedLeg, floatLeg_p); // Swap with null fixed leg and floating leg with negative gearing and spread<>0 Swap vanillaLeg_n = new Swap(fixedLeg, floatLeg_n); IPricingEngine engine = new DiscountingSwapEngine(vars.nominalTS); vanillaLeg.setPricingEngine(engine); // here use the autoset feature vanillaLeg_p.setPricingEngine(engine); vanillaLeg_n.setPricingEngine(engine); // CAPPED coupon - Decomposition of payoff // Payoff = Nom * Min(rate,strike) * accrualperiod = // = Nom * [rate + Min(0,strike-rate)] * accrualperiod = // = Nom * rate * accrualperiod - Nom * Max(rate-strike,0) * accrualperiod = // = VanillaFloatingLeg - Call // int whichPricer = 0; // Case gearing = 1 and spread = 0 List <CashFlow> cappedLeg = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps, floors0, vars.volatility); Swap capLeg = new Swap(fixedLeg, cappedLeg); capLeg.setPricingEngine(engine); YoYInflationCap cap = new YoYInflationCap(floatLeg, new List <double>() { capstrike }); cap.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvVanilla = vanillaLeg.NPV(); npvCappedLeg = capLeg.NPV(); npvCap = cap.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla - npvCap)); if (error > tolerance) { QAssert.Fail("\nYoY Capped Leg: gearing=1, spread=0%, strike=" + capstrike * 100 + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" + " Diff: " + error); } // gearing = 1 and spread = 0 // FLOORED coupon - Decomposition of payoff // Payoff = Nom * Max(rate,strike) * accrualperiod = // = Nom * [rate + Max(0,strike-rate)] * accrualperiod = // = Nom * rate * accrualperiod + Nom * Max(strike-rate,0) * accrualperiod = // = VanillaFloatingLeg + Put // List <CashFlow> flooredLeg = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps0, floors, vars.volatility); Swap floorLeg = new Swap(fixedLeg, flooredLeg); floorLeg.setPricingEngine(engine); YoYInflationFloor floor = new YoYInflationFloor(floatLeg, new List <double>() { floorstrike }); floor.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvFlooredLeg = floorLeg.NPV(); npvFloor = floor.NPV(); error = Math.Abs(npvFlooredLeg - (npvVanilla + npvFloor)); if (error > tolerance) { QAssert.Fail("YoY Floored Leg: gearing=1, spread=0%, strike=" + floorstrike * 100 + "%\n" + " Floored Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor) + "\n" + " Diff: " + error); } // gearing = 1 and spread = 0 // COLLARED coupon - Decomposition of payoff // Payoff = Nom * Min(strikem,Max(rate,strikeM)) * accrualperiod = // = VanillaFloatingLeg - Collar // List <CashFlow> collaredLeg = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps, floors, vars.volatility); Swap collarLeg = new Swap(fixedLeg, collaredLeg); collarLeg.setPricingEngine(engine); YoYInflationCollar collar = new YoYInflationCollar(floatLeg, new List <double>() { capstrike }, new List <double>() { floorstrike }); collar.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvCollaredLeg = collarLeg.NPV(); npvCollar = collar.NPV(); error = Math.Abs(npvCollaredLeg - (npvVanilla - npvCollar)); if (error > tolerance) { QAssert.Fail("\nYoY Collared Leg: gearing=1, spread=0%, strike=" + floorstrike * 100 + "% and " + capstrike * 100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar) + "\n" + " Diff: " + error); } // gearing = a and spread = b // CAPPED coupon - Decomposition of payoff // Payoff // = Nom * Min(a*rate+b,strike) * accrualperiod = // = Nom * [a*rate+b + Min(0,strike-a*rate-b)] * accrualperiod = // = Nom * a*rate+b * accrualperiod + Nom * Min(strike-b-a*rate,0) * accrualperiod // --> If a>0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg - Call(a*rate+b,strike) // --> If a<0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg + Nom * Min(strike-b+|a|*rate+,0) * accrualperiod = // = VanillaFloatingLeg + Put(|a|*rate+b,strike) // // Positive gearing List <CashFlow> cappedLeg_p = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps, floors0, vars.volatility, gearing_p, spread_p); Swap capLeg_p = new Swap(fixedLeg, cappedLeg_p); capLeg_p.setPricingEngine(engine); YoYInflationCap cap_p = new YoYInflationCap(floatLeg_p, new List <double>() { capstrike }); cap_p.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvVanilla = vanillaLeg_p.NPV(); npvCappedLeg = capLeg_p.NPV(); npvCap = cap_p.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla - npvCap)); if (error > tolerance) { QAssert.Fail("\nYoY Capped Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p * 100 + "%, strike=" + capstrike * 100 + "%, " + "effective strike= " + (capstrike - spread_p) / gearing_p * 100 + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " Vanilla Leg NPV: " + npvVanilla + "\n" + " Cap NPV: " + npvCap + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" + " Diff: " + error); } // Negative gearing List <CashFlow> cappedLeg_n = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps, floors0, vars.volatility, gearing_n, spread_n); Swap capLeg_n = new Swap(fixedLeg, cappedLeg_n); capLeg_n.setPricingEngine(engine); YoYInflationFloor floor_n = new YoYInflationFloor(floatLeg, new List <double>() { (capstrike - spread_n) / gearing_n }); floor_n.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvVanilla = vanillaLeg_n.NPV(); npvCappedLeg = capLeg_n.NPV(); npvFloor = floor_n.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla + gearing_n * npvFloor)); if (error > tolerance) { QAssert.Fail("\nYoY Capped Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n * 100 + "%, strike=" + capstrike * 100 + "%, " + "effective strike= " + ((capstrike - spread_n) / gearing_n * 100) + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " npv Vanilla: " + npvVanilla + "\n" + " npvFloor: " + npvFloor + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla + gearing_n * npvFloor) + "\n" + " Diff: " + error); } // gearing = a and spread = b // FLOORED coupon - Decomposition of payoff // Payoff // = Nom * Max(a*rate+b,strike) * accrualperiod = // = Nom * [a*rate+b + Max(0,strike-a*rate-b)] * accrualperiod = // = Nom * a*rate+b * accrualperiod + Nom * Max(strike-b-a*rate,0) * accrualperiod // --> If a>0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg + Put(a*rate+b,strike) // --> If a<0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg + Nom * Max(strike-b+|a|*rate+,0) * accrualperiod = // = VanillaFloatingLeg - Call(|a|*rate+b,strike) // // Positive gearing List <CashFlow> flooredLeg_p1 = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps0, floors, vars.volatility, gearing_p, spread_p); Swap floorLeg_p1 = new Swap(fixedLeg, flooredLeg_p1); floorLeg_p1.setPricingEngine(engine); YoYInflationFloor floor_p1 = new YoYInflationFloor(floatLeg_p, new List <double>() { floorstrike }); floor_p1.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvVanilla = vanillaLeg_p.NPV(); npvFlooredLeg = floorLeg_p1.NPV(); npvFloor = floor_p1.NPV(); error = Math.Abs(npvFlooredLeg - (npvVanilla + npvFloor)); if (error > tolerance) { QAssert.Fail("\nYoY Floored Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p * 100 + "%, strike=" + floorstrike * 100 + "%, " + "effective strike= " + (floorstrike - spread_p) / gearing_p * 100 + "%\n" + " Floored Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor) + "\n" + " Diff: " + error); } // Negative gearing List <CashFlow> flooredLeg_n = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps0, floors, vars.volatility, gearing_n, spread_n); Swap floorLeg_n = new Swap(fixedLeg, flooredLeg_n); floorLeg_n.setPricingEngine(engine); YoYInflationCap cap_n = new YoYInflationCap(floatLeg, new List <double>() { (floorstrike - spread_n) / gearing_n }); cap_n.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvVanilla = vanillaLeg_n.NPV(); npvFlooredLeg = floorLeg_n.NPV(); npvCap = cap_n.NPV(); error = Math.Abs(npvFlooredLeg - (npvVanilla - gearing_n * npvCap)); if (error > tolerance) { QAssert.Fail("\nYoY Capped Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n * 100 + "%, strike=" + floorstrike * 100 + "%, " + "effective strike= " + (floorstrike - spread_n) / gearing_n * 100 + "%\n" + " Capped Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - gearing_n * npvCap) + "\n" + " Diff: " + error); } // gearing = a and spread = b // COLLARED coupon - Decomposition of payoff // Payoff = Nom * Min(caprate,Max(a*rate+b,floorrate)) * accrualperiod // --> If a>0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg - Collar(a*rate+b, floorrate, caprate) // --> If a<0 (assuming positive effective strike): // Payoff = VanillaFloatingLeg + Collar(|a|*rate+b, caprate, floorrate) // // Positive gearing List <CashFlow> collaredLeg_p = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps, floors, vars.volatility, gearing_p, spread_p); Swap collarLeg_p1 = new Swap(fixedLeg, collaredLeg_p); collarLeg_p1.setPricingEngine(engine); YoYInflationCollar collar_p = new YoYInflationCollar(floatLeg_p, new List <double>() { capstrike }, new List <double>() { floorstrike }); collar_p.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvVanilla = vanillaLeg_p.NPV(); npvCollaredLeg = collarLeg_p1.NPV(); npvCollar = collar_p.NPV(); error = Math.Abs(npvCollaredLeg - (npvVanilla - npvCollar)); if (error > tolerance) { QAssert.Fail("\nYoY Collared Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p * 100 + "%, strike=" + floorstrike * 100 + "% and " + capstrike * 100 + "%, " + "effective strike=" + (floorstrike - spread_p) / gearing_p * 100 + "% and " + (capstrike - spread_p) / gearing_p * 100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar) + "\n" + " Diff: " + error); } // Negative gearing List <CashFlow> collaredLeg_n = vars.makeYoYCapFlooredLeg(whichPricer, vars.startDate, vars.length, caps, floors, vars.volatility, gearing_n, spread_n); Swap collarLeg_n1 = new Swap(fixedLeg, collaredLeg_n); collarLeg_n1.setPricingEngine(engine); YoYInflationCollar collar_n = new YoYInflationCollar(floatLeg, new List <double>() { (floorstrike - spread_n) / gearing_n }, new List <double>() { (capstrike - spread_n) / gearing_n }); collar_n.setPricingEngine(vars.makeEngine(vars.volatility, whichPricer)); npvVanilla = vanillaLeg_n.NPV(); npvCollaredLeg = collarLeg_n1.NPV(); npvCollar = collar_n.NPV(); error = Math.Abs(npvCollaredLeg - (npvVanilla - gearing_n * npvCollar)); if (error > tolerance) { QAssert.Fail("\nYoY Collared Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n * 100 + "%, strike=" + floorstrike * 100 + "% and " + capstrike * 100 + "%, " + "effective strike=" + (floorstrike - spread_n) / gearing_n * 100 + "% and " + (capstrike - spread_n) / gearing_n * 100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - gearing_n * npvCollar) + "\n" + " Diff: " + error); } // remove circular refernce vars.hy.linkTo(null); }
private Swap AttemptSwap(int x, int y, bool horizontal, Animal animal) { var xDelta = horizontal ? 1 : 0; var yDelta = horizontal ? 0 : 1; if ((!horizontal || x >= Width - 1) && (horizontal || y >= Height - 1)) return null; var other = GetAnimalAt(x + xDelta, y + yDelta); if (other == null) return null; SetAnimalAt(x, y, other); SetAnimalAt(x + xDelta, y + yDelta, animal); Swap swap = null; if (ChainExistsAt(x + xDelta, y + yDelta) || ChainExistsAt(x, y)) swap = new Swap(animal, other); SetAnimalAt(x, y, animal); SetAnimalAt(x + xDelta, y + yDelta, other); return swap; }
public static Task StartSwapRedeemedControlAsync( Swap swap, CurrencyConfig currency, DateTime refundTimeUtc, TimeSpan interval, bool cancelOnlyIfRefundTimeReached, Func <Swap, byte[], CancellationToken, Task> redeemedHandler, Func <Swap, DateTime, CancellationToken, Task> canceledHandler, CancellationToken cancellationToken = default) { return(Task.Run(async() => { try { while (!cancellationToken.IsCancellationRequested) { var isRedeemedResult = await IsRedeemedAsync( swap: swap, currency: currency, cancellationToken: cancellationToken) .ConfigureAwait(false); if (isRedeemedResult.HasError && isRedeemedResult.Error.Code != Errors.RequestError) // has error { await canceledHandler .Invoke(swap, refundTimeUtc, cancellationToken) .ConfigureAwait(false); break; } else if (!isRedeemedResult.HasError && isRedeemedResult.Value != null) // has secret { await redeemedHandler .Invoke(swap, isRedeemedResult.Value, cancellationToken) .ConfigureAwait(false); break; } if (!cancelOnlyIfRefundTimeReached || DateTime.UtcNow >= refundTimeUtc) { await canceledHandler .Invoke(swap, refundTimeUtc, cancellationToken) .ConfigureAwait(false); break; } await Task.Delay(interval, cancellationToken) .ConfigureAwait(false); } } catch (OperationCanceledException) { Log.Debug("StartSwapRedeemedControlAsync canceled."); } catch (Exception e) { Log.Error(e, "StartSwapRedeemedControlAsync error."); } }, cancellationToken)); }
protected override async Task <IEnumerable <EthereumTransaction> > CreatePaymentTxsAsync( Swap swap, int lockTimeInSeconds, CancellationToken cancellationToken = default) { var erc20 = Erc20; Log.Debug("Create payment transactions for swap {@swapId}", swap.Id); var requiredAmountInERC20 = AmountHelper.QtyToAmount(swap.Side, swap.Qty, swap.Price, erc20.DigitsMultiplier); var refundTimeStampUtcInSec = new DateTimeOffset(swap.TimeStamp.ToUniversalTime().AddSeconds(lockTimeInSeconds)).ToUnixTimeSeconds(); var isInitTx = true; var rewardForRedeemInERC20 = swap.PartyRewardForRedeem; var unspentAddresses = (await Erc20Account .GetUnspentAddressesAsync(cancellationToken) .ConfigureAwait(false)) .ToList() .SortList((a, b) => a.AvailableBalance().CompareTo(b.AvailableBalance())); var transactions = new List <EthereumTransaction>(); foreach (var walletAddress in unspentAddresses) { Log.Debug("Create swap payment tx from address {@address} for swap {@swapId}", walletAddress.Address, swap.Id); var balanceInEth = (await EthereumAccount .GetAddressBalanceAsync( address: walletAddress.Address, cancellationToken: cancellationToken) .ConfigureAwait(false)) .Available; var balanceInERC20 = (await Erc20Account .GetAddressBalanceAsync( address: walletAddress.Address, cancellationToken: cancellationToken) .ConfigureAwait(false)) .Available; Log.Debug("Available balance: {@balance}", balanceInERC20); var feeAmountInEth = (isInitTx ? rewardForRedeemInERC20 == 0 ? erc20.InitiateFeeAmount : erc20.InitiateWithRewardFeeAmount : erc20.AddFeeAmount) + erc20.ApproveFeeAmount; if (balanceInEth - feeAmountInEth <= 0) { Log.Warning( "Insufficient funds at {@address}. Balance: {@balance}, feeAmount: {@feeAmount}, result: {@result}.", walletAddress.Address, balanceInEth, feeAmountInEth, balanceInEth - feeAmountInEth); continue; } var amountInERC20 = requiredAmountInERC20 > 0 ? AmountHelper.DustProofMin(balanceInERC20, requiredAmountInERC20, erc20.DigitsMultiplier, erc20.DustDigitsMultiplier) : 0; requiredAmountInERC20 -= amountInERC20; var nonceResult = await EthereumNonceManager.Instance .GetNonceAsync(erc20, walletAddress.Address) .ConfigureAwait(false); if (nonceResult.HasError) { Log.Error("Nonce getting error with code {@code} and description {@description}", nonceResult.Error.Code, nonceResult.Error.Description); return(null); } var nonce = nonceResult.Value; var allowanceMessage = new ERC20AllowanceFunctionMessage() { Owner = walletAddress.Address, Spender = erc20.SwapContractAddress, FromAddress = walletAddress.Address }; var allowance = await((IEthereumBlockchainApi)erc20.BlockchainApi) .GetERC20AllowanceAsync( erc20: erc20, tokenAddress: erc20.ERC20ContractAddress, allowanceMessage: allowanceMessage, cancellationToken: cancellationToken) .ConfigureAwait(false); if (allowance.Value > 0) { transactions.Add(await CreateApproveTx(walletAddress, nonceResult.Value, 0) .ConfigureAwait(false)); nonce += 1; } else { transactions.Add(new EthereumTransaction()); } transactions.Add(await CreateApproveTx(walletAddress, nonce, erc20.TokensToTokenDigits(amountInERC20)) .ConfigureAwait(false)); nonce += 1; TransactionInput txInput; //actual transfer if (isInitTx) { var initMessage = new ERC20InitiateFunctionMessage { HashedSecret = swap.SecretHash, ERC20Contract = erc20.ERC20ContractAddress, Participant = swap.PartyAddress, RefundTimestamp = refundTimeStampUtcInSec, Countdown = lockTimeInSeconds, Value = erc20.TokensToTokenDigits(amountInERC20), RedeemFee = erc20.TokensToTokenDigits(rewardForRedeemInERC20), Active = true, FromAddress = walletAddress.Address, GasPrice = Atomex.Ethereum.GweiToWei(erc20.GasPriceInGwei), Nonce = nonce }; var initiateGasLimit = rewardForRedeemInERC20 == 0 ? erc20.InitiateGasLimit : erc20.InitiateWithRewardGasLimit; initMessage.Gas = await EstimateGasAsync(initMessage, new BigInteger(initiateGasLimit)) .ConfigureAwait(false); txInput = initMessage.CreateTransactionInput(erc20.SwapContractAddress); } else { var addMessage = new ERC20AddFunctionMessage { HashedSecret = swap.SecretHash, Value = erc20.TokensToTokenDigits(amountInERC20), FromAddress = walletAddress.Address, GasPrice = Atomex.Ethereum.GweiToWei(erc20.GasPriceInGwei), Nonce = nonce }; addMessage.Gas = await EstimateGasAsync(addMessage, new BigInteger(erc20.AddGasLimit)) .ConfigureAwait(false); txInput = addMessage.CreateTransactionInput(erc20.SwapContractAddress); } transactions.Add(new EthereumTransaction(erc20, txInput) { Type = BlockchainTransactionType.Output | BlockchainTransactionType.SwapPayment }); if (isInitTx) { isInitTx = false; } if (requiredAmountInERC20 <= 0) { break; } } if (requiredAmountInERC20 > 0) { Log.Warning("Insufficient ERC20 or Eth funds (left {@requiredAmount}).", requiredAmountInERC20); return(Enumerable.Empty <EthereumTransaction>()); } return(transactions); }
private void swapPoints(int i, int j) { Swap.swap(ref scores[i], ref scores[j]); Swap.swap(ref points[i].x, ref points[j].x); Swap.swap(ref points[i].y, ref points[j].y); }
public override async Task PayAsync( Swap swap, CancellationToken cancellationToken = default) { if (!CheckPayRelevance(swap)) { return; } var lockTimeInSeconds = swap.IsInitiator ? DefaultInitiatorLockTimeInSeconds : DefaultAcceptorLockTimeInSeconds; var txs = (await CreatePaymentTxsAsync(swap, lockTimeInSeconds) .ConfigureAwait(false)) .ToList(); if (txs.Count == 0) { Log.Error("Can't create payment transactions"); return; } try { foreach (int i in new int[] { 0, 1 }) { var approvalTxs = txs .Where((tx, j) => j % 3 == i) .ToList(); var isApproved = await ApproveAsync(swap, approvalTxs, cancellationToken) .ConfigureAwait(false); if (!isApproved) { Log.Error("Approve txs are not confirmed after timeout {@timeout}", InitiationTimeout.Minutes); return; } } txs = txs .Where(tx => tx.Type.HasFlag(BlockchainTransactionType.SwapPayment)) .ToList(); var isInitiateTx = true; foreach (var tx in txs) { var signResult = await SignTransactionAsync(tx, cancellationToken) .ConfigureAwait(false); if (!signResult) { Log.Error("Transaction signing error"); return; } if (isInitiateTx) { swap.PaymentTx = tx; swap.StateFlags |= SwapStateFlags.IsPaymentSigned; RaiseSwapUpdated(swap, SwapStateFlags.IsPaymentSigned); } await BroadcastTxAsync(swap, tx, cancellationToken) .ConfigureAwait(false); if (isInitiateTx) { swap.PaymentTx = tx; swap.StateFlags |= SwapStateFlags.IsPaymentBroadcast; RaiseSwapUpdated(swap, SwapStateFlags.IsPaymentBroadcast); isInitiateTx = false; // delay for contract initiation if (txs.Count > 1) { var isInitiated = await WaitPaymentConfirmationAsync( txId : tx.Id, timeout : InitiationTimeout, cancellationToken : cancellationToken) .ConfigureAwait(false); if (!isInitiated) { Log.Error("Initiation payment tx not confirmed after timeout {@timeout}", InitiationTimeout.Minutes); return; } } } } } catch (Exception e) { Log.Error(e, "Swap payment error for swap {@swapId}", swap.Id); return; } if (swap.StateFlags.HasFlag(SwapStateFlags.IsPaymentBroadcast)) { // start redeem control async await StartWaitForRedeemAsync(swap, cancellationToken) .ConfigureAwait(false); } }
private void LoadSettings_1_3_2(BinaryTextReader btr) { // items bool randAbilities = btr.ReadBool(); bool randTanks = btr.ReadBool(); if (randAbilities && randTanks) { AbilitySwap = Swap.GlobalPool; TankSwap = Swap.GlobalPool; } else if (randAbilities) { AbilitySwap = Swap.LocalPool; } else if (randTanks) { TankSwap = Swap.LocalPool; } if (btr.ReadBool()) { NumItemsRemoved = btr.ReadNumber(7); } if (SwapOrRemoveItems) { Completion = (GameCompletion)btr.ReadNumber(2); IceNotRequired = btr.ReadBool(); PlasmaNotRequired = btr.ReadBool(); NoPBsBeforeChozodia = btr.ReadBool(); ChozoStatueHints = btr.ReadBool(); InfiniteBombJump = btr.ReadBool(); WallJumping = btr.ReadBool(); } // locations if (btr.ReadBool()) { int count = btr.ReadNumber(7); for (int i = 0; i < count; i++) { int locNum = btr.ReadNumber(7); ItemType item = (ItemType)btr.ReadNumber(5); CustomAssignments[locNum] = item; } } // enemies RandoEnemies = btr.ReadBool(); // palettes TilesetPalettes = btr.ReadBool(); EnemyPalettes = btr.ReadBool(); BeamPalettes = btr.ReadBool(); if (RandomPalettes) { if (btr.ReadBool()) { HueMinimum = btr.ReadNumber(8); } if (btr.ReadBool()) { HueMaximum = btr.ReadNumber(8); } } // misc EnableItemToggle = btr.ReadBool(); ObtainUnkItems = btr.ReadBool(); HardModeAvailable = btr.ReadBool(); PauseScreenInfo = btr.ReadBool(); RemoveCutscenes = btr.ReadBool(); SkipSuitless = btr.ReadBool(); SkipDoorTransitions = btr.ReadBool(); }
public override async Task RedeemForPartyAsync( Swap swap, CancellationToken cancellationToken = default) { Log.Debug("Create redeem for counterParty for swap {@swapId}", swap.Id); var erc20 = Erc20; var walletAddress = (await Erc20Account .GetUnspentAddressesAsync( toAddress: null, // todo: get participant address amount: 0, fee: 0, feePrice: 0, feeUsagePolicy: FeeUsagePolicy.EstimatedFee, addressUsagePolicy: AddressUsagePolicy.UseOnlyOneAddress, transactionType: BlockchainTransactionType.SwapRedeem, cancellationToken: cancellationToken) .ConfigureAwait(false)) .FirstOrDefault(); if (walletAddress == null) { Log.Error("Insufficient balance for party redeem. Cannot find the address containing the required amount of funds."); return; } var nonceResult = await EthereumNonceManager.Instance .GetNonceAsync(erc20, walletAddress.Address, cancellationToken) .ConfigureAwait(false); if (nonceResult.HasError) { Log.Error("Nonce getting error with code {@code} and description {@description}", nonceResult.Error.Code, nonceResult.Error.Description); return; } var message = new RedeemFunctionMessage { FromAddress = walletAddress.Address, HashedSecret = swap.SecretHash, Secret = swap.Secret, Nonce = nonceResult.Value, GasPrice = Atomex.Ethereum.GweiToWei(erc20.GasPriceInGwei), }; message.Gas = await EstimateGasAsync(message, new BigInteger(erc20.RedeemGasLimit)) .ConfigureAwait(false); var txInput = message.CreateTransactionInput(erc20.SwapContractAddress); var redeemTx = new EthereumTransaction(erc20, txInput) { Type = BlockchainTransactionType.Output | BlockchainTransactionType.SwapRedeem }; var signResult = await SignTransactionAsync(redeemTx, cancellationToken) .ConfigureAwait(false); if (!signResult) { Log.Error("Transaction signing error"); return; } await BroadcastTxAsync(swap, redeemTx, cancellationToken) .ConfigureAwait(false); }
public override System.Collections.IList Operations() { System.Collections.IList operations = new System.Collections.ArrayList(); for (int i = 0; i < _code.Length - 1; i++) { if (_code[i][1] + _code[i][2] == _code[i + 1][1]) { // adjacent Operation op = new Swap(EnclosingInstance, index, i, i + 1); operations.Add(op); } } return operations; }
public static char[] BuildKey(string key, Mode mode, Swap swap) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } string seed = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char[] cipherKey = new char[5 * 5]; key = key.ToUpper(); char cSwap; char cMode; switch (swap) { case Swap.X: cSwap = 'X'; break; case Swap.Z: cSwap = 'Z'; break; default: throw new ArgumentOutOfRangeException("swap"); } switch (mode) { case Mode.Q: cMode = 'Q'; key = key.Replace('Q', cSwap); break; case Mode.J: cMode = 'J'; key = key.Replace('J', 'I'); break; case Mode.I: cMode = 'I'; key = key.Replace('I', 'J'); break; default: throw new ArgumentOutOfRangeException("mode"); } seed = seed.Replace(cMode.ToString(), ""); int pos = 0; foreach (char currentChar in key.ToCharArray()) { if (seed.IndexOf(currentChar) >= 0) { seed = seed.Replace(currentChar.ToString(), ""); cipherKey[pos++] = currentChar; } if (pos >= cipherKey.Length) { break; } } foreach (char currentChar in seed.ToCharArray()) { if (pos >= cipherKey.Length) { break; } cipherKey[pos++] = currentChar; } return(cipherKey); }
public static async Task <Result <byte[]> > IsRedeemedAsync( Swap swap, Currency currency, Atomex.Tezos tezos, CancellationToken cancellationToken = default) { try { Log.Debug("Tezos FA2: check redeem event"); var fa2 = (TezosTokens.FA2)currency; var contractAddress = fa2.SwapContractAddress; var blockchainApi = (ITezosBlockchainApi)tezos.BlockchainApi; var txsResult = await blockchainApi .TryGetTransactionsAsync(contractAddress, cancellationToken : cancellationToken) .ConfigureAwait(false); if (txsResult == null) { return(new Error(Errors.RequestError, $"Connection error while getting txs from contract {contractAddress}")); } if (txsResult.HasError) { Log.Error("Error while get transactions from contract {@contract}. Code: {@code}. Description: {@desc}", contractAddress, txsResult.Error.Code, txsResult.Error.Description); return(txsResult.Error); } var txs = txsResult.Value ?.Cast <TezosTransaction>() .ToList(); if (txs != null) { foreach (var tx in txs) { if (tx.To == contractAddress && IsSwapRedeem(tx, swap.SecretHash)) { // redeem! var secret = GetSecret(tx); Log.Debug("Redeem event received with secret {@secret}", Convert.ToBase64String(secret)); return(secret); } if (tx.BlockInfo?.BlockTime == null) { continue; } var blockTimeUtc = tx.BlockInfo.BlockTime.Value.ToUniversalTime(); var swapTimeUtc = swap.TimeStamp.ToUniversalTime(); if (blockTimeUtc < swapTimeUtc) { break; } } } } catch (Exception e) { Log.Error(e, "Tezos FA2 redeem control task error"); return(new Error(Errors.InternalError, e.Message)); } return((byte[])null); }
protected override void performCalculations() { Period indexTenor = index_.tenor(); double fixedRate = 0.04; // dummy value Date startDate, maturity; if ( includeFirstSwaplet_ ) { startDate = termStructure_.link.referenceDate(); maturity = termStructure_.link.referenceDate() + length_; } else { startDate = termStructure_.link.referenceDate() + indexTenor; maturity = termStructure_.link.referenceDate() + length_; } IborIndex dummyIndex = new IborIndex( "dummy", indexTenor, index_.fixingDays(), index_.currency(), index_.fixingCalendar(), index_.businessDayConvention(), index_.endOfMonth(), termStructure_.link.dayCounter(), termStructure_ ); InitializedList<double> nominals = new InitializedList<double>( 1, 1.0 ); Schedule floatSchedule = new Schedule( startDate, maturity, index_.tenor(), index_.fixingCalendar(), index_.businessDayConvention(), index_.businessDayConvention(), DateGeneration.Rule.Forward, false ); List<CashFlow> floatingLeg = new IborLeg( floatSchedule, index_ ) .withFixingDays( 0 ) .withNotionals( nominals ) .withPaymentAdjustment( index_.businessDayConvention() ); Schedule fixedSchedule = new Schedule( startDate, maturity, new Period( fixedLegFrequency_ ), index_.fixingCalendar(), BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Forward, false ); List<CashFlow> fixedLeg = new FixedRateLeg( fixedSchedule ) .withCouponRates( fixedRate, fixedLegDayCounter_ ) .withNotionals( nominals ) .withPaymentAdjustment( index_.businessDayConvention() ); Swap swap = new Swap( floatingLeg, fixedLeg ); swap.setPricingEngine( new DiscountingSwapEngine( termStructure_, false ) ); double fairRate = fixedRate - (double)(swap.NPV() / ( swap.legBPS( 1 ) / 1.0e-4 )); cap_ = new Cap( floatingLeg, new InitializedList<double>( 1, fairRate ) ); base.performCalculations(); }
protected SwapPricer(ILogger logger, ICoreCache cache, String nameSpace, List <Pair <IBusinessCalendar, IBusinessCalendar> > legCalendars, Swap swapFpML, string basePartyReference, ProductTypeSimpleEnum productType) : this(logger, cache, nameSpace, legCalendars, swapFpML, basePartyReference, productType, false) { }
public Strategy(XmlNode xmlNode) : base(xmlNode) { XmlNodeList strategyComponentIdentifierNodeList = xmlNode.SelectNodes("strategyComponentIdentifier"); foreach (XmlNode item in strategyComponentIdentifierNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { strategyComponentIdentifierIDRef = item.Attributes["id"].Name; List<StrategyComponentIdentification> ob = new List<StrategyComponentIdentification>(); ob.Add(new StrategyComponentIdentification(item)); IDManager.SetID(strategyComponentIdentifierIDRef, ob); } else if (item.Attributes.ToString() == "href") { strategyComponentIdentifierIDRef = item.Attributes["href"].Name; } else { strategyComponentIdentifier.Add(new StrategyComponentIdentification(item)); } } } XmlNodeList premiumProductReferenceNodeList = xmlNode.SelectNodes("premiumProductReference"); if (premiumProductReferenceNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in premiumProductReferenceNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { premiumProductReferenceIDRef = item.Attributes["id"].Name; ProductReference ob = ProductReference(); IDManager.SetID(premiumProductReferenceIDRef, ob); } else if (item.Attributes.ToString() == "href") { premiumProductReferenceIDRef = item.Attributes["href"].Name; } else { premiumProductReference = new ProductReference(item); } } } XmlNodeList productNodeList = xmlNode.SelectNodes("product"); if (productNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in productNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { productIDRef = item.Attributes["id"].Name; Product ob = Product(); IDManager.SetID(productIDRef, ob); } else if (item.Attributes.ToString() == "href") { productIDRef = item.Attributes["href"].Name; } else { product = new Product(item); } } } XmlNodeList forwardNodeList = xmlNode.SelectNodes("forward"); if (forwardNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in forwardNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { forwardIDRef = item.Attributes["id"].Name; ForwardSale ob = ForwardSale(); IDManager.SetID(forwardIDRef, ob); } else if (item.Attributes.ToString() == "href") { forwardIDRef = item.Attributes["href"].Name; } else { forward = new ForwardSale(item); } } } XmlNodeList bondOptionNodeList = xmlNode.SelectNodes("bondOption"); if (bondOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in bondOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { bondOptionIDRef = item.Attributes["id"].Name; BondOption ob = BondOption(); IDManager.SetID(bondOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { bondOptionIDRef = item.Attributes["href"].Name; } else { bondOption = new BondOption(item); } } } XmlNodeList creditDefaultSwapNodeList = xmlNode.SelectNodes("creditDefaultSwap"); if (creditDefaultSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in creditDefaultSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { creditDefaultSwapIDRef = item.Attributes["id"].Name; CreditDefaultSwap ob = CreditDefaultSwap(); IDManager.SetID(creditDefaultSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { creditDefaultSwapIDRef = item.Attributes["href"].Name; } else { creditDefaultSwap = new CreditDefaultSwap(item); } } } XmlNodeList creditDefaultSwapOptionNodeList = xmlNode.SelectNodes("creditDefaultSwapOption"); if (creditDefaultSwapOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in creditDefaultSwapOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { creditDefaultSwapOptionIDRef = item.Attributes["id"].Name; CreditDefaultSwapOption ob = CreditDefaultSwapOption(); IDManager.SetID(creditDefaultSwapOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { creditDefaultSwapOptionIDRef = item.Attributes["href"].Name; } else { creditDefaultSwapOption = new CreditDefaultSwapOption(item); } } } XmlNodeList commodityForwardNodeList = xmlNode.SelectNodes("commodityForward"); if (commodityForwardNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in commodityForwardNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { commodityForwardIDRef = item.Attributes["id"].Name; CommodityForward ob = CommodityForward(); IDManager.SetID(commodityForwardIDRef, ob); } else if (item.Attributes.ToString() == "href") { commodityForwardIDRef = item.Attributes["href"].Name; } else { commodityForward = new CommodityForward(item); } } } XmlNodeList commodityOptionNodeList = xmlNode.SelectNodes("commodityOption"); if (commodityOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in commodityOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { commodityOptionIDRef = item.Attributes["id"].Name; CommodityOption ob = CommodityOption(); IDManager.SetID(commodityOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { commodityOptionIDRef = item.Attributes["href"].Name; } else { commodityOption = new CommodityOption(item); } } } XmlNodeList commoditySwapNodeList = xmlNode.SelectNodes("commoditySwap"); if (commoditySwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in commoditySwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { commoditySwapIDRef = item.Attributes["id"].Name; CommoditySwap ob = CommoditySwap(); IDManager.SetID(commoditySwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { commoditySwapIDRef = item.Attributes["href"].Name; } else { commoditySwap = new CommoditySwap(item); } } } XmlNodeList commoditySwaptionNodeList = xmlNode.SelectNodes("commoditySwaption"); if (commoditySwaptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in commoditySwaptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { commoditySwaptionIDRef = item.Attributes["id"].Name; CommoditySwaption ob = CommoditySwaption(); IDManager.SetID(commoditySwaptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { commoditySwaptionIDRef = item.Attributes["href"].Name; } else { commoditySwaption = new CommoditySwaption(item); } } } XmlNodeList correlationSwapNodeList = xmlNode.SelectNodes("correlationSwap"); if (correlationSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in correlationSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { correlationSwapIDRef = item.Attributes["id"].Name; CorrelationSwap ob = CorrelationSwap(); IDManager.SetID(correlationSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { correlationSwapIDRef = item.Attributes["href"].Name; } else { correlationSwap = new CorrelationSwap(item); } } } XmlNodeList dividendSwapOptionTransactionSupplementNodeList = xmlNode.SelectNodes("dividendSwapOptionTransactionSupplement"); if (dividendSwapOptionTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in dividendSwapOptionTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { dividendSwapOptionTransactionSupplementIDRef = item.Attributes["id"].Name; DividendSwapOptionTransactionSupplement ob = DividendSwapOptionTransactionSupplement(); IDManager.SetID(dividendSwapOptionTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { dividendSwapOptionTransactionSupplementIDRef = item.Attributes["href"].Name; } else { dividendSwapOptionTransactionSupplement = new DividendSwapOptionTransactionSupplement(item); } } } XmlNodeList dividendSwapTransactionSupplementNodeList = xmlNode.SelectNodes("dividendSwapTransactionSupplement"); if (dividendSwapTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in dividendSwapTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { dividendSwapTransactionSupplementIDRef = item.Attributes["id"].Name; DividendSwapTransactionSupplement ob = DividendSwapTransactionSupplement(); IDManager.SetID(dividendSwapTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { dividendSwapTransactionSupplementIDRef = item.Attributes["href"].Name; } else { dividendSwapTransactionSupplement = new DividendSwapTransactionSupplement(item); } } } XmlNodeList instrumentTradeDetailsNodeList = xmlNode.SelectNodes("instrumentTradeDetails"); if (instrumentTradeDetailsNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in instrumentTradeDetailsNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { instrumentTradeDetailsIDRef = item.Attributes["id"].Name; InstrumentTradeDetails ob = InstrumentTradeDetails(); IDManager.SetID(instrumentTradeDetailsIDRef, ob); } else if (item.Attributes.ToString() == "href") { instrumentTradeDetailsIDRef = item.Attributes["href"].Name; } else { instrumentTradeDetails = new InstrumentTradeDetails(item); } } } XmlNodeList strategyNodeList = xmlNode.SelectNodes("strategy"); if (strategyNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in strategyNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { strategyIDRef = item.Attributes["id"].Name; Strategy ob = Strategy(); IDManager.SetID(strategyIDRef, ob); } else if (item.Attributes.ToString() == "href") { strategyIDRef = item.Attributes["href"].Name; } else { strategy = new Strategy(item); } } } XmlNodeList returnSwapNodeList = xmlNode.SelectNodes("returnSwap"); if (returnSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in returnSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { returnSwapIDRef = item.Attributes["id"].Name; ReturnSwap ob = ReturnSwap(); IDManager.SetID(returnSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { returnSwapIDRef = item.Attributes["href"].Name; } else { returnSwap = new ReturnSwap(item); } } } XmlNodeList brokerEquityOptionNodeList = xmlNode.SelectNodes("brokerEquityOption"); if (brokerEquityOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in brokerEquityOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { brokerEquityOptionIDRef = item.Attributes["id"].Name; BrokerEquityOption ob = BrokerEquityOption(); IDManager.SetID(brokerEquityOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { brokerEquityOptionIDRef = item.Attributes["href"].Name; } else { brokerEquityOption = new BrokerEquityOption(item); } } } XmlNodeList equityForwardNodeList = xmlNode.SelectNodes("equityForward"); if (equityForwardNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in equityForwardNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { equityForwardIDRef = item.Attributes["id"].Name; EquityForward ob = EquityForward(); IDManager.SetID(equityForwardIDRef, ob); } else if (item.Attributes.ToString() == "href") { equityForwardIDRef = item.Attributes["href"].Name; } else { equityForward = new EquityForward(item); } } } XmlNodeList equityOptionNodeList = xmlNode.SelectNodes("equityOption"); if (equityOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in equityOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { equityOptionIDRef = item.Attributes["id"].Name; EquityOption ob = EquityOption(); IDManager.SetID(equityOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { equityOptionIDRef = item.Attributes["href"].Name; } else { equityOption = new EquityOption(item); } } } XmlNodeList equityOptionTransactionSupplementNodeList = xmlNode.SelectNodes("equityOptionTransactionSupplement"); if (equityOptionTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in equityOptionTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { equityOptionTransactionSupplementIDRef = item.Attributes["id"].Name; EquityOptionTransactionSupplement ob = EquityOptionTransactionSupplement(); IDManager.SetID(equityOptionTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { equityOptionTransactionSupplementIDRef = item.Attributes["href"].Name; } else { equityOptionTransactionSupplement = new EquityOptionTransactionSupplement(item); } } } XmlNodeList fxSingleLegNodeList = xmlNode.SelectNodes("fxSingleLeg"); if (fxSingleLegNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fxSingleLegNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fxSingleLegIDRef = item.Attributes["id"].Name; FxSingleLeg ob = FxSingleLeg(); IDManager.SetID(fxSingleLegIDRef, ob); } else if (item.Attributes.ToString() == "href") { fxSingleLegIDRef = item.Attributes["href"].Name; } else { fxSingleLeg = new FxSingleLeg(item); } } } XmlNodeList fxSwapNodeList = xmlNode.SelectNodes("fxSwap"); if (fxSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fxSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fxSwapIDRef = item.Attributes["id"].Name; FxSwap ob = FxSwap(); IDManager.SetID(fxSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { fxSwapIDRef = item.Attributes["href"].Name; } else { fxSwap = new FxSwap(item); } } } XmlNodeList fxOptionNodeList = xmlNode.SelectNodes("fxOption"); if (fxOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fxOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fxOptionIDRef = item.Attributes["id"].Name; FxOption ob = FxOption(); IDManager.SetID(fxOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { fxOptionIDRef = item.Attributes["href"].Name; } else { fxOption = new FxOption(item); } } } XmlNodeList fxDigitalOptionNodeList = xmlNode.SelectNodes("fxDigitalOption"); if (fxDigitalOptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fxDigitalOptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fxDigitalOptionIDRef = item.Attributes["id"].Name; FxDigitalOption ob = FxDigitalOption(); IDManager.SetID(fxDigitalOptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { fxDigitalOptionIDRef = item.Attributes["href"].Name; } else { fxDigitalOption = new FxDigitalOption(item); } } } XmlNodeList termDepositNodeList = xmlNode.SelectNodes("termDeposit"); if (termDepositNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in termDepositNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { termDepositIDRef = item.Attributes["id"].Name; TermDeposit ob = TermDeposit(); IDManager.SetID(termDepositIDRef, ob); } else if (item.Attributes.ToString() == "href") { termDepositIDRef = item.Attributes["href"].Name; } else { termDeposit = new TermDeposit(item); } } } XmlNodeList genericProductNodeList = xmlNode.SelectNodes("genericProduct"); if (genericProductNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in genericProductNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { genericProductIDRef = item.Attributes["id"].Name; GenericProduct ob = GenericProduct(); IDManager.SetID(genericProductIDRef, ob); } else if (item.Attributes.ToString() == "href") { genericProductIDRef = item.Attributes["href"].Name; } else { genericProduct = new GenericProduct(item); } } } XmlNodeList nonSchemaProductNodeList = xmlNode.SelectNodes("nonSchemaProduct"); if (nonSchemaProductNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in nonSchemaProductNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { nonSchemaProductIDRef = item.Attributes["id"].Name; GenericProduct ob = GenericProduct(); IDManager.SetID(nonSchemaProductIDRef, ob); } else if (item.Attributes.ToString() == "href") { nonSchemaProductIDRef = item.Attributes["href"].Name; } else { nonSchemaProduct = new GenericProduct(item); } } } XmlNodeList bulletPaymentNodeList = xmlNode.SelectNodes("bulletPayment"); if (bulletPaymentNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in bulletPaymentNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { bulletPaymentIDRef = item.Attributes["id"].Name; BulletPayment ob = BulletPayment(); IDManager.SetID(bulletPaymentIDRef, ob); } else if (item.Attributes.ToString() == "href") { bulletPaymentIDRef = item.Attributes["href"].Name; } else { bulletPayment = new BulletPayment(item); } } } XmlNodeList capFloorNodeList = xmlNode.SelectNodes("capFloor"); if (capFloorNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in capFloorNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { capFloorIDRef = item.Attributes["id"].Name; CapFloor ob = CapFloor(); IDManager.SetID(capFloorIDRef, ob); } else if (item.Attributes.ToString() == "href") { capFloorIDRef = item.Attributes["href"].Name; } else { capFloor = new CapFloor(item); } } } XmlNodeList fraNodeList = xmlNode.SelectNodes("fra"); if (fraNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in fraNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { fraIDRef = item.Attributes["id"].Name; Fra ob = Fra(); IDManager.SetID(fraIDRef, ob); } else if (item.Attributes.ToString() == "href") { fraIDRef = item.Attributes["href"].Name; } else { fra = new Fra(item); } } } XmlNodeList swapNodeList = xmlNode.SelectNodes("swap"); if (swapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in swapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { swapIDRef = item.Attributes["id"].Name; Swap ob = Swap(); IDManager.SetID(swapIDRef, ob); } else if (item.Attributes.ToString() == "href") { swapIDRef = item.Attributes["href"].Name; } else { swap = new Swap(item); } } } XmlNodeList swaptionNodeList = xmlNode.SelectNodes("swaption"); if (swaptionNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in swaptionNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { swaptionIDRef = item.Attributes["id"].Name; Swaption ob = Swaption(); IDManager.SetID(swaptionIDRef, ob); } else if (item.Attributes.ToString() == "href") { swaptionIDRef = item.Attributes["href"].Name; } else { swaption = new Swaption(item); } } } XmlNodeList equitySwapTransactionSupplementNodeList = xmlNode.SelectNodes("equitySwapTransactionSupplement"); if (equitySwapTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in equitySwapTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { equitySwapTransactionSupplementIDRef = item.Attributes["id"].Name; EquitySwapTransactionSupplement ob = EquitySwapTransactionSupplement(); IDManager.SetID(equitySwapTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { equitySwapTransactionSupplementIDRef = item.Attributes["href"].Name; } else { equitySwapTransactionSupplement = new EquitySwapTransactionSupplement(item); } } } XmlNodeList standardProductNodeList = xmlNode.SelectNodes("standardProduct"); if (standardProductNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in standardProductNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { standardProductIDRef = item.Attributes["id"].Name; StandardProduct ob = StandardProduct(); IDManager.SetID(standardProductIDRef, ob); } else if (item.Attributes.ToString() == "href") { standardProductIDRef = item.Attributes["href"].Name; } else { standardProduct = new StandardProduct(item); } } } XmlNodeList varianceOptionTransactionSupplementNodeList = xmlNode.SelectNodes("varianceOptionTransactionSupplement"); if (varianceOptionTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in varianceOptionTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { varianceOptionTransactionSupplementIDRef = item.Attributes["id"].Name; VarianceOptionTransactionSupplement ob = VarianceOptionTransactionSupplement(); IDManager.SetID(varianceOptionTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { varianceOptionTransactionSupplementIDRef = item.Attributes["href"].Name; } else { varianceOptionTransactionSupplement = new VarianceOptionTransactionSupplement(item); } } } XmlNodeList varianceSwapNodeList = xmlNode.SelectNodes("varianceSwap"); if (varianceSwapNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in varianceSwapNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { varianceSwapIDRef = item.Attributes["id"].Name; VarianceSwap ob = VarianceSwap(); IDManager.SetID(varianceSwapIDRef, ob); } else if (item.Attributes.ToString() == "href") { varianceSwapIDRef = item.Attributes["href"].Name; } else { varianceSwap = new VarianceSwap(item); } } } XmlNodeList varianceSwapTransactionSupplementNodeList = xmlNode.SelectNodes("varianceSwapTransactionSupplement"); if (varianceSwapTransactionSupplementNodeList.Count > 1 ) { throw new Exception(); } foreach (XmlNode item in varianceSwapTransactionSupplementNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] == null) { if (item.Attributes["id"] != null) { varianceSwapTransactionSupplementIDRef = item.Attributes["id"].Name; VarianceSwapTransactionSupplement ob = VarianceSwapTransactionSupplement(); IDManager.SetID(varianceSwapTransactionSupplementIDRef, ob); } else if (item.Attributes.ToString() == "href") { varianceSwapTransactionSupplementIDRef = item.Attributes["href"].Name; } else { varianceSwapTransactionSupplement = new VarianceSwapTransactionSupplement(item); } } } }
protected SwapPricer(ILogger logger, ICoreCache cache, String nameSpace, List <Pair <IBusinessCalendar, IBusinessCalendar> > legCalendars, Swap swapFpML, string basePartyReference, ProductTypeSimpleEnum productType, Boolean forecastRateInterpolation) { Multiplier = 1.0m; if (swapFpML == null) { return; } BusinessCentersResolver.ResolveBusinessCenters(swapFpML); ForecastRateInterpolation = forecastRateInterpolation; //Get the effective date AdjustableDate adjustableEffectiveDate = XsdClassesFieldResolver.CalculationPeriodDatesGetEffectiveDate(swapFpML.swapStream[0].calculationPeriodDates); EffectiveDate = adjustableEffectiveDate.unadjustedDate.Value; //We make the assumption that the termination date is the same for all legs. AdjustableDate adjustableTerminationDate = XsdClassesFieldResolver.CalculationPeriodDatesGetTerminationDate(swapFpML.swapStream[0].calculationPeriodDates); var paymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, adjustableTerminationDate.dateAdjustments.businessCenters, nameSpace); TerminationDate = AdjustedDateHelper.ToAdjustedDate(paymentCalendar, adjustableTerminationDate); RiskMaturityDate = TerminationDate; //EffectiveDate is not set; ProductType = productType; PaymentCurrencies = new List <string>(); //Resolve the payer var legs = swapFpML.swapStream.Length; if (legs == 0) { return; } var flag = false; var index = 0; if (legCalendars != null && legCalendars.Count == legs) { flag = true; } foreach (var swapStream in swapFpML.swapStream) { bool payerIsBase = basePartyReference == swapStream.payerPartyReference.href;//TODO add in the calendar functionality. //Set the id of the first stream. PriceableInterestRateStream leg = flag ? new PriceableInterestRateStream(logger, cache, nameSpace, payerIsBase, swapStream, ForecastRateInterpolation, legCalendars[index].First, legCalendars[index].Second) : new PriceableInterestRateStream(logger, cache, nameSpace, payerIsBase, swapStream, ForecastRateInterpolation, null, null); Legs.Add(leg); //Add the currencies for the trade pricer. if (!PaymentCurrencies.Contains(leg.Currency.Value)) { PaymentCurrencies.Add(leg.Currency.Value); } index++; } if (swapFpML.additionalPayment != null) { AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, swapFpML.additionalPayment, null); foreach (var payment in swapFpML.additionalPayment) { if (!PaymentCurrencies.Contains(payment.paymentAmount.currency.Value)) { PaymentCurrencies.Add(payment.paymentAmount.currency.Value); } } } }
private SwapTrade getMtmTrade(bool initialExchange, bool intermediateExchange, bool finalExchange, double?initialNotional) { SwapLeg payLeg = RateCalculationSwapLeg.builder().payReceive(PAY).accrualSchedule(PeriodicSchedule.builder().startDate(LocalDate.of(2014, 1, 24)).endDate(LocalDate.of(2016, 1, 24)).frequency(P3M).businessDayAdjustment(BDA_MF).build()).paymentSchedule(PaymentSchedule.builder().paymentFrequency(P3M).paymentDateOffset(DaysAdjustment.NONE).build()).notionalSchedule(NotionalSchedule.builder().finalExchange(finalExchange).initialExchange(initialExchange).amount(ValueSchedule.of(NOTIONAL_EUR)).currency(EUR).build()).calculation(IborRateCalculation.builder().index(EUR_EURIBOR_3M).fixingDateOffset(DaysAdjustment.ofBusinessDays(-2, CalendarUSD.NYC, BDA_P)).spread(ValueSchedule.of(0.0020)).build()).build(); SwapLeg receiveLeg = RateCalculationSwapLeg.builder().payReceive(RECEIVE).accrualSchedule(PeriodicSchedule.builder().startDate(LocalDate.of(2014, 1, 24)).endDate(LocalDate.of(2016, 1, 24)).frequency(P3M).businessDayAdjustment(BDA_MF).build()).paymentSchedule(PaymentSchedule.builder().paymentFrequency(P3M).paymentDateOffset(DaysAdjustment.NONE).build()).notionalSchedule(NotionalSchedule.builder().finalExchange(finalExchange).initialExchange(initialExchange).intermediateExchange(intermediateExchange).amount(ValueSchedule.of(NOTIONAL_USD)).currency(USD).fxReset(FxResetCalculation.builder().fixingDateOffset(DaysAdjustment.ofBusinessDays(-2, CalendarUSD.NYC, BDA_P)).referenceCurrency(EUR).index(EUR_USD_WM).initialNotionalValue(initialNotional).build()).build()).calculation(IborRateCalculation.builder().index(USD_LIBOR_3M).fixingDateOffset(DaysAdjustment.ofBusinessDays(-2, CalendarUSD.NYC, BDA_P)).build()).build(); return(SwapTrade.builder().info(TradeInfo.builder().tradeDate(LocalDate.of(2014, 9, 10)).build()).product(Swap.of(payLeg, receiveLeg)).build()); }
private bool IsInitiate(Swap swap, Swap receivedSwap) { return(swap.IsStatusSet(receivedSwap.Status, SwapStatus.Initiated)); }
public bool EditBeerOfferedName(int _postid, Swap _swap, string _newName) { var query = from p in context.BeerPostings where p.BeerPostingID == _postid select p; BeerPosting found_post = null; bool result = true; try { found_post = query.Single<BeerPosting>(); _swap.BeerOffered = _newName; context.SaveChanges(); } catch (InvalidOperationException) { result = false; } catch (ArgumentNullException) { result = false; } return result; }
//----------------------------------------------------------------------- // XCcy swap with exchange of notional public virtual void test_XCcyEur3MSpreadVsUSD3M() { SwapLeg payLeg = RateCalculationSwapLeg.builder().payReceive(PAY).accrualSchedule(PeriodicSchedule.builder().startDate(LocalDate.of(2014, 1, 24)).endDate(LocalDate.of(2016, 1, 24)).frequency(P3M).businessDayAdjustment(BDA_MF).build()).paymentSchedule(PaymentSchedule.builder().paymentFrequency(P3M).paymentDateOffset(DaysAdjustment.NONE).build()).notionalSchedule(NotionalSchedule.builder().finalExchange(true).initialExchange(true).amount(ValueSchedule.of(NOTIONAL_EUR)).currency(EUR).build()).calculation(IborRateCalculation.builder().index(EUR_EURIBOR_3M).fixingDateOffset(DaysAdjustment.ofBusinessDays(-2, CalendarUSD.NYC, BDA_P)).spread(ValueSchedule.of(0.0020)).build()).build(); SwapLeg receiveLeg = RateCalculationSwapLeg.builder().payReceive(RECEIVE).accrualSchedule(PeriodicSchedule.builder().startDate(LocalDate.of(2014, 1, 24)).endDate(LocalDate.of(2016, 1, 24)).frequency(P3M).businessDayAdjustment(BDA_MF).build()).paymentSchedule(PaymentSchedule.builder().paymentFrequency(P3M).paymentDateOffset(DaysAdjustment.NONE).build()).notionalSchedule(NotionalSchedule.builder().finalExchange(true).initialExchange(true).amount(ValueSchedule.of(NOTIONAL_USD)).currency(USD).build()).calculation(IborRateCalculation.builder().index(USD_LIBOR_3M).fixingDateOffset(DaysAdjustment.ofBusinessDays(-2, CalendarUSD.NYC, BDA_P)).build()).build(); ResolvedSwapTrade trade = SwapTrade.builder().info(TradeInfo.builder().tradeDate(LocalDate.of(2014, 9, 10)).build()).product(Swap.of(payLeg, receiveLeg)).build().resolve(REF_DATA); double pvUsdExpected = 431944.6868; double pvEurExpected = -731021.1778; DiscountingSwapTradePricer pricer = swapPricer(); MultiCurrencyAmount pv = pricer.presentValue(trade, provider()); assertEquals(pv.getAmount(USD).Amount, pvUsdExpected, TOLERANCE_PV); assertEquals(pv.getAmount(EUR).Amount, pvEurExpected, TOLERANCE_PV); }