28#include <ql/errors.hpp>
29#include <ql/time/date.hpp>
45 LOG(
"Reset portfolio of size " <<
trades_.size());
53 for (Size i = 0; i < nodes.size(); i++) {
58 QL_REQUIRE(
id !=
"",
"No id attribute in Trade Node");
59 DLOG(
"Parsing trade id:" <<
id);
61 QuantLib::ext::shared_ptr<Trade> trade;
62 bool failedToLoad =
true;
64 trade = TradeFactory::instance().build(tradeType);
65 trade->fromXML(nodes[i]);
68 DLOG(
"Added Trade " <<
id <<
" (" << trade->id() <<
")"
69 <<
" type:" << tradeType);
71 }
catch (std::exception& ex) {
78 trade = TradeFactory::instance().build(
"Failed");
80 trade->fromXML(nodes[i]);
82 QuantLib::ext::shared_ptr<FailedTrade> failedTrade = QuantLib::ext::make_shared<FailedTrade>();
84 failedTrade->id() = id;
85 failedTrade->setUnderlyingTradeType(tradeType);
86 failedTrade->setEnvelope(trade->envelope());
89 WLOG(
"Added trade id " << failedTrade->id() <<
" type " << failedTrade->tradeType()
90 <<
" for original trade type " << trade->tradeType());
91 }
catch (std::exception& ex) {
96 LOG(
"Finished Parsing XML doc");
108 return trades_.erase(tradeID) > 0;
113 if ((*it).second->isExpired(asof)) {
122void Portfolio::build(
const QuantLib::ext::shared_ptr<EngineFactory>& engineFactory,
const std::string& context,
123 const bool emitStructuredError) {
124 LOG(
"Building Portfolio of size " <<
trades_.size() <<
" for context = '" << context <<
"'");
126 Size initialSize =
trades_.size();
127 Size failedTrades = 0;
128 while (trade !=
trades_.end()) {
134 (*trade).second = ft;
141 LOG(
"Built Portfolio. Initial size = " << initialSize <<
", size now " <<
trades_.size() <<
", built "
142 << failedTrades <<
" failed trades, context is " + context);
144 QL_REQUIRE(
trades_.size() > 0,
"Portfolio does not contain any built trades, context is '" + context +
"'");
148 QL_REQUIRE(
trades_.size() > 0,
"Cannot get maturity of an empty portfolio");
149 Date mat = Date::minDate();
151 mat = std::max(mat, t.second->maturity());
157 for (
const auto& [tradeId, _] :
trades_)
167 nettingSetMap[t.second->id()] = t.second->envelope().nettingSetId();
179 map<string, set<string>> cpNettingSets;
180 for (
const auto& [tradeId, trade] :
trades()) {
181 cpNettingSets[trade->envelope().counterparty()].insert(trade->envelope().nettingSetId());
183 return cpNettingSets;
187 QL_REQUIRE(!
has(trade->id()),
"Attempted to add a trade to the portfolio with an id, which already exists.");
204 for (
const auto& [tradeId, trade] :
trades()) {
205 portfolioIds.insert(trade->portfolioIds().begin(), trade->portfolioIds().end());
213 if (!t.second->envelope().nettingSetDetails().emptyOptionalFields()) {
221 map<string, RequiredFixings::FixingDates> result;
222 for (
const auto& t :
trades_) {
223 auto fixings = t.second->fixings(settlementDate);
224 for (
const auto& [index, fixingDates] :
fixings) {
225 if (!fixingDates.empty()) {
226 result[index].addDates(fixingDates);
233std::map<AssetClass, std::set<std::string>>
239 map<AssetClass, std::set<std::string>> result;
241 for (
const auto& t :
trades_) {
243 auto underlyings = t.second->underlyingIndices(referenceDataManager);
244 for (
const auto& kv : underlyings) {
245 result[kv.first].insert(kv.second.begin(), kv.second.end());
247 }
catch (
const std::exception& e) {
259 const QuantLib::ext::shared_ptr<ReferenceDataManager>& referenceDataManager) {
261 std::map<AssetClass, std::set<std::string>> indices =
underlyingIndices(referenceDataManager);
262 auto it = indices.find(assetClass);
263 if (it != indices.end()) {
266 return std::set<std::string>();
269std::pair<QuantLib::ext::shared_ptr<Trade>,
bool>
buildTrade(QuantLib::ext::shared_ptr<Trade>& trade,
270 const QuantLib::ext::shared_ptr<EngineFactory>& engineFactory,
271 const std::string& context,
const bool ignoreTradeBuildFail,
272 const bool buildFailedTrades,
const bool emitStructuredError) {
275 trade->build(engineFactory);
276 TLOG(
"Required Fixings for trade " << trade->id() <<
":");
278 return std::make_pair(
nullptr,
true);
279 }
catch (std::exception& e) {
280 if (emitStructuredError) {
283 ALOG(
"Error building trade '" << trade->id() <<
"' for context '" + context +
"': " + e.what());
285 if (ignoreTradeBuildFail) {
286 return std::make_pair(trade,
false);
287 }
else if (buildFailedTrades) {
288 QuantLib::ext::shared_ptr<FailedTrade> failed = QuantLib::ext::make_shared<FailedTrade>();
289 failed->id() = trade->id();
290 failed->setUnderlyingTradeType(trade->tradeType());
291 failed->setEnvelope(trade->envelope());
292 failed->build(engineFactory);
293 failed->resetPricingStats(trade->getNumberOfPricings(), trade->getCumulativePricingTime());
294 LOG(
"Built failed trade with id " << failed->id());
295 return std::make_pair(failed,
false);
297 return std::make_pair(
nullptr,
false);
void log() const
generate Boost log record to pass to corresponding sinks
QuantLib::Date maturity() const
Calculates the maturity of the portfolio.
const std::map< std::string, QuantLib::ext::shared_ptr< Trade > > & trades() const
Return the map tradeId -> trade.
std::set< std::string > counterparties() const
Build a set of all counterparties in the portfolio.
void add(const QuantLib::ext::shared_ptr< Trade > &trade)
Add a trade to the portfolio.
std::map< std::string, RequiredFixings::FixingDates > fixings(const QuantLib::Date &settlementDate=QuantLib::Date()) const
void removeMatured(const QuantLib::Date &asof)
Remove matured trades from portfolio for a given date, each removal is logged with an Alert.
std::map< std::string, QuantLib::ext::shared_ptr< Trade > > trades_
std::map< std::string, std::string > nettingSetMap() const
Build a map from trade Ids to NettingSet.
bool ignoreTradeBuildFail() const
Keep trade in the portfolio even after build fail.
void fromXML(XMLNode *node) override
XMLSerializable interface.
void build(const QuantLib::ext::shared_ptr< EngineFactory > &, const std::string &context="unspecified", const bool emitStructuredError=true)
Call build on all trades in the portfolio, the context is included in error messages.
std::set< std::string > portfolioIds() const
Compute set of portfolios.
XMLNode * toXML(XMLDocument &doc) const override
std::map< AssetClass, std::set< std::string > > underlyingIndices(const QuantLib::ext::shared_ptr< ReferenceDataManager > &referenceDataManager=nullptr)
bool hasNettingSetDetails() const
Check if at least one trade in the portfolio uses the NettingSetDetails node, and not just NettingSet...
bool remove(const std::string &tradeID)
Remove specified trade from the portfolio.
bool buildFailedTrades() const
Does this portfolio build failed trades?
std::map< AssetClass, std::set< std::string > > underlyingIndicesCache_
void clear()
Clear the portfolio.
void reset()
Reset all trade data.
std::map< std::string, std::set< std::string > > counterpartyNettingSets() const
Build a map from counterparty to NettingSet.
bool has(const string &id)
Check if a trade id is already in the portfolio.
QuantLib::ext::shared_ptr< Trade > get(const std::string &id) const
std::set< std::string > ids() const
Build a set of tradeIds.
Utility class for Structured Trade errors, contains the Trade ID and Type.
Utility classes for Structured warnings, contains the Trade ID and Type.
Small XML Document wrapper class.
XMLNode * allocNode(const string &nodeName)
util functions that wrap rapidxml
static string getAttribute(XMLNode *node, const string &attrName)
static void checkNode(XMLNode *n, const string &expectedName)
static vector< XMLNode * > getChildrenNodes(XMLNode *node, const string &name)
Returns all the children with a given name.
static string getChildValue(XMLNode *node, const string &name, bool mandatory=false, const string &defaultValue=string())
static void appendNode(XMLNode *parent, XMLNode *child)
Skeleton trade generated when trade loading/building fails.
FX Forward data model and serialization.
Classes and functions for log message handling.
#define LOG(text)
Logging Macro (Level = Notice)
#define DLOG(text)
Logging Macro (Level = Debug)
#define ALOG(text)
Logging Macro (Level = Alert)
#define TLOGGERSTREAM(text)
#define WLOG(text)
Logging Macro (Level = Warning)
#define TLOG(text)
Logging Macro (Level = Data)
std::pair< QuantLib::ext::shared_ptr< Trade >, bool > buildTrade(QuantLib::ext::shared_ptr< Trade > &trade, const QuantLib::ext::shared_ptr< EngineFactory > &engineFactory, const std::string &context, const bool ignoreTradeBuildFail, const bool buildFailedTrades, const bool emitStructuredError)
Serializable Credit Default Swap.
Structured Trade Error class.
Classes for structured trade warnings.
Swap trade data model and serialization.
Swaption data model and serialization.