Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Simple MACD Crossover Strategy that isn't so simple

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

    Simple MACD Crossover Strategy that isn't so simple

    I have spent a few weeks learning how to develop strategies in NinjaTrader. But I can't for the life of me figure out how to code the following strategy:

    1. If MACD >0 BUY

    2. If MACD < 0 SELL

    3. Stop Loss and Profit

    4. Do not check for these conditions again until a new MACD crossover occurs.

    The tricky party is coding no. 4 . 1, 2 and 3 are easy. The problem is that it keeps buying or selling, even if a stop loss or profit occurs because the conditions are still true and not waiting for the next macd crossover to occur. I know this is probably an if statement within an if statement, but nothing seems to be working for me. Any suggestions?

    #2
    Hello eberline,

    Thanks for your post and welcome to the forums.

    It sounds like you are wanting to buy when the Macd is above the zero line but you only want to do that once until it crosses to the downside and then you only want to sell once, wash, rinse, repeat, etc.

    One way to accomplish this is to use the CrossAbove or CrossBelow method when you check the macd line to the value of 0.0. For example:

    Code:
    if (CrossAbove(MACD(12, 26, 9), 0.0, 1))
                {
                    // buy....
                }
    similarly:
    if (CrossBelow(MACD(12, 26, 9), 0.0, 1))
                {
                   // sell
                }
    In the above example you will only enter if the macd line crosses the zero line and the entry would be on the next candle after the cross.
    Here is the help guide reference to the methods CossAbove/CrossBelow:





    It is not clear to me if you have other conditions that you wait for so if you do not want to buy/sell as the macd crosses you can instead add boolean logic statements to indicate that a cross has occurred and then reset that on each cross for example:

    Code:
    if (CrossAbove(MACD(12, 26, 9), 0.0, 1))  
                {
                    buyFlag = true;
                }
    
    if (your other conditions && buyFlag)   
    {
          // buy code here
         buyFlag = false; // set this false so we only enter once in the macd up cycle\
    }
    
    if (CrossBelow(MACD(12, 26, 9), 0.0, 1))  
                {
                   sellFlag = true;
                }
    if (your other conditions && sellFlag)
    {
          // sell code here
          sellFlag = false; // set this false so we only enter once in the macd down cycle
    }
    In the above code, the bools buyFlag and sellFlag are used to set the condition that the macd has crossed and that no previous buy/sell has occurred. As soon as a buy or sell is made the flag is set to false so that additional buy/sells cannot be made until the macd crosses zero.

    Please let me know if I can be of further assistance.
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      first macd cross, then wait to execute

      Paul, thanks for your prompt reply. I think i need to explain things further:

      Essentially here is what I am trying to code:

      Description:
      Begin when macd cross up or down occurs and then wait to execute until conditions 1 a or 2 a. beliw are met, then exit, and don't execute again until a new macd cross occurs.

      Logic:

      1. If macd cross up occurs, then wait until:

      A. If macd > 0 && stochastic %k > 80, then BUY

      2. If macd cross down occurs, then wait until

      A. If macd < 0 && stochastic %k < 20, then BUY

      3. Sell when either stop loss or profit target are met

      I can code 1 a, 2a and 3. But I'm unclear how to tell NinjaTrader to wait for a macd cross and not execute until 1a or 2a are met.

      Thanks again for your help.

      Comment


        #4
        Hello eberline,

        Thanks for your reply and question.

        In that case then you will want to examine the second code sample I originally provided where you use a bool to be true or false depending on the needed conditions. For example:

        if (CrossAbove(MACD(12, 26, 9), 0.0, 1))
        {
        buyFlag = true; // This flag means it is okay to buy and will remain true until reset with a buy condition.
        }

        if (macd > 0 && stochastic %k > 80 && buyFlag) // note used your pseudo code...
        {
        // buy code here
        buyFlag = false; // set this false so we only enter once in the macd up cycle
        }

        What the pseudo code above says is if the Macd crosses above the zero line, set the buyFlag to be true. To be able to place a buy order then the next line says if the MACD is >0 and stochastics %k is greater than 80 and the buyFlag = true, then place an order to buy, then reset the buyFlag so the buy code only executes once per macd up cycle. Actually you can remove the macd>0 condition because this condition is covered by the state of buyFlag.


        Please let me know if I can be of further assistance.
        Paul H.NinjaTrader Customer Service

        Comment


          #5
          Regarding the BuyFlag and ShortFlag, I should just set this up as a variables correct? So:

          for Long:

          BuyFlag = EnterLong()

          and for short

          SellFlag = EnterShort()

          Comment


            #6
            Hello eberline,

            Thanks for your reply.

            Let me clarify that the variables buyFlag and sellFlag were example variables, you can name them whatever suits you. The variables need to be declared as a bool because they need to be either a true or false condition.

            In the region "Variables" you would add:
            Code:
            private bool buyFlag= false;  // create. declare and initialize to false
            private bool sellFlag = false; // create. declare and initialize to false
            So your (up) code could look like:
            Code:
            if (Crossabove(MACD(12, 26, 9), 0.0, 1))
            { 
               buyFlag = true;  // enable ability to buy because Macd crossed above 0
               sellFlag = false; // disable ability to sell because Macd crossed above 0
            }
            
            if (buyFlag && Stochastics(7, 14, 3).K[0] > 80)  
            {
                EnterLong();   // BuyFlag and stochstics K are true so enter long
               buyFlag = false;  // reset buyFlag until next macd cross above
            }
            Please note that I used standard settings for macd and stochastics so you can change them as you need to.

            Please let me know if I can be of further assistance.
            Paul H.NinjaTrader Customer Service

            Comment


              #7
              works. Would like to add another condition

              Thank you so much for your help. The code works for buying.

              I would like to add another condition that states a sell order if a macd cross happens in the opposite direction or if stop loss limit is set. I've already initialized a stop loss that states SetStopLoss(50, false);

              Would this work for adding the macd condition:

              if (buyFlag && Stochastics(7, 14, 3).K[0] > 80)
              {
              EnterLong(); // BuyFlag and stochstics K are true so enter long
              if (CrossBelow(MACD(12, 26, 9).Avg, MACD(12, 26, 9), 1){
              exitLong();//Exit if MACD crossover occurs
              }

              buyFlag = false; // reset buyFlag until next macd cross above
              }

              Comment


                #8
                Hello eberline,

                Thanks for your reply.

                The code for the sell side would be the same but opposite of what I have been showing. Here then is the complete buy and sell side, please study carefully as while the code is similar on both sides there are subtle differences.

                Code:
                if (Crossabove(MACD(12, 26, 9), 0.0, 1))
                { 
                   buyFlag = true;  // enable ability to buy because Macd crossed above 0
                   sellFlag = false; // disable ability to sell because Macd crossed above 0
                }
                
                if (buyFlag && Stochastics(7, 14, 3).K[0] > 80)  
                {
                    EnterLong();   // BuyFlag and stochstics K are true so enter long
                   buyFlag = false;  // reset buyFlag until next macd cross above
                }
                
                if (CrossBelow(MACD(12, 26, 9), 0.0, 1))
                { 
                   buyFlag = false;  // disable ability to buy because Macd crossed below 0
                   sellFlag = true; // enable ability to sell because Macd crossed below 0
                }
                
                if (sellFlag && Stochastics(7, 14, 3).K[0] < 20)  // Assuming you want to enter stoch <20
                {
                    EnterShort();   // sellFlag and stochstics K are true so enter long
                   sellFlag = false;  // reset sellFlag until next macd cross above
                }
                For the SetStopLoss it is not clear what you are doing. I think what you are looking for is SetStopLoss ("",CalculationMode.Ticks, 50, false); // set a 50 tick stop loss. Here is the help guide reference: http://www.ninjatrader.com/support/h...etstoploss.htm
                Paul H.NinjaTrader Customer Service

                Comment


                  #9
                  Sell not working

                  Hi Paul,

                  Not sure why but after adding the selling, both the buying and selling are not working now. I double checked and when I remove the sell code, the buy code works. Here is the entire code:

                  protected override void OnBarUpdate()
                  {
                  //code working for buying
                  if (CrossAbove(MACD(12, 26, 9).Avg, MACD(12, 26, 9), 1))
                  {
                  buyFlag = true; // enable ability to buy because Macd crossed above 0
                  sellFlag = false; // disable ability to sell because Macd crossed above 0
                  }

                  if (buyFlag && Stochastics(7, 14, 3).K[0] > 80)
                  {
                  EnterLong(); // BuyFlag and stochstics K are true so enter long
                  buyFlag = false; // reset buyFlag until next macd cross above
                  }

                  //code added for selling
                  if (CrossBelow(MACD(12, 26, 9).Avg, MACD(12, 26, 9), 1))
                  {
                  buyFlag = false; // disable ability to buy because Macd crossed below 0
                  sellFlag = true; // enable ability to sell because Macd crossed below 0
                  }

                  if (sellFlag && Stochastics(7, 14, 3).K[0] < 20) // Assuming you want to enter stoch <20
                  {
                  EnterShort(); // sellFlag and stochstics K are true so enter long
                  sellFlag = false; // reset sellFlag until next macd cross above
                  }

                  //finished code added for selling
                  }

                  Question: Do you think maybe I need to separate the buying and selling into to sections with closed brackets?

                  Comment


                    #10
                    Hello eberline,,

                    Thanks for your reply.

                    Originally the MACD was crossing the zero line. If you would rather be using the MACD crossing the average line that should be fine, however as written you have the average line crossing the MACD line and that won't happen as the average line is the slow line.

                    So change: if (CrossAbove(MACD(12, 26, 9).Avg, MACD(12, 26, 9), 1))

                    to: if (CrossAbove(MACD(12, 26, 9), MACD(12, 26, 9).Avg, 1))

                    and change:

                    if (CrossBelow(MACD(12, 26, 9).Avg, MACD(12, 26, 9), 1))

                    to: if (CrossBelow(MACD(12, 26, 9), MACD(12, 26, 9).Avg, 1))

                    The logic conditions have changed and the results likely will be different so a good time to do a sanity check: With the correction made above, here is what will happen:

                    1) When the Macd line crosses above the average line the buyFlag will be set true and the sell flag set false.
                    2) If the stochastics K line is > 80 and if BuyFlag is true, enterlong will occur and the buyFlag will be set false prohibiting reentry until the Macd line crosses back up the average line.
                    3) When the MACD line crosses below the average line the sellFlag is set true and the buyFlag is set false.
                    4) if the stochastics K line goes less than 20 and the sellFlag is true then an enter short will be made and the sellFlag will be set false prohibiting reentry until the Macd line crosses back below the average line.

                    You will need to evaluate and adjust as you see the results.
                    Paul H.NinjaTrader Customer Service

                    Comment


                      #11
                      add macd crossover sell condition

                      Hi Paul,

                      The code works, thank you very much.

                      Now, instead of having a stop loss of 50, like I do now, I would like to add a condition to sell only if a cross occurs, either up or down.

                      So for example:

                      1. macd crosses up and %k > 80, only sell when macd crosses down.

                      Would the following code work:

                      if (CrossAbove(MACD(12, 26, 9), MACD(12, 26, 9).Avg, 1))
                      {
                      buyFlag = true; // enable ability to buy because Macd crossed above 0
                      sellFlag = false; // disable ability to sell because Macd crossed above 0
                      }

                      if (buyFlag && Stochastics(7, 14, 3).K[0] > 80)
                      {
                      EnterLong(); // BuyFlag and stochstics K are true so enter long

                      if (CrossBelow(MACD(12, 26, 9), MACD(12, 26, 9).Avg, 1)){
                      ExitLong();
                      }
                      buyFlag = false; // reset buyFlag until next macd cross above
                      }


                      Thank You.

                      Comment


                        #12
                        Hello eberline,

                        Thanks for your reply.

                        If I understand correctly, instead of the 50 tick stoploss you instead want to exit the position (long or short) on the opposite side macd cross.

                        You can use the same section (using the crossAbove as an example)
                        Code:
                        if (CrossAbove(MACD(12, 26, 9), MACD(12, 26, 9).Avg, 1))
                        { 
                        buyFlag = true; // enable ability to buy because Macd crossed above 0
                        sellFlag = false; // disable ability to sell because Macd crossed above 0
                        
                        if (Position.MarketPosition == MarketPosition.Short)  // test if in a short position first
                        {
                        ExitShort();  //  exit short position if macd crosses up.
                        }
                        }
                        You would add similar code but for the opposite direction in the crossbelow section.

                        Here is the helpguide reference to MarketPosition: http://www.ninjatrader.com/support/h...etposition.htm
                        Paul H.NinjaTrader Customer Service

                        Comment


                          #13
                          multiple long and short

                          Hi Paul,

                          i inserted the code. it works but the only problem is that it now sometimes executes multiple long and shorts, instead of just 1. So for example, now I see 2L and 3L in my executions list. Any idea why?

                          Thank You.

                          Comment


                            #14
                            Hello eberline,

                            Thanks for your reply and question.

                            The multiple entries are probably occurring because your stop or targets are not being hit before the next opportunity to enter arrives. There is no check prior to entry to see if you have a current position in the market.

                            Here again you can test for the being in a market position (long or short) or if you are Flat (no market position) prior to each entry condition. Using the same example for the entry condition:
                            Code:
                            if (Crossabove(MACD(12, 26, 9), 0.0, 1))
                            { 
                               buyFlag = true;  // enable ability to buy because Macd crossed above 0
                               sellFlag = false; // disable ability to sell because Macd crossed above 0
                            }
                            
                            if (buyFlag && Stochastics(7, 14, 3).K[0] > 80  [COLOR="Blue"]&& Position.MarketPosition == MarketPosition.Flat[/COLOR])  
                            {
                                EnterLong();   // BuyFlag and stochstics K are true so enter long
                               buyFlag = false;  // reset buyFlag until next macd cross above
                            }
                            So by adding "&& Position.MarketPosition == MarketPosition.Flat" we are adding the condition that says you must not have any positions (long or short) prior to entering long.

                            You would add exactly the same statement for the enter short section.
                            Paul H.NinjaTrader Customer Service

                            Comment


                              #15
                              Not exiting position

                              Hi Paul,

                              I put in the following code:

                              if (buyFlag && Stochastics(7, 14, 3).K[0] > 80 && Position.MarketPosition == MarketPosition.Flat)
                              {
                              EnterLong(); // BuyFlag and stochstics K are true so enter long
                              buyFlag = false; // reset buyFlag until next macd cross above

                              }

                              It didnt exit on a MACD cross. Could I instead put in the following:

                              if (buyFlag && Stochastics(7, 14, 3).K[0] > 80) //&& Position.MarketPosition == MarketPosition.Flat)
                              {
                              EnterLong(); // BuyFlag and stochstics K are true so enter long
                              if (CrossBelow(MACD(12, 26, 9), MACD(12, 26, 9).Avg, 1))
                              {
                              ExitLong();
                              }
                              buyFlag = false; // reset buyFlag until next macd cross above

                              }

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Waxavi, Today, 02:00 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post Waxavi
                              by Waxavi
                               
                              Started by elirion, Today, 01:36 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post elirion
                              by elirion
                               
                              Started by gentlebenthebear, Today, 01:30 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post gentlebenthebear  
                              Started by samish18, Yesterday, 08:31 AM
                              2 responses
                              9 views
                              0 likes
                              Last Post elirion
                              by elirion
                               
                              Started by Mestor, 03-10-2023, 01:50 AM
                              16 responses
                              391 views
                              0 likes
                              Last Post z.franck  
                              Working...
                              X