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

Walky-Talky Sim101 to RealTime

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

    Walky-Talky Sim101 to RealTime

    Hello,
    I am attempting to create a Public Variable when the strategy sees its account is Sim101, & calls Variable when it sees it is NOT Sim101.

    In the Strategy I know how to access
    Account Name = Account.Name
    Strategy Name = MyCustomeStrategy
    Instrument Name = Instrument.FullName
    Profit Factor = SystemPerformance.AllTrades.TradesPerformance.Prof itFactor

    The end product should ideally automatically generate a Dynamically named variable;
    Public var (Strategy Name Instrument Name Profit Factor) = Profit Factor

    The end product should also recognize what account it is trading on;
    if Sim101 == Account.Name
    Public var MyCustomeStrategyInstrumentNameProfitFactor = SystemPerformance.AllTrades.TradesPerformance.Prof itFactor

    if Sim101 <> Account.Name
    MyCustomeStrategyInstrumentNameProfitFactor > 1

    The Sim101 account would make Public TradesPerformance metrics for the RealTime account. The Strategy running on the RealTime account will make sure minimum values are maintained. if logic is true = trade, 1 metric is false=no trade.

    If there is a code already vetted, please point me in the correct direction. I know VBA for excel like the back of my hand but NinjaTrader Script is a new endeavor.

    #2
    Hello GTBrooks,

    Thanks for your post.

    You could make a public variable for your TradesPerformance metric and when you want to reference it externally, it would be referenced as a property of your NinjaScript strategy. For example, MyStrategy.MyPublicVariable. Since the variable would have to be created before compiling, it wouldn't be possible to have it dynamically named. I'll provide an example that demonstrates exposing public variables.

    Checking the account name could be done as follows:

    Code:
    if (Account.Name == "Sim101")
        myVar = SomeValue;
    I'll include publicly available documentation on TradesPerformance so the syntax can be referenced, and I will also provide a link to some educational C# resources we have in the NinjaTrader 7 help guide. For more in depth C# materials, I would recommend looking for resources external to NinjaTrader.

    Exposing public variables - https://ninjatrader.com/support/help...alues_that.htm

    TradesPerformance - https://ninjatrader.com/support/help...erformance.htm

    C# Educational materials (NT7 help guide) - https://ninjatrader.com/support/help...g_concepts.htm

    Also as a tip for getting introduced to NinjaScript, I recommend using the Strategy Builder and watching how the code gets generated with each addition after pressing View Code.

    Strategy Builder 301 - https://www.youtube.com/watch?v=HCyt90GAs9k

    Please let us know if you have any additional questions.
    JimNinjaTrader Customer Service

    Comment


      #3
      Series T

      Hello,

      Can you tell me if this basic logic is sound for <seriesT> or if I need to take something else under account?

      If (Account.Name == “Sim101”)

      private Series<int> name.strategy+instrument.name;

      protected override void OnStateChange()
      {
      if (State == State.DataLoaded)
      {
      name.strategy+instrument.name = new (ProfitFactor >=1 ? 1 : 0);
      }
      }

      If (Account.Name != “Sim101”)
      {
      //trading logic
      && name.strategy+instrument.name == 1
      }
      //if variable name == 1 Trading occurs if variable name == 0 no entry into Long/Short

      Comment


        #4
        Hello GTBrooks,

        You can't make dynamically named variables with C#. It is a hard-typed language, and you will have to give each variable a specific name so the compiler knows which variables you are referring to.

        Additionally, I see that you are creating your Series<T> within a condition. I also see that you are placing this condition outside of a method so it resides directly in the Strategy class. This is not valid and will not compile.

        You may check the publicly available Series<T> documentation for syntax reference. Since there are other C# related syntax errors in your code, I highly recommend using the Strategy Builder and clicking View Code with each addition so you can observe how the Builder generates the C# syntax.

        Series<T> - https://ninjatrader.com/support/help...us/seriest.htm

        Also, if it interests you, we could have a representative of our EcoSystem reach out with information on NinjaScript Consultants and Programming Educators that would be happy to write this strategy or assist you further with teaching the proper C# syntax.

        Please let us know if this is the case.
        Last edited by NinjaTrader_Jim; 07-25-2018, 09:40 AM.
        JimNinjaTrader Customer Service

        Comment


          #5
          Strategy Performance Metrics

          It looks like I might need someone else to write this code, but before that happens maybe you can help me with my comprehension of the problem I am facing, & a best approach at attaining what I seek.

          The Strategy behavior I want to attain;
          Strategy running will trade when Trades Performance meets certain criteria (Enter Long / Short on my Real-Money Account). Strategy can trade list of Instruments and only trade the instruments it meets minimum Trade Performance.

          What approach to attain a solution do you recommend.
          Again, simply the goal is to allow the Strategy to trade only when Trades Performance meets my requirements. (ProfitFactor >= 0) for example.
          Last edited by GTBrooks; 07-25-2018, 04:28 PM. Reason: not well worded

          Comment


            #6
            Hello GTBrooks,

            TradesPerformance may mean a couple things here.

            Strategies can retrieve a TradesPerformance report for their own trades that instance of a strategy makes with historical data or with realtime data. Strategies are designed to be independent of the actual account they run on. While you can subscribe to AccountItemUpdate events for the items seen in the Accounts tab of the Control Center, strategies do not have supported access to an overall Account TradesPerformance Report like we see in a Trades Performance window.

            With that said, you could design a strategy that loads instrument names from a file, and then uses those instruments for automated trading.

            How you would want to analyze potential instrument performance to determine if they are trade-worthy could involve using the Strategy Analyzer or running the strategy on another part of the platform so it is backtested and TradesPerformance results are generated. You could then use that information to create a new list of instruments that you wish to trade with.

            I've included some documentation resources that highlight the differences between Historical and Realtime data, Strategy vs. Account positions, Multi-Series NinjaScripts, and a couple examples on using a StreamReader and StreamWriter to read and write to a file. These items should provide enough foundation to accomplish your goal.


            I'll also have someone reach out with information on NinjaScript Consultants in our EcoSystem.

            If you have any other NinjaScript related questions, please don't hesitate to ask.
            JimNinjaTrader Customer Service

            Comment


              #7
              Hello GTBrooks,

              Thank you for your interest in NinjaTrader.

              You can search our extensive library of NinjaScript consultants through the link below. Simply enter a consultant name or search by using our filter categories. Once you have identified your consultants of choice, please visit each consultant's site for more information or contact them directly to learn more:

              Search trading indicators, apps and services to personalize your NinjaTrader software. Explore custom trading indicators, automated strategies, free trading apps & more!


              You can locate the contact information for the consultants on their direct websites for any additional questions you may have. Since these consultants are third-party services for NinjaTrader, all pricing and support information will need to be obtained through the consultant.

              This NinjaTrader Ecosystem website is for educational and informational purposes only and should not be considered a solicitation to buy or sell a futures contract or make any other type of investment decision. The companies and services listed on this website are not to be considered a recommendation and it is the reader's responsibility to evaluate any product, service, or company. NinjaTrader Ecosystem, LLC is not responsible for the accuracy or content of any product, service or company linked to on this website.
              Christopher S.NinjaTrader Customer Service

              Comment


                #8
                IncludeTradeHistory

                Includetradehistoryinbacktest == True
                When I first start my Strategy for the first time; will this give the Strategy 5 days of trade objects?
                I want historical data of the strategies trade objects even when the strategy does not trade due to profit factor being less than 1.
                So let’s say over the previous 5 days before the strategy is turned on for the first time would have traded 30 times, but only 10 had a trade performance greater that 1. Whorls the trade objects stored due to Includetradehistoryinbacktest == True, stored 30 or 10 trade objects.

                Same question, but the strategy ran last week and I turned off NinjaTrader platform on Saturday back on Sunday. How many trade objects stored 30 or 10?

                I have been through trade objects, tradesperformance, include trade history, & many other subjects in the https://ninjatrader.com/support/helpGuides/nt8/en-us/?. The help guide was not clear.

                Comment


                  #9
                  Hello GTBrooks,

                  Each time you enable a strategy, a new instance of that strategy is run. The strategy starts by processing the historical data that is loaded with it. This historical data is the OHLCV data that is saved on your platform locally. Historical trades should not be confused with the performance of your strategy from a previous run; past performance is not view-able in a strategy's TradesPerformance report.

                  NinjaTrader uses this historical data along with the strategy's Start Behavior to determine if the strategy should wait until the virtual historical position is closed before trading live (Wait Until Flat,) or if the strategy should attempt to match historical orders with live working orders that exist from a previous run and resume the previous position (Immediately Submit.) These behaviors are detailed in the Syncing Account Positions section of the help guide.

                  Syncing Account Positions further reading - https://ninjatrader.com/support/help..._positions.htm

                  IncludeTradeHistoryInBacktest tells the strategy if it should save historical trades to the strategy's SystemPerformance object. You can test with the property set to true and set to false while testing the print below in OnBarUpdate() and monitoring the NinjaScript Output window:

                  Code:
                  Print("The strategy has taken " + SystemPerformance.AllTrades.Count + " trades.");
                  If you would would like to save your TradesPerformance so it can be used by subsequent instances of your strategy, you could use a StreamReader/StreamWriter to write the trade performance to a file and then read the data from that file as needed.

                  Please let us know if you have any additional questions.
                  JimNinjaTrader Customer Service

                  Comment


                    #10
                    Strategy Performance Metrics

                    I am planning on using this code for now;

                    Code:
                    #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 ForexBasicLogic : Strategy
                    	{
                    		private WMA WMA1;
                    		private SMA SMA1;
                    
                    		protected override void OnStateChange()
                    		{
                    			if (State == State.SetDefaults)
                    			{
                    				Description						= @"Base Logic; comfirmation of 5 Bar movement.";
                    				Name							= "ForexBasicLogic";
                    				Calculate						= Calculate.OnEachTick;
                    				EntriesPerDirection					= 1;
                    				EntryHandling						= EntryHandling.AllEntries;
                    				IsExitOnSessionCloseStrategy				= true;
                    				ExitOnSessionCloseSeconds				= 900;
                    				IsFillLimitOnTouch					= true;
                    				MaximumBarsLookBack					= MaximumBarsLookBack.TwoHundredFiftySix;
                    				OrderFillResolution					= OrderFillResolution.Standard;
                    				Slippage						= 0;
                    				StartBehavior						= StartBehavior.WaitUntilFlat;
                    				TimeInForce						= TimeInForce.Day;
                    				TraceOrders						= false;
                    				RealtimeErrorHandling					= RealtimeErrorHandling.IgnoreAllErrors;
                    				StopTargetHandling					= StopTargetHandling.PerEntryExecution;
                    				BarsRequiredToTrade					= 20;
                    				// Disable this property for performance gains in Strategy Analyzer optimizations
                    				// See the Help Guide for additional information
                    				IsInstantiatedOnEachOptimizationIteration		= true;
                    				TrailingStopPips					= 1;
                    			}
                    			else if (State == State.Configure)
                    			{
                    			}
                    			else if (State == State.DataLoaded)
                    			{				
                    				WMA1				= WMA(Close, 5);
                    				SMA1				= SMA(Close, 5);
                    				SetTrailStop("", CalculationMode.Pips, TrailingStopPips, false);
                    			}
                    		}
                    
                    		protected override void OnBarUpdate()
                    		{
                    			if (BarsInProgress != 0) 
                    				return;
                    
                    			if (CurrentBars[0] < 1)
                    			return;
                    
                    			 // Set 1
                    			if ((WMA1[0] < SMA1[0]))
                    			&& (SystemPerformance.AllTrades.TradesPerformance.ProfitFactor >= 1)
                    			{
                    				EnterShort(Convert.ToInt32(DefaultQuantity), "");
                    			}
                    			
                    			 // Set 2
                    			if ((WMA1[0] > SMA1[0]))
                    			{
                    				ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
                    			}
                    			
                    			 // Set 3
                    			if ((WMA1[0] > SMA1[0]))
                    			&& (SystemPerformance.AllTrades.TradesPerformance.ProfitFactor >= 1)
                    			{
                    				EnterLong(Convert.ToInt32(DefaultQuantity), "");
                    			}
                    			
                    			 // Set 4
                    			if ((WMA1[0] < SMA1[0]))
                    			{
                    				ExitLong(Convert.ToInt32(DefaultQuantity), "", "");
                    			}
                    			
                    		}
                    
                    		#region Properties
                    		[NinjaScriptProperty]
                    		[Range(1, int.MaxValue)]
                    		[Display(Name="TrailingStopPips", Description="Trailing Stop set in Pips", Order=1, GroupName="Parameters")]
                    		public int TrailingStopPips
                    		{ get; set; }
                    
                    	}
                    }
                    I plan on making code currently in the works Walky-Talky see below. where the strategies operate in parellel; 1 on "Sim101", 2 on "Real-Time". while the strategies are running the Sim101 will Write and the Real-Time will Read.

                    Code:
                    #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 ForexBasicLogic : Strategy
                    	{
                    		private WMA WMA1;
                    		private SMA SMA1;
                    
                    		protected override void OnStateChange()
                    		{
                    		
                    			}
                    
                    			if (State == State.SetDefaults)
                    			{
                    				Description						= @"Base Logic; comfirmation of 5 Bar movement.";
                    				Name							= "ForexBasicLogic";
                    				Calculate						= Calculate.OnEachTick;
                    				EntriesPerDirection					= 1;
                    				EntryHandling						= EntryHandling.AllEntries;
                    				IsExitOnSessionCloseStrategy				= true;
                    				ExitOnSessionCloseSeconds				= 900;
                    				IsFillLimitOnTouch					= true;
                    				MaximumBarsLookBack					= MaximumBarsLookBack.TwoHundredFiftySix;
                    				OrderFillResolution					= OrderFillResolution.Standard;
                    				Slippage						= 0;
                    				StartBehavior						= StartBehavior.WaitUntilFlat;
                    				TimeInForce						= TimeInForce.Day;
                    				TraceOrders						= false;
                    				RealtimeErrorHandling					= RealtimeErrorHandling.IgnoreAllErrors;
                    				StopTargetHandling					= StopTargetHandling.PerEntryExecution;
                    				BarsRequiredToTrade					= 20;
                    				// Disable this property for performance gains in Strategy Analyzer optimizations
                    				// See the Help Guide for additional information
                    				IsInstantiatedOnEachOptimizationIteration		= true;
                    				TrailingStopPips					= 20;
                    			}
                    			else if (State == State.Configure)
                    			{
                    			}
                    			else if (State == State.DataLoaded)
                    			{				
                    				WMA1				= WMA(Close, 5);
                    				SMA1				= SMA(Close, 5);
                    				SetTrailStop("", CalculationMode.Pips, TrailingStopPips, false);
                    			}
                    		}
                    		protected override void OnBarUpdate()
                    		{
                    			if (BarsInProgress != 0) 
                    			return;
                    
                    			if (CurrentBars[0] < 1)
                    			return;
                    
                    			 // Set 1
                    			if ((WMA1[0] > SMA1[0]))
                    			{
                    				ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
                    			}
                    
                    			 // Set 2
                    			if ((WMA1[0] < SMA1[0]))
                    			{
                    				ExitLong(Convert.ToInt32(DefaultQuantity), "", "");
                    			}
                    
                    			        if (Account.Name == "Sim101")	
                    			        {
                    					
                    					 // Set 3
                    					if ((WMA1[0] < SMA1[0]))
                    					{
                    						EnterShort(Convert.ToInt32(DefaultQuantity), "");
                    					}
                    			
                    					 // Set 4
                    					if ((WMA1[0] > SMA1[0]))
                    					{
                    						EnterLong(Convert.ToInt32(DefaultQuantity), "");
                    					}
                    WriteLogic SharedFile(Wright file named: Strategy.Name+Instrument.Name+".txt"[Get = Strategy.Name + Instrument.Name] [Set = ProfitFactor])
                    			        }
                    	
                     			       else if (Account.Name != "Sim101")	
                    			        {
                    ReadLogic SharedFile(Read file named: Strategy.Name+Instrument.Name+".txt" [Get = Strategy.Name + Instrument.Name] [Set = ProfitFactor])
                    					 // Set 5
                    					if ((WMA1[0] < SMA1[0]))
                    					&& (SharedFile >= 1)
                    					{
                    						EnterShort(Convert.ToInt32(DefaultQuantity), "");
                    					}
                    			
                    					 // Set 6
                    					if ((WMA1[0] > SMA1[0]))
                    					&& (SharedFile >= 1)
                    					{
                    						EnterLong(Convert.ToInt32(DefaultQuantity), "");
                    					}
                    
                    			        }
                    
                    		}
                    
                    		#region Properties
                    		[NinjaScriptProperty]
                    		[Range(1, int.MaxValue)]
                    		[Display(Name="TrailingStopPips", Description="Trailing Stop set in Pips", Order=1, GroupName="Parameters")]
                    		public int TrailingStopPips
                    		{ get; set; }
                    
                    	}
                    }
                    Any help with the code would be nice.
                    Good Luck To All
                    Last edited by GTBrooks; 08-04-2018, 05:56 PM. Reason: refining Code in second set

                    Comment


                      #11
                      Hello GTBrooks,

                      NinjaScript strategies are designed to be independent of each other and any logic to have the strategies communicate with each other and work in parallel would have to be created on your own for your exact purposes. There would be a limited amount of advise we could provide, but we could offer some direction to get you started.

                      You may opt to use a StreamReader and a StreamWriter to have the strategies write to a file and to read from a file to communicate between each other. Keep in mind, you will have to come up with a solution for File Access Violations where one script is trying to read or write from the file when it is already in use.

                      You may also opt to implement your own static methods/variables in an AddOn that both strategies can read/write to.

                      Some examples for these items can be referenced below. The actual implementations would need to be tailored to your exact needs.

                      StreamReader - https://ninjatrader.com/support/help...o_read_fro.htm

                      StreamWriter - https://ninjatrader.com/support/help...o_write_to.htm

                      MyShardedMethodsExample - https://ninjatrader.com/support/foru...104#post457104

                      Please let us know if you have any further questions.
                      JimNinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by PhillT, Today, 02:16 PM
                      2 responses
                      3 views
                      0 likes
                      Last Post PhillT
                      by PhillT
                       
                      Started by Kaledus, Today, 01:29 PM
                      3 responses
                      9 views
                      0 likes
                      Last Post NinjaTrader_Jesse  
                      Started by frankthearm, Yesterday, 09:08 AM
                      14 responses
                      47 views
                      0 likes
                      Last Post NinjaTrader_Clayton  
                      Started by gentlebenthebear, Today, 01:30 AM
                      2 responses
                      14 views
                      0 likes
                      Last Post gentlebenthebear  
                      Started by PaulMohn, Today, 12:36 PM
                      2 responses
                      17 views
                      0 likes
                      Last Post PaulMohn  
                      Working...
                      X