Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Strategy triggers multiple trades...

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

    Strategy triggers multiple trades...

    Hello,

    I have the following strategy, which uses CCI & SMA for buy & sell signals, and it also calls an ATM to move the stop:

    protected override void OnBarUpdate()
    {
    if(Historical)
    return;

    //Resets the stop loss to the original value when all positions are closed
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    SetStopLoss(CalculationMode.Ticks, Stop);
    }

    // Condition set 1
    if (ToTime(Time[0]) >= ToTime(8, 30, 0)
    && ToTime(Time[0]) <= ToTime(9, 30, 0)
    && CCICustom(CCIPeriod).Buy[0] > 50
    && CCICustom(CCIPeriod).Buy[1] < 50
    && SMA(Fast)[0] > SMA(Fast)[1]
    && SMA(Slow)[0] > SMA(Slow)[1]
    && SMA(Fast)[0] > SMA(Slow)[0])
    {
    AtmStrategyCreate(Action.Buy, OrderType.Market,0,0,
    TimeInForce.Day, GetAtmStrategyUniqueId(),"TestStrategy",
    GetAtmStrategyUniqueId());
    DrawVerticalLine("My vertical line" + CurrentBar, 0, Color.LimeGreen);
    Print("Went Long - Close:"+Close[0]);
    }

    // Condition set 2
    if (ToTime(Time[0]) >= ToTime(8, 30, 0)
    && ToTime(Time[0]) <= ToTime(9, 30, 0)
    && CCICustom(CCIPeriod).Sell[0] < -50
    && CCICustom(CCIPeriod).Sell[1] > -50
    && SMA(Fast)[0] < SMA(Fast)[1]
    && SMA(Slow)[0] < SMA(Slow)[1]
    && SMA(Fast)[0] < SMA(Slow)[0])
    {
    AtmStrategyCreate(Action.Sell, OrderType.Market,0,0,
    TimeInForce.Day, GetAtmStrategyUniqueId(),"TestStrategy",
    GetAtmStrategyUniqueId());
    DrawVerticalLine("My vertical line" + CurrentBar, 0, Color.Fuchsia);
    Print("Went Short - Close:"+Close[0]);
    }

    Currently, the way this is written, the strategy will trigger a trade if the conditions are met, whether or not it is already in a trade.
    How would I change the code, so that if the strategy triggers a trade, it won't trigger another trade until the current trade is over?

    #2
    Hi ghunt,

    When calling ATM Strategies, you'll want to use GetAtmStrategyMarketPosition() instead:
    TimNinjaTrader Customer Service

    Comment


      #3
      Thanks Tim,

      From the example you gave me:

      protected override void OnBarUpdate()
      {
      // Check if flat
      if (GetAtmStrategyMarketPosition("id") == MarketPosition.Flat)
      Print("ATM Strategy position is currently flat");
      }


      Where do I get the "id" from?

      Comment


        #4
        Hi ghunt,

        This is established with:


        As seen in the sample at "Tools>Edit NS>Strategy>SampleAtmStrategy"
        TimNinjaTrader Customer Service

        Comment


          #5
          Tim,

          Here is my code. I used the GetAtmMarketPosition() like you suggested:


          public class UDTRaderForCL : Strategy
          {
          #region Variables
          // Wizard generated variables
          private int fast = 6; // Default setting for Fast
          private int slow = 86; // Default setting for Slow
          private int cCIPeriod = 14; // Default setting for CCIPeriod
          private int stop = 22; // Default setting for Stop
          private int target = 24; // Default setting for Target
          // User defined variables (add any user defined variables below)
          private bool intrade = false;
          #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()
          {
          Add(CCICustom(CCIPeriod));
          Add(SMA(Fast));
          Add(SMA(Slow));
          SetProfitTarget("GoLong", CalculationMode.Ticks, Target);
          SetStopLoss("GoShort", CalculationMode.Ticks, Stop, false);
          CalculateOnBarClose = true;
          }

          /// <summary>
          /// Called on each bar update event (incoming tick)
          /// </summary>
          protected override void OnBarUpdate()
          {
          if(Historical)
          return;

          string orderId = GetAtmStrategyUniqueId();

          //Resets the stop loss to the original value when all positions are closed
          if (GetAtmStrategyMarketPosition(orderId) == MarketPosition.Flat)
          {
          SetStopLoss(CalculationMode.Ticks, Stop);
          intrade = false;
          }

          // Strategy logic for Long entries
          if (ToTime(Time[0]) >= ToTime(8, 30, 0)
          && ToTime(Time[0]) <= ToTime(12, 30, 0)
          && CCICustom(CCIPeriod).Buy[0] > 50
          && CCICustom(CCIPeriod).Buy[1] < 50
          && SMA(Fast)[0] > SMA(Fast)[1]
          && SMA(Slow)[0] > SMA(Slow)[1]
          && SMA(Fast)[0] > SMA(Slow)[0]
          && intrade==false)
          {
          //MUST have an ATM Strategy named "TestStrategy" If using a different ATM, you must change "TestStrategy" in this code to the name of the ATM Strategy you are using.
          AtmStrategyCreate(Action.Buy, OrderType.Market,0,0,
          TimeInForce.Day, GetAtmStrategyUniqueId(),"TestStrategy",
          GetAtmStrategyUniqueId());
          BackColorAll = Color.PaleGreen;
          Print("Went Long - Close:"+Close[0]);
          intrade = true;
          }

          // Strategy logic for Short entries
          if (ToTime(Time[0]) >= ToTime(8, 30, 0)
          && ToTime(Time[0]) <= ToTime(9, 30, 0)
          && CCICustom(CCIPeriod).Sell[0] < -50
          && CCICustom(CCIPeriod).Sell[1] > -50
          && SMA(Fast)[0] < SMA(Fast)[1]
          && SMA(Slow)[0] < SMA(Slow)[1]
          && SMA(Fast)[0] < SMA(Slow)[0]
          && intrade==false)
          {
          //MUST have an ATM Strategy named "TestStrategy" If using a different ATM, you must change "TestStrategy" in this code to the name of the ATM Strategy you are using.
          AtmStrategyCreate(Action.Sell, OrderType.Market,0,0,
          TimeInForce.Day, GetAtmStrategyUniqueId(),"TestStrategy",
          GetAtmStrategyUniqueId());
          BackColorAll = Color.Pink;
          Print("Went Short - Close:"+Close[0]);
          intrade = true;
          }


          }

          I am using this code...

          //Resets the stop loss to the original value when all positions are closed
          if (GetAtmStrategyMarketPosition(orderId) == MarketPosition.Flat)
          {
          SetStopLoss(CalculationMode.Ticks, Stop);
          intrade = false;
          }

          to make sure stop is set to original stop when it enters a trade, and to set a variable is defined as "intrade" to false, meaning that I'm not in a trade.

          The variable "intrade" is initially set to false and should be set to true when the conditions are met for a long or short trade. It should remain "true" until a trade is finished. this does not work. When I use this strategy on replay or live data, it will enter a 2nd trade if conditions are met, even while in a prior position. Any help would be appreciated.

          Comment


            #6
            Hi ghunt,

            In your order creation...
            AtmStrategyCreate(Action.Buy,OrderType.Market,0,0, TimeInForce.Day,GetAtmStrategyUniqueId(),"TestStra tegy",GetAtmStrategyUniqueId());

            You get, or create another UniqueId, instead, use the one you've already created, "orderId".

            Track the bool with Print()'s to see if it is changing as you expect it to.
            TimNinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_Tim View Post
              Hi ghunt,

              In your order creation...
              AtmStrategyCreate(Action.Buy,OrderType.Market,0,0, TimeInForce.Day,GetAtmStrategyUniqueId(),"TestStra tegy",GetAtmStrategyUniqueId());

              You get, or create another UniqueId, instead, use the one you've already created, "orderId".
              Would I do it this way:

              AtmStrategyCreate(Action.Buy, OrderType.Market,0,0, TimeInForce.Day, GetAtmStrategyUniqueId(orderId),"TestStrategy", GetAtmStrategyUniqueId(orderId));

              or this way:

              AtmStrategyCreate(Action.Buy, OrderType.Market,0,0, TimeInForce.Day, orderId,"TestStrategy", orderId);


              Thanks for your help

              Comment


                #8
                Hi ghunt,

                Each of these need to be established/created in the code as in the sample. They both will use GetAtmStrategyUniqueId() to create it.

                AtmStrategyId = GetAtmStrategyUniqueId();
                orderId = GetAtmStrategyUniqueId();

                AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", atmStrategyId);
                TimNinjaTrader Customer Service

                Comment


                  #9
                  Thanks Tim,
                  When I used the following code, per your code sample:
                  AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", atmStrategyId);
                  I got the following error message upon compile:
                  The type or namespace name 'OrderAction' does not exist in the namespace 'NinjaTrader.Cbi' (are you missing an assembly reference?)
                  I changed the code to:
                  AtmStrategyCreate(Action.Buy, OrderType.Market,0,0, TimeInForce.Day, orderId, "TestStrategy", AtmStrategyId);
                  The compile was successful. Have not tested it yet. Seems the difference between the two lines of code is: Cbi.OrderAction.Buy -vs- Action.Buy. Have not tested it yet. If you think I need to use Cbi.OrderAction.Buy, what would I need to do to compile it without the error message?
                  Thanks!

                  Comment


                    #10
                    Hi ghunt,

                    Your second implementation is correct, please see the syntax here:
                    TimNinjaTrader Customer Service

                    Comment


                      #11
                      Thanks Tim!

                      I will test the strategy - it should work as planned!!

                      Comment


                        #12
                        Tim,

                        Well, something is still wrong...here is my current code:

                        protected override void Initialize()
                        {
                        Add(CCICustom(CCIPeriod));
                        Add(SMA(Fast));
                        Add(SMA(Slow));
                        SetProfitTarget("GoLong", CalculationMode.Ticks, Target);
                        SetStopLoss("GoShort", CalculationMode.Ticks, Stop, false);
                        CalculateOnBarClose = true;
                        }

                        /// <summary>
                        /// Called on each bar update event (incoming tick)
                        /// </summary>
                        protected override void OnBarUpdate()
                        {
                        if(Historical)
                        return;

                        string AtmStrategyId = GetAtmStrategyUniqueId();
                        string orderId = GetAtmStrategyUniqueId();


                        //Resets the stop loss to the original value when all positions are closed
                        if (GetAtmStrategyMarketPosition(AtmStrategyId) == MarketPosition.Flat)
                        {
                        SetStopLoss(CalculationMode.Ticks, Stop);
                        intrade = false;
                        Print("Intrade after setting stop to original stop = "+intrade);
                        }

                        // Strategy logic for Long entries
                        if (ToTime(Time[0]) >= ToTime(8, 30, 0)
                        && ToTime(Time[0]) <= ToTime(16, 0, 0)
                        && CCICustom(CCIPeriod).Buy[0] > 50
                        && CCICustom(CCIPeriod).Buy[1] < 50
                        && SMA(Fast)[0] > SMA(Fast)[1]
                        && SMA(Slow)[0] > SMA(Slow)[1]
                        && SMA(Fast)[0] > SMA(Slow)[0]
                        && intrade==false)
                        {
                        //MUST have an ATM Strategy named "TestStrategy"
                        AtmStrategyCreate(Action.Buy, OrderType.Market,0,0, TimeInForce.Day,
                        orderId, "TestStrategy", AtmStrategyId);
                        BackColorAll = Color.PaleGreen;
                        Print("Went Long - Close:"+Close[0]);
                        intrade = true;
                        Print("Intrade, after going long = "+intrade);
                        }

                        Here is what's happening: Once the strategy starts running I get the following log entry - "GetAtmStrategyMarketPosition() method error: AtmStrategyId 'fde9fc2b665f4d7ea5858309e784a141' does not exist. This comes on every completed bar, (with a different id no. each time) until the conditions are met and it goes long (or short). Right after it places the order, it prints out my bool variable "intrade" as True (as it should). But on the next bar, it prints out the variable "intrade" as False, even though it is still in a trade!

                        Seems to me that the problem is in this code:

                        protected override void OnBarUpdate()
                        {
                        if(Historical)
                        return;

                        string AtmStrategyId = GetAtmStrategyUniqueId();
                        string orderId = GetAtmStrategyUniqueId();


                        //Resets the stop loss to the original value when all positions are closed
                        if (GetAtmStrategyMarketPosition(AtmStrategyId) == MarketPosition.Flat)
                        {
                        SetStopLoss(CalculationMode.Ticks, Stop);
                        intrade = false;
                        Print("Intrade after setting stop to original stop = "+intrade);


                        I don't think I am using GetAtmStrategyUniqueID() right, because of the log error messages and it seems that (GetAtmStrategyMarketPosition(AtmStrategyId) == MarketPosition.Flat) always evaluates to Flat, because "intrade" is always set to false, even while in a trade.

                        Any ideas??
                        Last edited by ghunt; 07-27-2010, 03:49 PM.

                        Comment


                          #13
                          The problem is these lines of your code:

                          string AtmStrategyId = GetAtmStrategyUniqueId();
                          string orderId = GetAtmStrategyUniqueId();

                          You are setting new ID values on every single OnBarUpdate() event. You will not be able to do it like that. You should only set new values when you are ready to use a new ATM strategy. Setting it like that on every single OnBarUpdate() means you lose all tracking of your prior ATM strategy.

                          Please see SampleAtmStrategy for the if-statements on how it decides when to set AtmStrategyId and orderId. It only does so when they are null or empty. That state is only achieved when the ATM strategy has completed its trade.
                          Josh P.NinjaTrader Customer Service

                          Comment


                            #14
                            Thanks Josh,

                            The problem is these lines of your code:

                            string AtmStrategyId = GetAtmStrategyUniqueId();
                            string orderId = GetAtmStrategyUniqueId();

                            You are setting new ID values on every single OnBarUpdate() event. You will not be able to do it like that. You should only set new values when you are ready to use a new ATM strategy. Setting it like that on every single OnBarUpdate() means you lose all tracking of your prior ATM strategy.
                            That was the problem. I moved the lines of code from OnBarUpdate() to just above AtmStrategyCreate(xxxxxxxxxx). I also put GetAtmStrategyMarketPosition(AtmStrategyId) == MarketPosition.Flat into the conditions that must be true for the strategy to enter a trade.

                            I tested it on 4 days worth of Market Replay data and the strategy works as I had planned!

                            Thanks to you & Tim for your help!

                            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