### Execution Object Examples Source: https://developer.ninjatrader.com/docs/desktop/execution Code examples demonstrating how to use the Execution object, including finding executions for a specific order and generic execution logic. ```APIDOC ## Examples ### Finding the executions of a particular Order object ```csharp // Example #1 private Order entryOrder = null; protected override void OnBarUpdate() { if (entryOrder == null && Close[0] > Open[0]) EnterLong("myEntryOrder"); } protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time) { // Assign entryOrder in OnExecutionUpdate() to ensure the assignment occurs when expected. // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not guaranteed to be complete if it is referenced immediately after submitting if (execution.Order.Name == "myEntryOrder" && execution.Order.OrderState == OrderState.Filled) entryOrder = execution.Order; if (entryOrder != null && entryOrder == execution.Order) Print(execution.ToString()); } ``` ### Generic execution logic not specific to a particular Order object ```csharp // Example #2 protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time) { // Remember to check the underlying Order object for null before trying to access its properties if (execution.Order != null && execution.Order.OrderState == OrderState.Filled) Print(execution.ToString()); } ``` ``` -------------------------------- ### C# Example: Implementing NTWindow with Workspace Persistence Source: https://developer.ninjatrader.com/docs/desktop/ntwindow Demonstrates how to create a custom window by inheriting from NTWindow and implementing IWorkspacePersistence. This example shows setting window properties like caption and dimensions, configuring a TabControl for tabs, and handling workspace saving and restoration logic. ```csharp public class AddOnFrameworkWindow : NTWindow, IWorkspacePersistence { // default constructor public AddOnFrameworkWindow() { // set Caption property (not Title), since Title is managed internally to properly combine selected Tab Header and Caption for display in the Windows taskbar // This is the name displayed in the top-left of the window Caption = "AddOn Framework"; // Set the default dimensions of the window Width = 1085; Height = 900; // 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 achieve adding, removing, and moving tabs TabControlManager.SetIsMovable(tc, true); TabControlManager.SetCanAddTabs(tc, true); TabControlManager.SetCanRemoveTabs(tc, true); // if ability to add new tabs is desired, TabControl has to have attached property "Factory" set. TabControlManager.SetFactory(tc, new AddOnFrameworkWindowFactory()); Content = tc; /* In order to have link buttons functionality, tab control items must be derived from Tools.NTTabPage They can be added using extension method AddNTTabPage(NTTabPage page) */ tc.AddNTTabPage(new AddOnFrameworkTab()); // WorkspaceOptions property must be set Loaded += (o, e) => { if (WorkspaceOptions == null) WorkspaceOptions = new WorkspaceOptions("AddOnFramework-" + Guid.NewGuid().ToString("N"), this); }; } // IWorkspacePersistence member. Required for restoring window from workspace public void Restore(XDocument document, XElement element) { if (MainTabControl != null) MainTabControl.RestoreFromXElement(element); } // IWorkspacePersistence member. Required for saving window to workspace public void Save(XDocument document, XElement element) { if (MainTabControl != null) MainTabControl.SaveToXElement(element); } // IWorkspacePersistence member public WorkspaceOptions WorkspaceOptions { get; set; } } ``` -------------------------------- ### NinjaTrader C# Order Management Example Source: https://developer.ninjatrader.com/docs/desktop/order This C# example demonstrates how to manage entry orders in NinjaTrader Desktop. It shows how to place a long entry order when the close price is greater than the open price and how to update the entryOrder variable in the OnOrderUpdate method to reliably track order states, including when an order is filled. ```csharp private Order entryOrder = null; protected override void OnBarUpdate() { if (entryOrder == null && Close[0] > Open[0]) EnterLong("myEntryOrder"); } protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError) { // Assign entryOrder in OnOrderUpdate() to ensure the assignment occurs when expected. // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not guaranteed to be complete if it is referenced immediately after submitting if (order.Name == "myEntryOrder") entryOrder = order; if (entryOrder != null && entryOrder == order) { Print(order.ToString()); if (order.OrderState == OrderState.Filled) entryOrder = null; } } ``` -------------------------------- ### Account Class Example Source: https://developer.ninjatrader.com/docs/desktop/account_class Demonstrates how to find an account, access its properties, and subscribe to various account-related events. ```APIDOC ## Example ```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 } ``` ``` -------------------------------- ### Draw Line Example - NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/draw_line Demonstrates how to draw a dotted lime green line using the Draw.Line method in NinjaScript. The example specifies the owner, tag, auto-scale setting, start and end bar positions, start and end Y values, brush, dash style, and width. ```NinjaScript // Draws a dotted lime green line from 10 bars back to the current bar // with a width of 2 pixels Draw.Line(this, "tag1", false, 10, 1000, 0, 1001, Brushes.LimeGreen, DashStyleHelper.Dot, 2); ``` -------------------------------- ### Implement NTTabPage for Instrument and Interval Linking Source: https://developer.ninjatrader.com/docs/desktop/nttabpage Example demonstrating how to create a custom tab page by deriving from NTTabPage and implementing IInstrumentProvider and IIntervalProvider interfaces. This enables instrument and interval linking within the tab. The example shows the structure for constructor, cleanup, header retrieval, and workspace saving/restoring, along with handling instrument and bars period changes. ```csharp public class MyWindowTabPage : NTTabPage, NinjaTrader.Gui.Tools.IInstrumentProvider, IIntervalProvider { private Instrument instrument; public MyWindowTabPage() { /* Define the content for our NTTabPage. We can load loose XAML to define controls and layouts if we so choose here as well. Note: XAML with event handlers defined inside WILL FAIL when attempted to load. Note: XAML with "inline code" WILL FAIL when attempted to load */ } // Called by TabControl when a tab is being removed or window is closed public override void Cleanup() { /* Unsubscribe and clean up resources used by the tab that just closed. You may have resources you don't want to clean up just yet because the window is still being used */ } // NTTabPage member. Required for determining the tab header name protected override string GetHeaderPart(string variable) { // Determine the text for the tab header name return variable; } // NTTabPage member. Required for restoring elements from workspaces protected override void Restore(System.Xml.Linq.XElement element) { if (element == null) return; // Restore any elements you may have saved. e.g. selected accounts or instruments } // NTTabPage member. Required for saving elements to workspaces protected override void Save(System.Xml.Linq.XElement element) { if (element == null) return; // Save any elements you may want persisted. e.g. selected accounts or instruments } // IInstrumentProvider member public Instrument Instrument { get { return instrument; } set { if (instrument != null) { // Unsubscribe to subscriptions to previously selected instrument } if (value != null) { // Create subscriptions for the newly selected instrument } instrument = value; // Update the tab header name RefreshHeader(); } } // IIntervalProvider member public BarsPeriod BarsPeriod { get; set; } } ``` -------------------------------- ### Multi-Bars Data Access Example (NinjaScript) Source: https://developer.ninjatrader.com/docs/desktop/multi_time_frame_instruments Demonstrates how to safely access price data from multiple Bars objects in NinjaScript, including checks for sufficient bars and handling updates from different series. It shows how to get primary and secondary series close prices based on `BarsInProgress`. ```NinjaScript 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]; } } ``` -------------------------------- ### NinjaScript: Example method calling AverageRange Source: https://developer.ninjatrader.com/docs/desktop/functions_and_methods_explained This example method, 'ExampleMethod', demonstrates how to call the 'AverageRange' method twice. It checks if the current bar's range is greater than the calculated 3-bar average range and prints a message to the console if it is. This showcases the reusability of methods. ```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()); } } ``` -------------------------------- ### NinjaTrader Account Class Example - C# Source: https://developer.ninjatrader.com/docs/desktop/account_class This C# code snippet demonstrates how to use the NinjaTrader Account class to find an account, subscribe to account status and item update events, retrieve account information like cash value, and access execution data. It also shows how to unsubscribe from events when the state changes to Terminated. This example requires the NinjaTrader environment to run. ```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 } ``` -------------------------------- ### NinjaScript Example: Accessing Multi-Instrument Positions Source: https://developer.ninjatrader.com/docs/desktop/positionsaccount Demonstrates how to use PositionsAccount to access and print market positions for different instruments within a NinjaTrader strategy. It includes adding data series for multiple instruments and accessing their respective positions using array indexing. This example is specifically for strategies operating on multiple instruments. ```csharp protected override void OnStateChange() { if (State == State.SetDefaults) { Name = "ExampleStrategy"; } else if (State == State.Configure) { AddDataSeries("ES 03-15", BarsPeriodType.Minute, 5); AddDataSeries("NQ 03-15", BarsPeriodType.Minute, 5); } } protected override void OnBarUpdate() { Print("ES account position is " + PositionsAccount[0].MarketPosition); Print("NQ account position is " + PositionsAccount[2].MarketPosition); // Alternative approach. By checking what Bars object is calling the OnBarUpdate() // method, we can just use the Position property since its pointing to the correct // position. if (BarsInProgress == 0) Print("ES account position is " + PositionAccount.MarketPosition); else if (BarsInProgress == 2) Print("NQ account position is " + PositionAccount.MarketPosition); } ``` -------------------------------- ### Print() Method Examples in NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/print Demonstrates how to use the Print() method in NinjaScript to output various data types to the Output window. Includes examples of direct object printing, using string.Format() for formatted output, and storing variables for later printing. This method is essential for debugging and verifying values during script development. ```csharp protected override void OnBarUpdate() { // Generates a message Print("This is a message"); //Output: This is a message Print("The high of the current bar is : " + High[0]); //Output: The high of the current bar is : 2112.75 // Prints the current bar SMA value to the output window Print(SMA(Close, 20)[0]); //Output: 2110.5; } ``` ```csharp protected override void OnBarUpdate() { //Format and Print each bar value to the output window Print(string.Format("{0};{1};{2};{3};{4};{5}", Time[0], Open[0], High[0], Low[0], Close[0], Volume[0])); //Output: 2/24/2015 11:01:00 AM;2110.5;2110.5;2109.75;2110;1702 } ``` ```csharp protected override void OnBarUpdate() { //store the Close[0] value in a variable which can be printed later double myValue = Close[0]; //create and store a custom error message string myError = string.Format("Error on Bar {0}, value {1} was not expected", CurrentBar, myValue); //our first test case, if true print our error if(myValue > High[0]) Print(myError); //Output: Error on Bar 233, value 1588.25 was not expected //reassign myValue myValue = Low[0]; //our second test case (now uses Low[0]), if true print our error if(myValue > Close[0]) Print(myError); //Output: Error on Bar 57, value 1585.5 was not expected } ``` -------------------------------- ### Example: Drawing a Lime Green Ray - NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/draw_ray Demonstrates how to draw a lime green ray using the Draw.Ray method. It specifies the owner, a unique tag, the start and end points in terms of bars ago and their corresponding Y values, and the color. ```NinjaScript // Draws a lime green ray from 10 bars back through the current bar Draw.Ray(this, "tag1", 10, 1000, 0, 1001, Brushes.LimeGreen); ``` -------------------------------- ### SharpDX.Direct2D1.GeometrySink.BeginFigure() Source: https://developer.ninjatrader.com/docs/desktop/sharpdx_direct2d1_geometrysink_beginfigure Starts a new figure at the specified point. This method is part of the SharpDX SDK Reference and is intended to assist with 2D graphics concepts in NinjaTrader development. ```APIDOC ## SharpDX.Direct2D1.GeometrySink.BeginFigure() ### Description Starts a new figure at the specified point. This method does not return a value. ### Method Not applicable (method of a class) ### Endpoint Not applicable (method of a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) This method does not return a value. #### Response Example None ## Syntax `.BeginFigure(Vector2 vector2, FigureBegin figureBegin)` ## Parameters - **vector2** (SharpDX.Vector2) - Required - The **SharpDX.Vector2** at which to begin the new figure. - **figureBegin** (SharpDX.Direct2D1.FigureBegin) - Required - The **SharpDX.Direct2D1.FigureBegin** which determines whether the new figure should be hollow or filled. ``` -------------------------------- ### Volume Indicator (VOL) Example - NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/volume Demonstrates how to retrieve and print the current value of the Volume (VOL) indicator using NinjaScript. This example accesses the indicator for the current bar (index 0) and prints its value to the output log. ```NinjaScript // Prints the current value VOL double value = VOL()[0]; Print("The current VOL value is " + value.ToString()); ``` -------------------------------- ### Example Method Calling AverageRange (NinjaScript) Source: https://developer.ninjatrader.com/docs/desktop/functions_and_methods_explained This example method demonstrates how to call the 'AverageRange' method twice within its logic. It compares the current bar's range to the calculated 3-bar average range and prints a message if the current range is larger. This showcases practical application of custom methods. ```csharp // Example method that calls the AverageRange() method twice 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()); } } ``` -------------------------------- ### Block Volume Indicator Documentation Source: https://developer.ninjatrader.com/docs/desktop/block_volume Provides details on how to use the BlockVolume indicator, including its parameters and examples for implementation. ```APIDOC ## BlockVolume Indicator ### Description Block volume detects block trades and display how many occurred per bar. This can be displayed either as trades or volume. Historical tick data is required to plot historically. ### Syntax `BlockVolume(int blockSize, CountType countType)` `BlockVolume(ISeries input, int blockSize, CountType countType)` ### Return Value **double;** Accessing this method via an index value `[int barsAgo]` returns the indicator value of the referenced bar. ### Parameters #### Path Parameters - **input** (ISeries) - Optional - Indicator source data - **blockSize** (int) - Required - The minimum volume a trade must be to be considered a block trade - **countType** (CountType) - Required - The format to count the block trades. By number of block trades that occurred or total block trade volume ### Request Example ```csharp // A 1 tick data series must be added to OnStateChange() as this indicator runs off of tick data else if (State == State.Configure) { AddDataSeries(Data.BarsPeriodType.Tick, 1); } // Prints the current value of an 80 block trade size counted in volume for the Block Volume if (BarsInProgress == 0) { double value = BlockVolume(80, CountType.Volume)[0]; Print("The current Block Volume value is " + value.ToString()); } ``` ### Response #### Success Response (200) - **double** - The calculated block volume value for the specified bar. ``` -------------------------------- ### Aroon Indicator Reference Source: https://developer.ninjatrader.com/docs/desktop/aroon Documentation for the Aroon indicator, including its description, syntax, parameters, and examples. ```APIDOC ## Aroon Indicator ### Description Developed by Tushar Chande in 1995, Aroon is an indicator system that can be used to determine whether a stock is trending or not and how strong the trend is. "Aroon" means "Dawn's Early Light" in Sanskrit and Chande chose that name for this indicator since it is designed to reveal the beginning of a new trend. The Aroon indicator system consists of two lines, **Aroon(up)** and **Aroon(down)**. It takes a single parameter which is the number of time periods to use in the calculation. Aroon(up) is the amount of time (on a percentage basis) that has elapsed between the start of the time period and the point at which the highest price during that time period occurred. If the stock closes at a new high for the given period, Aroon(up) will be +100. For each subsequent period that passes without another new high, Aroon(up) moves down by an amount equal to (1 / # of periods) x 100. ### Syntax `Aroon(int period)` `Aroon(ISeries input, int period)` **Returns up value** `Aroon(int period).Up[int barsAgo]` `Aroon(ISeries<` double`> input, int period).Up[int barsAgo]` **Returns down value** `Aroon(int period).Down[int barsAgo]` `Aroon(ISeries<` double`> input, int period).Down[int barsAgo]` ### Return Value **double** ; Accessing this method via an index value `[int barsAgo]` returns the indicator value of the referenced bar. ### Parameters #### Path Parameters - **input** (ISeries) - Required - Indicator source data - **period** (int) - Required - Number of bars used in the calculation ### Request Example ```csharp // Prints the current up/down values of a 20 period Aroon indicator double upValue = Aroon(20).Up[0]; double downValue = Aroon(20).Down[0]; Print("The current Aroon up value is " + upValue); Print("The current Aroon down value is " + downValue); ``` ### Response #### Success Response (200) - **double** (double) - The indicator value for the referenced bar. #### Response Example ```json { "indicatorValue": 0.5 } ``` ### Source Code You can view this indicator method source code by selecting the menu New > NinjaScript Editor > Indicators within the NinjaTrader Control Center window. ``` -------------------------------- ### While Loop Syntax and Example in NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/looping_commands Demonstrates the syntax and a practical example of a While loop in NinjaScript. This loop continues to execute its block of code as long as a specified boolean expression evaluates to true. It's useful for repeating actions until a certain condition is met. ```NinjaScript while (Boolean expression) { //Do something here } ``` ```NinjaScript // Print NinjaTrader 100 times to the output window int x = 0; while (x < 100) { Print("NinjaTrader"); x = x + 1; } ``` -------------------------------- ### Swing Indicator - Example Usage Source: https://developer.ninjatrader.com/docs/desktop/swing Provides an example of how to use the Swing indicator to find and print the high price of the most recent swing high. ```APIDOC ## Example: Get Most Recent Swing High Price ### Description This example demonstrates how to retrieve the high price of the most recent swing high using the Swing indicator. ### Method GET ### Endpoint `/api/indicator/swing/high` ### Parameters #### Query Parameters - **strength** (int) - Required - Set to 10 for this example. - **barsAgo** (int) - Required - Set to 0 to evaluate the current bar. ### Request Example ``` GET /api/indicator/swing/high?strength=10&barsAgo=0 ``` ### Response #### Success Response (200) - **value** (double) - The high price of the swing bar. #### Response Example ```json { "value": 150.75 } ``` **Note:** The original NinjaScript example `Print("The high of the swing bar is " + High[Math.Max(0, Swing(5).SwingHighBar(0, 1, 10))]);` implies a more complex interaction within the NinjaTrader environment. The API equivalent focuses on retrieving the swing high value directly. ``` -------------------------------- ### NinjaScript: Get Open of Current Trading Day using BarsSinceNewTradingDay Source: https://developer.ninjatrader.com/docs/desktop/referencing_the_correct_bar Illustrates the use of the BarsSinceNewTradingDay property in NinjaScript to access data relative to the start of the current trading session. This example retrieves the opening price of the current session. ```csharp double openValue = Open[Bars.BarsSinceNewTradingDay]; ``` -------------------------------- ### Example: Drawing a Blue Rectangle in NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/draw_rectangle Demonstrates how to draw a simple blue rectangle using the Draw.Rectangle method in NinjaScript. This example specifies the owner, tag, bar offsets for start and end points, and the brush color. ```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); ``` -------------------------------- ### UpBrush Component Source: https://developer.ninjatrader.com/docs/desktop/upbrush Details about the UpBrush component, including its definition, property value, syntax, and examples. ```APIDOC ## UpBrush Component ### Description A Brush object used to determine the color to paint the up bars for the ChartStyle. This Windows Presentation Forms (WPF) implementation of the Brush class is not directly used to paint bars on the chart. Instead, it is converted to a SharpDX Brush in the UpBrushDX property. This property is used to capture user input for changing brush colors. ### Property Value A WPF Brush object used to paint the up bars. ### Syntax `UpBrush` ### Examples ```csharp protected override void OnStateChange() { if (State == State.Configure) { // Set a new name for the UpBrush property SetPropertyName("UpBrush", "AdvancingBrush"); } } ``` ``` -------------------------------- ### Draw Fibonacci Time Extensions in NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/draw_fibonaccitimeextensions This example demonstrates how to draw a Fibonacci time extension object using the Draw.FibonacciTimeExtensions method in NinjaScript. It specifies parameters such as the owner object, tag, autoscale, start bar, start Y value, and end bar. ```NinjaScript // Draws a fibonacci time extension object Draw.FibonacciTimeExtensions(this, "tag1", false, 10, Low[10], 0, High[0]); ``` -------------------------------- ### Get Chart Panel Y Coordinate in NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/y_coordinate_chartpanel This code snippet demonstrates how to retrieve and print the Y coordinate of a chart panel within the NinjaScript environment. It utilizes the ChartPanel.Y property to get the starting Y-coordinate of the panel. This is useful for custom rendering or positioning elements on the chart. ```csharp protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { base.OnRender(chartControl, chartScale); // Print the coordinates of the top-left corner of the panel Print(String.Format("The panel begins at coordinates {0},{1}",ChartPanel.X ,ChartPanel.Y)); } ``` -------------------------------- ### SharpDX.Direct2D1.SolidColorBrush API Source: https://developer.ninjatrader.com/docs/desktop/sharpdx_direct2d1_solidcolorbrush Documentation for the SharpDX.Direct2D1.SolidColorBrush class, including its definition, constructors, and methods. ```APIDOC ## SharpDX.Direct2D1.SolidColorBrush ### Description Paints an area with a solid color. ### Syntax `class SolidColorBrush` ### Constructors #### `new SolidColorBrush(RenderTarget renderTarget, Color4 color)` Creates a new **SolidColorBrush** that has the specified color and opacity. #### `new SolidColorBrush(RenderTarget renderTarget, Color4 color, Nullable brushProperties)` Creates a new **SolidColorBrush** that has the specified color and opacity. ### Methods and Properties #### Color Retrieves or sets the color of the solid color brush. #### Dispose() Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. #### IsDisposed Gets a value indicating whether this instance is disposed. #### Opacity Gets or sets the degree of opacity of this brush. #### Transform Gets or sets the transform applied to this brush. ``` -------------------------------- ### Draw a Dot using NinjaScript Source: https://developer.ninjatrader.com/docs/desktop/dot Demonstrates how to instantiate and configure a Dot drawing tool in NinjaScript. This example shows how to set the position, color, and disable auto-scaling for the drawing object. ```NinjaScript /// /// Represents an interface that exposes information regarding a Dot IDrawingTool. /// public class Dot { /// /// Gets or sets the ChartAnchor representing the point of the drawing object. /// public ChartAnchor Anchor { get; set; } /// /// Gets or sets the Brush object representing the fill color of the draw object. /// public Brush AreaBrush { get; set; } /// /// Gets or sets the Brush object representing the color of the draw object's outline. /// public Brush OutlineBrush { get; set; } /// /// Gets or sets a value indicating whether the dot's Auto Scale property is enabled. /// public bool IsAutoScale { get; set; } // Instantiates a red dot on the current bar 1 tick below the low public static Dot DrawDot(object owner, string tag, bool isAutoScale, int barOffset, double priceOffset, Brush areaBrush) { // Placeholder implementation for Draw.Dot Dot myDot = new Dot(); myDot.IsAutoScale = isAutoScale; // ... other initializations ... return myDot; } } public static class Brushes { public static Brush Red { get; } static Brushes() { // Placeholder for Brushes.Red Red = new Brush(); } } public class NinjaScriptBase { protected Low[] Low; protected double TickSize; public NinjaScriptBase() { Low = new Low[1]; // Simulate Low array TickSize = 0.00001; // Simulate TickSize } // Simulate execution context public void ExecuteExample() { // Instantiates a red dot on the current bar 1 tick below the low Dot myDot = Dot.DrawDot(this, "tag1", true, 0, Low[0] - TickSize, Brushes.Red); // Disable the dot's Auto Scale property myDot.IsAutoScale = false; } } // Example usage: // NinjaScriptBase script = new NinjaScriptBase(); // script.ExecuteExample(); ``` -------------------------------- ### NinjaScript CrossBelow() Method Examples Source: https://developer.ninjatrader.com/docs/desktop/crossbelow Demonstrates how to use the CrossBelow() method in NinjaScript to identify specific trading conditions. The examples show how to check for crossovers involving indicators and fixed values, and how to incorporate these checks into trading strategies like entering long or short positions. It highlights the flexibility of using different look-back periods. ```csharp protected override void OnBarUpdate() { // Go long if CCI crossed below -250 within the last bar if (CrossBelow(CCI(14), -250, 1)) EnterLong(); // Go short if 10 EMA crosses below 20 EMA within the last bar if (CrossBelow(EMA(10), EMA(20), 1)) EnterShort(); // Go short we have a down bar and the 10 EMA crosses below 20 EMA within the last 5 bars if (Close[0] < Open[0] && CrossBelow(EMA(10), EMA(20), 5)) EnterShort(); } ``` -------------------------------- ### Get Session Start Time in User's Time Zone (C#) Source: https://developer.ninjatrader.com/docs/desktop/actualsessionbegin Retrieves the start date and time of a trading session, converted to the user's configured time zone. This requires initializing a SessionIterator and calling GetNextSession to obtain historical data. The output is a DateTime structure representing the session's beginning. ```csharp SessionIterator sessionIterator; protected override void OnStateChange() { if (State == State.Historical) { sessionIterator = new SessionIterator(Bars); } } protected override void OnBarUpdate() { // on new bars session, find the next trading session if (Bars.IsFirstBarOfSession) { // use the current bar time to calculate the next session sessionIterator.GetNextSession(Time[0], true); Print("The current session start time is " + sessionIterator.ActualSessionBegin); } } ``` -------------------------------- ### Set Up Workspace Persistence for Custom Window (C#) Source: https://developer.ninjatrader.com/docs/desktop/creating_your_own_addon_window Implements the IWorkspacePersistence interface to enable custom windows to be saved and restored within NinjaTrader workspaces. It sets WorkspaceOptions and handles the Restore and Save methods by delegating to MainTabControl. ```csharp public class AddOnFrameworkWindow : NTWindow, IWorkspacePersistence { public AddOnFrameworkWindow() { ... // **WorkspaceOptions** property must be set Loaded += (o, e) => { if (WorkspaceOptions == null) WorkspaceOptions = new WorkspaceOptions("AddOnFramework-" + Guid.NewGuid().ToString("N"), this); }; } // **IWorkspacePersistence** member. Required for restoring window from workspace public void Restore(XDocument document, XElement element) { if (MainTabControl != null) MainTabControl.RestoreFromXElement(element); } // **IWorkspacePersistence** member. Required for saving window to workspace public void Save(XDocument document, XElement element) { if (MainTabControl != null) MainTabControl.SaveToXElement(element); } // **IWorkspacePersistence** member public WorkspaceOptions WorkspaceOptions { get; set; } } ``` -------------------------------- ### Setup Resources Reliant on Market Data After State.DataLoaded in C# Source: https://developer.ninjatrader.com/docs/desktop/ninjascript_best_practices Shows how to correctly instantiate objects in C# that depend on market data. The code ensures that resources like EMA indicators, Series, and SessionIterators are only created after the 'State.DataLoaded' phase, guaranteeing that the necessary market data is available. ```csharp // Best practice // these resources depend on bars, wait until State.DataLoaded to instantiated private EMA myEMA; private Series mySeries; private SessionIterator mySessionIterator; protected override void OnStateChange() { if (State == State.DataLoaded) { myEMA = EMA(20); mySeries = new Series(this); mySessionIterator = new SessionIterator(Bars); } } ``` -------------------------------- ### Get Daily S2 Pivot Value (C#) Source: https://developer.ninjatrader.com/docs/desktop/pivots This example shows how to retrieve and print the current S2 pivot value for a daily pivot range. It uses HLCCalculationMode.CalcFromIntradayData and accesses the S2[0] property. ```csharp // 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()); ``` -------------------------------- ### NinjaScript Order Placement Trace Example Source: https://developer.ninjatrader.com/docs/desktop/traceorders2 This is an example of the trace output generated when an order is placed using the SubmitOrderManaged method in NinjaScript. It provides details such as the timestamp, entry signal, order action, type, quantity, and prices, which are essential for verifying order submission logic. ```text Entered internal **SubmitOrderManaged()** method at 6/2/2015 8:42:00 AM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='market order' FromEntrySignal='' ``` -------------------------------- ### Define Window Layout Using XAML (XML) Source: https://developer.ninjatrader.com/docs/desktop/creating_your_own_addon_window Example of defining a user interface layout using XAML, specifically creating a two-column grid with transparent background. XAML files can be packaged with C# code in a DLL. ```xml ``` -------------------------------- ### Example: Drawing a Dotted Lime Green Extended Line Source: https://developer.ninjatrader.com/docs/desktop/draw_extendedline This C# code snippet demonstrates how to draw a dotted lime green extended line on a NinjaTrader chart. It uses bar offsets to define the start and end points and specifies the color, dash style, and width for the line. This example is practical for marking specific price levels or trends over a defined bar range. ```csharp // Draws a dotted lime green Draw.ExtendedLine(this, "tag1", 10, Close[10], 0, Close[0], Brushes.LimeGreen, DashStyleHelper.Dot, 2); ``` -------------------------------- ### RunIteration() Example in C# Source: https://developer.ninjatrader.com/docs/desktop/runiteration Demonstrates how to use the RunIteration() method within the OnOptimize() function in NinjaScript (C#). This method is used to execute a single backtesting iteration for the optimizer. It does not return any value. ```csharp protected override void OnOptimize() { // Optimizer logic RunIteration(); } ``` -------------------------------- ### Get Chart Panel Boundaries as Vector2 Source: https://developer.ninjatrader.com/docs/desktop/using_sharpdx_for_custom_chart_rendering Demonstrates how to obtain the starting and ending SharpDX.Vector2 points representing the boundaries of the current chart panel. These are essential for drawing within the panel's area. ```csharp // creates a vector located at the top left corner of the chart panel startPoint = new SharpDX.Vector2(ChartPanel.X, ChartPanel.Y); // creates a vector located at the bottom right corner of the chart panel endPoint = new SharpDX.Vector2(ChartPanel.X + ChartPanel.W, ChartPanel.Y + ChartPanel.H); ``` -------------------------------- ### Draw.PathTool() Method Source: https://developer.ninjatrader.com/docs/desktop/draw_pathtool This section details the Draw.PathTool() method, its various syntaxes, parameters, and provides usage examples. ```APIDOC ## Draw.PathTool() ### Description Draws a path which can have a user defined set of anchors. ### Method Return Value A **PathTool** object that represents the draw object. ### Syntax `Draw.PathTool(NinjaScriptBase owner, string tag, bool isAutoScale, List chartAnchors, bool isGlobal, string templateName)` `Draw.PathTool(NinjaScriptBase owner, string tag, bool isAutoScale, List chartAnchors, Brush brush, DashStyleHelper dashStyle)` `Draw.PathTool(NinjaScriptBase owner, string tag, bool isAutoScale, int anchor1BarsAgo, double anchor1Y, int anchor2BarsAgo, double anchor2Y, int anchor3BarsAgo, double anchor3Y)` `Draw.PathTool(NinjaScriptBase owner, string tag, bool isAutoScale, DateTime Anchor1Time, double anchor1Y, DateTime Anchor2Time, double anchor2Y, DateTime Anchor3Time, double anchor3Y)` `Draw.PathTool(NinjaScriptBase owner, string tag, bool isAutoScale, int anchor1BarsAgo, double anchor1Y, int anchor2BarsAgo, double anchor2Y, int anchor3BarsAgo, double anchor3Y, int anchor4BarsAgo, double anchor4Y)` `Draw.PathTool(NinjaScriptBase owner, string tag, bool isAutoScale, DateTime Anchor1Time, double anchor1Y, DateTime Anchor2Time, double anchor2Y, DateTime Anchor3Time, double anchor3Y, DateTime Anchor4Time, double anchor4Y)` `Draw.PathTool(NinjaScriptBase owner, string tag, bool isAutoScale, int anchor1BarsAgo, double anchor1Y, int anchor2BarsAgo, double anchor2Y, int anchor3BarsAgo, double anchor3Y, int anchor4BarsAgo, double anchor4Y, int anchor5BarsAgo, double anchor5Y)` `Draw.PathTool(NinjaScriptBase owner, string tag, bool isAutoScale, DateTime Anchor1Time, double anchor1Y, DateTime Anchor2Time, double anchor2Y, DateTime Anchor3Time, double anchor3Y, DateTime Anchor4Time, double anchor4Y, DateTime Anchor5Time, double anchor5Y)` ### Parameters owner| The hosting **NinjaScript** object which is calling the draw method. Typically will be the object which is calling the draw method (e.g., "this"). ---|--- tag| A user defined unique id used to reference the draw object. For example, if you pass in a value of "myTag", each time this tag is used, the same draw object is modified. If unique tags are used each time, a new draw object will be created each time. isAutoScale| Determines if the draw object will be included in the y-axis scale. Default value is false. chartAnchors| A list of the chart anchors. anchor1BarsAgo| The bar the first anchor of the object will be drawn at. A value of 10 would be 10 bars ago. anchor2BarsAgo| The bar the second anchor of the object will be drawn at. A value of 10 would be 10 bars ago. anchor3BarsAgo| The bar the third anchor of the object will be drawn at. A value of 10 would be 10 bars ago. anchor4BarsAgo| The bar the forth anchor of the object will be drawn at. A value of 10 would be 10 bars ago. anchor5BarsAgo| The bar the fifth anchor of the object will be drawn at. A value of 10 would be 10 bars ago. anchor1Y| The first anchor y value. anchor2Y| The second anchor y value. anchor3Y| The third anchor y value. anchor4Y| The forth anchor y value. anchor5Y| The fifth anchor y value. Anchor1Time| The time the first anchor of the object will be drawn at. Anchor2Time| The time the second anchor of the object will be drawn at. Anchor3Time| The time the third anchor of the object will be drawn at. Anchor4Time| The time the forth anchor of the object will be drawn at. Anchor5Time| The time the fifth anchor of the object will be drawn at. templateName| The name of the drawing tool template the object will use to determine various visual properties (empty string could be used to just use the UI default visuals instead). ### Request Example ```csharp // Draws a PathTool object based on bars ago and y anchors Draw.PathTool(this, "tag1", false, 20, 194, 10, 184, 13, 176, 25, 182); // Draws a PathTool object based on a list of anchors with specified times List anchors = new List(); anchors.Add(new ChartAnchor(new DateTime(2018, 5, 25), 194, ChartControl)); anchors.Add(new ChartAnchor(new DateTime(2018, 6, 12), 184, ChartControl)); anchors.Add(new ChartAnchor(new DateTime(2018, 6, 7), 176, ChartControl)); anchors.Add(new ChartAnchor(new DateTime(2018, 5, 21), 182, ChartControl)); Draw.PathTool(this, "tag1", false, anchors, Brushes.CornflowerBlue, DashStyleHelper.Solid, Brushes.CornflowerBlue, 40); ``` ### Response #### Success Response (200) This method returns a **PathTool** object. #### Response Example ```json { "PathToolObject": "(PathTool object details)" } ``` ```