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

Undocumented/Unsupported Ninja Tips and Tricks

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

    Originally posted by Trader_55 View Post
    Nobody from NT ever replied to this. Is there some way to detect the workspace that a chart/indicator is in from C# code?
    You can get the file name...

    Code:
    string workspaceName = NinjaTrader.Gui.WorkspaceOptions.GetCurrentFilename();
    			
    Print(workspaceName);
    
    // C:\Users\matthew\Documents\NinjaTrader 7\workspaces\PMTests.xml
    MatthewNinjaTrader Product Management

    Comment


      Originally posted by NinjaTrader_Matthew View Post
      You can get the file name...

      Code:
      string workspaceName = NinjaTrader.Gui.WorkspaceOptions.GetCurrentFilename();
                  
      Print(workspaceName);
      
      // C:\Users\matthew\Documents\NinjaTrader 7\workspaces\PMTests.xml
      Excellent! This is good enough. For my purposes however, it would also help if I could somehow detect if the indicator code itself was executing inside a workspace that was currently the visually displayed one.

      In other words, supposed there were two workspaces name "WS1" and "WS2". Supposed two different charts were loaded, one in WS1, and one in WS2. Suppose WS1 was currently being displayed on screen, and WS2 was hidden. Suppose the charts were running the exact same indicator code.

      I'd like to be able to do the following in the indicator code:

      if ( /* running in the currently visible workspace, whether it is WS1 or WS2 */ )
      {
      // execute indicator code
      }
      else
      {
      // return and do nothing
      }

      This way, I could save CPU cycles by making the indicator calculate only within the currently visible workspace.

      Is there something in the WorkspaceOptions class that would help me do this? I could already run a hack by comparing the currently displayed workspace name to the current instrument loaded and run one workspace per instrument (thereby detecting if the code is actually executing in the currently visible workspace), but a better way of doing it would also be helpful.

      Comment


        Synch Strategy from Account Postions

        Originally posted by rmt81 View Post
        The following code appears to copy the account positions to the strategy positions:

        protectedoverridevoid OnStartUp()
        {
        // Copy any outstanding Positions from the Account to the Strategy
        for (int i = 0; i < Positions.GetLength(0); i++)
        {
        Position StratPos = Positions[i];
        Position AcctPos = Account.Positions.FindByInstrument(StratPos.Instru ment);
        if (AcctPos != null)
        Positions.SetValue(AcctPos, i);
        }
        }

        Are there any particular issues or problems that I should look out for when using this approach to synchronize the strategy to match the account?
        The code above as is will not work for the case where your Account is Flat for the instrument, but your strategy position is not Flat. This is because (at least from my tests on the IB connection) if your Account is Flat for specified instrument then your resulting AcctPos will be null (not a nice object populated with stuff like MarketPosition==MarketPosition.Flat).

        It just needs a change at the end like this
        Code:
        if (AcctPos ==null) AcctPos =new  Cbi.Position(this.Account,this.Instrument,MarketPosition.Flat, 0,this.Instrument.MasterInstrument.Currency,0);//ie Account has no position in this instrument
        Positions.SetValue(AcctPos, i);
        There's also the fact that if you have the same instrument in more than one Position then the result for the 'subsequent' positions will not be in line with the documentation (which says that subsequent positions will be shown Flat).
        Partly to avoid the design oddities with multiple positions I only use one Position per strategy.
        Last edited by DaveE; 11-27-2013, 06:56 AM. Reason: code improved

        Comment


          Identify which Account Orders were created by strategy

          Originally posted by rmt81 View Post
          I suppose that if there was a possibility of orders left outstanding, I would need to do something similar for the Orders object as I did above for the Positions object.
          I have found that placing enough orders from NT strategy to IB will result in IB Account getting out of sync with Strategy.
          For instance in Managed using a strategy that reverses position will cause overfill after enough trades.
          Using Unmanaged strategy, if connection goes down while a limit order created by the strategy is active (and executes while connection down) then the strategy position gets out of sync when connection returns. In this case NT on reconnection will mark the limit order as status 'unknown' and unfilled (even though it IS filled on the server).
          In order to be able to code a correct recovery we need to be able to differentiate the Account Orders that were created by our strategy from those created by something else (like TWS or another strategy). Here's a start at the code:

          Code:
          Cbi.OrderCollection aoc = Account.Orders;
          			
          			for (int iaoc = 0; iaoc < aoc.Count; iaoc++) 
          			{
          				Cbi.Order ao = aoc[iaoc];
          				if (ao.Instrument.MasterInstrument.Name == Instrument.MasterInstrument.Name)
          				{//limit to account orders matching the strategy's instrument
          					Print(string.Format("Instrument.MasterInstrument.Name={0}, OrderType={1}, Account.Name={2}, OrderState={3}, Quantity={4}, LimitPrice={5},StopPrice={6}, Filled={7}, Info={8}",ao.Instrument.MasterInstrument.Name, ao.OrderType, ao.Account.Name, ao.OrderState, ao.Quantity, ao.LimitPrice, ao.StopPrice, ao.Filled, ao.Info));
          					Print(string.Format("  Name={0}, Oco={1}, OverFill={2}, TerminatedState={3}, Token={4}, UserLink={5}, Gtd={6}, OrderId={7}, Provider={8}, Time={9}",ao.Name, ao.Oco, ao.OverFill, ao.TerminatedState, ao.Token, ao.UserLink, ao.Gtd, ao.OrderId, ao.Provider, ao.Time));
          					Print(ao.ToString());
                                                  Cbi.Order mso = this.Orders.FindByToken(ao.Token);//matching strategy order (null if not found)
          				        if (mso!=null) Print("   token indicates there's a matching strategy order");
          					Print("");
          				}
          			}
          So we can match account orders to our strategy orders.
          You might think this would allow you to recover correct order status after a reconnect.
          However in the case of IB: After a reconnect the way NT currently works is to change the status of orders, that were executed at IB during disconnect,to 'unknown'. This happens both to Account.Orders and to the strategies orders (this.Orders). This means that we don't seem to have a way to find, in code, out the true status of the orders (that were working at disconnection) after reconnection.
          TWS does have the correct status (filled), and the execution is even recorded in NT's executions.txt file (after the reconnection), but no OnExecution() event is raised.
          Does anyone know an undocumented method to query the real (TWS) status of an order?
          Last edited by DaveE; 11-27-2013, 07:16 AM. Reason: added code to match strategy order

          Comment


            How to get the expected end DateTime of bar being built

            This code works for Minute or Second bars, if used in OnBarUpdate:
            Code:
            DateTime dtEndOfWorkingBar= Bars.Get(CurrentBar+1).Time
            However it does not work for Day bars (in this case it just shows the current date with no time component).
            Does anyone know how to get the expected DateTime end of the bar being built when using PeriodType.Day ?

            NT must surely have this data item (lets call it dtEndOfWorkingBar), because I assume their code that builds bars does something like this:
            if (dtTick > dtEndOfWorkingBar)
            {
            // close the working bar and start another one (recalculate dtEndOfWorkingBar)
            // trigger OnBarUpdate
            }
            So where is this data item hidden for day bars?

            Comment


              DaveE,

              You can use GetNextBeginEnd() to get the end time for the day bar.
              http://www.ninjatrader.com/support/h...xtbeginend.htm
              Cal H.NinjaTrader Customer Service

              Comment


                Originally posted by NinjaTrader_Cal View Post
                DaveE,

                You can use GetNextBeginEnd() to get the end time for the day bar.
                http://www.ninjatrader.com/support/h...xtbeginend.htm
                Cal, Your suggestion only works if user wants single day bars, and the session in use defines daily sessions. But it does not work if:
                User wants Value>1 (say 2 day bars), or a session template is being used where there is not a break defined every trading date.

                Comment


                  Account name

                  Hi all

                  I have a Strategy that is used for back testing

                  I would like to make sure it can only run on a SIM account

                  I have looked all over and cant find the solution

                  any ideas please

                  Comment


                    Hi Rich,

                    Sure. The first line of your OnBarUpdate(), please the following check


                    Code:
                    			
                    if(!this.Account.Name.Contains("SIM")
                    	return;
                    You can of course add some sort of message on the chart for the user if you'd like.
                    mrlogik
                    NinjaTrader Ecosystem Vendor - Purelogik Trading

                    Comment


                      Originally posted by mrlogik View Post
                      Hi Rich,

                      Sure. The first line of your OnBarUpdate(), please the following check


                      Code:
                                  
                      if(!this.Account.Name.Contains("SIM")
                          return;
                      You can of course add some sort of message on the chart for the user if you'd like.
                      Great Thank you

                      Comment


                        Some could help on the code wherein it can detect if the Buy/Sell Market button on the chart trader is being click?

                        Comment


                          GetBarIdxFromXPos

                          Hi:

                          Some code I worked up based off of the functionality in charthelper.cs.

                          This version, however, accurately gets the barIdx under the mouse (or x-pos) within the chart whether or not the chart has EquidistantBarSpacing set to TRUE or FALSE.

                          Included is a bonus function to get the last visible, valid bar index in the chart regardless of equidistant mode, timeframe or scrolling.

                          Code:
                                  public int ConvertXtoBarIdx(int x)
                                  {
                                      _debug = "";
                                      if (chartControl == null)
                                          return 0;
                          
                                      int numBarsOnCanvas = 0;
                                      int idxFirstBar = 0;
                                      int idxLastBar = 0;
                                      int barIndex;
                                      int firstBarX;
                                      double dRatio;
                                      int halfBarWidth = (int)Math.Round(((double)(chartControl.BarSpace / (double)2)), 0, MidpointRounding.AwayFromZero);
                          
                                      if (!chartControl.EquidistantBars)
                                      {
                                          // This appears to always be valid when bars are NOT equidistant
                                          idxLastBar = Bars.GetBar(chartControl.LastBarTimePainted);
                                          barIndex = idxLastBar;
                          
                                          firstBarX = chartControl.GetXByBarIdx(Bars, barIndex);
                          
                                          // In my case I detect if the mouse is beyond the rightmost bar in the chart by testing it against the last VisibleBar as calculated
                                          // by the helper function below...
                                          // so if the mouse is beyond the rightmost bar, let's return a barIndex that is beyond the rightmost valid visible bar index...
                                          if (x > (firstBarX + halfBarWidth))
                                              return (idxLastBar + 1);
                          
                                          while (firstBarX > (x+halfBarWidth))
                                          {
                                              barIndex--;
                                              firstBarX = chartControl.GetXByBarIdx(Bars, barIndex);
                                          }
                          
                                          // firstBarX will be the exact center of the bar...
                                          // we want to return the same index for the entire bar so we account for that...
                                          if (x < (firstBarX - halfBarWidth))
                                              barIndex--;
                                          else if (x > (firstBarX + halfBarWidth))
                                              barIndex++;
                                      }
                                      else
                                      {
                                          if (chartControl.LastBarPainted < Bars.Count)
                                          {
                                              numBarsOnCanvas = chartControl.LastBarPainted - chartControl.FirstBarPainted;
                                              idxFirstBar = chartControl.FirstBarPainted;
                                              idxLastBar = chartControl.LastBarPainted;
                                          }
                                          else
                                          {
                                              numBarsOnCanvas = Bars.Count - chartControl.FirstBarPainted;
                                              idxFirstBar = chartControl.FirstBarPainted;
                                              idxLastBar = Bars.Count - 1;
                                          }
                          
                                          firstBarX = chartControl.GetXByBarIdx(Bars, idxFirstBar);
                          
                                          int margin = firstBarX + halfBarWidth;
                                          dRatio = 1 + ((x - margin) / (double)(chartControl.BarSpace));
                                          int numberPeriods = (int)Math.Truncate(dRatio);
                          
                                          barIndex = idxFirstBar + numberPeriods;
                          
                                          _debug = "BarIndex = " + barIndex + " NumBarsCanvas= " + numBarsOnCanvas + " FirstBar=" + idxFirstBar + " LastBar=" + idxLastBar + " Ratio = " + dRatio + " NumPeriods =" + numberPeriods;
                                      }
                          
                                      return barIndex;
                                  }
                          
                          
                                  public int GetLastValidVisibleBarIdx()
                                  {
                                      int idxLastBar;
                          
                                      if (!chartControl.EquidistantBars)
                                          idxLastBar = Bars.GetBar(chartControl.LastBarTimePainted);
                                      else
                                          idxLastBar = chartControl.LastBarPainted;
                          
                          
                                      return Math.Min(idxLastBar, Bars.Count - 1);
                                  }

                          Comment


                            Coordinates for multi Panel

                            Hi,

                            I've been experimenting with charthelper and its basically working for me, which is great, but I haven't been able to get correct coordinates when the chart has extra panels in it.

                            I'm not sure if code modifications are required, or if its just a case of correctly initialising the bounds. Can anyone give me some tips, or example code on how to make these adjustments?

                            Thanks,
                            Will.

                            Comment


                              Backtest with Multiple Strategies

                              Hi everyone,

                              I am trying to create a strategy where I can instantiate other strategies and have them run.

                              This is my code. It actually gives an error but after ignoring it, it runs but only with the saved default settings. I should be able to change them.

                              Code:
                              #region Using declarations
                              using System;
                              using System.ComponentModel;
                              using System.Diagnostics;
                              using System.Drawing;
                              using System.Drawing.Drawing2D;
                              using System.Xml.Serialization;
                              using NinjaTrader.Cbi;
                              using NinjaTrader.Data;
                              using NinjaTrader.Indicator;
                              using NinjaTrader.Gui.Chart;
                              using NinjaTrader.Strategy;
                              #endregion
                              
                              namespace NinjaTrader.Strategy
                              {
                                  public class MultiStrategyTest : Strategy
                                  {
                                      protected override void Initialize()
                                      {
                                          CalculateOnBarClose 		= false;
                                          Unmanaged 					= true;
                                          MaximumBarsLookBack 		= MaximumBarsLookBack.Infinite;
                                          BarsRequired 				= 0;
                                          IncludeCommission 			= true;
                                          Slippage 					= 1;
                                          ConnectionLossHandling 		= ConnectionLossHandling.KeepRunning;
                              			RealtimeErrorHandling 		= RealtimeErrorHandling.TakeNoAction;
                                          ExitOnClose 				= false;
                              			MultiThreadSupport			= false;
                                      }
                              		
                              		public StrategyBase st1;
                              		
                              		protected override void OnStartUp()
                              		{
                              			if (st1 == null)
                              			{
                              				st1 					= new NinjaTrader.Strategy.CoreOne();
                              				st1.Account 			= this.Account;
                              				st1.CalculateOnBarClose = this.CalculateOnBarClose;
                              				st1.BarsRequired 		= this.BarsRequired;
                              				st1.FillType 			= this.FillType;
                              				st1.Slippage 			= this.Slippage;
                              				st1.BackTestFrom 		= this.BackTestFrom;
                              				st1.BackTestTo 			= this.BackTestTo;
                              				st1.BackTestMode		= this.BackTestMode;
                              				st1.IncludeCommission	= this.IncludeCommission;
                              				st1.MaximumBarsLookBack = this.MaximumBarsLookBack;
                              				st1.ExitOnClose			= this.ExitOnClose;
                              				st1.TimeInForce			= this.TimeInForce;			
                              				st1.Instrument 			= this.Instrument;
                              				st1.SetBarsPeriodInstrument(this.Bars.Period, this.Instrument);
                              				st1.SetUp();				
                              				
                              			}			
                              			if (!st1.Enabled) st1.Enabled = true;
                              			if (!st1.Running) st1.Running = true;
                              		}
                              		
                              		protected override void OnTermination()
                                      {
                                          if (st1 != null)
                                          {
                                              st1.Dispose();
                                              st1 = null;
                                          }
                                      }
                              		
                                      protected override void OnBarUpdate()
                                      {}
                              		
                              		
                                  }
                              }
                              What am I doing wrong here?

                              I'll be waiting for your suggestions, thanks in advance.

                              Comment


                                Chart Trader Labels???

                                Did anyone know how to turn the chart trader labels "On" (Stops/Targets) from within a custom strategy?
                                Attached Files

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by Noerclou, Today, 04:55 AM
                                0 responses
                                1 view
                                0 likes
                                Last Post Noerclou  
                                Started by llanqui, Yesterday, 09:59 AM
                                2 responses
                                16 views
                                0 likes
                                Last Post llanqui
                                by llanqui
                                 
                                Started by ThoriSten, Today, 03:56 AM
                                0 responses
                                6 views
                                0 likes
                                Last Post ThoriSten  
                                Started by PhillT, 04-19-2024, 02:16 PM
                                3 responses
                                20 views
                                0 likes
                                Last Post mangel2000  
                                Started by TraderBCL, Today, 02:37 AM
                                0 responses
                                4 views
                                0 likes
                                Last Post TraderBCL  
                                Working...
                                X