### OnStateChange setup for multi-instrument example Source: https://docs.ninjatrader.com/ninjascript/getcurrentbidvolume.md Configures the indicator with a name and adds MSFT as an additional data series using AddDataSeries. This is the setup for the subsequent multi-instrument example. ```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); } } ``` -------------------------------- ### Start ATM strategy from Add On window Source: https://docs.ninjatrader.com/ninjascript/startatmstrategy.md Example of starting an ATM strategy from an Add On window. The entry order must be named 'Entry' for the ATM strategy to start successfully. The code creates an order for AAPL on the Sim101 account and submits it with the ATM strategy named 'myAtmStrategyName'. ```csharp // Example of starting an ATM strategy from an Add On window. The concept can be carried over // to any NinjaScript object you may be working on. public class MyAddOnTab : NTTabPage { private Account account; private Order entryOrder; public MyAddOnTab() { // Find our Sim101 account lock (Account.All) account = Account.All.FirstOrDefault(a => a.Name == "Sim101"); if (account != null) { entryOrder = account.CreateOrder(Cbi.Instrument.GetInstrument("AAPL"), OrderAction.Buy, OrderType.Market, TimeInForce.Day, 1, 0, 0, string.Empty, "Entry", null); // Submits our entry order with the ATM strategy named "myAtmStrategyName" NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy("myAtmStrategyName", entryOrder); } } // Other required NTTabPage members left out for demonstration purposes. Be sure to add them in your own code if building an Add On window. } ``` -------------------------------- ### Example: Calling CloseStrategy() with Custom Signal Name Source: https://docs.ninjatrader.com/ninjascript/closestrategy.md Example strategy that calls CloseStrategy() with a custom signal name when the position is not flat and 45 minutes have passed since the strategy started. The start time is captured during the State.Transition state. ```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"); } ``` -------------------------------- ### C# example: Using SessionIterator.ActualSessionBegin to print session start time Source: https://docs.ninjatrader.com/ninjascript/actualsessionbegin.md This example demonstrates how to use the ActualSessionBegin property within a NinjaScript strategy. It initializes a SessionIterator in the Historical state and, on the first bar of a new session, calls GetNextSession with the current bar time to update the iterator, then prints the session start time. The property returns a DateTime in the user's configured time zone. ```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); } } ``` -------------------------------- ### Draw a line with RenderTarget.DrawLine Source: https://docs.ninjatrader.com/ninjascript/using_sharpdx_for_custom_chart_rendering.md Executes a drawing command on the SharpDX RenderTarget. This example draws a line using the provided start and end points and a brush. ```csharp RenderTarget.DrawLine(startPoint, endPoint, areaBrushDx) ``` -------------------------------- ### SetParabolicStop Examples Source: https://docs.ninjatrader.com/ninjascript/setparabolicstop.md Code examples demonstrating the usage of the SetParabolicStop method in NinjaScript. ```APIDOC ## SetParabolicStop(CalculationMode, double) ### Description Sets a parabolic stop using default acceleration (0.02), accelerationMax (0.2), accelerationStep (0.02) settings and a floor value of 12 ticks. ### Method SetParabolicStop ### Parameters - **calculationMode** (CalculationMode) - Required - The calculation mode for the floor value (e.g., CalculationMode.Ticks). - **value** (double) - Required - The floor value for the stop (e.g., 12 ticks). ### Request Example ```csharp SetParabolicStop(CalculationMode.Ticks, 12); ``` ### Response No return value. ``` ```APIDOC ## SetParabolicStop(string, CalculationMode, double, bool, double, double, double) ### Description Sets a parabolic stop with a currency floor of 500 and custom acceleration, accelerationMax, and accelerationStep values. ### Method SetParabolicStop ### Parameters - **signalName** (string) - Required - The name of the signal associated with the stop. - **calculationMode** (CalculationMode) - Required - The calculation mode for the floor value (e.g., CalculationMode.Currency). - **value** (double) - Required - The floor value for the stop (e.g., 500). - **isSimulated** (bool) - Required - Whether the stop is simulated (false in the example). - **acceleration** (double) - Required - The acceleration factor (e.g., 0.03). - **accelerationMax** (double) - Required - The maximum acceleration (e.g., 0.3). - **accelerationStep** (double) - Required - The acceleration step (e.g., 0.01). ### Request Example ```csharp SetParabolicStop("MyLongEntry", CalculationMode.Currency, 500, false, 0.03, 0.3, 0.01); ``` ### Response No return value. ``` -------------------------------- ### Foreach Loop Syntax and Example Source: https://docs.ninjatrader.com/ninjascript/looping_commands.md Shows the syntax of a foreach loop and a concrete example that counts oatmeal cookies in a cookie jar. The example iterates over a collection and uses an if statement to check the cookie type. ```csharp foreach (type identifier in boolean expression) { // Do something here } ``` ```csharp // Count the number of oatmeal cookies in a cookie jar int oatmealCookies = 0; foreach (cookie in cookieJar) { * if (cookie.Type == Oatmeal) { oatmealCookies = oatmealCookies + 1; } } Print("There are " + numberOatmeal.ToString() + " oatmeal cookies in the cookie jar."); ``` -------------------------------- ### Render text with RenderTarget.DrawText() Source: https://docs.ninjatrader.com/ninjascript/using_sharpdx_for_custom_chart_rendering.md Renders text using RenderTarget.DrawText() with a TextFormat, a RectangleF for positioning, and a SolidColorBrush. The example creates a 36-point Arial format, draws "I am some text" in DodgerBlue, and explicitly disposes both the textFormat and brush after use. ```csharp // define the point for the text to render SharpDX.Vector2 startPoint = new SharpDX.Vector2(ChartPanel.X, ChartPanel.Y); // construct the text format with desired font family and size SharpDX.DirectWrite.TextFormat textFormat = new SharpDX.DirectWrite.TextFormat(Core.Globals.DirectWriteFactory, "Arial", 36); // construct the rectangleF struct to describe the position and size the text SharpDX.RectangleF rectangleF = new SharpDX.RectangleF(startPoint.X, startPoint.Y, ChartPanel.W, ChartPanel.H); // define the brush used for the text SharpDX.Direct2D1.SolidColorBrush customDXBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.DodgerBlue); // execute the render target text command with desired values RenderTarget.DrawText("I am some text", textFormat, rectangleF, customDXBrush); // always dispose of textFormat when finished textFormat.Dispose(); // always dipose of brush when finished customDXBrush.Dispose(); ``` -------------------------------- ### Measure TextLayout with Metrics and draw a resizing rectangle Source: https://docs.ninjatrader.com/ninjascript/using_sharpdx_for_custom_chart_rendering.md Measures a TextLayout using its Metrics object to dynamically size a rectangle around the formatted text. The rectangle resizes to the text's width and height, and the example also draws the text and disposes of the layout, format, and brush. Note that Metrics height and width include line spacing; use GetLineMetrics() to calculate baseline distance. ```csharp // define the point for the text to render SharpDX.Vector2 startPoint = new SharpDX.Vector2(ChartPanel.X + 20, ChartPanel.Y + 20); // construct the text format with desired font family and size SharpDX.DirectWrite.TextFormat textFormat = new SharpDX.DirectWrite.TextFormat(Core.Globals.DirectWriteFactory, "Arial", 36); // construct the text layout with desired text, text format, max width and height SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, "I am also some text", textFormat, ChartPanel.W, ChartPanel.H); // create a rectangle which will automatically resize to the width/height of the textLayout SharpDX.RectangleF rectangleF = new SharpDX.RectangleF(startPoint.X, startPoint.Y, textLayout.Metrics.Width, textLayout.Metrics.Height); // define the brush used for the text and rectangle SharpDX.Direct2D1.SolidColorBrush customDXBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.DodgerBlue); // execute the render target draw rectangle with desired values RenderTarget.DrawRectangle(rectangleF, customDXBrush); // execute the render target text layout command with desired values RenderTarget.DrawTextLayout(startPoint, textLayout, customDXBrush); // always dispose of textLayout, textFormat, or brush when finished textLayout.Dispose(); textFormat.Dispose(); customDXBrush.Dispose(); ``` -------------------------------- ### Draw an Ellipse with RenderTarget.FillEllipse() Source: https://docs.ninjatrader.com/ninjascript/using_sharpdx_for_custom_chart_rendering.md Draws a filled ellipse on a SharpDX RenderTarget using a Direct2D1 Ellipse struct. Requires a Vector2 center point, RadiusX, and RadiusY; the example uses ChartPanel bounds to compute the center and a DodgerBlue SolidColorBrush. Always dispose of the brush after rendering. ```csharp // create two vectors to position the ellipse SharpDX.Vector2 startPoint = new SharpDX.Vector2(ChartPanel.X, ChartPanel.Y); SharpDX.Vector2 endPoint = new SharpDX.Vector2(ChartPanel.X + ChartPanel.W, ChartPanel.Y + ChartPanel.H); // calculate the center point of the ellipse from start/end points SharpDX.Vector2 centerPoint = (startPoint + endPoint) / 2; // set the radius of the ellipse float radiusX = 50; float radiusY = 50; // construct the rectangleF struct to describe the position and size the drawing SharpDX.Direct2D1.Ellipse ellipse = new SharpDX.Direct2D1.Ellipse(centerPoint, radiusX, radiusY); // define the brush used in the rectangle SharpDX.Direct2D1.SolidColorBrush customDXBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.DodgerBlue); // execute the render target fill ellipse with desired values RenderTarget.FillEllipse(ellipse, customDXBrush); // always dispose of a brush when finished customDXBrush.Dispose(); ``` -------------------------------- ### PlaySound() example with absolute path and InstallDir Source: https://docs.ninjatrader.com/ninjascript/playsound.md Plays a .wav file using the PlaySound() method. The first call plays a file from an absolute path, while the second uses the NinjaTrader.Core.Globals.InstallDir property to access the default sounds folder. Note that the method only executes in State.Realtime and requires PCM .wav format. ```csharp // 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"); ``` -------------------------------- ### C# example: Creating an ATM strategy with AtmStrategyCreate() Source: https://docs.ninjatrader.com/ninjascript/atmstrategycreate.md Use this example to create an ATM strategy from a NinjaScript strategy. It checks for real-time data, then calls AtmStrategyCreate() with a market buy order, using unique IDs and a callback to verify successful creation. The callback checks for errors and sets a boolean flag to indicate the ATM strategy is created. ```csharp private string atmStrategyId; private string atmStrategyOrderId; private bool isAtmStrategyCreated = false; protected override void OnBarUpdate() { if (State < State.Realtime) return; if (Close[0] > SMA(20)[0]) { atmStrategyId = GetAtmStrategyUniqueId(); atmStrategyOrderId = GetAtmStrategyUniqueId(); AtmStrategyCreate(OrderAction.Buy, OrderType.Market, 0, 0, TimeInForce.Day, atmStrategyOrderId, "MyTemplate", atmStrategyId, (atmCallbackErrorCode, atmCallbackId) => { // checks that the call back is returned for the current atmStrategyId stored if (atmCallbackId == atmStrategyId) { // check the atm call back for any error codes if (atmCallbackErrorCode == ErrorCode.NoError) { // if no error, set private bool to true to indicate the atm strategy is created isAtmStrategyCreated = true; } } }); } if(isAtmStrategyCreated) { // atm logic } else if(!isAtmStrategyCreated) { // custom handling for a failed atm Strategy } } ``` -------------------------------- ### Get Highest ZOrder Example Source: https://docs.ninjatrader.com/ninjascript/setzorder.md Example of retrieving the highest ZOrder currently in a chart. ```APIDOC ## ChartPanel.ChartObjects.Max(co => co.ZOrder) ### Description Retrieves the highest ZOrder currently in a chart. Setting higher values than this value will result in the ZOrder to be set to this value, so this can be thought of as the current 'top'. ### Method Max (LINQ) ### Syntax `ChartPanel.ChartObjects.Max(co => co.ZOrder)` ### Return Value The highest ZOrder value currently in the chart. ### Example ```csharp protected override void OnRender(ChartControl cc, ChartScale cs) { Print(ChartPanel.ChartObjects.Max(co => co.ZOrder)); } ``` ``` -------------------------------- ### StartAtmStrategy() Source: https://docs.ninjatrader.com/ninjascript/startatmstrategy.md Documentation for the StartAtmStrategy method overloads, including syntax, parameters, and examples. ```APIDOC ## StartAtmStrategy(AtmStrategy atmStrategyTemplate, Order entryOrder) ### Description Submits an entry order with an ATM strategy using an AtmStrategy object. ### Syntax `NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy(AtmStrategy atmStrategyTemplate, Order entryOrder)` ### Parameters - **atmStrategyTemplate** (AtmStrategy) - Required - An AtmStrategy representing the ATM strategy you wish to use. - **entryOrder** (Order) - Required - An Order representing the entry order. ### Remarks - The "name" argument on the **CreateOrder()** method MUST be named "Entry" for the ATM Strategy to be started successfully. ### Example ```csharp // Example of starting an ATM strategy from an Add On window. The concept can be carried over // to any NinjaScript object you may be working on. public class MyAddOnTab : NTTabPage { private Account account; private Order entryOrder; public MyAddOnTab() { // Find our Sim101 account lock (Account.All) account = Account.All.FirstOrDefault(a => a.Name == "Sim101"); if (account != null) { entryOrder = account.CreateOrder(Cbi.Instrument.GetInstrument("AAPL"), OrderAction.Buy, OrderType.Market, TimeInForce.Day, 1, 0, 0, string.Empty, "Entry", null); // Submits our entry order with the ATM strategy named "myAtmStrategyName" NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy("myAtmStrategyName", entryOrder); } } // Other required NTTabPage members left out for demonstration purposes. Be sure to add them in your own code if building an Add On window. } ``` ``` ```APIDOC ## StartAtmStrategy(string atmStrategyTemplateName, Order entryOrder) ### Description Submits an entry order with an ATM strategy using the name of the ATM strategy template. ### Syntax `NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy(string atmStrategyTemplateName, Order entryOrder)` ### Parameters - **atmStrategyTemplateName** (string) - Required - A string representing the name of the ATM strategy you wish to use. - **entryOrder** (Order) - Required - An Order representing the entry order. ### Remarks - The "name" argument on the **CreateOrder()** method MUST be named "Entry" for the ATM Strategy to be started successfully. ### Example ```csharp // Example of starting an ATM strategy from an Add On window. The concept can be carried over // to any NinjaScript object you may be working on. public class MyAddOnTab : NTTabPage { private Account account; private Order entryOrder; public MyAddOnTab() { // Find our Sim101 account lock (Account.All) account = Account.All.FirstOrDefault(a => a.Name == "Sim101"); if (account != null) { entryOrder = account.CreateOrder(Cbi.Instrument.GetInstrument("AAPL"), OrderAction.Buy, OrderType.Market, TimeInForce.Day, 1, 0, 0, string.Empty, "Entry", null); // Submits our entry order with the ATM strategy named "myAtmStrategyName" NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy("myAtmStrategyName", entryOrder); } } // Other required NTTabPage members left out for demonstration purposes. Be sure to add them in your own code if building an Add On window. } ``` ``` -------------------------------- ### MoveAnchor() Example Source: https://docs.ninjatrader.com/ninjascript/moveanchor.md Moves a chart anchor's x and y values from a start point by a delta point amount. The method does not return a value. The example passes the original starting location (lastPoint), the new location (newPoint), and the chart control, panel, scale, and drawing tool (this) that own the anchor. ```csharp //move the chart anchors x and y values MyAnchor.MoveAnchor(lastPoint, newPoint, chartControl, chartPanel, chartScale, this); ``` -------------------------------- ### Do While Loop Syntax and Example Source: https://docs.ninjatrader.com/ninjascript/looping_commands.md Shows the syntax of a do-while loop and a concrete example that prints 'NinjaTrader' 100 times. The loop body executes at least once before the condition is checked. ```csharp do { //Do something here } while (Boolean expression) ``` ```csharp // Print NinjaTrader 100 times to the output window int x = 0; do { Print("NinjaTrader"); x = x + 1; } while (x < 100) ``` -------------------------------- ### Get Previous Trading Day End - C# Example Source: https://docs.ninjatrader.com/ninjascript/getprevioustradingdayend.md Use inside OnBarUpdate() to get the end time of the previous trading session for the current bar's time. Resource intensive; avoid calling for every bar in OnBarUpdate(). The commented output shows an example with the previous session ending on 2/17/2015 3:15:00 PM. ```csharp protected override void OnBarUpdate() { if (Bars.IsFirstBarOfSession) { DateTime previousEndDate = TradingHours.GetPreviousTradingDayEnd(Time[0]); Print(string.Format("The current bars date is {0} - the previous trading session ended on {1}", Time[0], previousEndDate)); } //Output: The current bars date is 2/18/2015 12:35:00 PM - the previous trading session ended on 2/17/2015 3:15:00 PM } ``` -------------------------------- ### While Loop Syntax and Example Source: https://docs.ninjatrader.com/ninjascript/looping_commands.md Shows the syntax of a while loop and a concrete example that prints 'NinjaTrader' 100 times to the output window. The loop continues as long as the Boolean expression is true. ```csharp while (Boolean expression) { //Do something here } ``` ```csharp // Print NinjaTrader 100 times to the output window int x = 0; while (x < 100) { Print("NinjaTrader"); x = x + 1; } ``` -------------------------------- ### Log() method examples Source: https://docs.ninjatrader.com/ninjascript/log.md Two examples showing how to generate log messages: one with LogLevel.Information and one with LogLevel.Alert which also generates a pop-up notification window. ```csharp // Generates a log message Log("This is a log message", LogLevel.Information); // Generates a log message with a notification window Log("This will generate a pop-up notification window as well", LogLevel.Alert); ``` -------------------------------- ### Compare() usage example Source: https://docs.ninjatrader.com/ninjascript/compare.md Shows how to use Compare() to check if a computed price is greater than another price, with a comment indicating the action to take when the condition is true. ```csharp double newPrice = Close[0] + High[0] + Open[0]; if (Instrument.MasterInstrument.Compare(newPrice, Close[1]) == 1) // Do something since price1 is greater than price2 ``` -------------------------------- ### Declare Order object variable Source: https://docs.ninjatrader.com/ninjascript/checking_for_null_references.md Declares a private Order object variable initialized to null. This is the starting point for the example. ```csharp private Order entryOrder = null; ``` -------------------------------- ### For Loop Syntax and Example Source: https://docs.ninjatrader.com/ninjascript/looping_commands.md Shows the syntax of a for loop and a concrete example that prints 'NinjaTrader' 100 times. The loop uses an initializer, a boolean condition, and an iterator. ```csharp for (initializer; boolean expression; iterator) { //Do something here } ``` ```csharp // Print NinjaTrader 100 times to the output window for (int x = 0; x < 100; x++) { Print("NinjaTrader"); } ``` -------------------------------- ### GetCurrentAsk(int barsSeriesIndex) multi-instrument example Source: https://docs.ninjatrader.com/ninjascript/getcurrentask.md Use this example for multi-instrument scripts. It adds MSFT as an additional data series and uses the barsSeriesIndex parameter to get the ask price for each bar series, printing the primary and MSFT ask prices. ```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 } ``` -------------------------------- ### C# example: Store start time as int variable and trade after 9:30 AM Source: https://docs.ninjatrader.com/ninjascript/totime.md This snippet shows how to store a start time as an integer variable using ToTime(9, 30, 00) which returns 93000, then compare the current bar time against it to trade only after 9:30 AM. ```csharp // Store start time as an int variable to be compared int startTime = ToTime(9, 30, 00); // 93000 // Only trade after 9:30 AM if (ToTime(Time[0]) >= startTime) { // Strategy logic goes here } ``` -------------------------------- ### AtmStrategyCreate() Source: https://docs.ninjatrader.com/ninjascript/atmstrategycreate.md Documentation for the AtmStrategyCreate() method, including syntax, parameters, return value, and a C# example. ```APIDOC ## AtmStrategyCreate(OrderAction action, OrderType orderType, double limitPrice, double stopPrice, TimeInForce timeInForce, string orderId, string strategyTemplateName, string atmStrategyId, Action callback) ### Description Submits an entry order that will execute a specified ATM Strategy. This method is NOT backtestable and will NOT execute on historical data. The ATM Strategy will be created asynchronously on the hosting NinjaScripts UI Thread, and a callback is provided solely to check when the ATM Strategy is started on that thread. ### Method N/A (NinjaScript method) ### Syntax `AtmStrategyCreate(OrderAction action, OrderType orderType, double limitPrice, double stopPrice, TimeInForce timeInForce, string orderId, string strategyTemplateName, string atmStrategyId, Action callback)` ### Parameters - **action** (OrderAction) - Required - Sets if the entry order is a buy or sell order. Possible values are: OrderAction.Buy, OrderAction.Sell - **orderType** (OrderType) - Required - Sets the order type of the entry order. Possible values are: OrderType.Limit, OrderType.Market, OrderType.MIT, OrderType.StopMarket, OrderType.StopLimit - **limitPrice** (double) - Required - The limit price of the order - **stopPrice** (double) - Required - The stop price of the order - **timeInForce** (TimeInForce) - Required - Sets the time in force of the entry order. Possible values are: TimeInForce.Day, TimeInForce.Gtc - **orderId** (string) - Required - The unique identifier for the entry order - **strategyTemplateName** (string) - Required - Specifies which strategy template will be used - **atmStrategyId** (string) - Required - The unique identifier for the ATM strategy - **callback** (Action) - Required - The callback action is used to check that the ATM Strategy is successfully started ### Return Value This method does not return a value ### Example ```csharp private string atmStrategyId; private string atmStrategyOrderId; private bool isAtmStrategyCreated = false; protected override void OnBarUpdate() { if (State < State.Realtime) return; if (Close[0] > SMA(20)[0]) { atmStrategyId = GetAtmStrategyUniqueId(); atmStrategyOrderId = GetAtmStrategyUniqueId(); AtmStrategyCreate(OrderAction.Buy, OrderType.Market, 0, 0, TimeInForce.Day, atmStrategyOrderId, "MyTemplate", atmStrategyId, (atmCallbackErrorCode, atmCallbackId) => { // checks that the call back is returned for the current atmStrategyId stored if (atmCallbackId == atmStrategyId) { // check the atm call back for any error codes if (atmCallbackErrorCode == ErrorCode.NoError) { // if no error, set private bool to true to indicate the atm strategy is created isAtmStrategyCreated = true; } } }); } if(isAtmStrategyCreated) { // atm logic } else if(!isAtmStrategyCreated) { // custom handling for a failed atm Strategy } } ``` ``` -------------------------------- ### C# example using Typical property Source: https://docs.ninjatrader.com/ninjascript/typical.md Shows how to access the Typical price for the current bar, 10 bars ago, and use it in an EMA calculation. ```csharp // Current bar typical price double barTypicalPrice = Typical[0]; // Typical price of 10 bars ago double barTypicalPrice = Typical[10]; // Current bar value of a 20 period exponential moving average of typical prices double value = EMA(Typical, 20)[0]; ``` -------------------------------- ### Get session end time with SessionIterator.ActualSessionEnd Source: https://docs.ninjatrader.com/ninjascript/actualsessionend.md Shows how to obtain the actual session end time using SessionIterator.ActualSessionEnd. Requires calling GetNextSession from a stored SessionIterator object to get historical information. The example prints the session end time on the first bar of each session. ```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 end time is " + sessionIterator.ActualSessionEnd); } } ``` -------------------------------- ### GetPixelsForDistance example in OnRender Source: https://docs.ninjatrader.com/ninjascript/getpixelsfordistance.md Use this C# snippet inside the OnRender method to get the number of pixels for a specified distance (e.g., 0.25 points). The example prints the result, noting that 0.25 points corresponds to 20 pixels per tick on the chart scale. ```csharp protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { // the number of pixels between the point value passed as a distance to the method float pixelForDistance = chartScale.GetPixelsForDistance(0.25); Print("pixelForDistance: " + pixelForDistance); //20 pixels per every 1 tick on the chart scale } ``` -------------------------------- ### Continue Command Example (Duplicate) Source: https://docs.ninjatrader.com/ninjascript/looping_commands.md A duplicate of the continue command example that never prints 'NinjaTrader'. It appears again in the source, likely as a repeated illustration. ```csharp // Never prints "NinjaTrader" for (int x = 0; x < 100; x++) { continue; Print("NinjaTrader"); } ``` -------------------------------- ### Connect to a configured connection using ConnectOptions Source: https://docs.ninjatrader.com/ninjascript/connectoptions.md C# example showing how to retrieve a ConnectOptions instance by name from Core.Globals.ConnectOptions and pass it to Connection.Connect(). It locks collections to avoid in-flight changes, checks if the connection is already connected, and returns the connection only if its status is ConnectionStatus.Connected. ```csharp // Connecting to a configured connection private Connection Connect(string connectionName) { // Get the configured account connection by using the string passed into this custom Connect() method // We will lock the ConnectOptions collection to avoid in-flight changes causing any issues ConnectOptions connectOptions = null; lock (Core.Globals.ConnectOptions) connectOptions = Core.Globals.ConnectOptions.FirstOrDefault(o => o.Name == connectionName); // If connection is not already connected, connect to it lock (Connection.Connections) if (Connection.Connections.FirstOrDefault(c => c.Options.Name == connectionName) == null) { Connection connect = Connection.Connect(connectOptions); // Only return connection if successfully connected if (connect.Status == ConnectionStatus.Connected) return connect; else return null; } } ``` -------------------------------- ### Draw.TrendChannel Example Source: https://docs.ninjatrader.com/ninjascript/draw_trendchannel.md Draws a trend channel using the Draw.TrendChannel method. The example uses a tag 'tag1', sets the channel to be drawn on the chart, and specifies the start and end points using bar indices and price levels. The end point includes an offset of 5 * TickSize. ```csharp // Draws a trend channel Draw.TrendChannel(this, "tag1", true, 10, Low[10], 0, High[0], 10, High[10] + 5 * TickSize); ``` -------------------------------- ### C# examples for accessing Open property Source: https://docs.ninjatrader.com/ninjascript/open.md These examples show how to access the current bar opening price, the opening price 10 bars ago, and the current value of a 20-period simple moving average of opening prices using the Open property. ```csharp //Current bar opening price double barOpenPrice = Open[0]; // Opening price of 10 bars ago double barOpenPrice = Open[10]; //Current bar value of a 20 period simple moving average of opening prices double value = SMA(Open, 20)[0]; ``` -------------------------------- ### HorizontalLine Interface Source: https://docs.ninjatrader.com/ninjascript/horizontalline.md Represents an interface that exposes information regarding a Horizontal Line IDrawingTool. It includes properties for the starting anchor and stroke, and provides an example of usage. ```APIDOC ## HorizontalLine Interface ### Description Represents an interface that exposes information regarding a Horizontal Line **IDrawingTool**. ### Properties - **StartAnchor** (ChartAnchor) - An **IDrawingTool's ChartAnchor** representing the starting point of the drawing object. - **Stroke** (Stroke) - A **Stroke** object used to draw the object. ### Example ```csharp // Instantiate a HorizontalLine object HorizontalLine myLine = Draw.HorizontalLine(this, "tag1", 1000, Brushes.Black); // Set a new Stroke for the object myLine.Stroke = new Stroke(Brushes.Green, DashStyleHelper.Dash, 5); ``` ``` -------------------------------- ### Connection.Connect(ConnectOptions options) Source: https://docs.ninjatrader.com/ninjascript/connect.md Documentation for the Connection.Connect method, which establishes a connection using the provided ConnectOptions. ```APIDOC ## Connection.Connect(ConnectOptions options) ### Description Connects to a connection using the specified connection options. ### Method Connect ### Syntax `Connection.Connect(ConnectOptions options)` ### Parameters - **options** (ConnectOptions) - Required - The connection option of what you want to connect to. ### Example ```csharp // Example of subscribing/unsubscribing to execution update events from an Add On. The concept can be carried over // to any NinjaScript object you may be working on. public class MyAddOnTab : NTTabPage { private Connection connection; public MyAddOnTab() { // Connect to Kinetick EOD if (connection == null) connection = Connect("Kinetick - End Of Day (Free)"); } private Connection Connect(string connectionName) { // Output the execution try { // Get the configured account connection ConnectOptions connectOptions = null; lock (Core.Globals.ConnectOptions) connectOptions = Core.Globals.ConnectOptions.FirstOrDefault(o => o.Name == connectionName); if (connectOptions == null) { NinjaTrader.Code.Output.Process("Could not connect. No connection found.", PrintTo.OutputTab1); return null; } // If connection is not already connected, connect. lock (Connection.Connections) if (Connection.Connections.FirstOrDefault(c => c.Options.Name == connectionName) == null) { Connection connect = Connection.Connect(connectOptions); // Only return connection if successfully connected if (connect.Status == ConnectionStatus.Connected) return connect; else return null; } return null; } catch (Exception error) { NinjaTrader.Code.Output.Process("Connect exception: " + error.ToString(), PrintTo.OutputTab1); return null; } } // Called by TabControl when tab is being removed or window is closed public override void Cleanup() { // Disconnect from our connection if (connection != null) connection.Disconnect(); } // Other required NTTabPage members left out for demonstration purposes. Be sure to add them in your own code. } ``` ``` -------------------------------- ### GetBarIdxByX() Example: Convert Mouse X to Bar Index Source: https://docs.ninjatrader.com/ninjascript/getbaridxbyx.md Use this example to convert a mouse click's x-coordinate to a bar index in a NinjaScript indicator. It retrieves the mouse down point, converts it to device pixels for DPI accuracy, then calls ChartBars.GetBarIdxByX to get the bar index and prints it. ```csharp protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { // get the users mouse down point and convert to device pixels for DPI accuracy int mousePoint = chartControl.MouseDownPoint.X.ConvertToHorizontalPixels(chartControl.PresentationSource); // convert mouse point to bar index int barIdx = ChartBars.GetBarIdxByX(chartControl, mousePoint); Print("User clicked on Bar #" + barIdx); } ``` -------------------------------- ### C# example: GetTimeBySlotIndex() in OnRender Source: https://docs.ninjatrader.com/ninjascript/gettimebyslotindex.md Shows how to call chartControl.GetTimeBySlotIndex(150) to get the timestamp of the bar at slot index 150 and print its date. Use within OnRender override. ```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); } ``` -------------------------------- ### ConnectOptions Class Source: https://docs.ninjatrader.com/ninjascript/connectoptions.md Documentation for the ConnectOptions abstract class, including its properties and a C# example of connecting to a configured connection. ```APIDOC ## ConnectOptions Class ### Description Abstract class used to configure options for a specific configured Connection. An instance of ConnectOptions can be passed into the Connection.Connect() method to initiate a connection. ### Properties - **BrandName** (string) - The provider name. - **CanEnableHds** (bool) - Determines if the connection can use NinjaTrader Historical Data Servers. Related properties: HasHdsAlwaysEnabled, IsHdsEnabled. - **CanManageOrders** (bool) - Determines if orders can be managed on the Connection. Related property: IsDataProviderOnly. - **Mode** (NinjaTrader.Cbi.Mode) - The current mode of the connection (Mode.Live or Mode.Simulation). - **Name** (string) - The user-configured name of the Connection. - **Provider** (string) - The provider configured in the Connection. ### Example ```csharp // Connecting to a configured connection private Connection Connect(string connectionName) { // Get the configured account connection by using the string passed into this custom Connect() method // We will lock the ConnectOptions collection to avoid in-flight changes causing any issues ConnectOptions connectOptions = null; lock (Core.Globals.ConnectOptions) connectOptions = Core.Globals.ConnectOptions.FirstOrDefault(o => o.Name == connectionName); // If connection is not already connected, connect to it lock (Connection.Connections) if (Connection.Connections.FirstOrDefault(c => c.Options.Name == connectionName) == null) { Connection connect = Connection.Connect(connectOptions); // Only return connection if successfully connected if (connect.Status == ConnectionStatus.Connected) return connect; else return null; } } ``` ``` -------------------------------- ### EnterShort() Source: https://docs.ninjatrader.com/ninjascript/entershort.md Documentation for the EnterShort() method, including syntax variations, parameters, and an example. ```APIDOC ## EnterShort() ### Description Generates a sell short market order to enter a short position. ### Method Return Value An **Order** read-only object that represents the order. Reserved for experienced programmers, additional information can be found within the [Advanced Order Handling](/ninjascript/advanced_order_handling) section. ### Syntax `EnterShort()` `EnterShort(string signalName)` `EnterShort(int quantity)` `EnterShort(int quantity, string signalName)` The following method variation is for experienced programmers who fully understand [Advanced Order Handling](/ninjascript/advanced_order_handling) concepts: `EnterShort(int barsInProgressIndex, int quantity, string signalName)` > **Note** > > If using a method signature that does not have the parameter quantity, the order quantity will be taken from the quantity value set in the strategy dialog window when running or backtesting a strategy. ### Parameters | Parameter | Description | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **signalName** | User defined signal name identifying the order generated. Max 50 characters. | | **quantity** | Entry order quantity (if 0 is passed in, will be set to 1, except for stocks 100). | | **barsInProgressIndex** | The index of the Bars object the order is to be submitted against. Used to determine what instrument the order is submitted for. See the [BarsInProgress](/ninjascript/barsinprogress) property. | ### Examples ```csharp protected override void OnBarUpdate() { if (CurrentBar < 20) return; // Only enter if at least 10 bars has passed since our last entry if ((BarsSinceEntryExecution() > 10 || BarsSinceEntryExecution() == -1) && CrossAbove(SMA(10), SMA(20), 1)) EnterShort("SMA Cross Entry"); } ``` ``` -------------------------------- ### GetXByTime() example in OnRender Source: https://docs.ninjatrader.com/ninjascript/getxbytime.md Overrides OnRender to get the chart-canvas x-coordinate for a specific DateTime using GetXByTime and prints it. The returned coordinate changes as new bars are painted or the chart is scrolled. ```csharp protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { DateTime timeToCheck = new DateTime(2017, 8, 6, 11, 0, 0); // Find the chart-canvas x-coordinate of the bar at the specified time int xCoordinate = chartControl.GetXByTime(timeToCheck); // Print the x-coordinate value Print(xCoordinate); } ``` -------------------------------- ### MoveAnchorY() C# example Source: https://docs.ninjatrader.com/ninjascript/moveanchory.md Moves only the chart anchor's Y (price) value by calling MoveAnchorY with the original starting point, the new point, and the chart control and scale. This method does not return a value. ```csharp //move only the chart anchors Y (price) value MyAnchor.MoveAnchorY(lastPoint, newPoint, chartControl, chartPanel, chartScale); ``` -------------------------------- ### Enter orders for multiple instruments using BarsInProgress Source: https://docs.ninjatrader.com/ninjascript/multi_time_frame_instruments.md Shows how to submit orders for different instruments based on the BarsInProgress context. The example checks that all Bars objects have enough bars, then submits a buy market order for MSFT when BarsInProgress is 0 and for AAPL when BarsInProgress is 2, including an order for MSFT from the AAPL context using the overload EnterLong(0, 100, "BUY MSFT"). ```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"); } } ```