Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Weekdays,Time and daily Loss/Profit

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

    Weekdays,Time and daily Loss/Profit

    Hello,

    I have the following code:
    But im having an issue regarding the protection of the strategy. Like its written i can choose days of the week to run and set the last trade entry time and exit time but i still have trades that are closed at 2130 when its set to exit at 15000. In terms of last entry is okay, no trades being set after the hour established.

    Also the daily loss is not working correctly. It assumes its the daily loss of the trade, so in fact i have days that the maximum daily allowed loss is not respected. Meaning i have days that the loss is more than the allowed because it continues to trade.

    Both these problems reside in the fact that the strategy should just stop and wait until next day to trade again.

    Please assist.

    Thank You very much

    Code:
     protected override void OnBarUpdate()
            {
    			if (base.BarsInProgress != 1)
                {
                    return;
                }
                if (base.Bars.FirstBarOfSession)
                {
                    this.initVariables();
                }
    			if (base.CurrentBar < 20)
    			{
    				return;
    			}
    			if (!this.runDays[(int)base.Time[0].DayOfWeek] && base.Position.MarketPosition == MarketPosition.Flat)
    			{
    				return;
    			}
              
    			if (base.CurrentBar <= this.BarsRequired || base.CurrentBars[0] <= this.BarsRequired)
                {
                    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;
                }
    		// *** Calculate the toal profit (cumulative profit minus prior profit plus the current position profit 
    			double myMaxProfit = maxprofit;
    			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 ;
    			{priorCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;}
    		// *** STOP the strategy! if a total profit or loss exceeds the max
    			
    		if (totCumProfit <= myMaxLoss || totCumProfit >= myMaxProfit)
    				{
    		if (Position.MarketPosition == MarketPosition.Long) {ExitLong("DMA: Exit Long - max Profit/Loss exceeded", "");}
    		if (Position.MarketPosition == MarketPosition.Short) {ExitShort("DMA: Exit Short - max Profit/Loss exceeded", "");}
    
    				return;
    				}
    							
    // Buy sell logic************************************************************************************	
    
    protected override void OnStartUp()
            {
                this.sDebug = this.debug;
    			
    			try
    			{
    				if (this.daysToRun == "")
    				{
    					this.runDays[0] = true;
    				}
    				else
    				{
    					string[] strArrays = this.daysToRun.Split(new char[] { ',' });
    					for (int i = 0; i < (int)strArrays.Length; i++)
    					{
    						string str = strArrays[i];
    						this.runDays[Math.Min(Math.Max(0, int.Parse(str)), 6)] = true;
    					}
    				}
    			}
    			catch (ArgumentException argumentException)
    			{
    				this.runDays[0] = true;
    			}
    			if (this.runDays[0])
    			{
    				for (int j = 0; j < 7; j++)
    				{
    					this.runDays[j] = true;
    					if (this.debug)
    					{
    						base.Print(string.Concat(base.Name, " Day to run: ", j));
    					}
    				}
    			}
    		
            }	
    
    
    		}

    Edit: Strangely (or maybe not), i get different results if i put the daily loss after the buy/sell and stoploss logic.
    Last edited by hliboi; 05-05-2014, 09:25 AM.

    #2
    Hello hliboi,

    Thank you for your post.

    For the time to exit you are checking that the position is not long and then trying to exit long, and the same for short. I would believe this would need to be a check for the position being long and then exit long.
    Code:
                if (base.ToTime(base.Time[0]) >= this.exitTimeInt * 100 && this.exitTimeInt > 0)
                {
                    if (base.Position.MarketPosition != MarketPosition.Long) [COLOR="Red"]// check that we are not long?[/COLOR]
                    {
                        base.ExitLong(); [COLOR="Red"]// then exit long?[/COLOR]
                    }
                    if (base.Position.MarketPosition != MarketPosition.Short) [COLOR="Red"]// check that we are not short?[/COLOR]
                    {
                        base.ExitShort(); [COLOR="Red"]// then exit short?[/COLOR]
                    }
                    return;
                }
    For the profit, you are basing it off of the current trade and this is why it is calculating as such. You take your total CumProfit minus the current CumProfit (which are going to be the same if you are still in a trade) and then you add only the current position's profit. If you want the total profit you would just add the CumProfit to the Position.GetProfitLoss().
    Code:
    			double cumProfit = (double) Performance.AllTrades.TradesPerformance.Currency.CumProfit;
    			double curPosition = (double) Position.GetProfitLoss(Close[0], PerformanceUnit.Currency);
    			[COLOR="Red"]// Below you subtract the prior cumulative profit from the current profit,
    			// this will likely return 0 if no other trades have completed since the last 
    			// time the priorCumProfit was assigned.[/COLOR]
    			double totCumProfit = (double) cumProfit - priorCumProfit + curPosition ;

    Comment


      #3
      Thank a whole bunch Patrick.
      For the exit time is fixed. I still got some exits pass eg: 1500 but I think its because of the finish of the bar and in those cases it proceeds to close at the end of the bar. Could this be? Im using renko bars.

      For the profit i tried to add but it takes into account the cumulative profit of all the days. Could you provide the example:

      Performance.AllTrades.TradesPerformance.Currency.C umProfit;

      but only for the day otherwise it wont trade. So im thinking about some setting to reset it daily.

      Thank You and thank you for your fast reply

      Comment


        #4
        Hello hliboi,

        Thank you for your response.

        For the exit time on the Renko bars are you using CalculateOnBarClose = True? This would explain how this occurs and confirm your hypothesis.

        For the cumulative profit for the day we would need to track this on our own. Below you will find an example:
        Code:
        if(Bars.FirstBarOfSession)
        {
        profitAtStart = Performance.AllTrades.TradesPerformance.Currency.CumProfit;
        }
        ...
        // Current day's profit can then be calculated in the following manner.
        currentDayProfit = (Performance.AllTrades.TradesPerformance.Currency.CumProfit - profitAtStart) + Position.GetProfitLoss(Close[0], PerformanceUnit.Currency));

        Comment


          #5
          As a matter of fact Patrick i had it set on false. It seems to close on the completion of bar after 1900 it then waits for the completion 1905 and then closes.
          In renko bars I have for example a candle that closes at 1904 but he does not close there it will close in the next bar, 1940. Its weird because i changed all the setting in the indicators that it calls to CalculateOnBarClose even added for for indicators that didn't have that parameter.

          *****I tested the example but it makes no trades now. Sorry. Did not change much but seeing your code saw that it was the same but with parentheses.**********

          Edit: It does make make trades. Sorry Patrick. Must have been something else wrong.



          protected override void OnBarUpdate()
          {
          // if (CurrentBar < 20)
          // return;
          if (base.BarsInProgress != 1)
          {
          return;
          }
          if (base.Bars.FirstBarOfSession)

          {priorCumProfit = Performance.AllTrades.TradesPerformance.Currency.C umProfit;}
          // {profitAtStart = Performance.AllTrades.TradesPerformance.Currency.C umProfit;}

          // *** Calculate the toal profit (cumulative profit minus prior profit plus the current position profit
          double myMaxProfit = maxprofit;
          double myMaxLoss = maxloss;
          double cumProfit = (double) Performance.AllTrades.TradesPerformance.Currency.C umProfit;
          double curPosition = (double) Position.GetProfitLoss(Close[0], PerformanceUnit.Currency);
          double totCumProfit = (double) (cumProfit - priorCumProfit) + curPosition ;

          // double currentDayProfit = (Performance.AllTrades.TradesPerformance.Currency. CumProfit - profitAtStart) + curPosition;
          Thanks for your help
          Last edited by hliboi; 05-05-2014, 12:44 PM.

          Comment


            #6
            Hello hliboi,

            Thank you for your response.

            I would continue to use CalculateOnBarClose = False. I would suggest to use Print() statements in the code, especially when the time condition should return true.
            Something like the following:
            Code:
                        if (base.ToTime(base.Time[0]) >= this.exitTimeInt * 100 && this.exitTimeInt > 0)
                        {
                                    Print("Exit Time: " + Time[0]);
                                    ....

            Comment


              #7
              Thanks Patrick ill keep investigating this issue with the exitTimeInt. Thanks.

              Regarding the daily Profit Loss is there anyway to only count the losses. Meaning only counting the compound losses during the day instead of subtracting it from previous profit made that day?

              Thank You

              Comment


                #8
                Hello hliboi,

                Thank you for your response.

                You can use Performance.AllTrades.LosingTrades: http://www.ninjatrader.com/support/h...singtrades.htm

                Comment


                  #9
                  Thank Very Much Patrick you were very helpful.
                  Thanks

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by ZenCortexCLICK, Today, 04:58 AM
                  0 responses
                  5 views
                  0 likes
                  Last Post ZenCortexCLICK  
                  Started by sidlercom80, 10-28-2023, 08:49 AM
                  172 responses
                  2,280 views
                  0 likes
                  Last Post sidlercom80  
                  Started by Irukandji, Yesterday, 02:53 AM
                  2 responses
                  18 views
                  0 likes
                  Last Post Irukandji  
                  Started by adeelshahzad, Today, 03:54 AM
                  0 responses
                  7 views
                  0 likes
                  Last Post adeelshahzad  
                  Started by Barry Milan, Yesterday, 10:35 PM
                  3 responses
                  13 views
                  0 likes
                  Last Post NinjaTrader_Manfred  
                  Working...
                  X