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

Entering Twice with Candlestick Pattern

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

    Entering Twice with Candlestick Pattern

    NinjaTrader Support,

    I am trying to code a strategy where I enter long when a candlestick pattern forms. I then take profit at the first profitable close.

    However if the strategy shows a loss of -$100 and the candlestick pattern forms again, I want to add to my position.

    I can't get that part of the strategy to work, it always just goes long with both contracts.

    Code and screenshot below:

    protected override void OnBarUpdate()
    {

    //Gets Strategy Unrealized PL
    currentPnL = SystemPerformance.AllTrades.TradesPerformance.NetP rofit;

    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 3)
    return;

    // Set 1
    if <pattern>
    {
    EnterLong(1, 10000, "Enter Long 10000");

    }


    if ((IsFirstTickOfBar))
    {
    if(Position.GetUnrealizedProfitLoss(PerformanceUni t.Points, Close[0]) > 0)
    {
    ExitLong(10000);

    }

    }

    else if <pattern> && (Position.MarketPosition != MarketPosition.Flat) && (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) < -100))


    {
    EnterLong(1, 20000, "Enter Long Again");

    }



    if (IsFirstTickOfBar)
    {
    if(Position.GetUnrealizedProfitLoss(PerformanceUni t.Points, Close[0]) > 0)
    {
    ExitLong(30000);

    }

    }

    I have Entries Per Direction set to 2, and Entry Handling set to Unique Entries.
    Attached Files

    #2
    Hello omermirza,

    Thanks for your post.

    I would set your entries per direction to 1 with Unique entries. That way you will only get one EnterLong and EnterLong again at the same time.

    However, if you are using Calculate.OnEachtick or Calculate.OnPriceChange, you will need to add further logic to prevent additional orders. A simple way to do this is to add a condition to your entry conditions that is true initially and then is set false when the first order is placed. Create an int variable called savedBar. In your entry conditions add: CurrentBar != savedBar. In the section where you place the order, add this assignment: savedBar =CurrentBar; This will allow the order once per bar. CurrentBar is the systems bar counter.

    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_PaulH View Post
      Hello omermirza,

      Thanks for your post.

      I would set your entries per direction to 1 with Unique entries. That way you will only get one EnterLong and EnterLong again at the same time.

      However, if you are using Calculate.OnEachtick or Calculate.OnPriceChange, you will need to add further logic to prevent additional orders. A simple way to do this is to add a condition to your entry conditions that is true initially and then is set false when the first order is placed. Create an int variable called savedBar. In your entry conditions add: CurrentBar != savedBar. In the section where you place the order, add this assignment: savedBar =CurrentBar; This will allow the order once per bar. CurrentBar is the systems bar counter.
      Thank you, that works beautifully.

      -Omer

      Comment


        #4
        Quick question Paul,

        Would the stop loss be calculated for both entries or just one? Currently I have it set like this:

        else if (State == State.Configure)
        {
        SetStopLoss("", CalculationMode.Currency, 400, false);
        AddDataSeries(Data.BarsPeriodType.Tick, 1);
        }

        Comment


          #5
          Hello omermirza,

          Thanks for your reply.

          It would be by position quantity.
          Last edited by NinjaTrader_PaulH; 06-24-2021, 06:49 AM. Reason: Original reply was per entry, testing showed it is by position quantity.
          Paul H.NinjaTrader Customer Service

          Comment


            #6
            Is there a way to set it for the total number of entries?

            Comment


              #7
              Hello omermirza,

              Thanks for your reply.

              In testing here when you have one entry the stop will go to the full $400.

              When you have a second entry, the entry price is averaged and the stop is moved to $200, so I was incorrect in my earlier statement in post #5 (I will change that post).



              Paul H.NinjaTrader Customer Service

              Comment


                #8
                Bumping this thread. Unfortunately, even though everything looks fine on the chart NinjaTrader does not close the positions correctly. There's always one mini lot (10000) left open.

                Any ideas?

                -Omer

                Comment


                  #9
                  Hello Omer,

                  Thanks for your reply.

                  Is this latest inquiry related to the same thread subject?

                  If so can you provide some level of detail to help identify your observations?

                  Let's start with the instrument, bar type, bar size, time frame, testing on live data, or playback with market replay data, or testing in the strategy analyzer.

                  Can you provide an overview screenshot of the chart (and if using the strategy analyzer, one of the settings) to help illustrate the issue?

                  are you still using:
                  else if (State == State.Configure)
                  {
                  SetStopLoss("", CalculationMode.Currency, 400, false);
                  AddDataSeries(Data.BarsPeriodType.Tick, 1);
                  }
                  ?
                  Paul H.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Paul,

                    I'm testing this on FX data on the 4 hour timeframe. I am using the built-in Sim101 account to test the strategy live.

                    In the attached chart, you can see that everything works the way it's suppose to.

                    I am no longer using a stop loss, and my logic is as follows:

                    1) Once the candlestick pattern appears, buy 10000
                    2) if at the close of the next bar we are in profit, exit the trade
                    3) if we see the pattern again and are open P/L is less than -$300, add another 20000
                    4) Close 30000 once in profit at bar close

                    My code is below:

                    #region Using declarations
                    using System;
                    using System.Collections.Generic;
                    using System.ComponentModel;
                    using System.ComponentModel.DataAnnotations;
                    using System.Linq;
                    using System.Text;
                    using System.Threading.Tasks;
                    using System.Windows;
                    using System.Windows.Input;
                    using System.Windows.Media;
                    using System.Xml.Serialization;
                    using NinjaTrader.Cbi;
                    using NinjaTrader.Gui;
                    using NinjaTrader.Gui.Chart;
                    using NinjaTrader.Gui.SuperDom;
                    using NinjaTrader.Gui.Tools;
                    using NinjaTrader.Data;
                    using NinjaTrader.NinjaScript;
                    using NinjaTrader.Core.FloatingPoint;
                    using NinjaTrader.NinjaScript.Indicators;
                    using NinjaTrader.NinjaScript.DrawingTools;
                    #endregion

                    //This namespace holds Strategies in this folder and is required. Do not change it.
                    namespace NinjaTrader.NinjaScript.Strategies
                    {
                    public class ThreeDownOneUpLONGProfitableCloseMGMT : Strategy

                    {
                    private int savedBar;
                    private double currentPnL = 0;
                    private double unrealizedPL = 0;
                    protected override void OnStateChange()

                    {
                    if (State == State.SetDefaults)
                    {
                    Description = @"Enter the description for your new custom Strategy here.";
                    Name = "ThreeDownOneUpLONGProfitableCloseMGMT";
                    Calculate = Calculate.OnPriceChange;
                    EntriesPerDirection = 1;
                    EntryHandling = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy = true;
                    ExitOnSessionCloseSeconds = 30;
                    IsFillLimitOnTouch = false;
                    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution = OrderFillResolution.Standard;
                    Slippage = 0;
                    StartBehavior = StartBehavior.WaitUntilFlat;
                    TimeInForce = TimeInForce.Gtc;
                    TraceOrders = false;
                    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade = 20;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration = true;
                    }
                    else if (State == State.Configure)
                    {
                    //SetStopLoss("", CalculationMode.Currency, 400, false);
                    AddDataSeries(Data.BarsPeriodType.Tick, 1);


                    } Click image for larger version

Name:	mgnt.PNG
Views:	337
Size:	66.5 KB
ID:	1173537
                    }

                    protected override void OnBarUpdate()
                    {

                    //Gets Strategy Unrealized PL
                    currentPnL = SystemPerformance.AllTrades.TradesPerformance.NetP rofit;

                    if (BarsInProgress != 0)
                    return;

                    if (CurrentBars[0] < 3)
                    return;

                    // Set 1
                    if ((Low[2] < Low[3])
                    && (Low[1] < Low[2])
                    && (Close[0] > High[1]) && (CurrentBar != savedBar))
                    {
                    EnterLong(1, 10000, "Enter Long 10000");
                    savedBar =CurrentBar;
                    }


                    if ((IsFirstTickOfBar))
                    {
                    if(Position.GetUnrealizedProfitLoss(PerformanceUni t.Points, Close[0]) > 0)
                    {
                    ExitLong(10000);

                    }

                    }

                    else if ((Low[2] < Low[3])
                    && (Low[1] < Low[2])
                    && (Close[0] > High[1]) && (Position.MarketPosition != MarketPosition.Flat) && (Position.GetUnrealizedProfitLoss(PerformanceUnit. Currency, Close[0]) < -300))


                    {
                    EnterLong(1, 20000, "Enter Long Again");
                    //savedBar =CurrentBar;
                    }



                    if (IsFirstTickOfBar)
                    {
                    if(Position.GetUnrealizedProfitLoss(PerformanceUni t.Points, Close[0]) > 0)
                    {
                    ExitLong(30000);

                    }

                    }
                    Print("Draw down of all trades is: " + SystemPerformance.AllTrades.TradesPerformance.Curr ency.Drawdown);
                    Draw.TextFixed(this, "LowLeftext", "Draw down of all trades is: " + SystemPerformance.AllTrades.TradesPerformance.Curr ency.Drawdown, TextPosition.BottomRight);

                    }
                    }
                    }

                    Comment


                      #11
                      Hello Omer,

                      Thanks for your reply.

                      In looking at your code, it seems like the two exits could be made into a simple one exit using ExitLong() without the contract size as that will cause it to exit the entire position.

                      That you have two identical exits (other than the quantity) could cause a racing issue that ends up with what you have observed.

                      So just test with:

                      if (IsFirstTickOfBar)
                      {
                      if(Position.GetUnrealizedProfitLoss(PerformanceUni t.Points, Close[0]) > 0)
                      {
                      ExitLong();

                      }



                      Paul H.NinjaTrader Customer Service

                      Comment


                        #12
                        Ok cool I will test with that and keep you updated.

                        Thanks!

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by ender_wiggum, Today, 09:50 AM
                        1 response
                        5 views
                        0 likes
                        Last Post NinjaTrader_Gaby  
                        Started by rajendrasubedi2023, Today, 09:50 AM
                        1 response
                        11 views
                        0 likes
                        Last Post NinjaTrader_BrandonH  
                        Started by geotrades1, Today, 10:02 AM
                        0 responses
                        4 views
                        0 likes
                        Last Post NinjaTrader_BrandonH  
                        Started by bmartz, Today, 09:30 AM
                        1 response
                        9 views
                        0 likes
                        Last Post NinjaTrader_Erick  
                        Started by geddyisodin, Today, 05:20 AM
                        3 responses
                        26 views
                        0 likes
                        Last Post NinjaTrader_Gaby  
                        Working...
                        X