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

Multiple Target profits

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

    #16
    Dear Kate,

    I have another question
    I wrote an indicator and I would like to change 1 of the variables "MoveUpAfterLow" from int to double
    because I want to change the value 10 in (High[0]/200)
    Is this possible?
    I hereby send you the parts of the code

    namespace NinjaTrader.NinjaScript.Indicators
    {
    public class LongDOWJONES1minBestPRT1401 : Indicator
    {
    // Internal variables
    bool hammer = false;
    double irsi = 0;
    int tolowrsi = 0;
    double point1v, point2v,point3v,RSI1,RSI2,LOW1,LOW2,CLOSE1,CLOSE2;
    int point1bar,point2bar,point3bar;
    RSI rsi;

    bool bInit = false;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Mijn indicator uit PRT";
    Name = "LongDOWJONES1minBestPRT1401";
    Calculate = Calculate.OnBarClose;
    IsOverlay = false;
    DisplayInDataBox = true;
    DrawOnPricePanel = true;
    //DrawHorizontalGridLines = true;
    //DrawVerticalGridLines = true;
    PaintPriceMarkers = true;
    ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
    //Disable this property if your indicator requires custom values that cumulate with each new market data event.
    //See Help Guide for additional information.
    IsSuspendedWhileInactive = true;

    // Input default values
    RSIbottom1 = 28;
    MoveUpAfterLow = 10;
    NumberOfBars = 35;
    Laagstersiwaarde = 20;
    RSI_Period = 14;

    //Plots/Lines
    AddPlot(new Stroke(Brushes.LimeGreen, 2), PlotStyle.TriangleUp, "CompletedSignal");
    }
    else if (State == State.Configure)
    {

    }
    else if (State == State.DataLoaded)
    {
    tolowrsi = 0;
    rsi = RSI(RSI_Period,1);
    }
    }

    protected override void OnBarUpdate()
    {
    if (Calculate != Calculate.OnBarClose)
    {
    if (CurrentBar < 5)
    Draw.TextFixed(this,"COBC",Name+" must run with Calculate set to OnBarClose",TextPosition.Center,Brushes.Red,new SimpleFont("Tahoma",20),Brushes.Red,Brushes.LightP ink,100);
    return;
    }
    if (CurrentBar < 75)
    return; // there is a lookback in here hardwired to 75!

    if (!bInit)
    {
    //my setup search system
    RSI1=1000;
    RSI2=1000;
    LOW1=Close[0]*100;
    LOW2=Close[0]*100;
    CLOSE1=Close[0]*100;

    bInit = true;
    return;
    }
    RSI1=1000;
    RSI2=1000;
    LOW1=Close[0]*100;
    LOW2=Close[0]*100;
    CLOSE1=Close[0]*100;

    bInit = true;
    return;
    }

    *
    *
    *


    then all the code of the indicator

    And then

    #region NinjaScript generated code. Neither change nor remove.

    namespace NinjaTrader.NinjaScript.Indicators
    {
    public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
    {
    private LongDOWJONES1minBestPRT1401[] cacheLongDOWJONES1minBestPRT1401;
    public LongDOWJONES1minBestPRT1401 LongDOWJONES1minBestPRT1401(int rSIbottom1, int moveUpAfterLow, int numberOfBars, int laagstersiwaarde, int rSI_Period)
    {
    return LongDOWJONES1minBestPRT1401(Input, rSIbottom1, moveUpAfterLow, numberOfBars, laagstersiwaarde, rSI_Period);
    }

    public LongDOWJONES1minBestPRT1401 LongDOWJONES1minBestPRT1401(ISeries<double> input, int rSIbottom1, int moveUpAfterLow, int numberOfBars, int laagstersiwaarde, int rSI_Period)
    {
    if (cacheLongDOWJONES1minBestPRT1401 != null)
    for (int idx = 0; idx < cacheLongDOWJONES1minBestPRT1401.Length; idx++)
    if (cacheLongDOWJONES1minBestPRT1401[idx] != null && cacheLongDOWJONES1minBestPRT1401[idx].RSIbottom1 == rSIbottom1 && cacheLongDOWJONES1minBestPRT1401[idx].MoveUpAfterLow == moveUpAfterLow && cacheLongDOWJONES1minBestPRT1401[idx].NumberOfBars == numberOfBars && cacheLongDOWJONES1minBestPRT1401[idx].Laagstersiwaarde == laagstersiwaarde && cacheLongDOWJONES1minBestPRT1401[idx].RSI_Period == rSI_Period && cacheLongDOWJONES1minBestPRT1401[idx].EqualsInput(input))
    return cacheLongDOWJONES1minBestPRT1401[idx];
    return CacheIndicator<LongDOWJONES1minBestPRT1401>(new LongDOWJONES1minBestPRT1401(){ RSIbottom1 = rSIbottom1, MoveUpAfterLow = moveUpAfterLow, NumberOfBars = numberOfBars, Laagstersiwaarde = laagstersiwaarde, RSI_Period = rSI_Period }, input, ref cacheLongDOWJONES1minBestPRT1401);
    }
    }
    }

    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
    public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
    {
    public Indicators.LongDOWJONES1minBestPRT1401 LongDOWJONES1minBestPRT1401(int rSIbottom1, int moveUpAfterLow, int numberOfBars, int laagstersiwaarde, int rSI_Period)
    {
    return indicator.LongDOWJONES1minBestPRT1401(Input, rSIbottom1, moveUpAfterLow, numberOfBars, laagstersiwaarde, rSI_Period);
    }

    public Indicators.LongDOWJONES1minBestPRT1401 LongDOWJONES1minBestPRT1401(ISeries<double> input , int rSIbottom1, int moveUpAfterLow, int numberOfBars, int laagstersiwaarde, int rSI_Period)
    {
    return indicator.LongDOWJONES1minBestPRT1401(input, rSIbottom1, moveUpAfterLow, numberOfBars, laagstersiwaarde, rSI_Period);
    }
    }
    }

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
    {
    public Indicators.LongDOWJONES1minBestPRT1401 LongDOWJONES1minBestPRT1401(int rSIbottom1, int moveUpAfterLow, int numberOfBars, int laagstersiwaarde, int rSI_Period)
    {
    return indicator.LongDOWJONES1minBestPRT1401(Input, rSIbottom1, moveUpAfterLow, numberOfBars, laagstersiwaarde, rSI_Period);
    }

    public Indicators.LongDOWJONES1minBestPRT1401 LongDOWJONES1minBestPRT1401(ISeries<double> input , int rSIbottom1, int moveUpAfterLow, int numberOfBars, int laagstersiwaarde, int rSI_Period)
    {
    return indicator.LongDOWJONES1minBestPRT1401(input, rSIbottom1, moveUpAfterLow, numberOfBars, laagstersiwaarde, rSI_Period);
    }
    }
    }

    #endregion

    Kind regards,

    Ladis

    Comment


      #17
      Hello Pladijske,

      Thank you for your reply.

      Is moveUpAfterLow a user input? I'm not seeing where the variable is instantiated in the code you've provided? If it is, you'd need to adjust the type of variable it is down in the Properties section of your code.

      Thanks in advance; I look forward to assisting you further.
      Kate W.NinjaTrader Customer Service

      Comment


        #18
        Hello Kate,

        Do you mean by user input the fact that I can change it when selecting it in the graph or when I set up a Strategy? In that case it is, but I don't know how to change it?



        #region Properties
        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name="RSIbotom1", Order=10, GroupName="Parameters")]
        public int RSIbottom1
        { get; set; }

        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name="MoveUpAfterLow", Order=20, GroupName="Parameters")]
        public int MoveUpAfterLow
        { get; set; }

        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name="NumberOfBars", Order=30, GroupName="Parameters")]
        public int NumberOfBars
        { get; set; }

        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name="Laagstersiwaarde", Order=40, GroupName="Parameters")]
        public int Laagstersiwaarde
        { get; set; }

        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name="RSI_Period", Order=100, GroupName="Parameters")]
        public int RSI_Period
        { get; set; }

        [Browsable(false)]
        [XmlIgnore]
        public Series<double> signal
        {
        get { return Values[0]; }
        }

        #endregion

        Which part do I have to change?

        Kind regards,

        Ladis

        Comment


          #19
          Hello Pladijske,

          Thank you for your reply.

          You'd just need to change it from this:

          Code:
          [NinjaScriptProperty]
          [Range(1, int.MaxValue)]
          [Display(Name="MoveUpAfterLow", Order=20, GroupName="Parameters")]
          public int MoveUpAfterLow
          { get; set; }
          To this:

          Code:
          [NinjaScriptProperty]
          [Range(1, double.MaxValue)]
          [Display(Name="MoveUpAfterLow", Order=20, GroupName="Parameters")]
          public double MoveUpAfterLow
          { get; set; }
          Once you've done that, it'll be initialized as a double rather than an int.

          Please let us know if we may be of further assistance to you.
          Kate W.NinjaTrader Customer Service

          Comment


            #20
            Fantastic!
            Thank you very much an have a nice weekend!

            Comment


              #21
              Dear Kate,

              If a specific condition in my strategy is reached, I send an email to myself.
              Is it possible to send a printscreen or a chart window with it? Or is there a specific codestring that I can implement in the strategy?
              I know it is possible when you set an alert in a chart, but when I close the chart and reopen it, I have to restate the alert and not when it is in a strategy.

              kind regards,

              Ladis

              Comment


                #22
                Hello Pladijske,

                Thank you for your reply.

                Yes, but instead of using SendMail, you would need to use Share() with a Mail Share service:

                Code:
                Share(string serviceName, string message, string screenshotPath)


                // using "args" as the Mail "To" and "Subject" parameters
                Share("Gmail", "Test Message", , @"C:\MyImages\chart03.PNG", new object[]{ "[email protected]", "Test Subject Line" });

                Please let us know if we may be of further assistance to you.



                Kate W.NinjaTrader Customer Service

                Comment


                  #23
                  Hello Kate,
                  Many thanks for your reply.

                  About the printscreen: Does the ninjatraderprogram "take" screenshot then? And where can I then find the location of this "png"?

                  Comment


                    #24
                    Hello Pladijske,

                    Thank you for your reply.

                    There is not a method to take the screenshot through NinjaScript - you would need to have an existing screenshot to share. You can use the share service from the chart to take one, but you can't have the script take one.

                    Here's a link to our help guide on sharing screenshots manually:



                    Please let us know if we may be of further assistance to you.
                    Kate W.NinjaTrader Customer Service

                    Comment


                      #25
                      Dear Kate,

                      My strategy buys futures on different prices '(see below)
                      I first buy 1 future when I get a signal.
                      Then I add 1 future when the price goes futher 30 pips down
                      I add another when the average price goes even futher down 50 pips etc...

                      I sell them at (average price) +14 pips
                      When at the end of day I have too much futures left and my target isn't reached. I sell 1 future at market. Just to help getting my overnight margin ok.
                      So I sell the @"laatste" (which is dutch for "last" :-) ) maybe at a price far below the buying price.


                      So the next day, when I have 3 futures left, the average price is still the average price from when I had 4 futures.

                      Is it possible to adjust this?

                      I tried with the tools>options>trading>fifo method, but that's even worse.

                      I include the code for reference.

                      Kidn regards,

                      Ladis


                      //This namespace holds Strategies in this folder and is required. Do not change it.
                      namespace NinjaTrader.NinjaScript.Strategies
                      {
                      public class StrategyLongDax1minHoogsteRendement : Strategy
                      {
                      double indicator,target2,target3;

                      private LongDax1HoogsteRendement0602 LongDax1HoogsteRendement06021;

                      protected override void OnStateChange()
                      {
                      if (State == State.SetDefaults)
                      {
                      Description = @"Geeft een kooporder als de indicator 2 of meer is";
                      Name = "StrategyLongDax1minHoogsteRendement";
                      Calculate = Calculate.OnBarClose;
                      EntriesPerDirection = 5;
                      EntryHandling = EntryHandling.AllEntries;
                      IsExitOnSessionCloseStrategy = false;
                      ExitOnSessionCloseSeconds = 30;
                      IsFillLimitOnTouch = false;
                      MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                      OrderFillResolution = OrderFillResolution.Standard;
                      Slippage = 2;
                      StartBehavior = StartBehavior.WaitUntilFlat;
                      TimeInForce = TimeInForce.Gtc;
                      TraceOrders = true;
                      RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                      StopTargetHandling = StopTargetHandling.ByStrategyPosition;
                      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)
                      {
                      }
                      else if (State == State.DataLoaded)
                      {
                      LongDax1HoogsteRendement06021 = LongDax1HoogsteRendement0602(Close, 28, 35, 19, 14);
                      }
                      }

                      protected override void OnBarUpdate()
                      {
                      if (BarsInProgress != 0)
                      return;

                      if (CurrentBars[0] < 1)
                      return;

                      // Set 1
                      if ((Times[0][0].TimeOfDay > new TimeSpan(8, 10, 0))
                      && (Times[0][0].TimeOfDay < new TimeSpan(21, 00, 0))
                      && (Position.Quantity == 0))
                      {
                      if ((LongDax1HoogsteRendement06021[0] == 2))
                      {
                      Draw.VerticalLine(this, @"DaxLong1min Vertical line_1", 0, Brushes.Red, DashStyleHelper.Solid, 2);
                      EnterLong(1, @"EERSTE2");
                      indicator=2;
                      target2=High[1]*0.002076;
                      }
                      else if ((LongDax1HoogsteRendement06021[0] == 3))
                      {
                      Draw.VerticalLine(this, @"DaxLong1min Vertical line_1", 0, Brushes.Green, DashStyleHelper.Solid, 2);
                      EnterLong(1, @"EERSTE3");
                      indicator=3;
                      target3=High[1]*0.003;
                      }
                      }

                      // Set 2
                      if ((Close[0] < (Position.AveragePrice - 30) )
                      && (Position.Quantity == 1))
                      {
                      EnterLong(1, @"TWEEDE");
                      }

                      // Set 3
                      if ((Close[0] < (Position.AveragePrice - 50) )
                      && (Position.Quantity == 2))
                      {
                      EnterLong(1, @"DERDE");
                      }

                      // // Set 4
                      if ((Position.Quantity == 3)
                      && (Close[0] < (Position.AveragePrice - 100) ))
                      && (Times[0][0].TimeOfDay < new TimeSpan(21, 55, 0))
                      && (Times[0][0].TimeOfDay > new TimeSpan(7, 30, 0)))
                      {
                      EnterLong(1, @"LAATSTE");
                      }
                      // // Set 5
                      if ((Times[0][0].TimeOfDay > new TimeSpan(21, 55, 0))
                      && (Position.Quantity >= 3))
                      {
                      ExitLong(1, "", @"LAATSTE");
                      }
                      if ((LongDax1HoogsteRendement06021[0] == 2) && indicator ==2)
                      {
                      SetProfitTarget(CalculationMode.Ticks, target2);
                      }
                      if ((LongDax1HoogsteRendement06021[0] == 3) && indicator ==3)
                      {
                      SetProfitTarget(CalculationMode.Ticks, target3);
                      }
                      }

                      #region Properties
                      // [NinjaScriptProperty]
                      // [Range(1, int.MaxValue)]
                      // [Display(Name="Profittarget", Description="Number of points from entry", Order=1, GroupName="Parameters")]
                      // public int Profittarget
                      // { get; set; }
                      #endregion

                      }
                      }

                      Comment


                        #26
                        Hello Pladijske,

                        Thank you for your reply.

                        I'm not sure this has anything to do with your strategy itself, but rather how your broker carries orders overnight.

                        Brokerages do what is called 'mark to market'/'carrying price' balancing to match up executions for the day. This can result in the average entry price changing. The average entry will be the highest or the lowest trade entry price for that day.

                        I would advise speaking to your broker to confirm exactly how they handle this, but here's a basic explanation:
                        • The reason the position you show on the platform is different than the most recent trade price is due to the way the FCM carries the position from one session to the next. Futures clearing firms will carry positions in the following ways:
                          • 1.) The first day you carry a position, they will carry the highest or lowest traded price. This is simply an accounting method they use to give the account the highest possible value to be used for margin. It does not affect the balance of the account in any way. Your open PnL may be off, but it will be incorrect by the same amount the closed PnL for the previous day is. For example, if you buy 2 and sell 1 contract on day 1:
                            • Say you buy at 10 first and at 5 second, you then sell one at 20. The broker will carry the buy at 10 forward to the next day. Let's assume the market is still trading 20. What this has done is brought your closed profit to 15, (20-5 because the 10 is still "open") and the open profit is now 10. (20-10 current price- carry price). Because they carried the highest price, they have increased the closed PnL by 5 (20-5=15, 20-10=10, 15-10 = 5) and decreased the open profit by 5. These two values will offset each other when the position is closed. Assume the final contract is closed at 30 on day 2. We now have 2 buys across 2 days, one at 5, and one at 10. We also have to sells now. one at 20 and one at 30. Either way we match these, the profit will be the same. (30 - 5 = 25) (20-10 = 10) total = 35. (30-10=20, 20-5=15) total = 35. When the statement runs on day 2, the offsetting journal entries will be fixed and the balance will reflect the correct value.
                          • 2.) If you are carrying a position for multiple days, they will carry the oldest price. In our example above, we have a carry price of 10 on day 2. If you were to do a 1x1 trade on day 2. Let's say we buy at 15 and sell at 20, the statement that night will show the 15B and 20S with a profit of 5. The open position will remain the buy at 10 because it is the oldest.
                        • This process will leave the platform inaccurate at times according to what you would expect to see. It is important to remember that the prices will not matter in the end. You can trade the position from the carry price, or treat it as if you are entered from the price you did most recently. Either way, the balance of the account will always be correct and will become clear when the position is closed.
                        Please let us know if we may be of further assistance to you.
                        Kate W.NinjaTrader Customer Service

                        Comment


                          #27
                          Hello Kate,

                          Thank you very much for your explanation.
                          I understand your point.

                          My problem here is with the "backtesting" of ninjatrader. At least I think so.

                          When I buy the first future at 1000, the second at 700 and the thirth at 500 the average is (1000+700+500)/3=+/-733.5
                          When my target profit is average+14, then my target is 733.5+14 points = 747.5
                          But when I have to sell the last one (500) forcefully at the end of the day, lets say at 420, the profittarget the next day, in ninjatrader backtest, for the remaining futures remains 747.5 in stead of ((1000+700)/2)=850 +14 = 864

                          So the backtest sells them at 747.5 in stead of 864.

                          Can I adjust that?

                          Again many thanks!
                          Kind regards,

                          Ladis

                          Comment


                            #28
                            Hello Pladijske,

                            Thank you for your reply.

                            How are you running the backtest the next day? Market Replay, the Strategy Analyzer, or simply reapplying the Strategy to a chart?

                            This sounds like you're disabling the strategy at night and re-enabling the next day, is that accurate?

                            Thanks in advance; I look forward to assisting you further.
                            Kate W.NinjaTrader Customer Service

                            Comment


                              #29
                              Hello Kate,

                              I just rightclick in the chart. Select strategy and click on enable and the apply.
                              So I am just applying the strategie to the chart (with historical data from the last 5 years)
                              So the trades appear on the chart and I can follow them. That's how I found out.
                              I don't think I break at end of day. At least I don't know where this option would be. (I disable the tickbox "break at end of day")

                              What is the difference between a New>strategy analyzer>backtest and a chart rightclick>strategy performance?

                              Again, thank you very much;

                              Ladis

                              Comment


                                #30
                                Dear Kate,

                                Considering my above question about the difference ,
                                I just checked both and there seems to be no difference between in chart>strategy performance and strategy analyzer>backtest.

                                When I recalculated some trades, I concluded the following:

                                1. I buy 1e fut at 1000 ->average price is 1000
                                2. I buy second AVG-30(= 970) -> average price is 985
                                3. I buy 3th at AVG-50(=935) -> the average price is 968 (rounded)
                                4. I buy 4th at AVG-100(=868) -> average price is 943 (rounded) (At least I think so: (1000+970+935+868)/4 Is this correct??)

                                When I have to sell the 4th at end of day for -let's say- 843, I lose 100 pips from the AVG. I think, after looking at the calculations of the ninjatrader backtest, that the AVG then still remains 943.

                                So when the next day my strategy continues and I still have 3 futs from the day before and the strategy says "when price is<AVG-100 buy 1 fut" it only buys when price is <(943-100=843)
                                Is this correct?

                                Is there a way, when the 4th fut it sold, to recalculate the AVG of the remaining futs?

                                Because now when the index wouldn't go down more then AVG-100 and the new target (AVG+20pips=943+20=963) is reached, I lose on 3 out of 4 futs:
                                1st fut 1000-963=37pips
                                2nd fut 970-963=7 pips
                                (and in this example) 4th fut

                                I explained it the best I can (with my humble nowledge of the english language) so I hope you can make sense of my question.

                                Kind regards,

                                Ladis

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by RookieTrader, Today, 09:37 AM
                                3 responses
                                15 views
                                0 likes
                                Last Post NinjaTrader_ChelseaB  
                                Started by kulwinder73, Today, 10:31 AM
                                0 responses
                                5 views
                                0 likes
                                Last Post kulwinder73  
                                Started by terofs, Yesterday, 04:18 PM
                                1 response
                                23 views
                                0 likes
                                Last Post terofs
                                by terofs
                                 
                                Started by CommonWhale, Today, 09:55 AM
                                1 response
                                4 views
                                0 likes
                                Last Post NinjaTrader_Erick  
                                Started by Gerik, Today, 09:40 AM
                                2 responses
                                7 views
                                0 likes
                                Last Post Gerik
                                by Gerik
                                 
                                Working...
                                X