/** * */ private BuildingObject GetCoordinatesById(XmlNodeList nodeTags, List <long> nodeTagIds, XmlNode wayTag, float buildingHeight) { if (buildingHeight == DefaultBuildingHeight) { buildingHeight = 1; } //ids for coordinate pairing from way tag var locationIDs = LoaderUtils.GetWayTagIDs(wayTag); var latLngObjects = new LatLngObject[locationIDs.Count]; var numOfFoundedIDs = 0; for (var k = 0; k < nodeTags.Count; k++) { //cached id from node tag var id = nodeTagIds[k]; int locationIndex; if ((locationIndex = locationIDs.IndexOf(id)) != -1) { var nodeTag = nodeTags[k]; var lat = float.Parse(nodeTag.Attributes["lat"].Value); var lon = float.Parse(nodeTag.Attributes["lon"].Value); latLngObjects[locationIndex] = new LatLngObject(lat, lon); ++numOfFoundedIDs; } //pokud všechny souřadnice byly spárovány s IDčkama od budovy if (locationIDs.Count == numOfFoundedIDs) { break; } } return(new BuildingObject(latLngObjects.ToList(), buildingHeight)); }
private static Multimap <LocalDate, Curve> parseSingle(System.Predicate <LocalDate> datePredicate, CharSource curvesResource, IDictionary <CurveName, LoadedCurveSettings> settingsMap) { CsvFile csv = CsvFile.of(curvesResource, true); IDictionary <LoadedCurveKey, IList <LoadedCurveNode> > allNodes = new Dictionary <LoadedCurveKey, IList <LoadedCurveNode> >(); foreach (CsvRow row in csv.rows()) { string dateStr = row.getField(CURVE_DATE); string curveNameStr = row.getField(CURVE_NAME); string pointDateStr = row.getField(CURVE_POINT_DATE); string pointValueStr = row.getField(CURVE_POINT_VALUE); string pointLabel = row.getField(CURVE_POINT_LABEL); LocalDate date = LoaderUtils.parseDate(dateStr); if (datePredicate(date)) { LocalDate pointDate = LoaderUtils.parseDate(pointDateStr); double pointValue = Convert.ToDouble(pointValueStr); LoadedCurveKey key = LoadedCurveKey.of(date, CurveName.of(curveNameStr)); IList <LoadedCurveNode> curveNodes = allNodes.computeIfAbsent(key, k => new List <LoadedCurveNode>()); curveNodes.Add(LoadedCurveNode.of(pointDate, pointValue, pointLabel)); } } return(buildCurves(settingsMap, allNodes)); }
// variable fixed rate private static SwapTrade parseVariableRates(SwapTrade trade, IList <CsvRow> variableRows) { ImmutableList.Builder <ValueStep> stepBuilder = ImmutableList.builder(); foreach (CsvRow row in variableRows) { LocalDate date = LoaderUtils.parseDate(row.getValue(START_DATE_FIELD)); row.findValue(FIXED_RATE_FIELD).map(str => LoaderUtils.parseDoublePercent(str)).ifPresent(fixedRate => stepBuilder.add(ValueStep.of(date, ValueAdjustment.ofReplace(fixedRate)))); } ImmutableList <ValueStep> varRates = stepBuilder.build(); if (varRates.Empty) { return(trade); } // adjust the trade, inserting the variable rates ImmutableList.Builder <SwapLeg> legBuilder = ImmutableList.builder(); foreach (SwapLeg swapLeg in trade.Product.Legs) { RateCalculationSwapLeg leg = (RateCalculationSwapLeg)swapLeg; if (leg.Calculation is FixedRateCalculation) { FixedRateCalculation baseCalc = (FixedRateCalculation)leg.Calculation; FixedRateCalculation calc = baseCalc.toBuilder().rate(ValueSchedule.of(baseCalc.Rate.InitialValue, varRates)).build(); legBuilder.add(leg.toBuilder().calculation(calc).build()); } else { legBuilder.add(leg); } } return(replaceLegs(trade, legBuilder.build())); }
internal static void SetDefaults(NPC npc, bool createModNPC = true) { if (IsModNPC(npc)) { if (createModNPC) { npc.ModNPC = GetNPC(npc.type).NewInstance(npc); } else //the default NPCs created and bound to ModNPCs are initialized before ResizeArrays. They come here during SetupContent. { Array.Resize(ref npc.buffImmune, BuffLoader.BuffCount); } } GlobalNPC Instantiate(GlobalNPC g) => g.InstancePerEntity ? g.NewInstance(npc) : g; LoaderUtils.InstantiateGlobals(npc, globalNPCs, ref npc.globalNPCs, Instantiate, () => { npc.ModNPC?.SetDefaults(); }); foreach (GlobalNPC g in HookSetDefaults.Enumerate(npc.globalNPCs)) { g.SetDefaults(npc); } }
//------------------------------------------------------------------------- // notional schedule private static NotionalSchedule parseNotionalSchedule(CsvRow row, string leg) { NotionalSchedule.Builder builder = NotionalSchedule.builder(); // basics Currency currency = Currency.of(getValueWithFallback(row, leg, CURRENCY_FIELD)); builder.currency(currency); builder.amount(ValueSchedule.of(LoaderUtils.parseDouble(getValueWithFallback(row, leg, NOTIONAL_FIELD)))); // fx reset Optional <FxIndex> fxIndexOpt = findValue(row, leg, FX_RESET_INDEX_FIELD).map(s => FxIndex.of(s)); Optional <Currency> notionalCurrencyOpt = findValue(row, leg, NOTIONAL_CURRENCY_FIELD).map(s => Currency.of(s)); Optional <FxResetFixingRelativeTo> fxFixingRelativeToOpt = findValue(row, leg, FX_RESET_RELATIVE_TO_FIELD).map(s => FxResetFixingRelativeTo.of(s)); Optional <DaysAdjustment> fxResetAdjOpt = parseDaysAdjustment(row, leg, FX_RESET_OFFSET_DAYS_FIELD, FX_RESET_OFFSET_CAL_FIELD, FX_RESET_OFFSET_ADJ_CNV_FIELD, FX_RESET_OFFSET_ADJ_CAL_FIELD); if (fxIndexOpt.Present) { FxIndex fxIndex = fxIndexOpt.get(); FxResetCalculation.Builder fxResetBuilder = FxResetCalculation.builder(); fxResetBuilder.index(fxIndex); fxResetBuilder.referenceCurrency(notionalCurrencyOpt.orElse(fxIndex.CurrencyPair.other(currency))); fxFixingRelativeToOpt.ifPresent(v => fxResetBuilder.fixingRelativeTo(v)); fxResetAdjOpt.ifPresent(v => fxResetBuilder.fixingDateOffset(v)); builder.fxReset(fxResetBuilder.build()); } else if (notionalCurrencyOpt.Present || fxFixingRelativeToOpt.Present || fxResetAdjOpt.Present) { throw new System.ArgumentException("Swap trade FX Reset must define field '" + leg + FX_RESET_INDEX_FIELD + "'"); } // optionals findValue(row, leg, NOTIONAL_INITIAL_EXCHANGE_FIELD).map(s => LoaderUtils.parseBoolean(s)).ifPresent(v => builder.initialExchange(v)); findValue(row, leg, NOTIONAL_INTERMEDIATE_EXCHANGE_FIELD).map(s => LoaderUtils.parseBoolean(s)).ifPresent(v => builder.intermediateExchange(v)); findValue(row, leg, NOTIONAL_FINAL_EXCHANGE_FIELD).map(s => LoaderUtils.parseBoolean(s)).ifPresent(v => builder.finalExchange(v)); return(builder.build()); }
private static IDictionary <CurveName, LoadedCurveSettings> parseCurveSettings(CharSource settingsResource) { ImmutableMap.Builder <CurveName, LoadedCurveSettings> builder = ImmutableMap.builder(); CsvFile csv = CsvFile.of(settingsResource, true); foreach (CsvRow row in csv.rows()) { string curveNameStr = row.getField(SETTINGS_CURVE_NAME); string valueTypeStr = row.getField(SETTINGS_VALUE_TYPE); string dayCountStr = row.getField(SETTINGS_DAY_COUNT); string interpolatorStr = row.getField(SETTINGS_INTERPOLATOR); string leftExtrapolatorStr = row.getField(SETTINGS_LEFT_EXTRAPOLATOR); string rightExtrapolatorStr = row.getField(SETTINGS_RIGHT_EXTRAPOLATOR); if (!VALUE_TYPE_MAP.containsKey(valueTypeStr.ToLower(Locale.ENGLISH))) { throw new System.ArgumentException(Messages.format("Unsupported {} in curve settings: {}", SETTINGS_VALUE_TYPE, valueTypeStr)); } CurveName curveName = CurveName.of(curveNameStr); ValueType valueType = VALUE_TYPE_MAP.get(valueTypeStr.ToLower(Locale.ENGLISH)); CurveInterpolator interpolator = CurveInterpolator.of(interpolatorStr); CurveExtrapolator leftExtrap = CurveExtrapolator.of(leftExtrapolatorStr); CurveExtrapolator rightExtrap = CurveExtrapolator.of(rightExtrapolatorStr); // ONE_ONE day count is not used DayCount dayCount = LoaderUtils.parseDayCount(dayCountStr); LoadedCurveSettings settings = LoadedCurveSettings.of(curveName, ValueType.YEAR_FRACTION, valueType, dayCount, interpolator, leftExtrap, rightExtrap); builder.put(curveName, settings); } return(builder.build()); }
private static IIsolatedEnvironment InternalCreateIsolatedEnvironment(AppDomain appDomain, string runtimePath) { Type initializerType = typeof(IsolatedInitializer); Assembly initializerAssembly = initializerType.Assembly; IsolatedInitializer initializer; try { try { initializer = (IsolatedInitializer) appDomain.CreateInstanceAndUnwrap(initializerAssembly.FullName, initializerType.FullName); } catch (Exception) { string initializerAssemblyPath = LoaderUtils.GetAssemblyPath(initializerAssembly); initializer = (IsolatedInitializer) appDomain.CreateInstanceFromAndUnwrap(initializerAssemblyPath, initializerType.FullName); } } catch (Exception ex) { throw new LoaderException("Failed to load the loader into the remote AppDomain.", ex); } var environment = new IsolatedEnvironment(appDomain, runtimePath, initializer); environment.Initialize(); return(environment); }
internal static void ResizeArrays(bool unloading = false) { //Textures Array.Resize(ref TextureAssets.Wall, nextWall); //Sets LoaderUtils.ResetStaticMembers(typeof(WallID), true); //Etc Array.Resize(ref Main.wallHouse, nextWall); Array.Resize(ref Main.wallDungeon, nextWall); Array.Resize(ref Main.wallLight, nextWall); Array.Resize(ref Main.wallBlend, nextWall); Array.Resize(ref Main.wallLargeFrames, nextWall); Array.Resize(ref Main.wallFrame, nextWall); Array.Resize(ref Main.wallFrameCounter, nextWall); ModLoader.BuildGlobalHook(ref HookKillSound, globalWalls, g => g.KillSound); ModLoader.BuildGlobalHook(ref HookNumDust, globalWalls, g => g.NumDust); ModLoader.BuildGlobalHook(ref HookCreateDust, globalWalls, g => g.CreateDust); ModLoader.BuildGlobalHook(ref HookDrop, globalWalls, g => g.Drop); ModLoader.BuildGlobalHook(ref HookKillWall, globalWalls, g => g.KillWall); ModLoader.BuildGlobalHook(ref HookCanExplode, globalWalls, g => g.CanExplode); ModLoader.BuildGlobalHook(ref HookModifyLight, globalWalls, g => g.ModifyLight); ModLoader.BuildGlobalHook(ref HookRandomUpdate, globalWalls, g => g.RandomUpdate); ModLoader.BuildGlobalHook(ref HookPreDraw, globalWalls, g => g.PreDraw); ModLoader.BuildGlobalHook(ref HookPostDraw, globalWalls, g => g.PostDraw); ModLoader.BuildGlobalHook(ref HookPlaceInWorld, globalWalls, g => g.PlaceInWorld); if (!unloading) { loaded = true; } }
// loads a single CSV file, filtering by date private static void parseSingle(System.Predicate <LocalDate> datePredicate, CharSource resource, IDictionary <LocalDate, ImmutableMap.Builder <FxRateId, FxRate> > mutableMap) { try { CsvFile csv = CsvFile.of(resource, true); foreach (CsvRow row in csv.rows()) { string dateText = row.getField(DATE_FIELD); LocalDate date = LoaderUtils.parseDate(dateText); if (datePredicate(date)) { string currencyPairStr = row.getField(CURRENCY_PAIR_FIELD); string valueStr = row.getField(VALUE_FIELD); CurrencyPair currencyPair = CurrencyPair.parse(currencyPairStr); double value = Convert.ToDouble(valueStr); ImmutableMap.Builder <FxRateId, FxRate> builderForDate = mutableMap.computeIfAbsent(date, k => ImmutableMap.builder()); builderForDate.put(FxRateId.of(currencyPair), FxRate.of(currencyPair, value)); } } } catch (Exception ex) { throw new System.ArgumentException(Messages.format("Error processing resource as CSV file: {}", resource), ex); } }
//------------------------------------------------------------------------- // accrual schedule private static PeriodicSchedule parseAccrualSchedule(CsvRow row, string leg) { PeriodicSchedule.Builder builder = PeriodicSchedule.builder(); // basics builder.startDate(LoaderUtils.parseDate(getValueWithFallback(row, leg, START_DATE_FIELD))); builder.endDate(LoaderUtils.parseDate(getValueWithFallback(row, leg, END_DATE_FIELD))); builder.frequency(Frequency.parse(getValue(row, leg, FREQUENCY_FIELD))); // adjustments BusinessDayAdjustment dateAdj = parseBusinessDayAdjustment(row, leg, DATE_ADJ_CNV_FIELD, DATE_ADJ_CAL_FIELD).orElse(BusinessDayAdjustment.NONE); Optional <BusinessDayAdjustment> startDateAdj = parseBusinessDayAdjustment(row, leg, START_DATE_CNV_FIELD, START_DATE_CAL_FIELD); Optional <BusinessDayAdjustment> endDateAdj = parseBusinessDayAdjustment(row, leg, END_DATE_CNV_FIELD, END_DATE_CAL_FIELD); builder.businessDayAdjustment(dateAdj); if (startDateAdj.Present && !startDateAdj.get().Equals(dateAdj)) { builder.startDateBusinessDayAdjustment(startDateAdj.get()); } if (endDateAdj.Present && !endDateAdj.get().Equals(dateAdj)) { builder.endDateBusinessDayAdjustment(endDateAdj.get()); } // optionals builder.stubConvention(findValueWithFallback(row, leg, STUB_CONVENTION_FIELD).map(s => StubConvention.of(s)).orElse(StubConvention.SMART_INITIAL)); findValue(row, leg, ROLL_CONVENTION_FIELD).map(s => LoaderUtils.parseRollConvention(s)).ifPresent(v => builder.rollConvention(v)); findValue(row, leg, FIRST_REGULAR_START_DATE_FIELD).map(s => LoaderUtils.parseDate(s)).ifPresent(v => builder.firstRegularStartDate(v)); findValue(row, leg, LAST_REGULAR_END_DATE_FIELD).map(s => LoaderUtils.parseDate(s)).ifPresent(v => builder.lastRegularEndDate(v)); parseAdjustableDate(row, leg, OVERRIDE_START_DATE_FIELD, OVERRIDE_START_DATE_CNV_FIELD, OVERRIDE_START_DATE_CAL_FIELD).ifPresent(d => builder.overrideStartDate(d)); return(builder.build()); }
// loads a single CSV file, filtering by date private static void parseSingle(System.Predicate <LocalDate> datePredicate, CharSource resource, IDictionary <LocalDate, ImmutableMap.Builder <QuoteId, double> > mutableMap) { try { CsvFile csv = CsvFile.of(resource, true); foreach (CsvRow row in csv.rows()) { string dateText = row.getField(DATE_FIELD); LocalDate date = LoaderUtils.parseDate(dateText); if (datePredicate(date)) { string symbologyStr = row.getField(SYMBOLOGY_FIELD); string tickerStr = row.getField(TICKER_FIELD); string fieldNameStr = row.getField(FIELD_NAME_FIELD); string valueStr = row.getField(VALUE_FIELD); double value = Convert.ToDouble(valueStr); StandardId id = StandardId.of(symbologyStr, tickerStr); FieldName fieldName = fieldNameStr.Length == 0 ? FieldName.MARKET_VALUE : FieldName.of(fieldNameStr); ImmutableMap.Builder <QuoteId, double> builderForDate = mutableMap.computeIfAbsent(date, k => ImmutableMap.builder()); builderForDate.put(QuoteId.of(id, fieldName), value); } } } catch (Exception ex) { throw new System.ArgumentException(Messages.format("Error processing resource as CSV file: {}", resource), ex); } }
//------------------------------------------------------------------------- // fixed rate calculation private static RateCalculation parseFixedRateCalculation(CsvRow row, string leg, Currency currency, DayCount defaultFixedLegDayCount) { FixedRateCalculation.Builder builder = FixedRateCalculation.builder(); // basics double fixedRate = LoaderUtils.parseDoublePercent(getValue(row, leg, FIXED_RATE_FIELD)); DayCount dayCount = findValue(row, leg, DAY_COUNT_FIELD).map(s => LoaderUtils.parseDayCount(s)).orElse(defaultFixedLegDayCount); if (dayCount == null) { throw new System.ArgumentException("Swap leg must define day count using '" + leg + DAY_COUNT_FIELD + "'"); } builder.dayCount(dayCount); builder.rate(ValueSchedule.of(fixedRate)); // initial stub double?initialStubRateOpt = findValue(row, leg, INITIAL_STUB_RATE_FIELD).map(s => LoaderUtils.parseDoublePercent(s)); double?initialStubAmountOpt = findValue(row, leg, INITIAL_STUB_AMOUNT_FIELD).map(s => LoaderUtils.parseDouble(s)); if (initialStubRateOpt.HasValue && initialStubAmountOpt.HasValue) { throw new System.ArgumentException("Swap leg must not define both '" + leg + INITIAL_STUB_RATE_FIELD + "' and '" + leg + INITIAL_STUB_AMOUNT_FIELD + "'"); } initialStubRateOpt.ifPresent(v => builder.initialStub(FixedRateStubCalculation.ofFixedRate(v))); initialStubAmountOpt.ifPresent(v => builder.initialStub(FixedRateStubCalculation.ofKnownAmount(CurrencyAmount.of(currency, v)))); // final stub double?finalStubRateOpt = findValue(row, leg, FINAL_STUB_RATE_FIELD).map(s => LoaderUtils.parseDoublePercent(s)); double?finalStubAmountOpt = findValue(row, leg, FINAL_STUB_AMOUNT_FIELD).map(s => LoaderUtils.parseDouble(s)); if (finalStubRateOpt.HasValue && finalStubAmountOpt.HasValue) { throw new System.ArgumentException("Swap leg must not define both '" + leg + FINAL_STUB_RATE_FIELD + "' and '" + leg + FINAL_STUB_AMOUNT_FIELD + "'"); } finalStubRateOpt.ifPresent(v => builder.finalStub(FixedRateStubCalculation.ofFixedRate(v))); finalStubAmountOpt.ifPresent(v => builder.finalStub(FixedRateStubCalculation.ofKnownAmount(CurrencyAmount.of(currency, v)))); return(builder.build()); }
//------------------------------------------------------------------------- // ibor rate calculation private static RateCalculation parseIborRateCalculation(CsvRow row, string leg, IborIndex iborIndex, BusinessDayAdjustment bda, Currency currency) { IborRateCalculation.Builder builder = IborRateCalculation.builder(); // basics builder.index(iborIndex); // reset Optional <Frequency> resetFrequencyOpt = findValue(row, leg, RESET_FREQUENCY_FIELD).map(v => Frequency.parse(v)); IborRateResetMethod resetMethod = findValue(row, leg, RESET_METHOD_FIELD).map(v => IborRateResetMethod.of(v)).orElse(IborRateResetMethod.WEIGHTED); BusinessDayAdjustment resetDateAdj = parseBusinessDayAdjustment(row, leg, RESET_DATE_CNV_FIELD, RESET_DATE_CAL_FIELD).orElse(bda); resetFrequencyOpt.ifPresent(freq => builder.resetPeriods(ResetSchedule.builder().resetFrequency(freq).resetMethod(resetMethod).businessDayAdjustment(resetDateAdj).build())); // optionals, no ability to set firstFixingDateOffset findValue(row, leg, DAY_COUNT_FIELD).map(s => LoaderUtils.parseDayCount(s)).ifPresent(v => builder.dayCount(v)); findValue(row, leg, FIXING_RELATIVE_TO_FIELD).map(s => FixingRelativeTo.of(s)).ifPresent(v => builder.fixingRelativeTo(v)); Optional <DaysAdjustment> fixingAdjOpt = parseDaysAdjustment(row, leg, FIXING_OFFSET_DAYS_FIELD, FIXING_OFFSET_CAL_FIELD, FIXING_OFFSET_ADJ_CNV_FIELD, FIXING_OFFSET_ADJ_CAL_FIELD); fixingAdjOpt.ifPresent(v => builder.fixingDateOffset(v)); findValue(row, leg, NEGATIVE_RATE_METHOD_FIELD).map(s => NegativeRateMethod.of(s)).ifPresent(v => builder.negativeRateMethod(v)); findValue(row, leg, FIRST_RATE_FIELD).map(s => LoaderUtils.parseDoublePercent(s)).ifPresent(v => builder.firstRate(v)); findValue(row, leg, GEARING_FIELD).map(s => LoaderUtils.parseDouble(s)).ifPresent(v => builder.gearing(ValueSchedule.of(v))); findValue(row, leg, SPREAD_FIELD).map(s => LoaderUtils.parseDoublePercent(s)).ifPresent(v => builder.spread(ValueSchedule.of(v))); // initial stub Optional <IborRateStubCalculation> initialStub = parseIborStub(row, leg, currency, builder, INITIAL_STUB_RATE_FIELD, INITIAL_STUB_AMOUNT_FIELD, INITIAL_STUB_INDEX_FIELD, INITIAL_STUB_INTERPOLATED_INDEX_FIELD); initialStub.ifPresent(stub => builder.initialStub(stub)); // final stub Optional <IborRateStubCalculation> finalStub = parseIborStub(row, leg, currency, builder, FINAL_STUB_RATE_FIELD, FINAL_STUB_AMOUNT_FIELD, FINAL_STUB_INDEX_FIELD, FINAL_STUB_INTERPOLATED_INDEX_FIELD); finalStub.ifPresent(stub => builder.finalStub(stub)); return(builder.build()); }
// an Ibor stub private static Optional <IborRateStubCalculation> parseIborStub(CsvRow row, string leg, Currency currency, IborRateCalculation.Builder builder, string rateField, string amountField, string indexField, string interpolatedField) { double?stubRateOpt = findValue(row, leg, rateField).map(s => LoaderUtils.parseDoublePercent(s)); double?stubAmountOpt = findValue(row, leg, amountField).map(s => LoaderUtils.parseDouble(s)); Optional <IborIndex> stubIndexOpt = findValue(row, leg, indexField).map(s => IborIndex.of(s)); Optional <IborIndex> stubIndex2Opt = findValue(row, leg, interpolatedField).map(s => IborIndex.of(s)); if (stubRateOpt.HasValue && !stubAmountOpt.HasValue && !stubIndexOpt.Present && !stubIndex2Opt.Present) { return(IborRateStubCalculation.ofFixedRate(stubRateOpt.Value)); } else if (!stubRateOpt.HasValue && stubAmountOpt.HasValue && !stubIndexOpt.Present && !stubIndex2Opt.Present) { return(IborRateStubCalculation.ofKnownAmount(CurrencyAmount.of(currency, stubAmountOpt.Value))); } else if (!stubRateOpt.HasValue && !stubAmountOpt.HasValue && stubIndexOpt.Present) { if (stubIndex2Opt.Present) { return(IborRateStubCalculation.ofIborInterpolatedRate(stubIndexOpt.get(), stubIndex2Opt.get())); } else { return(IborRateStubCalculation.ofIborRate(stubIndexOpt.get())); } } else if (stubRateOpt.HasValue || stubAmountOpt.HasValue || stubIndexOpt.Present || stubIndex2Opt.Present) { throw new System.ArgumentException("Swap leg must define only one of the following fields " + ImmutableList.of(leg + rateField, leg + amountField, leg + indexField) + ", and '" + leg + interpolatedField + "' is only allowed with '" + leg + indexField + "'"); } return(null); }
// variable notional private static SwapTrade parseVariableNotional(SwapTrade trade, IList <CsvRow> variableRows) { // parse notionals ImmutableList.Builder <ValueStep> stepBuilder = ImmutableList.builder(); foreach (CsvRow row in variableRows) { LocalDate date = LoaderUtils.parseDate(row.getValue(START_DATE_FIELD)); row.findValue(NOTIONAL_FIELD).map(str => LoaderUtils.parseDouble(str)).ifPresent(notional => stepBuilder.add(ValueStep.of(date, ValueAdjustment.ofReplace(notional)))); } ImmutableList <ValueStep> varNotionals = stepBuilder.build(); if (varNotionals.Empty) { return(trade); } // adjust the trade, inserting the variable notionals ImmutableList.Builder <SwapLeg> legBuilder = ImmutableList.builder(); foreach (SwapLeg swapLeg in trade.Product.Legs) { RateCalculationSwapLeg leg = (RateCalculationSwapLeg)swapLeg; NotionalSchedule notionalSchedule = leg.NotionalSchedule.toBuilder().amount(ValueSchedule.of(leg.NotionalSchedule.Amount.InitialValue, varNotionals)).build(); legBuilder.add(leg.toBuilder().notionalSchedule(notionalSchedule).build()); } return(replaceLegs(trade, legBuilder.build())); }
internal static void ResizeArrays() { //Sets LoaderUtils.ReloadSets(typeof(MountID.Sets)); //Etc Array.Resize(ref Mount.mounts, MountCount); }
internal static void ResizeArrays() { //Sets LoaderUtils.ResetStaticMembers(typeof(MountID), true); //Etc Array.Resize(ref Mount.mounts, MountCount); }
private static IIsolatedEnvironment CreateSharedEnvironment() { IIsolatedEnvironment environment = IsolatedEnvironmentManager.CreateIsolatedEnvironment(); environment.Loader.AddHintDirectory(LoaderUtils.GetLoaderDirectoryPath()); environment.Loader.SetupRuntime(); return(environment); }
//------------------------------------------------------------------------- /// <summary> /// Parses the year-month and variant. /// </summary> /// <param name="row"> the CSV row to parse </param> /// <param name="type"> the ETD type </param> /// <returns> the expiry year-month and variant </returns> /// <exception cref="IllegalArgumentException"> if the row cannot be parsed </exception> public static Pair <YearMonth, EtdVariant> parseEtdVariant(CsvRow row, EtdType type) { YearMonth yearMonth = LoaderUtils.parseYearMonth(row.getValue(EXPIRY_FIELD)); int week = row.findValue(EXPIRY_WEEK_FIELD).map(s => LoaderUtils.parseInteger(s)).orElse(0); int day = row.findValue(EXPIRY_DAY_FIELD).map(s => LoaderUtils.parseInteger(s)).orElse(0); Optional <EtdSettlementType> settleType = row.findValue(SETTLEMENT_TYPE_FIELD).map(s => parseEtdSettlementType(s)); Optional <EtdOptionType> optionType = row.findValue(EXERCISE_STYLE_FIELD).map(s => parseEtdOptionType(s)); // check valid combinations if (!settleType.Present) { if (day == 0) { if (week == 0) { return(Pair.of(yearMonth, EtdVariant.ofMonthly())); } else { return(Pair.of(yearMonth, EtdVariant.ofWeekly(week))); } } else { if (week == 0) { return(Pair.of(yearMonth, EtdVariant.ofDaily(day))); } else { throw new System.ArgumentException("ETD date columns conflict, cannot set both expiry day and expiry week"); } } } else { if (day == 0) { throw new System.ArgumentException("ETD date columns conflict, must set expiry day for Flex " + type); } if (week != 0) { throw new System.ArgumentException("ETD date columns conflict, cannot set expiry week for Flex " + type); } if (type == EtdType.FUTURE) { return(Pair.of(yearMonth, EtdVariant.ofFlexFuture(day, settleType.get()))); } else { if (!optionType.Present) { throw new System.ArgumentException("ETD option type not found for Flex Option"); } return(Pair.of(yearMonth, EtdVariant.ofFlexOption(day, settleType.get(), optionType.get()))); } } }
//------------------------------------------------------------------------- // parses the file in grid format private void parseGridFormat(CsvIterator csv, ListMultimap <string, CurveSensitivities> parsed, IList <FailureItem> failures) { // find the applicable reference columns IDictionary <string, CurveName> references = new LinkedHashMap <string, CurveName>(); foreach (string header in csv.headers()) { string headerLowerCase = header.ToLower(Locale.ENGLISH); if (!REF_HEADERS.contains(headerLowerCase) && !resolver.isInfoColumn(headerLowerCase)) { references[header] = CurveName.of(header); } } // loop around all rows, peeking to match batches with the same identifier // no exception catch at this level to avoid infinite loops while (csv.hasNext()) { CsvRow peekedRow = csv.peek(); PortfolioItemInfo info = parseInfo(peekedRow); //JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter: string id = info.Id.map(StandardId::toString).orElse(""); // process in batches, where the ID is the same CurveSensitivitiesBuilder builder = CurveSensitivities.builder(info); IList <CsvRow> batchRows = csv.nextBatch(r => matchId(r, id)); foreach (CsvRow batchRow in batchRows) { try { ParameterMetadata metadata = parseMetadata(batchRow, true); CurveSensitivitiesType type = batchRow.findValue(TYPE_HEADER).map(str => CurveSensitivitiesType.of(str)).orElse(CurveSensitivitiesType.ZERO_RATE_DELTA); foreach (KeyValuePair <string, CurveName> entry in references.SetOfKeyValuePairs()) { CurveName reference = entry.Value; CurveName resolvedCurveName = resolver.checkCurveName(reference); string valueStr = batchRow.getField(entry.Key); Currency currency = parseCurrency(batchRow, reference); if (valueStr.Length > 0) { double value = LoaderUtils.parseDouble(valueStr); builder.add(type, resolvedCurveName, currency, metadata, value); } } } catch (System.ArgumentException ex) { failures.Add(FailureItem.of(PARSING, "CSV file could not be parsed at line {}: {}", batchRow.lineNumber(), ex.Message)); } } CurveSensitivities sens = builder.build(); if (!sens.TypedSensitivities.Empty) { parsed.put(sens.Id.map(object.toString).orElse(""), sens); } } }
// parses a SecurityTrade from the CSV row private static SecurityTrade parseSecurityTrade(CsvRow row, TradeInfo info, TradeCsvInfoResolver resolver) { string securityIdScheme = row.findValue(SECURITY_ID_SCHEME_FIELD).orElse(DEFAULT_SECURITY_SCHEME); string securityIdValue = row.getValue(SECURITY_ID_FIELD); SecurityId securityId = SecurityId.of(securityIdScheme, securityIdValue); double price = LoaderUtils.parseDouble(row.getValue(PRICE_FIELD)); double quantity = parseTradeQuantity(row); return(SecurityTrade.of(info, securityId, quantity, price)); }
// parse a single leg private static RateCalculationSwapLeg parseLeg(CsvRow row, string leg, FloatingRateIndex index, DayCount defaultFixedLegDayCount) { PayReceive payReceive = LoaderUtils.parsePayReceive(getValue(row, leg, DIRECTION_FIELD)); PeriodicSchedule accrualSch = parseAccrualSchedule(row, leg); PaymentSchedule paymentSch = parsePaymentSchedule(row, leg, accrualSch.Frequency); NotionalSchedule notionalSch = parseNotionalSchedule(row, leg); RateCalculation calc = parseRateCalculation(row, leg, index, defaultFixedLegDayCount, accrualSch.BusinessDayAdjustment, notionalSch.Currency); return(RateCalculationSwapLeg.builder().payReceive(payReceive).accrualSchedule(accrualSch).paymentSchedule(paymentSch).notionalSchedule(notionalSch).calculation(calc).build()); }
// parses the trade quantity, considering the optional buy/sell field private static double parseTradeQuantity(CsvRow row) { double quantity = LoaderUtils.parseDouble(row.getValue(QUANTITY_FIELD)); Optional <BuySell> buySellOpt = row.findValue(BUY_SELL_FIELD).map(str => LoaderUtils.parseBuySell(str)); if (buySellOpt.Present) { quantity = buySellOpt.get().normalize(quantity); } return(quantity); }
//------------------------------------------------------------------------- // inflation rate calculation private static RateCalculation parseInflationRateCalculation(CsvRow row, string leg, PriceIndex priceIndex, Currency currency) { InflationRateCalculation.Builder builder = InflationRateCalculation.builder(); // basics builder.index(priceIndex); builder.lag(parseInflationLag(findValue(row, leg, INFLATION_LAG_FIELD), currency)); builder.indexCalculationMethod(parseInflationMethod(findValue(row, leg, INFLATION_METHOD_FIELD), currency)); // optionals findValue(row, leg, INFLATION_FIRST_INDEX_VALUE_FIELD).map(s => LoaderUtils.parseDouble(s)).ifPresent(v => builder.firstIndexValue(v)); findValue(row, leg, GEARING_FIELD).map(s => LoaderUtils.parseDouble(s)).ifPresent(v => builder.gearing(ValueSchedule.of(v))); return(builder.build()); }
// adjustable date, defaulting business day convention and holiday calendar private static Optional <AdjustableDate> parseAdjustableDate(CsvRow row, string leg, string dateField, string cnvField, string calField) { Optional <LocalDate> dateOpt = findValue(row, leg, dateField).map(s => LoaderUtils.parseDate(s)); if (!dateOpt.Present) { return(null); } BusinessDayConvention dateCnv = findValue(row, leg, cnvField).map(s => LoaderUtils.parseBusinessDayConvention(s)).orElse(BusinessDayConventions.MODIFIED_FOLLOWING); HolidayCalendarId cal = findValue(row, leg, calField).map(s => HolidayCalendarId.of(s)).orElse(HolidayCalendarIds.NO_HOLIDAYS); return(AdjustableDate.of(dateOpt.get(), BusinessDayAdjustment.of(dateCnv, cal))); }
//------------------------------------------------------------------------- // overnight rate calculation private static RateCalculation parseOvernightRateCalculation(CsvRow row, string leg, OvernightIndex overnightIndex, OvernightAccrualMethod accrualMethod) { OvernightRateCalculation.Builder builder = OvernightRateCalculation.builder(); // basics builder.index(overnightIndex); builder.accrualMethod(findValue(row, leg, ACCRUAL_METHOD_FIELD).map(s => OvernightAccrualMethod.of(s)).orElse(accrualMethod)); // optionals findValue(row, leg, DAY_COUNT_FIELD).map(s => LoaderUtils.parseDayCount(s)).ifPresent(v => builder.dayCount(v)); findValue(row, leg, RATE_CUT_OFF_DAYS_FIELD).map(s => Convert.ToInt32(s)).ifPresent(v => builder.rateCutOffDays(v)); findValue(row, leg, NEGATIVE_RATE_METHOD_FIELD).map(s => NegativeRateMethod.of(s)).ifPresent(v => builder.negativeRateMethod(v)); findValue(row, leg, GEARING_FIELD).map(s => LoaderUtils.parseDouble(s)).ifPresent(v => builder.gearing(ValueSchedule.of(v))); findValue(row, leg, SPREAD_FIELD).map(s => LoaderUtils.parseDoublePercent(s)).ifPresent(v => builder.spread(ValueSchedule.of(v))); return(builder.build()); }
// convention-based // ideally we'd use the trade date plus "period to start" to get the spot/payment date // but we don't have all the data and it gets complicated in places like TRY, RUB and AED private static FxSingleTrade parseConvention(CsvRow row, TradeInfo info) { CurrencyPair pair = CurrencyPair.parse(row.getValue(CONVENTION_FIELD)); BuySell buySell = LoaderUtils.parseBuySell(row.getValue(BUY_SELL_FIELD)); Currency currency = Currency.parse(row.getValue(CURRENCY_FIELD)); double notional = LoaderUtils.parseDouble(row.getValue(NOTIONAL_FIELD)); double fxRate = LoaderUtils.parseDouble(row.getValue(FX_RATE_FIELD)); LocalDate paymentDate = LoaderUtils.parseDate(row.getValue(PAYMENT_DATE_FIELD)); Optional <BusinessDayAdjustment> paymentAdj = parsePaymentDateAdjustment(row); CurrencyAmount amount = CurrencyAmount.of(currency, buySell.normalize(notional)); FxSingle fx = paymentAdj.map(adj => FxSingle.of(amount, FxRate.of(pair, fxRate), paymentDate, adj)).orElseGet(() => FxSingle.of(amount, FxRate.of(pair, fxRate), paymentDate)); return(FxSingleTrade.of(info, fx)); }
//------------------------------------------------------------------------- // payment schedule private static PaymentSchedule parsePaymentSchedule(CsvRow row, string leg, Frequency accrualFrequency) { PaymentSchedule.Builder builder = PaymentSchedule.builder(); // basics builder.paymentFrequency(findValue(row, leg, PAYMENT_FREQUENCY_FIELD).map(s => Frequency.parse(s)).orElse(accrualFrequency)); Optional <DaysAdjustment> offsetOpt = parseDaysAdjustment(row, leg, PAYMENT_OFFSET_DAYS_FIELD, PAYMENT_OFFSET_CAL_FIELD, PAYMENT_OFFSET_ADJ_CNV_FIELD, PAYMENT_OFFSET_ADJ_CAL_FIELD); builder.paymentDateOffset(offsetOpt.orElse(DaysAdjustment.NONE)); // optionals findValue(row, leg, PAYMENT_RELATIVE_TO_FIELD).map(s => PaymentRelativeTo.of(s)).ifPresent(v => builder.paymentRelativeTo(v)); findValue(row, leg, COMPOUNDING_METHOD_FIELD).map(s => CompoundingMethod.of(s)).ifPresent(v => builder.compoundingMethod(v)); findValue(row, leg, PAYMENT_FIRST_REGULAR_START_DATE_FIELD).map(s => LoaderUtils.parseDate(s)).ifPresent(v => builder.firstRegularStartDate(v)); findValue(row, leg, PAYMENT_LAST_REGULAR_END_DATE_FIELD).map(s => LoaderUtils.parseDate(s)).ifPresent(v => builder.lastRegularEndDate(v)); return(builder.build()); }
//------------------------------------------------------------------------- // loads a single fixing series CSV file private static ImmutableMap <ObservableId, LocalDateDoubleTimeSeries> parseSingle(CharSource resource) { IDictionary <ObservableId, LocalDateDoubleTimeSeriesBuilder> builders = new Dictionary <ObservableId, LocalDateDoubleTimeSeriesBuilder>(); try { CsvFile csv = CsvFile.of(resource, true); foreach (CsvRow row in csv.rows()) { string referenceStr = row.getField(REFERENCE_FIELD); string dateStr = row.getField(DATE_FIELD); string valueStr = row.getField(VALUE_FIELD); Index index = LoaderUtils.findIndex(referenceStr); ObservableId id = IndexQuoteId.of(index); double value = double.Parse(valueStr); LocalDate date; if (index is PriceIndex) { try { YearMonth ym = LoaderUtils.parseYearMonth(dateStr); date = ym.atEndOfMonth(); } catch (Exception) { date = LoaderUtils.parseDate(dateStr); if (date.DayOfMonth != date.lengthOfMonth()) { throw new System.ArgumentException(Messages.format("Fixing Series CSV loader for price index must have date at end of month: {}", resource)); } } } else { date = LoaderUtils.parseDate(dateStr); } LocalDateDoubleTimeSeriesBuilder builder = builders.computeIfAbsent(id, k => LocalDateDoubleTimeSeries.builder()); builder.put(date, value); } } catch (Exception ex) { throw new System.ArgumentException(Messages.format("Error processing resource as CSV file: {}", resource), ex); } return(MapStream.of(builders).mapValues(builder => builder.build()).toMap()); }
// parses the additional GenericSecurityPosition information internal static Position parseNonEtdPosition(CsvRow row, PositionInfo info, PositionCsvInfoResolver resolver) { SecurityPosition @base = parseSecurityPosition(row, info, resolver); double? tickSizeOpt = row.findValue(TICK_SIZE).map(str => LoaderUtils.parseDouble(str)); Optional <Currency> currencyOpt = row.findValue(CURRENCY).map(str => Currency.of(str)); double? tickValueOpt = row.findValue(TICK_VALUE).map(str => LoaderUtils.parseDouble(str)); double contractSize = row.findValue(CONTRACT_SIZE).map(str => LoaderUtils.parseDouble(str)).orElse(1d); if (tickSizeOpt.HasValue && currencyOpt.Present && tickValueOpt.HasValue) { SecurityPriceInfo priceInfo = SecurityPriceInfo.of(tickSizeOpt.Value, CurrencyAmount.of(currencyOpt.get(), tickValueOpt.Value), contractSize); GenericSecurity sec = GenericSecurity.of(SecurityInfo.of(@base.SecurityId, priceInfo)); return(GenericSecurityPosition.ofLongShort(@base.Info, sec, @base.LongQuantity, @base.ShortQuantity)); } return(@base); }