Profile Picture

Setting Position Interest

Posted By johan 2 Years Ago
Message
Posted Thursday July 23 2015
Daniel

I am trading an instrument (stocks) which carries interest on the open positions when long (as the shares are bought with a debt instrument).  I calculate the interest on a daily basis, and want to write this through to the interest property of the position class.  This is, however, a read-only property.  Is there a different way to assign this value to the position interest property?

Thanks

Johan

Edited: Thursday July 23 2015 by johan
Posted Friday July 24 2015
RightEdge will calculate interest for you on open Forex positions and apply them to a position.  Calculating the interest yourself is probably possible, but you would need to dig into some of the internals of the PositionManager and probably call some non-public things via reflection.

Basically what you would need to do is create a TradeInfo object with a TransactionType of Interest, then add that to the Trades list for the position it applies to.

Thanks,
Daniel
Posted Saturday July 25 2015
Thanks Daniel.  Can you maybe help with some code, as I have limited experience with C#, and have not used reflection.  I basically calculate last night's interest in the NewBar().  I first calculate the interest rate to be applied (dailyInterest) based on the number of overnights between bars, and then calculate interest as follows:

foreach (Position openPositions in OpenPositions)
            {
                //Calculate overnight interest
                overnightValue=Bars.LookBack(1)*openPositions.CurrentSize;
                overnightInterest=overnightValue*dailyInterest;
 
                //Write overnight interest to interest property
                //I tried the following
                openPositions.SubmitOrder(1, TransactionType.Interest, OrderType.Market, dailyInterest);
            }
The ideal would be if I could write this to the Interest property, and if this can then be picked up in PositionStats.  I tried the SubmitOrder, but it seems that it does not recognize interest for anything but forex.  Furthermore, above will result in an additional transaction per day - I do not know if it will affect for example number of transactions if it is interest - if not, maybe this will be the easiest solution, if you can get RE to recognize interest for stocks as well.  If you add this functionality, you will in essence have a CFD, as it is an instrument that provides leverage, but charges overnight interest on the full open position when long (and no interest when short).  You also earn interest on deposits, but for backtesting, this is easy, as you can set this in SystemData, as it is not linked to a specific position.  If I can get the interest right, I will be able to use the standard System results, which is much better than my own plugin.

 I tried to play around with TradeInfo, but am struggling to get it right.  My code on TradeInfo is as follow:

TradeInfo item = new TradeInfo();
                    item.FilledTime = DateTime.Parse("00:00:00");
                    item.TransactionType = TransactionType.Interest;
                    item.Price = new Price(0.0, 0.0);
                    item.Size = openPositions.CurrentSize;
                    item.OrderType = OrderType.Market;
                    item.Commission = 0.0;
                    item.BuyingPowerChange = -overnightInterest;
                    item.Description = "";

I can't get it added to the open positions's trade list, as this requires a Trade object.

Thanks
Johan

Edited: Wednesday July 29 2015 by johan
Posted Friday July 31 2015
Daniel

I have worked on the reflection and can set the <Interest>k_BackingField in PositionStats now.  It, however, does not have any effect on the backtesting.  I suspect, one has to update this field with the right logic, i.e. buying power change, therefore entering it as a trade with Transaction type as interest.  I am struggling to get this right, as I can not get the TradeInfo object I create entered into the trade list of the open position.  I will appreciate if you could point me in the right direction, and if possible some code or examples that could help me.

Thanks

Johan
Posted Friday July 31 2015
I think the following is more or less what you need to do.  It doesn't work as is because C# dynamic by default doesn't allow you to call private members.  So you'll need to convert it to a bunch of reflection code, or perhaps use the library described here: Use C# 4.0 dynamic to drastically simplify your private reflection code


void AddInterestToPosition(Position position, double interest, string description = "")
  {
   TradeInfo trade = new TradeInfo();
   trade.FilledTime = SystemData.CurrentDate;
   trade.TransactionType = TransactionType.Interest;
   trade.Price = new Price(0.0, 0.0);
   trade.Size = position.CurrentSize;
   trade.OrderType = OrderType.Market;
   trade.Commission = 0.0;
   trade.BuyingPowerChange = interest;
   trade.Description = description;

   dynamic dynPositionManager = PositionManager;
   dynamic positionData = dynPositionManager.GetPositionData(position.ID);
   dynamic brokerPositionData = dynPositionManager.GetBrokerPosition(position.Symbol, position.Type, false);

   positionData.Trades.Add(trade);
   brokerPositionData.Trades.Add(trade);

   dynPositionManager.OnOrderFilled(position.Trades.Last(), position, position.Info);
  }

Posted Friday July 31 2015
Thanks Daniel.  Will try and see if I can get it to work.
Posted Tuesday August 04 2015
Daniel

After a bunch of reflection, I am getting everything right, except for the OnOrderFilled method, which gives me following error:

