Security security = trade.getSecurityLink().resolve(_securitySource);
// this slightly awkward approach is due to the portfolio master API. you can look up a node directly but in order
// to save it you have to save the whole portfolio. this means you need to look up the node to find the portfolio
// ID, look up the portfolio, find the node in the portfolio, modify that copy of the node and save the portfolio
// TODO can use a portfolio search request and only hit the master once
ManageablePortfolioNode node = _portfolioMaster.getNode(nodeId);
ManageablePortfolio portfolio = _portfolioMaster.get(node.getPortfolioId()).getPortfolio();
ManageablePortfolioNode portfolioNode = findNode(portfolio, nodeId);
ManageablePosition position = findPosition(portfolioNode, security);
if (position == null) {
// no position in this security on the node, create a new position just for this trade
ManageablePosition newPosition = new ManageablePosition(trade.getQuantity(), security.getExternalIdBundle());
newPosition.addTrade(trade);
ManageablePosition savedPosition = getPositionMaster().add(new PositionDocument(newPosition)).getPosition();
portfolioNode.addPosition(savedPosition.getUniqueId());
_portfolioMaster.update(new PortfolioDocument(portfolio));
return savedPosition.getTrades().get(0).getUniqueId();
} else {
position.addTrade(trade);
position.setQuantity(position.getQuantity().add(trade.getQuantity()));