Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

PnL for separate instruments

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    PnL for separate instruments

    Hello,

    I have the following code to close the strategy based on amount of losses suffered for a day:
    Code:
    if (base.Bars.FirstBarOfSession)
    			{
      			  priorCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;
    			}
    			// *** Calculate the total profit (cumulative profit minus prior profit plus the current position profit 
    			double myMaxLoss = maxloss;
    			double cumProfit = (double) Performance.AllTrades.TradesPerformance.Currency.CumProfit;
    			double curPosition = (double) Position.GetProfitLoss(Close[0], PerformanceUnit.Currency);
    			double totCumProfit = (double) (cumProfit - priorCumProfit) + curPosition ;
    					
    			// *** STOP the strategy! if a total profit or loss exceeds the max
    				if (totCumProfit <= myMaxLoss )
    				{
    				if (Position.MarketPosition == MarketPosition.Long) {ExitLong("DMA: Exit Long ", "");}
    				if (Position.MarketPosition == MarketPosition.Short) {ExitShort("DMA: Exit Short", "");}
    				return;
    				}
    What I'm seeing is that when running the strategy with multiple instruments every instrument counts to this code while in backtesting this doesn't happen (its calculating only for one instrument). I'm wanting to have this code calculate only for each instrument I wouldn't like to multiply the total loss by the number of instruments traded. Each instrument should have their own maxloss.

    Could this be achieved? Is there any workaround ?

    Thank You

    #2
    Hi hliboi,

    Without seeing the rest of the script it would be hard to say.

    Are you using a BarsInProgress index when submitting the order?

    Are you using multiple data series that are the same instrument?

    Are you using multiple variables to track the profit for each series?

    I am including a test that shows when you add multiple instruments to a script, both series will affect the last trade count.

    Each series in the test will place one order.

    Then on the last historical bar, you will see in the output a print for each trade in the trade collection.
    Attached Files
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hello ChelseaB,

      Im only using Add(PeriodType.Tick,1); to add granularity. Should I add the series of all the instruments that i trade in in the strategy and have the Performance.AllTrades.TradesPerformance.Currency.C umProfit be calculated for each instrument? should i create a separate strategy for each instrument?

      Thank You


      Code:
       public class Strat24: Strategy
          {
      		private int	amp = 40;
      		private int	trail1 = 30;
      		private int	trail2 = 30;
      		private int	be2	= 1;
      		private int	be3	= 1;
      		private int breakeven = 1;
      		private int	quantity1 = 5000;
      		private int startTimeInt = 600;
      		private int exitTimeInt = 1700;
              private int lastEntryTimeInt = 1630;
              private DateTime exitTimeDT;
              private DateTime startTimeDT;
      		private double priorCumProfit= 0;
      		private double maxloss= -20;
      		
      		
      		
              /// <summary>
              /// This method is used to configure the strategy and is called once before any strategy method is called.
              /// </summary>
              protected override void Initialize()
              {
               	CalculateOnBarClose = false;
      			EntryHandling		= EntryHandling.UniqueEntries;
      			Add(PeriodType.Tick,1);
      
      			
      		}
      
              private void GoLong()
      		{
      			EnterLong(quantity1,"Long1");
      
      		}
      		
      		private void GoShort()
      		{
      			EnterShort(quantity1,"Short1");
      
      		}
      		
      		
      		private void ManageOrders()
      		{
      			if (Position.MarketPosition == MarketPosition.Long)
      			{
      				if (BE2==1 && High[0] > (Position.AvgPrice +( (breakeven*100)*TickSize)))
      					SetTrailStop("Long1", CalculationMode.Ticks, trail1, false);
      				
      				if (BE3==1 && High[0] > (Position.AvgPrice +( (breakeven*100)*TickSize)))
      					SetTrailStop("Long2", CalculationMode.Ticks,trail2, false);
      			}
      			
      			if (Position.MarketPosition == MarketPosition.Short)
      			{
      				if (BE2==1 && Low[0] < (Position.AvgPrice + ((breakeven*100)*TickSize)))
      					SetTrailStop("Short1", CalculationMode.Ticks,trail1, false);
      				
      				if (BE3==1 && Low[0] < (Position.AvgPrice +  ((breakeven*100)*TickSize)))
      					SetTrailStop("Short2", CalculationMode.Ticks, trail2, false);
      			}
      		}
      		
      		
      		
              protected override void OnBarUpdate()
      			
              {
      			EntryHandling		= EntryHandling.UniqueEntries;
      
      			
      			//	Daily Loss
                  if (base.Bars.FirstBarOfSession)
      			{
        			  priorCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;
      			}
      			// *** Calculate the toal profit (cumulative profit minus prior profit plus the current position profit 
      			double myMaxLoss = maxloss;
      			double cumProfit = (double) Performance.AllTrades.TradesPerformance.Currency.CumProfit;
      			double curPosition = (double) Position.GetProfitLoss(Close[0], PerformanceUnit.Currency);
      			double totCumProfit = (double) (cumProfit - priorCumProfit) + curPosition ;
      					
      			
      						
      			// *** STOP the strategy! if a total profit or loss exceeds the max
      				if (totCumProfit <= myMaxLoss )
      				{
      				if (Position.MarketPosition == MarketPosition.Long) {ExitLong("DMA: Exit Long ", "");}
      				if (Position.MarketPosition == MarketPosition.Short) {ExitShort("DMA: Exit Short", "");}
      				return;
      				}
      
      			if (base.ToTime(base.Time[0]) < this.startTimeInt * 100 && this.startTimeInt > 0)
                  {
                      return;
                  }
      			
      			if (base.ToTime(base.Time[0]) >= this.exitTimeInt * 100 && this.exitTimeInt > 0)
                  {
      				if (base.Position.MarketPosition == MarketPosition.Long)
                      {
                          base.ExitLong();
                      }
                      if (base.Position.MarketPosition == MarketPosition.Short)
                      {
                          base.ExitShort();
                      }
                      return;
                  }
      
      		if (base.ToTime(base.Time[0]) <= this.lastEntryTimeInt * 100 || this.lastEntryTimeInt == 0)
      			{	
      			ManageOrders();
      		
      			if (Position.MarketPosition != MarketPosition.Flat) return;
      			
      			if (somevalue> amp && Close[0] > Open[0]) 
      				GoLong();
      			else if (somevalue > amp && Close[0] < Open[0])
      				GoShort();
      			}
      		}
      Last edited by hliboi; 10-13-2014, 07:43 AM.

      Comment


        #4
        Hi hliboi,

        This depends on what you are trying to do.

        If you want your script to trade multiple instruments, then add multiple instruments and logic to your script.

        If you want your script to trade just one instrument, then do not add multiple instruments to your script, and instead run one instance of the script for each instrument separately.

        Each unique instrument will add to the trade collection for that script instance. You can have these filter into performance variables for each instrument if that is what you wish to do.

        Are you trying to add multiple instruments to one script and then create individual performance values for each instrument?

        If so, have you added a variable to store the performance for each instrument?
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hello ChelseaB,

          I'm guessing that a script for each instrument would work in both the strategy analyzer and live. So I'm thinking for the moment to have a script for each traded instrument.
          I'm trying to make this work but i get error could you please clarify what Im doing wrong?

          Thank You very much

          Code:
          protected override void Initialize()
                  {
                   	CalculateOnBarClose = false;
          			EntryHandling		= EntryHandling.UniqueEntries;
          			Add(PeriodType.Tick,1);//1
          			Add("$EURUSD", BarsPeriod.Id, BarsPeriod.Value);//2
          		}
          
                  private void GoLong()
          		{
          			EnterLong(quantity1,"Long1");
          		}
          		
          		private void GoShort()
          		{
          			EnterShort(quantity1,"Short1");
          		}
          		
                  protected override void OnBarUpdate()
          			
                  {
          			EntryHandling		= EntryHandling.UniqueEntries;
          			
          			//	Daily Loss
                      if (base.Bars.FirstBarOfSession)
          			{
            			  priorCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit[2];
          			}
          			// *** Calculate the toal profit (cumulative profit minus prior profit plus the current position profit 
          			double myMaxLoss = maxloss;
          			double cumProfit = (double) Performance[2].AllTrades.TradesPerformance.Currency.CumProfit;
          			double curPosition = (double) Position[2].GetProfitLoss(Close[2], PerformanceUnit.Currency);
          			double totCumProfit = (double) (cumProfit - priorCumProfit) + curPosition ;
          					
          			// *** STOP the strategy! if a total profit or loss exceeds the max
          				if (totCumProfit <= myMaxLoss )
          				{
          				if (Position[2].MarketPosition == MarketPosition.Long) {ExitLong("DMA: Exit Long ", "");}
          				if (Position[2].MarketPosition == MarketPosition.Short) {ExitShort("DMA: Exit Short", "");}
          				return;
          				}

          Comment


            #6
            Hello hliboi,

            A script with multiple data series added will work in backtest in the Strategy Analyzer and live.
            A script with one data series will also work in backtest in the Strategy Analyzer and live.

            May I have a screenshot of the error?
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Sure!
              Thank You
              Attached Files

              Comment


                #8
                Hi hliboi,

                The issue is you are attempting to call a bars in progress index with Position instead of Positions (plural).

                Position is for the current bar in progress' position.

                Positions[0] is for the first position collection.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Thanks ChelseaB

                  How to call the Performance for that instrument solely?

                  Thank You


                  Code:
                  Performance[2].AllTrades.TradesPerformance.Currency.CumProfit;

                  Comment


                    #10
                    Hello hliboi,

                    The performance will need to looped through to find your trade.

                    If it was the last trade you can use:

                    Performance.AllTrades[Performance.AllTrades.Count-1].ProfitCurrency
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Hello ChelseaB,

                      What if its not the last trade? What if its a collection of trades that amount to the daily max loss for that instrument.

                      Thank You

                      Comment


                        #12
                        Hello hliboi,

                        You can loop through the collection with a for loop.

                        You could also accumulate the PnL to a variable for the last trade every time a trade closes.
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Thanks I'll try that.

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                          0 responses
                          574 views
                          0 likes
                          Last Post Geovanny Suaza  
                          Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                          0 responses
                          333 views
                          1 like
                          Last Post Geovanny Suaza  
                          Started by Mindset, 02-09-2026, 11:44 AM
                          0 responses
                          101 views
                          0 likes
                          Last Post Mindset
                          by Mindset
                           
                          Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                          0 responses
                          553 views
                          1 like
                          Last Post Geovanny Suaza  
                          Started by RFrosty, 01-28-2026, 06:49 PM
                          0 responses
                          551 views
                          1 like
                          Last Post RFrosty
                          by RFrosty
                           
                          Working...
                          X