2,"Exception RightEdge.Common.RightEdgeError: Previous value for position ID 1 not found.

   at RightEdge.Common.SystemStatistics.OrderFilled(BarStatistic stats, TradeInfo trade, PositionInfo position, Double lastPrice, IAccountInfo accountInfo, Dictionary`2 positionValues)

   at RightEdge.Common.SystemStatistics.OrderFilled(TradeInfo trade, PositionInfo position, Double lastPrice, IAccountInfo accountInfo)

   at RightEdge.Common.BaseSystemHistory.OrderFilled(TradeInfo trade, PositionInfo pos, PositionState state)

   at RightEdge.Common.BaseSystemHistory.positionManager_OrderFilled(Object sender, OrderFilledEventArgs e)

   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)",,,2012-02-16 00:00:00


Any idea where I am going wrong?  Here is the code - it is a bit cumbersome, but reflection is a new thing for me.

    public void AddInterestToPosition(Position position, double interest, string description="")

    {

        TradeInfo trade = new TradeInfo();

        trade.FilledTime =SystemData.CurrentDate;

        trade.TransactionType = TransactionType.Interest;

        trade.Price = new Price(0.0, 0.0);

        trade.Size = position.CurrentSize;

        trade.OrderType = OrderType.Market;

        trade.Commission = 0.0;

        trade.BuyingPowerChange = -(double) interest;

        trade.Description = description;

 

        var dynPositionManager = PositionManager;

        Type dynPositionManagerType = dynPositionManager.GetType();

 

        MethodInfo getPositionDataMethodInfo =dynPositionManagerType.GetMethod("GetPositionData", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic, null,CallingConventions.Any, new Type[] {typeof(string)},null);

        string[] positionId = new String[1];

        positionId[0] = position.ID;

        PositionManager.PositionData positionData=(PositionManager.PositionData) getPositionDataMethodInfo.Invoke(dynPositionManager,positionId);

       

        MethodInfo getBrokerPositionDataMethodInfo =dynPositionManagerType.GetMethod("GetBrokerPosition",BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);

        Object[]paramBrokerPositionData = new Object[3];

        paramBrokerPositionData[0] =position.Symbol;

        paramBrokerPositionData[1] =position.Type;

        paramBrokerPositionData[2] = false;

        PositionManager.PositionData brokerPositionData = (PositionManager.PositionData)getBrokerPositionDataMethodInfo.Invoke(dynPositionManager,paramBrokerPositionData);

          

        positionData.Trades.Add(trade);

        brokerPositionData.Trades.Add(trade);

             

        MethodInfo getOnOrderFilledMethod =dynPositionManagerType.GetMethod("OnOrderFilled", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, new Type[] { typeof(Trade), typeof(Position), typeof(PositionInfo) }, null);

        Object[]paramOnOrderFilled = new Object[3];

        paramOnOrderFilled[0] = (Trade)position.Trades[position.Trades.Count-1];

        paramOnOrderFilled[1] = (Position) position;

        paramOnOrderFilled[2] = (PositionInfo)position.Info;

       

       getOnOrderFilledMethod.Invoke(dynPositionManager, paramOnOrderFilled);


Thanks

Johan


Edited: Tuesday August 04 2015 by johan
Posted Tuesday August 04 2015
Hi Johan,

Sorry, this is caused by an error in the code I posted.  The last parameter to OnOrderFilled should be brokerPositionData.PositionInfo, not position.Info.  Here's what the last bit of reflection code should look like now:


MethodInfo getOnOrderFilledMethod = dynPositionManagerType.GetMethod("OnOrderFilled",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any,
    new Type[] { typeof(Trade), typeof(Position), typeof(PositionInfo) }, null);
Object[] paramOnOrderFilled = new Object[3];
paramOnOrderFilled[0] = (Trade)position.Trades[position.Trades.Count - 1];
paramOnOrderFilled[1] = (Position)position;
paramOnOrderFilled[2] = (PositionInfo)brokerPositionData.PositionInfo;

getOnOrderFilledMethod.Invoke(dynPositionManager, paramOnOrderFilled);


Thanks,
Daniel

Edited: Tuesday August 04 2015 by dplaisted
Posted Tuesday August 04 2015
Thanks Daniel.  Works perfectly!
Posted Tuesday August 04 2015
Daniel
I have analysed results, and the results summary is correct in terms of ending capital, profit, etc.  I do, however get a warning that the broker account balance and bar statistic account balance are different, e.g. my System results show an ending capital of 464 998.46, which is the right value.  The warning, however indicates a Broker account balance of -362 524.85 and the Bar statistics account balance of -469 815.49.
I am not sure how these relate - should I just ignore the warning?  Does it have an effect in the rest of my System results or anywhere in my system, as not one of the two is close to what it should be?
Thanks

Johan


Similar Topics


Reading This Topic


2005-2017 © RightEdge Systems