49 QL_REQUIRE(node,
"Failed to create trade node");
58Date
Trade::addPremiums(std::vector<QuantLib::ext::shared_ptr<Instrument>>& addInstruments, std::vector<Real>& addMultipliers,
59 const Real tradeMultiplier,
const PremiumData& premiumData,
const Real premiumMultiplier,
60 const Currency& tradeCurrency,
const QuantLib::ext::shared_ptr<EngineFactory>& factory,
61 const string& configuration) {
63 Date latestPremiumPayDate = Date::minDate();
66 QL_REQUIRE(d.amount != Null<Real>(),
"Trade contains invalid premium data.");
70 auto fee = QuantLib::ext::make_shared<QuantExt::Payment>(premiumAmount, premiumCurrency, d.payDate);
72 addMultipliers.push_back(premiumMultiplier);
74 Handle<YieldTermStructure> yts = factory->market()->discountCurve(d.ccy, configuration);
76 if (tradeCurrency.code() != d.ccy) {
77 fx = factory->market()->fxRate(d.ccy + tradeCurrency.code(), configuration);
80 fee->setPricingEngine(discountingEngine);
83 addInstruments.push_back(fee);
88 Leg(1, QuantLib::ext::make_shared<SimpleCashFlow>(fee->cashFlow()->amount() * premiumMultiplier / tradeMultiplier,
89 fee->cashFlow()->date())));
96 latestPremiumPayDate = std::max(latestPremiumPayDate, d.payDate);
98 DLOG(
"added fee " << d.amount <<
" " << d.ccy <<
" payable on " << d.payDate <<
" to trade");
101 return latestPremiumPayDate;
105 QL_REQUIRE(
id_ !=
"",
"Trade id has not been set.");
106 QL_REQUIRE(
tradeType_ !=
"",
"Trade id has not been set.");
108 "Trade " <<
id_ <<
" requires either QuantLib instruments or legs to be created.");
109 QL_REQUIRE(
npvCurrency_ !=
"",
"NPV currency has not been set for trade " <<
id_ <<
".");
112 QL_REQUIRE(
maturity_ != Null<Date>(),
"Maturity not set for trade " <<
id_ <<
".");
114 if (
legs_.size() > 0) {
116 "Inconsistent number of pay/receive indicators for legs in trade " <<
id_ <<
".");
118 "Inconsistent number of leg currencies for legs in trade " <<
id_ <<
".");
137 instrument_ = QuantLib::ext::shared_ptr<InstrumentWrapper>();
154 if (
legs_.size() < i + 1)
156 Date asof = Settings::instance().evaluationDate();
157 string legID = std::to_string(resultLegId == Null<Size>() ? i + 1 : resultLegId);
158 for (Size j = 0; j <
legs_[i].size(); ++j) {
159 QuantLib::ext::shared_ptr<CashFlow> flow =
legs_[i][j];
161 if (flow->date() > asof) {
162 Real flowAmount = 0.0;
164 flowAmount = flow->amount();
165 }
catch (std::exception& e) {
166 ALOG(
"flow amount could not be determined for trade " <<
id() <<
", set to zero: " << e.what());
170 QuantLib::ext::shared_ptr<Coupon> coupon = QuantLib::ext::dynamic_pointer_cast<Coupon>(flow);
175 }
catch (std::exception& e) {
176 ALOG(
"current notional could not be determined for trade " <<
id()
177 <<
", set to zero: " << e.what());
183 rate = coupon->rate();
184 }
catch (std::exception& e) {
185 ALOG(
"coupon rate could not be determined for trade " <<
id() <<
", set to zero: " << e.what());
189 if (
auto frc = QuantLib::ext::dynamic_pointer_cast<FloatingRateCoupon>(flow)) {
194 if (
auto eqc = QuantLib::ext::dynamic_pointer_cast<QuantExt::EquityCoupon>(flow)) {
195 auto arc = eqc->pricer()->additionalResultCache();
198 if (arc.startFixing != Null<Real>())
200 if (arc.startFixingTotal != Null<Real>())
202 arc.startFixingTotal;
203 if (arc.endFixingTotal != Null<Real>())
204 additionalData_[
"endEquityFixingTotal[" + legID +
"]"] = arc.endFixingTotal;
205 if (arc.startFxFixing != Null<Real>())
207 if (arc.endFxFixing != Null<Real>())
209 if (arc.pastDividends != Null<Real>())
211 if (arc.forecastDividends != Null<Real>())
212 additionalData_[
"forecastDividends[" + legID +
"]"] = arc.forecastDividends;
215 if (
auto cpic = QuantLib::ext::dynamic_pointer_cast<QuantExt::CPICoupon>(flow)) {
217 baseCPI = cpic->baseCPI();
218 if (baseCPI == Null<Real>()) {
221 QuantLib::CPI::laggedFixing(cpic->cpiIndex(), cpic->baseDate() + cpic->observationLag(),
222 cpic->observationLag(), cpic->observationInterpolation());
223 }
catch (std::exception& e) {
224 ALOG(
"CPICoupon baseCPI could not be interpolated for additional results for trade " <<
id()
230 }
else if (
auto cpicf = QuantLib::ext::dynamic_pointer_cast<QuantLib::CPICashFlow>(flow)) {
232 baseCPI = cpicf->baseFixing();
233 if (baseCPI == Null<Real>()) {
235 baseCPI = QuantLib::CPI::laggedFixing(cpicf->cpiIndex(),
236 cpicf->baseDate() + cpicf->observationLag(),
237 cpicf->observationLag(), cpicf->interpolation());
238 }
catch (std::exception& e) {
239 ALOG(
"CPICashFlow baseCPI could not be interpolated for additional results for trade " <<
id()
251 QuantLib::ext::shared_ptr<Coupon> coupon = QuantLib::ext::dynamic_pointer_cast<Coupon>(
legs_[i][0]);
256 }
catch (std::exception& e) {
257 ALOG(
"original nominal could not be determined for trade " <<
id() <<
", set to zero: " << e.what());
260 if (
auto eqc = QuantLib::ext::dynamic_pointer_cast<QuantExt::EquityCoupon>(coupon)) {
261 Real quantity = eqc->quantity();
262 if (quantity == Null<Real>()) {
263 if (eqc->legInitialNotional() != Null<Real>() && eqc->initialPrice() != Null<Real>()) {
264 quantity = eqc->legInitialNotional() / eqc->initialPrice();
269 Real currentPrice = Null<Real>();
270 if (eqc->equityCurve()->isValidFixingDate(asof)) {
271 currentPrice = eqc->equityCurve()->equitySpot()->value();
279 for (Size j = 0; j <
legs_[i].size(); ++j) {
280 QuantLib::ext::shared_ptr<CashFlow> flow =
legs_[i][j];
281 if (flow->date() > asof) {
283 for (
auto const& [
fixingDate, index, multiplier] :
285 auto label =
"[" + legID +
"][" + std::to_string(j) +
"][" + std::to_string(k) +
"]";
288 index ==
nullptr ?
"na" : IndexNameTranslator::instance().oreName(index->name());
308 id(),
tradeType(),
"No valid sensitivty template.",
309 "Either build() was not called, or the trade builder did not set the sensitivity template.")
Base PricingEngine Builder class for a specific model and engine.
std::string engineParameter(const std::string &p, const std::vector< std::string > &qualifiers={}, const bool mandatory=true, const std::string &defaultValue="") const
Serializable object holding generic trade data, reporting dimensions.
virtual void fromXML(XMLNode *node) override
virtual XMLNode * toXML(XMLDocument &doc) const override
bool initialized() const
Check if the envelope is initialized.
void log() const
generate Boost log record to pass to corresponding sinks
Serializable object holding premium data.
const std::vector< PremiumDatum > & premiumData() const
Utility classes for Structured warnings, contains the Trade ID and Type.
bool empty() const
Returns true of this set of actions is empty.
virtual void fromXML(XMLNode *node) override
virtual XMLNode * toXML(XMLDocument &doc) const override
void clear()
Clear the trade actions.
void setEnvelope(const Envelope &envelope)
Set the envelope with counterparty and portfolio info.
const std::string & sensitivityTemplate() const
std::vector< bool > legPayers_
string sensitivityTemplate_
std::vector< string > legCurrencies_
std::vector< QuantLib::Leg > legs_
TradeActions tradeActions_
virtual void fromXML(XMLNode *node) override
Date addPremiums(std::vector< QuantLib::ext::shared_ptr< Instrument > > &instruments, std::vector< Real > &multipliers, const Real tradeMultiplier, const PremiumData &premiumData, const Real premiumMultiplier, const Currency &tradeCurrency, const QuantLib::ext::shared_ptr< EngineFactory > &factory, const string &configuration)
void setSensitivityTemplate(const EngineBuilder &builder)
virtual XMLNode * toXML(XMLDocument &doc) const override
string & id()
Set the trade id.
bool sensitivityTemplateSet_
virtual const std::map< std::string, boost::any > & additionalData() const
returns all additional data returned by the trade once built
void setAdditionalData(const std::map< std::string, boost::any > &additionalData)
RequiredFixings requiredFixings_
void validate() const
Utility to validate that everything that needs to be set in this base class is actually set.
const Envelope & envelope() const
boost::timer::nanosecond_type savedCumulativePricingTime_
QuantLib::ext::shared_ptr< InstrumentWrapper > instrument_
void reset()
Reset trade, clear all base class data. This does not reset accumulated timings for this trade.
std::size_t savedNumberOfPricings_
const string & tradeType() const
void setLegBasedAdditionalData(const Size legNo, Size resultLegId=Null< Size >()) const
std::map< std::string, boost::any > additionalData_
Small XML Document wrapper class.
XMLNode * allocNode(const string &nodeName)
util functions that wrap rapidxml
static void addAttribute(XMLDocument &doc, XMLNode *node, const string &attrName, const string &attrValue)
static void checkNode(XMLNode *n, const string &expectedName)
static string getChildValue(XMLNode *node, const string &name, bool mandatory=false, const string &defaultValue=string())
static XMLNode * getChildNode(XMLNode *n, const string &name="")
static XMLNode * addChild(XMLDocument &doc, XMLNode *n, const string &name)
static void appendNode(XMLNode *parent, XMLNode *child)
Currency parseCurrencyWithMinors(const string &s)
Convert text to QuantLib::Currency.
QuantLib::Real convertMinorToMajorCurrency(const std::string &s, QuantLib::Real value)
Convert a value from a minor ccy to major.
translates between QuantLib::Index::name() and ORE names
#define DLOG(text)
Logging Macro (Level = Debug)
#define ALOG(text)
Logging Macro (Level = Alert)
QuantLib::Date fixingDate(const QuantLib::Date &d, const QuantLib::Period obsLag, const QuantLib::Frequency freq, bool interpolated)
std::vector< std::tuple< Date, boost::shared_ptr< Index >, Real > > getIndexedCouponOrCashFlowFixingDetails(const boost::shared_ptr< CashFlow > &c)
Real currentNotional(const Leg &leg)
Size size(const ValueType &v)
Real originalNotional(const Leg &leg)
std::string to_string(const LocationInfo &l)
Serializable Credit Default Swap.
Classes for structured trade warnings.
string conversion utilities
base trade data model and serialization