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

Strategy Multi-Time Frame with gain-loss

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

    Strategy Multi-Time Frame with gain-loss

    Hi,

    first of all, I apologize for my English, I hope the question is understandable. I attach my strategy so that my questions are clearer (I put further strategy considerations highlighted with a double comment).

    I created a Multi-Time Frame strategy with ninjiascript 8, which uses 1 minute bars as "primary bars" and 1 bar as "secondary bars".
    My goal is to use 1 minute bars for analysis and 1 bar for trading. To do this I used a Boolean "control" variable that allows me not to scroll the bars with 1 tick until the strategy is active.
    Once the strategy comes into play, the problems begin.

    1) When the "control" variable becomes true at the end of minute X of the "primary bars", I have not been able to understand whether the "secondary bars" start from time X or from time X + 1 (as it would be in reality).
    2) I tried the strategy on Futures ESM2020 of 29 April 2020, the result of the simulated strategy in Matlab gave me the following results:
    - Enter long: 00:12 and 00:13 used as condition to primary bars; 00:14 used as secondary bars for trading.
    - Enter to tick in second: 00:14:32 at the exact price of 2869.75 (=Highs[0][0])
    - Exit to tick in second: 00:14:43 with stop-loss at 2868.00 (=Lows[0][0])

    I should go out with the stop loss instead the exit is this:

    DATE-TIME: 29/04/2020 00:12:00
    HIGH[1]: 2870,5
    LOW[1]: 2869
    DATE-TIME: 29/04/2020 00:13:00
    HIGH[0]: 2869,75
    LOW[0]: 2868
    gain_lose_gap: 1,75
    enter_level: 2869,75
    exit_level: 2868
    gain_level: 2871,5
    Print pre-order: 29/04/2020 00:13:01
    29/04/2020 00:13:01 Strategy 'ProvaLongPosition4/200517373': Entered internal SubmitOrderManaged() method at 29/04/2020 00:13:01: BarsInProgress=1 Action=Buy OrderType=StopLimit Quantity=1 LimitPrice=2869,75 StopPrice=2869,75 SignalName='My_first_strategy' FromEntrySignal=''
    Print post-order 29/04/2020 00:13:01
    29/04/2020 00:13:32 Strategy 'ProvaLongPosition4/200517373': Entered internal SubmitOrderManaged() method at 29/04/2020 00:13:32: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=2868,00 SignalName='exit' FromEntrySignal='My_first_strategy'
    29/04/2020 00:13:32 Strategy 'ProvaLongPosition4/200517373': Entered internal SubmitOrderManaged() method at 29/04/2020 00:13:32: BarsInProgress=1 Action=Sell OrderType=Limit Quantity=1 LimitPrice=2871,50 StopPrice=0 SignalName='gain' FromEntrySignal='My_first_strategy'
    29/04/2020 00:13:43 Strategy 'ProvaLongPosition4/200517373: Cancelled pending exit order, since associated position is closed, orderId='NT-00002-48' account='Sim101' name='gain' orderState=Working instrument='ES 06-20' orderAction=Sell orderType='Limit' limitPrice=2871.5 stopPrice=0 quantity=1 tif=Day oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-04-29 00:13:32' gtd='2099-12-01' statementDate='2020-05-10'
    Attached Files

    #2
    Hi Apo84,
    I had a quick look at your code. Calculate.OnBarClose is likely not the best setting if you use the longer time frame as primary data series. To use Ticks as primary data series or Calculate.OnEachTick is probably better.

    I'd recommend to start with building a strategy using the StrategyBuilder with a primary and a secondary data series. Throw in a few conditions referring to the primary and some to the secondary data series, then press view code and compare what you see to your NinjaScript code. You will notice a lot of things. For example that this here is not true:

    "// CASO 2
    if ( Close[0]<exit_level ) //// Close[0] is value of single tick"

    You can copy/paste code snippets from the StrategyBuilder version to your NinjaScript version and thereby benefit from coding assistance (behind the scenes) from StategyBuilder.
    NT-Roland
    Last edited by NT-Roland; 05-10-2020, 10:27 AM.

    Comment


      #3
      Thank you very much for your reply.
      Is it better to use Calculate.OnBarClose with tick as the first data series and the minute as the second data series or that you use Calculate.OnEachTick with the minute as the first data series and the tick as the second data series?

      Comment


        #4
        Hi Apo84,
        I myself would use the minute as primary data series and tick as secondary.
        If you want more granularity, you can always "upgrade" and either use Calculate.OnPriceChange or Calculate.OnEachTick.
        By contrast to Calculate.OnEachTick, Calculate.OnPriceChange will run the OnBarUpdate (only) when the price changes.
        The combination of Calculate.OnBarClose and one tick as primary series is somewhat redundant. Each tick is O-H-L-C at the same time.
        NT-Roland

        Comment


          #5
          Thanks again for the answer. I will use the minute as the first data series and the tick for the second with Calculate.OnPriceChange or Calculate.OnEachTick. Itry strategy.builder and I'll tell you how it went. I can ask you for documentation to understand if an order is active, has gone in gain or in stop-loss.

          Comment


            #6
            Hello Apo84,

            I'm including a link to a forum post about intra-bar granularity which you may also find helpful.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Thanks for the reply.
              I read the discussion in the link. (https://ninjatrader.com/support/foru...377#post773377)
              If I understand correctly I can have a strategy that combines backtesting analysis with real-time action.
              Then:
              - I use minute data as a primary series;
              - I use tick data as a secondary series;
              - I use OnPriceChange or OnEachTick as Calculate;
              - I use IsFirstTickOfBar so that the conditions for trading (EnterLong, ...) are applied with the minute bar closed;
              - I have to set the TickReplay option;

              It's correct?
              Is there an example I can follow?

              Thanks Alberto

              Comment


                #8
                Hello Apo84,

                The example we have uses 1 tick intra-bar granularity, which works historically and in real-time. The SampleIntraBarBacktest_NT8 linked from this post is the example that demonstrates this. TickReplay can be necessary to drive indicators in real-time historically specifically.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Thanks again for the reply

                  I studied OnBarUpdate, OnMarketData. I did printing tests with and without TickReplay. I also read the forum a lot. I still have several doubts.
                  Questions:
                  1) What are the differences between OnBarUpdate and OnMarketData as regards backtesting work and real time work? If I use OnBarUpdate with Ticks as data series and Calculate.OnEachTick, is the same as OnMarketData?
                  2) Is TickReplay just for viewing data?
                  3) If I was only interested in trading I could use OrderFillResolution HIGH or alternatively insert ticks as a secondary series with Calculate.OnEachTick? it's the same thing?

                  Thanks Alberto

                  Comment


                    #10
                    Hello Alberto,

                    When adding a 1 tick series with AddDataSeries(), this allows OnBarUpdate to process for every tick allowing for intra-bar actions, and can be provided as the BarsInProgress id to use as data for an order entry to increase the accuracy of order fills. This is allowing for intra-bar actions even when Calculate is OnBarClose in both historical data and in real-time.

                    TickReplay is a new introduction in NinjaTrader 8 that just allows for scripts to allow the Calculate.OnEachTick and Calculate.OnPriceChange to trigger OnBarUpdate in historical data only. This cannot be used for increasing accuracy with order fills. This is often useful for indicators that must update for every tick such as ones that collect volume.

                    OrderFillResolution is also a new introduction in NinjaTrader 8 that allows for orders to fill with increased accuracy. This does not cause OnBarUpdate() to trigger intra-bar historically when Calculate is .OnEachTick or .OnPriceChange. OrderFillResolution set to high cannot work with TickReplay.


                    For both Calculate to work historically with .OnEachTick and .OnPriceChange and also have high fill accuracy, TickReplay and coding the addition of a 1 tick series with AddDataSeries() is necessary.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Thanks for your help.

                      I finally managed to advance in the project.
                      With:
                      - OnEachTick
                      - primary data series: minute
                      - secondary data series: tick
                      - TickReplay: active
                      The problem: with a tick granularity, when I want the end of minute values (Open [0], High [0], Low [0], Close [0]) for some conditions, I often get half-candle values.
                      I guess there is an answer in the forum, but I haven't found it

                      Thanks Alberto

                      Comment


                        #12
                        Hello Alberto,

                        If you have Calculate set to OnEachTick with TickReplay enabled this would be updating on each tick before the bar closes intra-bar.
                        Since this is before the bar closes, the values can change while the bar is open and is still building.

                        Are you only wanting the values when the bar closes and not the intra-bar values?

                        Are you trying to trigger actions intra-bar?
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Thanks for the quick response.

                          Originally posted by NinjaTrader_ChelseaB View Post
                          Are you only wanting the values when the bar closes and not the intra-bar values?

                          Are you trying to trigger actions intra-bar?
                          For the condition I want values when the bar is close. After if the conditions are true I want also trigger actions intra-bar.

                          // These checks must be done on closing the primary bar (minute bar):
                          if ( control==false
                          && ( (Low[1] > SMA1[1])
                          && (Low[0] <= Low[1])
                          && (High[0] < High[1])
                          && (Math.Abs(Open[1] - Close[1]) > 0)
                          && (Math.Abs(Open[0] - Close[0]) > 0)
                          && ( (Open[0] <= Open[1] && Open[0] >= Close[1])
                          || (Open[0] >= Open[1] && Open[0] <= Close[1]) ) )
                          )
                          {
                          // Here I operate on the tick intr-bar

                          EnterLongStopLimit(1,true,1, enter_level, enter_level, @"EnterLong1");
                          }

                          Last edited by Apo84; 05-13-2020, 01:52 PM.

                          Comment


                            #14
                            Hello Apo84,

                            When Calculate is .OnEachTick, require IsFirstTickOfBar to be true to trigger actions only after a bar has closed.
                            https://ninjatrader.com/support/help...ttickofbar.htm

                            If you want the previous fully closed bar use barsAgo 1.
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Thanks for the answer, it helped me a lot.

                              For a long order with a precise price, I use:
                              EnterLongStopLimit with the same price for stopPrice and limitPrice.

                              Is there another way to get an order at a specific price?
                              Because sometimes if the opening price from the next bar is equal to stopPrice, the order is canceled.
                              Can I manage the cancellation?

                              Thanks Alberto

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by r68cervera, Today, 05:29 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post r68cervera  
                              Started by geddyisodin, Today, 05:20 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post geddyisodin  
                              Started by JonesJoker, 04-22-2024, 12:23 PM
                              6 responses
                              35 views
                              0 likes
                              Last Post JonesJoker  
                              Started by GussJ, 03-04-2020, 03:11 PM
                              12 responses
                              3,239 views
                              0 likes
                              Last Post Leafcutter  
                              Started by AveryFlynn, Today, 04:57 AM
                              0 responses
                              6 views
                              0 likes
                              Last Post AveryFlynn  
                              Working...
                              X