Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Long Strategy Has Suddenly Been Trading Short This Last Week

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

    Long Strategy Has Suddenly Been Trading Short This Last Week

    hello all; thanks in advance for any help

    I have a divergence strategy that is designed to go long, that for the last week has been making short trades.

    Here is the code:

    Code:
    #region Using declarations
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Data;
    using NinjaTrader.Indicator;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Strategy;
    #endregion
    
    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
        /// <summary>
        /// Identify divergence of selected indicator with Price
        /// </summary>
        [Description("Identify divergence of selected indicator with Price. I use CCI, MACD & Ergodic indicator, two indicators forming divergence provides confirmation")]
        public class DivergenceLong8TickHardStop : Strategy
        {
            #region Variables
            // Wizard generated variables
            private string positiveD = @"YES"; // Default setting for PositiveD
            //private string indicatorType = @"MACD"; // Default setting for IndicatorType
            private int macdfastPeriod = 12; // Default setting for FastPeriod
            private int macdslowPeriod = 26; // Default setting for SlowPeriod
            private int macdsignalPeriod = 9; // Default setting for SignalPeriod
            private int ergodicfastPeriod = 20; // Default setting for Ergodic FastPeriod
            private int ergodicslowPeriod = 12; // Default setting for Ergodic SlowPeriod	
            private int cciPeriod = 40; // Default setting for CCI Period		
            private double stopLossPct = 0.020; // Default setting for StopLossPct
            private double trailingStopPct = 0.020; // Default setting for TrailingStopPct		
            // User defined variables (add any user defined variables below)
    		private double trailStop = 0; // Default setting for TrailStop
    		private double StopLoss = 0;
            private double prevValue = 0; // Default setting for PrevValue
            private bool justEntered = false; // Default setting for JustEntered		
            #endregion
    
            /// <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 = true;
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
                // Condition set 1 - Positive Divergence
                if (((Divergence(ergodicfastPeriod, "ergodic", positiveD, 1,ergodicslowPeriod).Plot0[0] == 2 && Divergence(cciPeriod, "cci", positiveD, 9,26).Plot0[0] == 2) ||
    				(Divergence(ergodicfastPeriod, "ergodic", positiveD, 1,ergodicslowPeriod).Plot0[0] == 2 && Divergence(macdfastPeriod, "macd", positiveD, macdsignalPeriod,macdslowPeriod).Plot0[0] == 2) ||
    				(Divergence(cciPeriod, "cci", positiveD, 9,26).Plot0[0] == 2 && Divergence(macdfastPeriod, "macd", positiveD, macdsignalPeriod,macdslowPeriod).Plot0[0] == 2)) &&
    				Position.MarketPosition == MarketPosition.Flat &&
                    (LinRegSlope(60)[0] > 0
    				&& LinRegSlope(60)[0] > LinRegSlope(60)[5]
    				&& EMA(60)[0] > EMA(60)[10]
                    && ADX(5)[0] > 30) )
                {
                    EnterLong(1, "Long");
    				justEntered = true;
                }
    			if (Position.MarketPosition == MarketPosition.Long && justEntered == true)
    			{
    				trailStop = Position.AvgPrice - (trailingStopPct * Position.AvgPrice);
    				StopLoss = Position.AvgPrice - (stopLossPct * Position.AvgPrice);
        			prevValue = Position.AvgPrice;
        			justEntered = false;
        			Print(" TRAIL STOP TRACKING: " + trailStop + " symbol " + Instrument.FullName);
    			}
    			if (Position.MarketPosition == MarketPosition.Long)
    			{
    				if (High[0] > Position.AvgPrice && High[0] > prevValue)
    				{
    					trailStop = trailStop + (High[0] - prevValue);
           				prevValue = High[0];
           				Print(" TRAIL STOP RAISED: " + trailStop + " PrevValue " + prevValue + " symbol " + Instrument.FullName);
    				}
    				Print(Time[0] + " High " + High[0] + " PrevValue " + prevValue + " symbol " + Instrument.FullName);
    			}
    			if (Low[0] <= trailStop && Position.MarketPosition == MarketPosition.Long && Position.AvgPrice < trailStop)
    			{
    				Print(" TRAIL STOP HIT: " + trailStop + " " + Close[0] + " symbol " + Instrument.FullName);
        			// Trailing stop has been hit; do whatever you want here
    				ExitLong(1,"Trailing Stop" ,"Long");
       				trailStop = 0;
    				StopLoss = 0;
        			prevValue = 0;
    			}
    			else SetStopLoss("", CalculationMode.Ticks, 8, false);		
    			
                // Condition set 2 - Negative divergence
                if (((Divergence(ergodicfastPeriod, "ergodic", positiveD, 1,ergodicslowPeriod).Plot0[0] == -2 && Divergence(cciPeriod, "cci", positiveD, 9,26).Plot0[0] == -2) ||
    				(Divergence(ergodicfastPeriod, "ergodic", positiveD, 1,ergodicslowPeriod).Plot0[0] == -2 && Divergence(macdfastPeriod, "macd", positiveD, macdsignalPeriod,macdslowPeriod).Plot0[0] == -2) ||
    				(Divergence(cciPeriod, "cci", positiveD, 9,26).Plot0[0] == -2 && Divergence(macdfastPeriod, "macd", positiveD, macdsignalPeriod,macdslowPeriod).Plot0[0] == -2)) &&
    				Position.MarketPosition == MarketPosition.Flat)
           
    			if (Position.MarketPosition == MarketPosition.Short && justEntered == true)
    			{
    				trailStop = Position.AvgPrice + (trailingStopPct * Position.AvgPrice);
    				StopLoss = Position.AvgPrice + (stopLossPct * Position.AvgPrice);
        			prevValue = Position.AvgPrice;
        			justEntered = false;
        			Print(" TRAIL STOP TRACKING: " + trailStop + " symbol " + Instrument.FullName);
    			}
    			if (Position.MarketPosition == MarketPosition.Short)
    			{
    				if (Low[0] < Position.AvgPrice && Low[0] < prevValue)
    				{
    					trailStop = trailStop - (prevValue - Low[0]);
           				prevValue = Low[0];
           				Print(" TRAIL STOP Lowered: " + trailStop + " PrevValue " + prevValue + " symbol " + Instrument.FullName);
    				}
    				Print(Time[0] + " Low " + Low[0] + " PrevValue " + prevValue + " symbol " + Instrument.FullName);
    			}			
    			if (High[0] >= trailStop && Position.MarketPosition == MarketPosition.Short && Position.AvgPrice > trailStop)
    			{
    				Print(" TRAIL STOP HIT: " + trailStop + " " + Close[0] + " symbol " + Instrument.FullName);
        			// Trailing stop has been hit; do whatever you want here
       				trailStop = 0;
    				StopLoss = 0;
        			prevValue = 0;
    			}
    			else if (High[0] >= StopLoss && Position.MarketPosition == MarketPosition.Short && Position.AvgPrice < StopLoss)
    			{
    				Print(" STOP LOSS HIT: " + StopLoss + " " + Close[0] + " symbol " + Instrument.FullName);
    				// Trailing stop has been hit; do whatever you want here
    				trailStop = 0;
    				StopLoss = 0;
    				prevValue = 0;					
    			}			
            }
    
            #region Properties
            [Description("Enter 'YES' for positive divergence and 'NO' for negative divergence")]
            [Category("Parameters")]
            public string PositiveD
            {
                get { return positiveD; }
                set { positiveD = value; }
            }
    
    //        [Description("MACD,Ergodic,FStoch,StochRSI,CCI,BOP,CMO,ChaikinMoneyFlow,Momentum,MFI,RSI,ROC")]
    //        [Category("Parameters")]
    //        public string IndicatorType
    //        {
    //            get { return indicatorType; }
    //            set { indicatorType = value; }
    //        }
    
            [Description("Used only on the MACD indicator")]
            [Category("Parameters")]
            public int MACDFastPeriod
            {
                get { return macdfastPeriod; }
                set { macdfastPeriod = Math.Max(1, value); }
            }
    
            [Description("Used only on the MACD indicator")]
            [Category("Parameters")]
            public int MACDSlowPeriod
            {
                get { return macdslowPeriod; }
                set { macdslowPeriod = Math.Max(1, value); }
            }
    
            [Description("Used only on the MACD indicator")]
            [Category("Parameters")]
            public int MACDSignalPeriod
            {
                get { return macdsignalPeriod; }
                set { macdsignalPeriod = Math.Max(0, value); }
            }		
    		
            [Description("Used only on the Ergodic indicator")]
            [Category("Parameters")]
            public int ErgodicFastPeriod
            {
                get { return ergodicfastPeriod; }
                set { ergodicfastPeriod = Math.Max(1, value); }
            }
    
            [Description("Used only on the Ergodic indicator")]
            [Category("Parameters")]
            public int ErgodicSlowPeriod
            {
                get { return ergodicslowPeriod; }
                set { ergodicslowPeriod = Math.Max(1, value); }
            }		
    
    		[Description("Used only on the CCI indicator")]
            [Category("Parameters")]
            public int CCIPeriod
            {
                get { return cciPeriod; }
                set { cciPeriod = Math.Max(1, value); }
            }
    		
            [Description("")]
            [Category("Parameters")]
            public double StopLossPct
            {
                get { return stopLossPct; }
                set { stopLossPct = Math.Max(0.010, value); }
            }
    
            [Description("")]
            [Category("Parameters")]
            public double TrailingStopPct
            {
                get { return trailingStopPct; }
                set { trailingStopPct = Math.Max(0.010, value); }
            }		
            #endregion
        }
    }
    You'll see that this code has a whole "short" section to it, however, I long ago removed the part of the code that entered a short trade.

    Any ideas why, after months of only making long trades, it is now making short trades?

    Thanks

    #2
    Hello outstretchedarm,

    Thank you for your post.

    I recommend enabling TraceOrders to track each order created within the Output Window (Tools > Ouput Window).

    I also recommend placing Print() statments throughout your code to track when your conditions return true including your "short" conditions.

    For information on debugging your NinjaScript code please visit the following link: http://www.ninjatrader.com/support/f...ead.php?t=3418

    Please let me know if you have any questions.

    Comment


      #3
      Thanks for your prompt reply. I will look into the concepts you've suggested. I'm sure they'll make me a better trader.

      Is it possible that you could look at that code I posted, and if there is anything in there that might put in for a short trade? I'm not seeing it; maybe you in your expertise can.

      Comment


        #4
        Hello outstretchedarm,

        Thank you for your response.

        I cannot see what would be causing the short entries to occur from the code you have posted. I would use the Print() statements for when the short conditions are true and track this with the TraceOrders to see when these short orders are placed and what conditions coincide with the order placement.

        Please let me know if I may be of further assistance.

        Comment


          #5
          Its going to take me some time to learn how to use those print statements, but I will learn them because you suggest it.

          Let me give you a little more background on the mystery. Last tuesday, I created a clone of that strategy that went short. Also, I made a few changes to the original strategy, one of which was to delete the old, legacy part of the code about the strategy going short.

          The short version of the strategy was trading on the same account for about a day. I was displeased with the results, and later decided to delete the strategy altogether.

          After that, the original long strategy continued to make short trades. Frustrated by this, I decided to do a backup of the strategy (from May of last year) to bring back the original strategy. But I made a tuesday night backup of everything first.

          After restoring the May backup, I copied and pasted the original divergence strategy code, which I knew worked, into a notepad. I then restored the tuesday night backup. I went into the long divergence strategy, copied and pasted over it with the strategy from the notepad, compiled and saved.

          Its been a few days since I did this. Since then, the strategy has continued to create short trades, though I have no short version of the strategy. Even when I isolate this strategy, and this account, on the accounts performance tab, it will show that in the last few days long and short trades.

          Any ideas? Thanks in advance.

          Comment


            #6
            To complicate matters more, I've been going methodically through all my strategies performance for last week, and found another strategy, a DmiMA strategy, that I made *no* changes to, suddenly made 427 short trades last week. But in the month of december, it made no short trades, just like it is not programmed to.

            How could this be possible?

            Comment


              #7
              Originally posted by outstretchedarm View Post
              To complicate matters more, I've been going methodically through all my strategies performance for last week, and found another strategy, a DmiMA strategy, that I made *no* changes to, suddenly made 427 short trades last week. But in the month of december, it made no short trades, just like it is not programmed to.

              How could this be possible?
              It sounds as if your strategy is making trades in an attempt to sync your strategy and account positions?

              Comment


                #8
                Hello outstretchedarm,

                Thank you for your response.

                Please go to the NinjaTrader Control Center > Tools > Options > Strategies > NinjaScript > what is the 'On starting a real-time strategy' set to?

                When enabling your strategy what do you set the parameter 'Sync account position' to?

                For information on Syncing Account Positions please visit the following link: http://www.ninjatrader.com/support/h..._positions.htm

                I look forward to your response.

                Comment


                  #9
                  Its set to "wait until flat before executing live."


                  Originally posted by koganam View Post
                  It sounds as if your strategy is making trades in an attempt to sync your strategy and account positions?
                  Thanks for joining the discussion. Your comments are definitely welcome.

                  Apart from "flattening all positions", which hasn't seemed to solve the problem so far, how might I fix this?

                  Comment


                    #10
                    Hello outstretchedarm,

                    Thank you for your response.

                    When enabling your strategy what do you set the parameter 'Sync account position' to? True or False?

                    For information on Syncing Account Positions please visit the following link: http://www.ninjatrader.com/support/h..._positions.htm

                    I look forward to your response.

                    Comment


                      #11
                      Thank you again.

                      Sync account position is set to false for all strategies in question.

                      Comment


                        #12
                        Hello outstretchedarm,

                        Thank you for your response.

                        In this case there would be no orders to "sync" your positions. However, if the Strategy Position is not flat, the strategy will place all trades in a "virtual" sense until the Strategy Position reaches or crosses a flat state. Once a flat state is achieved the Strategy Position will be assumed to be in sync with the Account Position and all future orders will be placed live.

                        For information on Account versus Strategy Position please visit the following link: http://www.ninjatrader.com/support/f...ead.php?t=4033

                        Please let me know if I may be of further assistance.

                        Comment


                          #13
                          OK here we go again.

                          After a week of nice, normal trading after I reset all the simulation accounts, we are back at it again.

                          At least four different accounts, that only have long strategies automatically trading in them, are making short trades in them, trying to "get right." This is frustrating; this will be the third week in a row my automated trading will have been affected by this problem.

                          I believe that part of the problem is that, sometime , I make a change to NT while it is running. For example, I will do a backup, or add a new simulation account. However, in order for these changes to take effect, I have to close the connection on NT. NT will give me a warning about there being open orders and position, but I will have to close the connection anyway.

                          It may be that, when NT reconnects again, it does not properly sync positions.

                          I thought that whenever you restarted NT (or closed and reopened a connection), the automated strategies were intelligent enough to identify that open positions in the account were the result of a trade the automated strategy opened the last time it was connected, and that it should follow through and close that position (see the trade through to the end) before starting a new trade.

                          Can you please give more insight into how NT handles this type of situation? Because as of now, its ruining my trading statistics, and I am nowhere near confident of trading with real money until I resolve this.

                          Comment


                            #14
                            Hello outstratchedarm,

                            Thank you for your update on this matter.

                            This can occur when setting the Sync Account Position option to False.The resulting behavior when the Strategy Position and Account Position are out of sync is when your strategy closes a long position with a sell order it would bring the Strategy Position to flat and your Account Position to SHORT 1.

                            For information on Account Position versus Strategy Position please visit the following link: http://www.ninjatrader.com/support/h..._account_p.htm

                            And you can find information on this matter on the Support Forum at the following link: http://www.ninjatrader.com/support/f...ead.php?t=4033

                            Please let me know if you have any questions.

                            Comment


                              #15
                              so whats the solution? how do I stop this from happening all the time.

                              Comment

                              Latest Posts

                              Collapse

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