ITQuants blog

Fusion Invest/Capital Sophis: how to use CSMExtraction?

Mar 12

Written by:
3/12/2015 12:28 AM  RssIcon

Since one of my conversation between Alexis de Bernis, me and a Misys consultant was forwarded to several clients by Misys, the best thing I can do is perhaps to publish it. The topic was analyzed and resolved by Alexis, who I thank again for his judicious remark. The description concerns the way we have to use the CSMExtraction, and most of the class of the C# API provided by Misys for their product Fusion Capital Sophis.

For remember, even in the last versions of Fusion Invest (ex Sophis Value) and Fusion Capital Sophis (ex Sophis Risque) v7.x, most of the native classes are still written in C++ and objects are wrapped in C++ managed code to provide a .Net,C# API. This can create some problems when pointer references are used in the wrapper classes and are wrong referenced (misusing of the sharedptr).

I will reproduce the case identified by Alexis there from now:

Consider the following code:

double RealizedPnL(int rootPortfolioId)
{
    var realizedPnL  = 0;
    var extraction = new CSMExtraction("trade.portfolio = rootPortfolioId");
    var portfolio = extraction.GetRootPortfolio();
    for( var i = 0; i < portfolio.Count; i++)
    {
         var position = portfolio.GetPosition(i);
         realizedPnL += position.RealisedPnL;
    }
}

From a pure C# point of view, the extraction object can be released as soon as line 7 -> it is not used anymore.

However, what the CLR does not see, is that the CSMPortfolio instance wraps a CSRPortfolio native instance which holds a reference to the CSRExtraction instance wrapped by CSMExtraction.

If CSMExtraction is GC’ed, the CSRExtraction instance is deleted, and as a result the CSRPortfolio object used by CSMPortfolio now points to unallocated memory (and that’s usually a Bad Thing™).

Before garbage collection:



After garbage collection – the native reference is now invalid and will most probably crash the app if dereferenced:



To solve this, you need to make sure the CSMExtraction object is not destroyed before all the calls to CSMPortfolio have been done.

The recommended way:

double RealizedPnL(int rootPortfolioId)
{
    var realizedPnL  = 0;
    using (var extraction = new CSMExtraction("trade.portfolio = rootPortfolioId"))
    {
        var portfolio = extraction.GetRootPortfolio();
        for( var i = 0; i < portfolio.Count; i++)
        {
             var position = portfolio.GetPosition(i);
             realizedPnL += position.RealisedPnL;
        }
    }
}

Search blog