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

RealTimeTrades issue

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

    RealTimeTrades issue

    Hi, I'm trying to insert the pnl management code from your sample pnl script into my strategy. However, I'm getting an error:

    NinjaTradder.Cbi.SystmPerformance does not contain a definition for RealtimeTraades and no extension method RealtimeTrades accepting a first argument of type NinjaTrader."Cbi.SystemPerformance could be found. (Are you missing a using directive or an assembly reference?)

    Here's the code. I changed allTrades to RealtimeTrades as instructed in the comments

    // pnl management
    if (Bars.IsFirstBarOfSession)
    {
    // Store the strategy's prior cumulated realized profit and number of trades
    priorTradesCount = SystemPerformance.RealtimeTrades.Count;
    priorTradesCumProfit = SystemPerformance.RealtimeTrades.TradesPerformance .Currency.CumProfit;

    /* NOTE: Using .AllTrades will include both historical virtual trades as well as real-time trades.
    If you want to only count profits from real-time trades please use .RealtimeTrades. */
    }

    /* Prevents further trading if the current session's realized profit exceeds $1000 or if realized losses exceed $400.
    Also prevent trading if 10 trades have already been made in this session. */
    if (SystemPerformance.RealtimeTrades.TradesPerformanc e.Currency.CumProfit - priorTradesCumProfit >= MaxDailyProfit
    || SystemPerformance.RealtimeTrades.TradesPerformance .Currency.CumProfit - priorTradesCumProfit <= MaxDailyLoss
    || SystemPerformance.RealtimeTrades.Count - priorTradesCount > 10)
    {
    /* TIP FOR EXPERIENCED CODERS: This only prevents trade logic in the context of the OnBarUpdate() method. If you are utilizing
    other methods like OnOrderUpdate() or OnMarketData() you will need to insert this code segment there as well. */

    // Returns out of the OnBarUpdate() method. This prevents any further evaluation of trade logic in the OnBarUpdate() method.
    return;
    }

    #2
    Hello trader3000a,

    Thanks for your post.

    Can you provide a reference link for what "your sample pnl script" is so I can be sure we are looking at the same thing?

    Thanks in advance.
    Paul H.NinjaTrader Customer Service

    Comment


      #3

      Comment


        #4
        Hello trader3000a,

        Thanks for your reply.

        In looking at what you have typed, I think you have typo. Ninjascript is written in C# and uses the syntax rules of C# programming language.

        You are using .RealtimeTrades and it really should be RealTimeTrades (the difference is the capitalization of time vs Time).

        Paul H.NinjaTrader Customer Service

        Comment


          #5
          oh, jeez, thanks Paul. sorry for taking up your time, ha

          Comment


            #6
            Hey Paul, I just noticed something. The comment text by the author of the sample wrote "RealtimeTrades" which is what I copied and pasted. If it should be RealTimeTrades, then that script comment section needs an edit!

            Comment


              #7
              Hello trader3000a,

              Thanks for your reply.

              Glad that resolved for you.

              "The comment text by the author of the sample wrote "RealtimeTrades" which is what I copied and pasted. If it should be RealTimeTrades, then that script comment section needs an edit!"

              Good observation, I will work through our system to get that comment corrected.

              Thank-you.
              Paul H.NinjaTrader Customer Service

              Comment


                #8
                Hi Paul, I can't get the pnl code working. It compiles within the strategy fine, but the strategy won't place any trades. Any ideas? I've highlighted the section in blue. Did I insert it in the wrong spot?
                David


                #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 GoGo001 : Strategy
                {
                private SMA SMA1;
                private int priorTradesCount = 0;
                private double priorTradesCumProfit = 0;

                protected override void OnStateChange()
                {
                if (State == State.SetDefaults)
                {
                Description = @"Enter the description for your new custom Strategy here.";
                Name = "GoGo001";
                Calculate = Calculate.OnBarClose;
                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 = 1;
                // Disable this property for performance gains in Strategy Analyzer optimizations
                // See the Help Guide for additional information
                IsInstantiatedOnEachOptimizationIteration = true;
                StopTicks = 1;
                ProfitTicks = 1;
                BeTicks = 1;
                CrossSma = 1;
                EntryOffsetTicks = 1;
                ExitSmaOffsetTicks = 1;
                MaxDailyProfit = 1;
                MaxDailyLoss = 1;
                MaxDailyTrades = 1;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {
                SMA1 = SMA(Close, Convert.ToInt32(CrossSma));
                SetStopLoss("", CalculationMode.Ticks, StopTicks, false);
                SetProfitTarget("", CalculationMode.Ticks, ProfitTicks);
                }
                }

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

                if (CurrentBars[0] < 1)
                return;

                // pnl management
                if (Bars.IsFirstBarOfSession)
                {
                priorTradesCount = SystemPerformance.RealTimeTrades.Count;
                priorTradesCumProfit = SystemPerformance.RealTimeTrades.TradesPerformance .Currency.CumProfit;
                }

                if (SystemPerformance.RealTimeTrades.TradesPerformanc e.Currency.CumProfit - priorTradesCumProfit >= MaxDailyProfit
                || SystemPerformance.RealTimeTrades.TradesPerformance .Currency.CumProfit - priorTradesCumProfit <= MaxDailyLoss
                || SystemPerformance.RealTimeTrades.Count - priorTradesCount > MaxDailyTrades)
                {
                return;
                }


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

                // if a long position is open, allow for a stop loss modification to breakeven
                else if (Position.MarketPosition == MarketPosition.Long)
                {
                if (Close[0] >= Position.AveragePrice + (BeTicks * TickSize))
                {
                SetStopLoss(CalculationMode.Price, Position.AveragePrice);
                }

                if (CrossBelow(Close, SMA1, 1))

                {
                SetProfitTarget(CalculationMode.Price, High[0]);
                }

                }




                // entry
                if (Close[0] > Open[0])
                {
                EnterLongLimit(Convert.ToInt32(DefaultQuantity), (Median[0] + (EntryOffsetTicks * TickSize)) , "");
                }

                }

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

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

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

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

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

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

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

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

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

                #endregion

                }
                }

                Comment


                  #9
                  Hi Paul, I've narrowed it down. I replaced the areas in blue (that were numerical values in the sample) with user inputs. Is there a mistake in my syntax? Do they need quotes or...?

                  // pnl management
                  if (Bars.IsFirstBarOfSession)
                  {
                  priorTradesCount = SystemPerformance.RealTimeTrades.Count;
                  priorTradesCumProfit = SystemPerformance.RealTimeTrades.TradesPerformance .Currency.CumProfit;
                  }

                  if (SystemPerformance.RealTimeTrades.TradesPerformanc e.Currency.CumProfit - priorTradesCumProfit >= MaxDailyProfit
                  || SystemPerformance.RealTimeTrades.TradesPerformance .Currency.CumProfit - priorTradesCumProfit <= MaxDailyLoss
                  || SystemPerformance.RealTimeTrades.Count - priorTradesCount > MaxDailyTrades)
                  {
                  return;
                  }

                  Comment


                    #10
                    Hello trader3000a,

                    Thanks for your reply.

                    The location looks fine.

                    I assume you are entering realistic user input values for MaxDailyLoss , MaxDailyProfit and MaxDailyTrades when you apply the strategy as the defaults are set to 1.

                    I do see that you have set the minimum daily loss as 1 when you start the strategy the pnl will be zero so that may be preventing your strategy from placing trades. You may want to change [Range(1, int.MaxValue)] so that you can enter a value such as -100 or whatever loss value you wish.


                    Paul H.NinjaTrader Customer Service

                    Comment


                      #11
                      looks like i forgot to use a large negative number as minimum value for the max loss section. it's going now

                      Comment


                        #12
                        Hi again, Paul. I can't get the MaxDailyTrades working. Do you think the count isn't updating or resetting for any reason?
                        Attached Files

                        Comment


                          #13
                          Hello trader3000a,

                          Thanks for your reply.

                          The best way to answer these types of questions would be to add a print statement to your code and print out what the values are as well as verify what the value of MaxDailyTrades is set to.

                          Print (Time[0]+" prior TradesCount: "+priorTradesCount+" total trades count: "+SystemPerformance.RealTimeTrades.Count.ToString( )+" Max set at: "+MaxDailyTrades);
                          Paul H.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi Paul, where do i place that line? after the enterLong line? where does the data print? nothing comes up in the log or on the chart

                            Comment


                              #15
                              Hello trader3000a,

                              Thanks for your reply.

                              You can put the print statement just before the block of code that checks the PNL.

                              To see the output of a print statement, go to New>Ninjascript Output, this will open a ninjascript output window where all print statements will print.
                              Paul H.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by cre8able, Today, 03:20 PM
                              0 responses
                              1 view
                              0 likes
                              Last Post cre8able  
                              Started by Fran888, 02-16-2024, 10:48 AM
                              3 responses
                              45 views
                              0 likes
                              Last Post Sam2515
                              by Sam2515
                               
                              Started by martin70, 03-24-2023, 04:58 AM
                              15 responses
                              114 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by The_Sec, Today, 02:29 PM
                              1 response
                              7 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by jeronymite, 04-12-2024, 04:26 PM
                              2 responses
                              31 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Working...
                              X