Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
NinjaTrader
https://github.com/wf-injoy/ninjatrader-documentation
Admin
06052025 Desktop
Tokens:
190,197
Snippets:
1,202
Trust Score:
1.7
Update:
1 year ago
Context
Chat
Benchmark
55
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Configure Multi-Instrument Setup - NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getcurrentbidvolume.md Shows how to configure an indicator or strategy to use multiple instruments by adding an additional data series (e.g., 'MSFT') during the `State.Configure` phase in the `OnStateChange` event. ```C# protected override void OnStateChange() { if (State == State.SetDefaults) { Name = "Examples Indicator"; } if (State == State.Configure) { //Add MSFT as our additional data series AddDataSeries("MSFT", BarsPeriodType.Minute, 1); } } ``` -------------------------------- ### OnShare Method Implementation Example - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_onshare.md Provides a basic example of how to implement the OnShare method override in C#. Custom logic for handling the shared text and image file path should be placed within the method body. ```csharp public override void OnShare(string text, string imgFilePath) { // place your share service logic here } ``` -------------------------------- ### Example GetInitialLookBackDays Implementation C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getinitiallookbackdays.md Provides an example implementation of the GetInitialLookBackDays method for a monthly Bars type. It calculates the minimum number of days needed by multiplying the bars period value, the requested bars back, and a factor (31 days) to ensure sufficient data is loaded. ```C# public override int GetInitialLookBackDays(BarsPeriod barsPeriod, TradingHours tradingHours, int barsBack) { // Returns the minimum number of days needed to successfully load the number // of bars back requested for a monthly Bars type return (int) barsPeriod.Value * barsBack * 31; } ``` -------------------------------- ### Configuring Multi-Instrument Setup - NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getcurrentaskvolume.md Shows how to add a secondary data series (MSFT) during the State.Configure phase within the OnStateChange method. This setup is required for accessing data from multiple instruments. ```csharp protected override void OnStateChange() { if (State == State.SetDefaults) { Name = "Examples Indicator"; } if (State == State.Configure) { //Add MSFT as our additional data series AddDataSeries("MSFT", BarsPeriodType.Minute, 1); } } ``` -------------------------------- ### Using CloseStrategy with Time Condition in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_closestrategy.md This example demonstrates how to initialize a start time in OnStateChange and then use it within OnBarUpdate to call CloseStrategy after a specific duration (45 minutes) if a position is still open. It shows a practical application of the CloseStrategy method. ```csharp DateTime StartTime = new DateTime(); protected override void OnStateChange() { if (State == State.SetDefaults) { Name = "ExampleStrategy"; } else if (State == State.Transition) StartTime = Core.Globals.Now; } protected override void OnBarUpdate() { // if we're still in position 45 minutes after the start time, close strategy if(Position.MarketPosition != MarketPosition.Flat && Time[0] >= StartTime.AddMinutes(45)) CloseStrategy("My Custom Close"); } ``` -------------------------------- ### SolidColorBrush Class Syntax Example Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_direct2d1_radialgradientbrush.md This snippet shows the basic syntax for defining a class, presented in the context of Direct2D brushes, although the main topic is RadialGradientBrush. ```C# class SolidColorBrush ``` -------------------------------- ### Subscribing to Fundamental Data in NinjaTrader C# Add On Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_fundamentaldata.md This C# example demonstrates how to subscribe to fundamental data updates for a specific instrument within a NinjaTrader Add On tab (NTTabPage). It shows how to get an Instrument object, subscribe to the FundamentalData.Update event, access snapshot data upon initialization, define an event handler for updates, and properly unsubscribe during cleanup. ```C# // Example of subscribing/unsubscribing to fundamental data from an Add On. The concept can be carried over // to any NinjaScript object you may be working on. public class MyAddOnTab : NTTabPage { private Instrument instrument; public MyAddOnTab() { instrument = Instrument.GetInstrument("AAPL"); if (instrument == null) return; // Subscribe to fundamental data. Snapshot data is provided right on subscription if (!instrument.Dispatcher.HasShutdownStarted) instrument.Dispatcher.InvokeAsync(() => instrument.FundamentalData.Update += OnFundamentalData); // Printing snapshot fundamental data for average daily volume NinjaTrader.Code.Output.Process(instrument.FundamentalData.AverageDailyVolume, PrintTo.OutputTab1); } // This method is fired on fundamental data events private void OnFundamentalData(object sender, FundamentalDataEventArgs e) { // Do something with fundamental data events } // Called by TabControl when tab is being removed or window is closed public override void Cleanup() { // Make sure to unsubscribe to the fundamental data subscription if (instrument != null) instrument.FundamentalData.Update -= OnFundamentalData; } // Other required NTTabPage members left out for demonstration purposes. Be sure to add them in your own code. } ``` -------------------------------- ### Drawing a Basic Rectangle - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_draw_rectangle.md This example demonstrates drawing a simple blue rectangle on the chart. The rectangle is defined by its start and end points using bars ago (10 bars back to 5 bars back) and calculated Y-values based on the Low and High prices, with a blue outline brush. ```C# // Draws a blue rectangle from the low 10 bars back to the high of 5 bars back Draw.Rectangle(this, "tag1", 10, Low[10] - TickSize, 5, High[5] + TickSize, Brushes.Blue); ``` -------------------------------- ### Calling C# Method Multiple Times Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_functions_and_methods_explained.md Shows an example C# method `ExampleMethod` that demonstrates calling the `AverageRange()` method multiple times: once in an `if` condition and again within a `Print` statement to reuse the calculation logic. ```csharp private void ExampleMethod() { if (High[0] - Low[0] > AverageRange()) { Print("The current bar range is greater than the 3 bar average range of " + AverageRange().ToString()); } } ``` -------------------------------- ### Example Accessing Multi-Bars Price Data in NinjaScript C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_multi_time_frame_instruments.md Provides a comprehensive example within the OnBarUpdate method demonstrating how to access current bar closing prices from different Bars objects (primary, MSFT 3min, AAPL 1min) based on the current BarsInProgress context. Includes checks for sufficient bars. ```csharp protected override void OnBarUpdate() { // Checks to ensure all Bars objects contain enough bars before beginning // If this is a strategy, use BarsRequiredToTrade instead of BarsRequiredToPlot if (CurrentBars[0] <= BarsRequiredToPlot || CurrentBars[1] <= BarsRequiredToPlot || CurrentBars[2] <= BarsRequiredToPlot) return; // Checks if OnBarUpdate() is called from an update on the primary Bars if (BarsInProgress == 0) { double primaryClose = Close[0]; double msft3minClose = Closes[1][0]; double aapl1minClose = Closes[2][0]; // primaryClose could also be expressed as // primaryClose = Closes[0][0]; } // Checks if OnBarUpdate() is called from an update on **MSFT** 3 minute Bars object if (BarsInProgress == 1) { double primaryClose = Closes[0][0]; double msft3minClose = Close[0]; double aapl1minClose = Closes[2][0]; } } ``` -------------------------------- ### Example Usage of NinjaTrader Account Class in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_account_class.md This C# snippet demonstrates how to interact with a NinjaTrader Account instance within the OnStateChange method of a script. It shows how to find a specific account by name, subscribe to static and instance-specific account events, access account properties using the AccountItem indexer, retrieve cash value, iterate through executions, and properly unsubscribe from events when the script terminates. ```csharp private Account myAccount; protected override void OnStateChange() { if (State == State.SetDefaults) { // Find our Sim101 account lock (Account.All) myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101"); // Subscribe to static events. Remember to unsubscribe with -= when you are done Account.AccountStatusUpdate += OnAccountStatusUpdate; if (myAccount != null) { // Print some information about our account using the AccountItem indexer Print(string.Format("Account Name: {0} Connection Name: {1} Cash Value {2}", myAccount.Name, myAccount.Connection.Options.Name, myAccount.Get(AccountItem.CashValue, Currency.UsDollar))); // Print the prices of the executions on our account lock (myAccount.Executions) foreach (Execution execution in myAccount.Executions) Print("Price: " + execution.Price); // Subscribe to events. Remember to unsubscribe with -= when you are done myAccount.AccountItemUpdate += OnAccountItemUpdate; myAccount.ExecutionUpdate += OnExecutionUpdate; } } else if (State == State.Terminated) { // Unsubscribe to events myAccount.AccountItemUpdate -= OnAccountItemUpdate; myAccount.ExecutionUpdate -= OnExecutionUpdate; Account.AccountStatusUpdate -= OnAccountStatusUpdate; } } private void OnAccountStatusUpdate(object sender, AccountStatusEventArgs e) { // Do something with the account status update } private void OnAccountItemUpdate(object sender, AccountItemEventArgs e) { // Do something with the account item update } private void OnExecutionUpdate(object sender, ExecutionEventArgs e) { // Do something with the execution update } ``` -------------------------------- ### Get Current Bid Volume (Multi-Instrument) - NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getcurrentbidvolume.md Illustrates how to access the current real-time bid volume for different instruments in a multi-instrument setup using the `GetCurrentBidVolume(int barsSeriesIndex)` method, checking the `BarsInProgress` property to identify the updating series. ```C# protected override void OnBarUpdate() { if(BarsInProgress == 0) { long currentBidVolume = GetCurrentBidVolume(0); Print("The Current Bid volume is: " + currentBidVolume); //The Current Bid volume is: 346 } if(BarsInProgress == 1) { long msftBidVolume = GetCurrentBidVolume(1); Print("MSFT's Current Bid volume is: " + msftBidVolume); //MSFT's Current Bid volume is: 1548 } } ``` -------------------------------- ### Helper Method Usage - ToDxBrush - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_direct2d1_solidcolorbrush.md Illustrates the use of the NinjaTrader helper method to convert a System.Windows.Media.SolidColorBrush to a SharpDX.Direct2D1.SolidColorBrush. ```C# NinjaTrader.Gui.DxExtensions.ToDxBrush() ``` -------------------------------- ### Playing WAV Files using NinjaTrader PlaySound (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_playsound.md This C# snippet demonstrates how to use the PlaySound method in NinjaTrader. It shows two common ways to play a .wav file: by providing a direct absolute file path and by constructing a path relative to the NinjaTrader installation directory using NinjaTrader.Core.Globals.InstallDir. ```C# // Plays the wav file mySound.wav PlaySound(@"C:\mySound.wav"); // Plays the default Alert1 sound that comes packaged with NinjaTrader PlaySound(NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav"); ``` -------------------------------- ### Getting Slot Time in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_gettimebyslotindex.md This snippet demonstrates how to use the ChartControl.GetTimeBySlotIndex method within the OnRender method of a NinjaTrader indicator or strategy. It retrieves the DateTime for a specific slot index (150 in this example) and then prints the date part of the returned DateTime object. ```csharp protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { // Find the timestamp of the bar at index 150 DateTime slotTime = chartControl.GetTimeBySlotIndex(150); // Print the date of slotTime Print(slotTime.Date); } ``` -------------------------------- ### Syntax Definition - SolidColorBrush - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_direct2d1_solidcolorbrush.md Defines the basic syntax for the SharpDX.Direct2D1.SolidColorBrush class. ```C# class SolidColorBrush ``` -------------------------------- ### Getting RSquared Indicator Value in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_r_squared.md This snippet demonstrates how to retrieve the current value of the RSquared indicator in NinjaTrader using C#. It shows examples for accessing the value for the most recent bar using both the default price type and a specific price type (High), and then prints the calculated value. ```csharp // Prints the current value of a 20 period R-squared using default price type double value = RSquared(20)[0]; Print("The current R-squared value is " + value.ToString()); // Prints the current value of a 20 period R-squared using high price type double value = RSquared(High, 20)[0]; Print("The current R-squared value is " + value.ToString()); ``` -------------------------------- ### Constructor - SolidColorBrush(RenderTarget, Color4, BrushProperties) - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_direct2d1_solidcolorbrush.md Creates a new instance of SolidColorBrush with a specified render target, color, and optional brush properties. ```C# new SolidColorBrush(RenderTarget renderTarget, Color4 color, Nullable< brushproperties > brushProperties) ``` -------------------------------- ### Getting Current ATR Value in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_average_true_range_atr.md This snippet demonstrates how to access the current value of the Average True Range (ATR) indicator in NinjaTrader using C#. It calculates the ATR for a specified period (20 in this example) using the default price type and prints the resulting value to the output. ```csharp // Prints the current value of a 20 period ATR using default price type double value = ATR(20)[0]; Print("The current ATR value is " + value.ToString()); ``` -------------------------------- ### Set Static Profit Target in OnStateChange (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_setprofittarget.md This example demonstrates how to set a static profit target for a strategy within the OnStateChange method during the State.Configure phase. This ensures the profit target is defined once upon strategy initialization. ```C# protected override void OnStateChange() { if (State == State.Configure) { // Submits a profit target order 10 ticks away from the avg entry price SetProfitTarget(CalculationMode.Ticks, 10); } } ``` -------------------------------- ### Constructor - SolidColorBrush(RenderTarget, Color4) - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_direct2d1_solidcolorbrush.md Creates a new instance of SolidColorBrush with a specified render target and color. ```C# new SolidColorBrush(RenderTarget renderTarget, Color4 color) ``` -------------------------------- ### Compare Current Bar Date using ToDay in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_today.md This NinjaScript C# example demonstrates how to use the ToDay function within the OnBarUpdate method to get the integer date of the current bar (Time[0]) and compare it to a specific date (20140915). If the current bar's date is later, a placeholder action is indicated. ```C# protected override void OnBarUpdate() { // Compare the date of the current bar to September 15, 2014 if (ToDay(Time[0]) > 20140915) { // Do something } } ``` -------------------------------- ### Getting Standard Deviation (StdDev) Value in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_standard_deviation_stddev.md This snippet demonstrates how to retrieve the current Standard Deviation (StdDev) value for a specified period in NinjaTrader using C#. It shows examples for both the default price type and the High price type, accessing the value for the current bar using the [0] index. ```C# // Prints the current value of a 20 period **StdDev** using default price type double value = StdDev(20)[0]; Print("The current **StdDev** value is " + value.ToString()); // Prints the current value of a 20 period **StdDev** using high price type double value = StdDev(High, 20)[0]; Print("The current **StdDev** value is " + value.ToString()); ``` -------------------------------- ### Setting up TabControl with Factory in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_tabcontrol.md This C# example demonstrates how to use the TabControl class within an NTWindow. It shows how to instantiate TabControl, configure its attached properties for enabling tab add, remove, and move features, set a custom factory (MyWindowFactory) for creating new tabs, and add an initial tab (MyTab). It also includes the implementation of the INTTabFactory interface. ```csharp public class MyWindow : NTWindow, IWorkspacePersistence { public MyWindow() { // TabControl should be created for window content if tab features are wanted TabControl tc = new TabControl(); // Attached properties defined in the TabControlManager class should be set to add, remove, or move tabs TabControlManager.SetIsMovable(tc, true); TabControlManager.SetCanAddTabs(tc, true); TabControlManager.SetCanRemoveTabs(tc, true); // if the ability to add new tabs is desired, TabControl must have attached property "Factory" set. TabControlManager.SetFactory(tc, new MyWindowFactory()); Content = tc; /* In order to have link buttons functionality, tab control items must be derived from Tools.NTTabPage They can be added using extention method AddNTTabPage(NTTabPage page) */ tc.AddNTTabPage(new MyTab()); } } /* Class which implements Tools.INTTabFactory must be created and set as an attached property for TabControl in order to use tab page add/remove/move/duplicate functionality */ public class MyWindowFactory : INTTabFactory { // INTTabFactory member. Required to create parent window public NTWindow CreateParentWindow() { return new MyWindow(); } // INTTabFactory member. Required to create tabs public NTTabPage CreateTabPage(string typeName, bool isTrue) { return new MyTab(); } } ``` -------------------------------- ### Getting Linear Regression Intercept Value in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_linear_regression_intercept.md This snippet demonstrates how to retrieve the current Linear Regression Intercept value for a specified period using the LinRegIntercept method in NinjaScript. It shows examples for both the default price input and the 'High' price input, accessing the current bar's value using the [0] indexer and printing the result. ```csharp // Prints the current intercept value of a 20 period LinReg using default price type double value = LinRegIntercept(20)[0]; Print("The current intercept value is " + value.ToString()); // Prints the current intercept value of a 20 period LinReg using high price type double value = LinRegIntercept(High, 20)[0]; Print("The current intercept value is " + value.ToString()); ``` -------------------------------- ### Setting up resources that rely on market data - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_ninjascript_best_practices.md Objects or resources that require market data for their construction or initialization, such as indicators or data series, should be instantiated only after the strategy's State has reached State.DataLoaded to ensure they have valid data inputs. ```csharp // Best practice // these resources depend on bars, wait until State.DataLoaded to instantiated private EMA myEMA; private Series<double> mySeries; private SessionIterator mySessionIterator; protected override void OnStateChange() { if (State == State.DataLoaded) { myEMA = EMA(20); mySeries = new Series<double>(this); mySessionIterator = new SessionIterator(Bars); } ``` -------------------------------- ### Initializing SharpDX Direct2D1 BrushProperties Structure (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_direct2d1_brushproperties.md Initializes a new instance of the `BrushProperties` structure, setting default values for opacity and transformation. ```C# new BrushProperties() ``` -------------------------------- ### Accessing WMA Value in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_moving_average_weighted_wma.md This snippet demonstrates how to retrieve the current value of a 20-period Weighted Moving Average (WMA) in NinjaTrader using C#. It shows examples for accessing the WMA value based on the default price series and a specific price series (High). The `[0]` index is used to get the value for the current bar. ```csharp // Prints the current value of a 20 period WMA using default price type double value = WMA(20)[0]; Print("The current WMA value is " + value.ToString()); // Prints the current value of a 20 period WMA using high price type double value = WMA(High, 20)[0]; Print("The current WMA value is " + value.ToString()); ``` -------------------------------- ### Using MIN to find lowest value in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_minimum_min.md This snippet demonstrates how to use the MIN method in C# within NinjaTrader. It shows how to get the lowest value of the Low series over the last 20 bars, both including the current bar (using [0]) and excluding the current bar (using [1]). It also includes an example of using the historical MIN value ([1]) to check for a break condition and draw an arrow. ```csharp // Prints the lowest low value over the last 20 periods double value = MIN(Low, 20)[0]; Print("The current MIN value is " + value.ToString()); // Note the above call with a barsAgo of 0 includes the current MIN of the input low series in the value. If we want to check for example for a break of this value, storing the last bar's MIN would be needed. double value = MIN(Low, 20)[1]; if (Low[0] < value) Draw.ArrowDown(this, CurrentBar.ToString(), true, 0, High[0] + TickSize, Brushes.Red); ``` -------------------------------- ### Initializing FibonacciPivots (With Input) in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_fibonacci_pivots.md Provides the syntax for initializing the FibonacciPivots indicator using a specified input series (e.g., another indicator's output) instead of default price data. ```C# FibonacciPivots(ISeries<double> input, PivotRange pivotRangeType, HLCCalculationMode priorDayHLC, double userDefinedClose, double userDefinedHigh, double userDefinedLow, int width) ``` -------------------------------- ### Getting Current Ask Price for Multiple Instruments in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getcurrentask.md This example illustrates how to handle multiple instruments when using GetCurrentAsk() in a NinjaTrader script. The OnStateChange method is used to add a secondary data series (MSFT). The OnBarUpdate method then checks the BarsInProgress property to determine which data series is currently updating and calls GetCurrentAsk() with the appropriate barsSeriesIndex (0 for the primary series, 1 for the secondary) to retrieve the ask price for that specific instrument. ```csharp protected override void OnStateChange() { if (State == State.SetDefaults) { Name = "Example's Indicator"; } if (State == State.Configure) { //Add MSFT as our additional data series AddDataSeries("MSFT", BarsPeriodType.Minute, 1); } } protected override void OnBarUpdate() { // Ensure we do not call GetCurrentBid() on historical data if (State == State.Historical) return; if (BarsInProgress == 0) { double primaryAsk = GetCurrentAsk(0); Print("The Primary Ask price is: " + primaryAsk); // The Primary Ask price is: 1924.75 } if (BarsInProgress == 1) { double msftAsk = GetCurrentAsk(1); Print("MSFT's Current Ask price is: " + msftAsk); // MSFT's Current Ask is: 43.63 } } ``` -------------------------------- ### Implementing INTTabFactory in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_inttabfactory_interface.md This C# class demonstrates how to implement the INTTabFactory interface. It provides implementations for CreateParentWindow to create the main window container and CreateTabPage to create new tab instances when needed. This is required for custom tab management features. ```csharp public class MyWindowFactory : INTTabFactory { // INTTabFactory member. Creates the parent window that contains tabs public NTWindow CreateParentWindow() { return new MyWindow(); } // INTTabFactory member. Creates new tab pages whenever the user presses the + button public NTTabPage CreateTabPage(string typeName) { return new MyWindowTabPage(); } } ``` -------------------------------- ### Configuring Indicator States - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getcurrentbidvolume.md Shows how to handle different states in a NinjaTrader indicator's OnStateChange method, including setting default properties and adding an additional data series during the Configure state. ```csharp protected override void OnStateChange() { if (State == State.SetDefaults) { Name = "Examples Indicator"; } if (State == State.Configure) { //Add MSFT as our additional data series AddDataSeries("MSFT", BarsPeriodType.Minute, 1); } } ``` -------------------------------- ### Transitioning NinjaTrader Order References (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_ninjascript_best_practices.md Demonstrates how to update locally stored order references when a strategy order transitions from historical backtest to real-time execution in NinjaTrader. It also shows how to null the reference once the order is filled or cancelled. ```csharp // Best practice private Order entryOrder = null; protected override void OnBarUpdate() { if (entryOrder == null && Close[0] > Open[0]) entryOrder = EnterLongLimit("myEntryOrder", Low[0]); } protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError) { // One time only, as we transition from historical // Convert any old historical order object references to the live order submitted to the real-time account if (entryOrder != null && entryOrder.IsBacktestOrder && State == State.Realtime) entryOrder = GetRealtimeOrder(entryOrder); // Null entryOrder if filled or cancelled. We do not use the Order objects after the order is filled, so we can null it here if (entryOrder != null && entryOrder == order) { if (order.OrderState == OrderState.Cancelled && order.Filled == 0) entryOrder = null; if (order.OrderState == OrderState.Filled) entryOrder = null; } ``` -------------------------------- ### Initializing SharpDX.Color Default Constructor (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_color.md Initializes a new instance of the Color struct using its default, parameterless constructor. ```C# new Color() ``` -------------------------------- ### Example Implementation of OnRestoreValues C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_onrestorevalues.md Provides a basic example of overriding the OnRestoreValues method. This method is called when the column is restored from a workspace, allowing custom logic to be executed, such as triggering a repaint. ```csharp public override void OnRestoreValues() { // Do something with the restored values. Can also trigger a repaint via OnPropertyChanged() } ``` -------------------------------- ### Setting Up Market Data Dependent Resources in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_ninjascript_best_practices.md Describes the recommended approach for constructing or initializing resources and objects that depend on market data in NinjaTrader. It advises delaying the instantiation of such objects (like indicators, series, or iterators) until the State.DataLoaded state is reached in the OnStateChange method, ensuring their underlying inputs are valid. ```C# // Best practice // these resources depend on bars, wait until State.DataLoaded to instantiated private EMA myEMA; private Series<double> mySeries; private SessionIterator mySessionIterator; protected override void OnStateChange() { if (State == State.DataLoaded) { myEMA = EMA(20); mySeries = new Series<double>(this); mySessionIterator = new SessionIterator(Bars); } ``` -------------------------------- ### Skipping Loop Iterations with Continue (C#) - Example 2 Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_looping_commands.md Another illustration of the 'continue' command in a 'for' loop, identical to the previous example. The 'continue' statement prevents the 'Print' statement from being reached in any iteration. ```C# // Never prints "NinjaTrader" for (int x = 0; x < 100; x++) { continue; Print("NinjaTrader"); } ``` -------------------------------- ### Calling AlertCallback Method in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_alertcallback.md This snippet demonstrates how to call the Alert.AlertCallback method with various parameters. It shows how to specify the instrument, source, unique ID, time, priority, message, sound file location (using Globals.InstallDir), background/foreground colors, and rearm duration (set to 0). ```csharp NinjaTrader.NinjaScript.Alert.AlertCallback(NinjaTrader.Cbi.Instrument.GetInstrument("MSFT"), this, "someId", NinjaTrader.Core.Globals.Now, Priority.High, "message", NinjaTrader.Core.Globals.InstallDir+@"\sounds\Alert1.wav", new SolidColorBrush(Colors.Blue), new SolidColorBrush(Colors.White), 0); ``` -------------------------------- ### Get Current S2 Pivot Value - NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_pivots.md Demonstrates how to get the current S2 pivot value from the Pivots indicator using daily range and intraday data calculation mode. It then prints the value to the output. ```C# // Prints the current S2 pivot value double value = Pivots(PivotRange.Daily, HLCCalculationMode.CalcFromIntradayData, 0, 0, 0, 20).S2[0]; Print("The current Pivots' S2 pivot value is " + value.ToString()); ``` -------------------------------- ### Constructor with Weight, Style, Stretch, and Size - SharpDX TextFormat - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_directwrite_textformat.md Creates a TextFormat object with specified font family name, weight, style, stretch, and size. Requires a DirectWrite Factory object. ```C# new TextFormat(Factory factory, string fontFamilyName, [FontWeight](sharpdx_directwrite_textformat_fontweight) fontWeight, [FontStyle](sharpdx_directwrite_textformat_fontstyle) fontStyle, [FontStretch](sharpdx_directwrite_textformat_fontstretch) fontStretch, float fontSize) ``` -------------------------------- ### Example: Setting FormatDecimals in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_formatdecimals.md This C# example demonstrates how to set the FormatDecimals property within the OnStateChange method during the State.SetDefaults phase to specify the number of decimal places for the displayed value. It also shows how to update the CurrentValue in the OnMarketData method. ```csharp protected override void OnStateChange() { if (State == State.SetDefaults) { // Round CurrentValue to one decimal place FormatDecimals = 1; } } protected override void OnMarketData(MarketDataEventArgs marketDataUpdate) { CurrentValue = marketDataUpdate.Price; } ``` -------------------------------- ### Get Current Pivot Point Value - NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_pivots.md Demonstrates how to get the current pivot point (Pp) value from the Pivots indicator using daily range and intraday data calculation mode. It then prints the value to the output. ```C# // Prints the current pivot point value double value = Pivots(PivotRange.Daily, HLCCalculationMode.CalcFromIntradayData, 0, 0, 0, 20).Pp[0]; Print("The current Pivots' pivot value is " + value.ToString()); ``` -------------------------------- ### Class Definition Syntax - SharpDX TextFormat - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_directwrite_textformat.md Shows the basic class definition syntax for the SharpDX DirectWrite TextFormat class. ```C# class TextFormat ``` -------------------------------- ### Getting Current Bid Volume (Default Series) - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getcurrentbidvolume.md Demonstrates how to retrieve the current bid volume for the primary data series within the OnBarUpdate method of a NinjaTrader indicator. Prints the volume to the output window. ```csharp protected override void OnBarUpdate() { long currentBidVolume = GetCurrentBidVolume(); Print("The Current Bid volume is: " + currentBidVolume); //The Current Bid volume is: 158 } ``` -------------------------------- ### Creating SharpDX SolidColorBrush (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_working_with_brushes.md Demonstrates how to instantiate a SharpDX SolidColorBrush using either a predefined SharpDX color or a custom color with specified alpha transparency. These brushes must be created per render target. ```csharp // use predefined "Blue" SharpDX Color SharpDX.Direct2D1.SolidColorBrush solidBlueDXBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Blue); // create custom Brush using a "Red" SharpDX Color with "Alpha" (0.100f) transparency/opacity SharpDX.Direct2D1.SolidColorBrush transparentRedDXBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, new SharpDX.Color4(new SharpDX.Color3(220f, 0f, 0f), 0.100f)); ``` -------------------------------- ### Get Current Bid Volume (Single Instrument) - NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getcurrentbidvolume.md Demonstrates how to retrieve and print the current real-time bid volume for the primary instrument using the parameterless `GetCurrentBidVolume()` method within the `OnBarUpdate` event. ```C# protected override void OnBarUpdate() { long currentBidVolume = GetCurrentBidVolume(); Print("The Current Bid volume is: " + currentBidVolume); //The Current Bid volume is: 158 } ``` -------------------------------- ### Creating TextFormat and TextLayout using DirectWriteFactory (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_directwritefactory.md This snippet demonstrates how to use the default NinjaTrader DirectWrite factory to create SharpDX.DirectWrite.TextFormat and SharpDX.DirectWrite.TextLayout objects. It requires references to SharpDX.DirectWrite and NinjaTrader.Core. ```csharp // create a text format object with default NinjaTrader DirectWrite factory SharpDX.DirectWrite.TextFormat textFormat = new SharpDX.DirectWrite.TextFormat(NinjaTrader.Core.Globals.DirectWriteFactory, "Arial", 12f); // create a text layout object with default NinjaTrader DirectWrite factory SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(NinjaTrader.Core.Globals.DirectWriteFactory, "text to render", textFormat, ChartPanel.W, ChartPanel.H); ``` -------------------------------- ### Get ATM Strategy Position Average Price in OnBarUpdate (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getatmstrategypositionaverageprice.md Demonstrates how to retrieve and print the average price of an active ATM strategy position within the OnBarUpdate() method. It first checks if the strategy is flat before attempting to get the average price. ```csharp protected override void OnBarUpdate() { // Check if flat if (GetAtmStrategyMarketPosition("id") != MarketPosition.Flat) Print("Average price is " + GetAtmStrategyPositionAveragePrice("id").ToString()); } ``` -------------------------------- ### Get Bar Index by Time in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getbaridxbytime.md This snippet demonstrates how to use the ChartBars.GetBarIdxByTime method within the OnBarUpdate override to get the bar index for the current bar's time and print it to the output window. It first checks if ChartBars is initialized. ```csharp protected override void OnBarUpdate() { if (ChartBars != null) { Print(ChartBars.GetBarIdxByTime(ChartControl, Time[0])); } } ``` -------------------------------- ### Initializing SharpDX.Color4 (From Color3, C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_color4.md Initializes a new instance of the Color4 struct using a SharpDX.Color3 struct for the RGB components and defaulting the alpha component to 1.0 (fully opaque). ```C# new Color4(Color3 color3) ``` -------------------------------- ### Example Entering Trades in Multi-Bars NinjaScript Strategy C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_multi_time_frame_instruments.md Shows how to submit market buy orders (EnterLong) within a NinjaScript strategy's OnBarUpdate method. It demonstrates placing orders for the instrument associated with the current BarsInProgress and also placing an order for a different instrument by specifying its BarsInProgress index. Includes checks for sufficient bars. ```csharp protected override void OnBarUpdate() { // Checks to ensure all Bars objects contain enough bars before beginning // If this is an indicator, use BarsRequiredToPlot instead of BarsRequiredToTrade if (CurrentBars[0] <= BarsRequiredToPlot || CurrentBars[1] <= BarsRequiredToPlot || CurrentBars[2] <= BarsRequiredToPlot) return; // Checks if OnBarUpdate() is called from an update on the primary Bars if (BarsInProgress == 0) { // Submits a buy market order for **MSFT** EnterLong(); } // Checks if OnBarUpdate() is called from an update on **AAPL** 1 minute Bars object if (BarsInProgress == 2) { // Submits a buy market order for **AAPL** EnterLong(); // Submits a buy market for **MSFT** when OnBarUpdate() is called for **AAPL** EnterLong(0, 100, "BUY MSFT"); } } ``` -------------------------------- ### GetXByBarIndex Example in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getxbybarindex.md This C# example demonstrates how to use the ChartControl.GetXByBarIndex method within the OnRender override to retrieve the chart-canvas x-coordinate for a specific bar index (100 in this case) and print its value. This method is typically used when drawing objects on the chart canvas. ```csharp protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { double xCoordinate = chartControl.GetXByBarIndex(ChartBars, 100); // Print the x-coordinate value Print(xCoordinate); } ``` -------------------------------- ### Flatten a list of instruments - NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_flatten.md This example shows how to flatten the account for multiple instruments by providing a collection. It requires adding using System.Collections.ObjectModel;. A Collection<cbi.instrument> is instantiated, instruments are added using Instrument.GetInstrument, and the collection is passed to Account.Flatten. ```C# // Please note that your 'Using declarations' section needs to have // // using System.Collections.ObjectModel; // //added in order for this example to compile correctly // instantiate a list of instruments Collection<cbi.instrument> instrumentsToClose = new Collection<instrument>(); // add instruments to the collection instrumentsToClose.Add(Instrument.GetInstrument("AAPL")); instrumentsToClose.Add(Instrument.GetInstrument("MSFT")); // pass the instrument collection to the Flatten() method to be flattened Account.Flatten(instrumentsToClose); ``` -------------------------------- ### Drawing Rectangles with Draw.Rectangle in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_draw_rectangle.md This snippet demonstrates two common ways to use the Draw.Rectangle method in NinjaTrader C#. The first example draws a rectangle outline using BarsAgo and price coordinates. The second example adds a fill color with transparency. ```csharp // Draws a blue rectangle from the low 10 bars back to the high of 5 bars back Draw.Rectangle(this, "tag1", 10, Low[10] - TickSize, 5, High[5] + TickSize, Brushes.Blue); // Draws a blue rectangle from the low 10 bars back to the high of 5 bars back with a fill color or pale green with a transparency level of 2 Draw.Rectangle(this, "tag1", false, 10, Low[10] - TickSize, 5, High[5] + TickSize, Brushes.PaleGreen, Brushes.PaleGreen, 2); ``` -------------------------------- ### C# Method with Return Type and Parameter Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_functions_and_methods_explained.md Shows a C# method `Multiply` that accepts a single `double` parameter named `input` and returns a `double` value. It calculates the product of the input and 10 and returns the result. ```csharp private double Multiply(double input) { return input * 10; } ``` -------------------------------- ### Initializing ATM Strategy Selector Controls (C#) Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_atmstrategyselector.md This C# code snippet demonstrates how to find UI controls (QuantityUpDown, TifSelector, AtmStrategySelector) within the logical tree, set up data bindings, and attach event handlers to manage user interactions and updates related to ATM strategy selection, quantity, and time-in-force settings. ```csharp private QuantityUpDown qudSelector; private TifSelector tifSelector; private AtmStrategy.AtmStrategySelector atmStrategySelector; private DependencyObject LoadXAML() { qudSelector = LogicalTreeHelper.FindLogicalNode(pageContent, "qudSelector") as QuantityUpDown; tifSelector = LogicalTreeHelper.FindLogicalNode(pageContent, "tifSelector") as TifSelector; tifSelector.SetBinding(TifSelector.AccountProperty, new Binding { Source = accountSelector, Path = new PropertyPath("SelectedAccount") }); tifSelector.SelectionChanged += (o, args) => { if (atmStrategySelector.SelectedAtmStrategy != null) atmStrategySelector.SelectedAtmStrategy.TimeInForce = tifSelector.SelectedTif; }; atmStrategySelector = LogicalTreeHelper.FindLogicalNode(pageContent, "atmStrategySelector") as AtmStrategy.AtmStrategySelector; atmStrategySelector.Id = Guid.NewGuid().ToString("N"); if (atmStrategySelector != null) atmStrategySelector.CustomPropertiesChanged += OnAtmCustomPropertiesChanged; atmStrategySelector.SetBinding(AtmStrategy.AtmStrategySelector.AccountProperty, new Binding { Source = accountSelector, Path = new PropertyPath("SelectedAccount") }); atmStrategySelector.SelectionChanged += (o, args) => { if (atmStrategySelector.SelectedItem == null) return; if (args.AddedItems.Count > 0) { AtmStrategy selectedAtmStrategy = args.AddedItems[0] as AtmStrategy; if (selectedAtmStrategy != null) tifSelector.SelectedTif = selectedAtmStrategy.TimeInForce; } }; } private void OnAtmCustomPropertiesChanged(object sender, NinjaScript.AtmStrategy.CustomPropertiesChangedEventArgs args) { tifSelector.SelectedTif = args.NewTif; qudSelector.Value = args.NewQuantity; } public override void Cleanup() { base.Cleanup(); } ``` -------------------------------- ### Getting Current Bid Volume (Multiple Series) - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getcurrentbidvolume.md Illustrates how to access the current bid volume for different data series within OnBarUpdate by checking the BarsInProgress index. Retrieves volume for both the primary series (index 0) and an additional series (index 1). ```csharp protected override void OnBarUpdate() { if(BarsInProgress == 0) { long currentBidVolume = GetCurrentBidVolume(0); Print("The Current Bid volume is: " + currentBidVolume); //The Current Bid volume is: 346 } if(BarsInProgress == 1) { long msftBidVolume = GetCurrentBidVolume(1); Print("MSFT's Current Bid volume is: " + msftBidVolume); //MSFT's Current Bid volume is: 1548 } } ``` -------------------------------- ### Getting ATM Strategy Realized Profit Loss in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getatmstrategyrealizedprofitloss.md This snippet demonstrates how to call the GetAtmStrategyRealizedProfitLoss method within the OnBarUpdate event handler in a NinjaTrader script (indicator or strategy) to retrieve and print the realized profit and loss for a specific ATM strategy using its ID. ```csharp protected override void OnBarUpdate() { Print("PnL is " + GetAtmStrategyRealizedProfitLoss("id").ToString()); } ``` -------------------------------- ### Constructor with Weight, Style, and Size - SharpDX TextFormat - C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_sharpdx_directwrite_textformat.md Creates a TextFormat object with specified font family name, weight, style, and size, using default normal stretch. Requires a DirectWrite Factory object. ```C# new TextFormat(Factory factory, string fontFamilyName, [FontWeight](sharpdx_directwrite_textformat_fontweight) fontWeight, [FontStyle](sharpdx_directwrite_textformat_fontstyle) fontStyle, float fontSize) ``` -------------------------------- ### Using MAX Indicator in NinjaTrader C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_maximum_max.md This snippet demonstrates how to use the MAX method in C# within NinjaTrader. It shows how to get the current highest value over the last 20 bars and print it, and also how to get the highest value from the previous bar to check for a breakout condition and draw an arrow. ```csharp // Prints the highest high value over the last 20 periods double value = MAX(High, 20)[0]; Print("The current MAX value is " + value.ToString()); // Note the above call with a barsAgo of 0 includes the current MAX of the input high series in the value. If we want to check for example for a break of this value, storing the last bar's MAX would be needed. double value = MAX(High, 20)[1]; if (High[0] > value) Draw.ArrowUp(this, CurrentBar.ToString(), true, 0, Low[0] - TickSize, Brushes.Blue); ``` -------------------------------- ### Running Optimizer Iteration in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_runiteration.md Demonstrates how to call the RunIteration() method within the OnOptimize() override in a NinjaTrader optimizer class. This method triggers a single backtesting iteration based on the current optimizer settings. ```csharp protected override void OnOptimize() { // Optimizer logic RunIteration(); } ``` -------------------------------- ### Getting ATM Strategy Unrealized PnL in C# Source: https://github.com/wf-injoy/ninjatrader-documentation/blob/main/docs/developer_ninjatrader_com_docs_desktop_getatmstrategyunrealizedprofitloss.md This C# snippet demonstrates how to call the GetAtmStrategyUnrealizedProfitLoss method within the OnBarUpdate event handler to retrieve and print the unrealized profit and loss for an ATM strategy identified by 'id'. It requires access to the Print method and the GetAtmStrategyUnrealizedProfitLoss method. ```csharp protected override void OnBarUpdate() { Print("Unrealized PnL is " + GetAtmStrategyUnrealizedProfitLoss("id").ToString()); } ```