Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Sync strategy after disabling it

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

    Sync strategy after disabling it

    What the strategy does
    - The strategy is active long term, traded via a VPS and may hold a position for months
    - Checks if market position is flat and then submits a buy order when certain conditions are met + a stop loss order at the same time
    - Checks if market position is long and then closes position if certain conditions are met
    - Order quantity is calculated by an int TradeSize()

    What I want to achieve / What the problem is
    - I need to be able to deactivate a running strategy (for e.g. server updates/restarts etc) and to reactivate it
    - Running strategy particularly means the strategy has one open long position and one stopp loss order (when strategy is flat syncing seems not to be a problem)
    - I need the strategy to commence from where it stopped, which means:
    a) It must not cancel the stopp loss order when I reactivate the strategy or sell the open position
    b) It must close an open position when the conditions as specified are met going forward
    c) It must not open new additional long positions until the strategy is flat again

    What I tried
    - I was researching the internet, the NT8 guide and especially this forum for days and I still can't make it work:
    • I tried to reactive the strategy with "Wait until flat": Strategy turns yellow, sync tab shows "False" and the pending stopp loss gets cancelled
    • I tried to reactive the strategy with "Wait until flat (sync account)": Strategy turns yellow, sync tab shows "True", open position gets closed and my stopp gets cancelled
    • I tried to reactive the strategy with "Immediately submit": Sometimes it seems to work (while columns: "avg. price" and "unrealised show" different values on the strategy and the positions tab and the stopp loss sometimes has a different value), sometimes also strange things happen: stopp loss remains, strategy turns green but account position is not recognised (=0) even though a position exists and sync tab says "False". Obviously NT can’t allocate the account position to the strategy
    • I tried to reactive the strategy with "Immediately submit (sync account)": Shows same result as "Immediately submit"
    • I tried to reactive the strategy with "AdoptAccountPosition": Strategy turns green, sync tab shows "False", open position is recognised but strategy position is not recognised (=0) even though it should be long, stopp loss gets cancelled. There are also occasions where it syncs just fine but the stopp is gone.

    Conclusion
    I believe that "wait until flat“ will not bring me anywhere, so I do concentrate on "Immediately submit" and "AdoptAccountPosition" methods, however I believe I need to adjust the code in order to make things work properly. This is particularly difficult for the "AdoptAccountPosition" option, as the help guide says "Only set to true if you have specifically programmed your strategy to be able to adopt account positions.", but I couldn’t find any documentation how to do that. I would greatly appreciate your help with solving this issue!
    Last edited by sagetrade; 11-11-2017, 09:10 AM.

    #2
    Hello sagetrade,

    To confirm, you are wanting a strategy to resume previously placed orders and positions when re-enabled, is this correct?

    Below is a link to a forum post where I have detailed what is necessary for NinjaTrader to attempt to resume a strategy.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hello Chelsea,

      Yes that is what I want to achieve.

      I have read through that thread you linked before I opened this thread, but it doesn't help me unfortunately.

      I will never be able to ensure that the historical trades match the real time trades. The reason is that the strategy might find that conditions for a BUY are true 1st of Oct 3rd of Oct 6 of Oct and 12th of Oct.

      If I start my strategy End of September a trade will be placed on the 1st of Oct, but if I will start it only on the 5th Oct it will go long only on the 6th. However, if i backtest the strategy it will still assume that 1st of Oct is the trade entry date and the actual account position will look different as it was opened on another day with another quantity at another price etc.

      All I want the strategy to do is: Close the open position when conditions are met and keep either the initial stop loss or (if that is easier to achieve) recalculate the stop loss based on an actual indicator value.

      Comment


        #4
        Hello,

        Thank you for the reply.

        I wanted to get some clarification here on the following statement:

        If I start my strategy End of September a trade will be placed on the 1st of Oct, but if I will start it only on the 5th Oct it will go long only on the 6th. However, if i backtest the strategy it will still assume that 1st of Oct is the trade entry date and the actual account position will look different as it was opened on another day with another quantity at another price etc.
        The first part of your statement is important:
        If I start my strategy End of September a trade will be placed on the 1st of Oct, but if I will start it only on the 5th Oct it will go long only on the 6th
        I would expect the strategy to have different outcomes in case its dataseries has changed to new dates. Generally a strategies output should change based on the data that was input. Because the data to produce the trade on the first was not present, it was not possible to simulate that trade to proceed down the same path. For the strategy to place the same series of trades again in the same order, it would need to remain on the same data as it started with before you disabled it.

        However, if i backtest the strategy it will still assume that 1st of Oct is the trade entry date and the actual account position will look different as it was opened on another day with another quantity at another price etc.
        The latter part of that message you have noted that you are comparing backtesting. Are you referring to changing the timeframe of the chart which in turn is changing the result of the historical trades placed by the strategy? Or are you instead comparing the strategy analyzer to a test that was run on a chart? I would still expect differences in case there were differences in data between the two tests. In case the analyzer was not started at the same specific time as the test you had talked about, there would likely be differences but there could be other differences in these tests such as granularity differences for fills among other items.

        I look forward to being of further assistance.
        JesseNinjaTrader Customer Service

        Comment


          #5
          Dear Jesse,

          please forget my last post I was just trying to explain the problem further, which probably caused more confusion than it shed light onto the issue. My goal is simple: I want to have a synced strategy upon restart including a SL that is protecting my position.

          I made some nice progress with regards to that problem:

          I use AdoptAccountPosition, start a strategy, this strategy is opening a long position and a corresponding StopLoss. Now if I disable the strategy and reenable, it can't sync. But if I cancel the StopLoss and then restart, it will be in sync, but my SL is gone.

          So what I did, I found some useful code in THIS THREAD from Alan, which I now use to recalculate a corresponding SL. It seems to work and after a restart, my position is protected again (next bar update, but fine can live with that). Now this looks as follows: If I disable the strategy, I cancel the SL manually, reenable the strategy and it is synced (SL is gone). But on the first bar close it calculates a new SL.

          In principle this is a solution for me, the only problem that Im experiencing now is that I get error messages like the below and I can't understand the cause. It seems to occur right after a long position is opened and the corresponding SL is set.
          Attached Files
          Last edited by sagetrade; 10-30-2017, 02:46 PM.

          Comment


            #6
            Hello,

            Thank you for clairifing.

            In this case this is not an error but simply a note letting you know the order was ignored based on the internal order handling rules. Because you are using the Managed approach, specific orders can be ignored based on the logic you are trying to use.

            Here is the page for the managed approach that shows the various rules https://ninjatrader.com/support/help...antedPositions

            Without seeing the logic I couldn't say which specific rule you are hitting, but there are descriptions of each which will make it easy for you to determine what part of your logic is causing the warning.

            To avoid this message, you would need to correct the logic to prevent that situation from happening. Alternatively, if you need more control over the orders past what the managed approach can offer, you would instead need to use the unmanaged approach which does not have these rules but does require that you take 100% control over the strategies logic.

            I look forward to being of further assistance.
            JesseNinjaTrader Customer Service

            Comment


              #7
              Dear Jesse,

              thanks for your reply. I wasn't able to detect the cause of the warning. I would also prefer to keep my hands off the unmanaged approach. Please see my code logic below, maybe you spot something:

              public class LongDevelop : Strategy
              {

              private bool DoOnceLong = false;
              private Order slLongOrder = null;

              protected override void OnStateChange()
              {
              if (State == State.SetDefaults)
              {
              Description = @"Description";
              Name = "LongDevelop";
              Calculate = Calculate.OnBarClose;
              EntriesPerDirection = 1;
              EntryHandling = EntryHandling.AllEntries;
              IsExitOnSessionCloseStrategy = false;
              ExitOnSessionCloseSeconds = 30;
              IsFillLimitOnTouch = false;
              MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
              OrderFillResolution = OrderFillResolution.Standard;
              Slippage = 0;
              StartBehavior = StartBehavior.AdoptAccountPosition;
              IsAdoptAccountPositionAware = true;
              TimeInForce = TimeInForce.Gtc;
              TraceOrders = false;
              RealtimeErrorHandling = RealtimeErrorHandling.IgnoreAllErrors;
              StopTargetHandling = StopTargetHandling.ByStrategyPosition;
              BarsRequiredToTrade = 202;

              // Disable this property for performance gains in Strategy Analyzer optimizations
              // See the Help Guide for additional information
              IsInstantiatedOnEachOptimizationIteration = true;

              }
              else if (State == State.Configure)
              {

              }
              else if (State == State.DataLoaded)
              {

              }
              }

              protected override void OnBarUpdate()
              {
              if (CurrentBars[0] <= BarsRequiredToTrade)
              return;

              // Open New Trades
              if (Position.MarketPosition == MarketPosition.Flat)
              {
              // Condition set 1
              {
              EnterLong(TradeSize(), "Buy Long");
              SetStopLoss(CalculationMode.Price, IndicatorValue[0]);
              }
              }

              // Exit Open Trades
              if (Position.MarketPosition == MarketPosition.Long)
              {
              //Condition set 2
              {
              ExitLong("Exit Long", "");
              }
              }

              ///AdoptAccountPosition Code
              if(State == State.Historical) return;

              Print(State.ToString() + PositionsAccount[0].Quantity.ToString());
              Print(PositionsAccount[0].MarketPosition.ToString());

              //If account position is long upon starting strategy, submit a SL order for the open position.
              if(PositionsAccount[0].MarketPosition == MarketPosition.Long && DoOnceLong == false)
              {
              Print("Position is long");
              ExitLongStopMarket(0, true, PositionsAccount[0].Quantity, amaSuperTrendU111.StopDot[0], "Stop Loss II", "");
              DoOnceLong = true;
              }

              //Should 1 SL or manual order close the position, then need to cancel orders.
              if(PositionsAccount[0].MarketPosition == MarketPosition.Flat)
              {
              Print("Cancel all orders");

              if(slLongOrder != null);
              {
              CancelOrder(slLongOrder);
              slLongOrder = null;
              }
              }
              }

              ///AdoptAccountPosition Code
              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
              {
              //Assiging order objects to SL for the purpose of canceling orders if the position becomes flat.
              if (order.Name == "Stop Loss II" && orderState != OrderState.Accepted )
              slLongOrder = order;
              }

              Comment


                #8
                Hello,

                Thank you for the reply.

                It looks like this logic can cause the warning you are seeing.

                In this situation, you have the logic to Enter Long and submit a Stop Loss. Later you check if you are Long and if so you submit a ExitLongStopMarket order. This is noted in the internal order handling rules as a situation that will be ignored:

                Methods that generate orders to exit a position will be ignored if:
                A position is open and an order submitted by a set method (SetStopLoss() for example) is active
                The ExitLongStopMarket is ignored in case the SetStopLoss is active. Because I don't know the specifics of the test where this occurred from you, this would be my guess at where the ignored warning came from. You can test this situation pretty easy to see the warning with TraceOrders enabled.



                If you wanted to continue using the ExitLongStopMarket where you have, you would need to ensure there are no active SetStopLoss orders prior to submitting it. You can cancel the SetStopLoss order using CancelOrder but you would need to collect its Order object from OnOrderUpdate prior to doing that.

                I look forward to being of further assistance.
                JesseNinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by NinjaTrader_Jesse View Post

                  If you wanted to continue using the ExitLongStopMarket where you have, you would need to ensure there are no active SetStopLoss orders prior to submitting it. You can cancel the SetStopLoss order using CancelOrder but you would need to collect its Order object from OnOrderUpdate prior to doing that.

                  I look forward to being of further assistance.
                  I wouldn't want to cancel it but rather want to add a condition that in case of an active SetStopLoss do nothing. Is there an easy way to add that to the code?

                  Comment


                    #10
                    Hello,

                    In the case of an active stop loss, you could use a bool to delegate that or as noted previously you would need to use OnOrderUpdate to populate a variable with the Order object if you wanted to use that instead.

                    A bool is likely easiest, if you have called the logic with SetStopLoss, you could set the bool to true, if that is true do not submit the other order, otherwise if false submit it.

                    You could also use OnOrderUpdate and Order objects to control your logic more accurately. The following sample shows how to access orders from OnOrderUpdate and OnExecutionUpdate: https://ninjatrader.com/support/foru...ead.php?t=7499

                    This would be another way to delegate your logic based on what orders are being submitted or filled. In OnOrderUpdate you could look for an order with the name of your StopLoss order, and then store it in a variable. Later in your logic, you could check if this variable is null, and if so submit the other order, otherwise if it is not null you know the stop loss has been submitted so you can avoid submitting the other order. Using this approach you would also need to observe the fill/cancellation for the stop to set the Order variable back to null when appropriate.

                    I look forward to being of further assistance.
                    JesseNinjaTrader Customer Service

                    Comment


                      #11
                      Syncing strategy stoploss after disable

                      I'd like to bump this topic back up, and add my vote to solve the important issue sagetrade have raised:
                      I want to have a synced strategy upon restart including a SL that is protecting my position
                      I can't emphasize enough how much this capability is missing and not just for SL but to Profit Targets and Trailing stops as well - so please count my vote to offer a solution for this.

                      Right now, I'm using a very inconvenient AddOn hack that cancels all supplementary orders on all open positions before I enable all strategies, and initialize each strategy with the appropriate SL/PT/TS orders from an external database (again, using a shared-state static AddOn). I'm sure you can imagine the possible horrific scenarios this can end with...

                      A minimal solution, for starters, would be to not block me from syncing a strategy with open orders - even if I have to programatically scan all orders and assign those to their relevant strategy on initialization. Just a suggestion.

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by ScottWalsh, 04-16-2024, 04:29 PM
                      7 responses
                      34 views
                      0 likes
                      Last Post NinjaTrader_Gaby  
                      Started by cls71, Today, 04:45 AM
                      0 responses
                      1 view
                      0 likes
                      Last Post cls71
                      by cls71
                       
                      Started by mjairg, 07-20-2023, 11:57 PM
                      3 responses
                      213 views
                      1 like
                      Last Post PaulMohn  
                      Started by TheWhiteDragon, 01-21-2019, 12:44 PM
                      4 responses
                      544 views
                      0 likes
                      Last Post PaulMohn  
                      Started by GLFX005, Today, 03:23 AM
                      0 responses
                      3 views
                      0 likes
                      Last Post GLFX005
                      by GLFX005
                       
                      Working...
                      X