#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
public class zzzzadxvma : Strategy
{
private BzvOpeningRange4 OR1;
private ADXVMA SMA1;
private ADXVMA SMA2;
private bool TradeSwitch;
private int period = 6;
private double k = 0.0;
private double hhp = 0.0;
private double llp = 0.0;
private double hhv = 0.0;
private double llv = 0.0;
private double epsilon = 0.0;
private Series<double> up;
private Series<double> down;
private Series<double> ups;
private Series<double> downs;
private Series<double> index;
private Series<int> trend;
private ATR volatility;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Enter the description for your new custom Strategy here.";
Name = "zzzzadxvma";
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
// ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = true;
MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
OrderFillResolution = OrderFillResolution.High;
OrderFillResolutionType = BarsPeriodType.Tick;
OrderFillResolutionValue = 1;
Slippage = 1;
StartBehavior = StartBehavior.AdoptAccountPosition;
IsAdoptAccountPositionAware = true;
IncludeCommission = true;
TimeInForce = TimeInForce.Day;
TraceOrders = true;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.ByStrategyPosition;
BarsRequiredToTrade = 20;
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = true;
UpProfit =80;
UpLoss =210;
DownProfit =20;
DownLoss =130;
EMASlowPeriod = 1000;
}
else if (State == State.Configure)
{
up = new Series<double>(this);
down = new Series<double>(this);
ups = new Series<double>(this);
downs = new Series<double>(this);
index = new Series<double>(this);
trend = new Series<int>(this);
}
else if (State == State.DataLoaded)
{
OR1 = BzvOpeningRange4(Close, @"0530", @"0540", @"1600");
SMA1 =ADXVMA(10);
SMA2 =ADXVMA(EMASlowPeriod);
SMA1.Plots[0].Brush = Brushes.Green;
SMA2.Plots[0].Brush = Brushes.Red;
AddChartIndicator(OR1);
AddChartIndicator(SMA1);
AddChartIndicator(SMA2);
}
}
protected override void OnBarUpdate()
{
if (CurrentBar == 1)
{
k = 1.0 / (double)period;
volatility = ATR(200);
up[0] = 0.0;
down[0] = 0.0;
ups[0] = 0.0;
downs[0] = 0.0;
index[0] = 0.0;
trend[0] = 0;
ADXVMA[0] = Input[0];
}
else
{
double currentUp = Math.Max(Input[0] - Input[1], 0);
double currentDown = Math.Max(Input[1] - Input[0], 0);
up[0] = (1 - k) * up[1] + k * currentUp;
down[0] = (1 - k) * down[1] + k * currentDown;
double sum = up[0] + down[0];
double fractionUp = 0.0;
double fractionDown = 0.0;
if (sum > double.Epsilon)
{
fractionUp = up[0] / sum;
fractionDown = down[0] / sum;
}
ups[0] = (1 - k) * ups[1] + k * fractionUp;
downs[0] = (1 - k) * downs[1] + k * fractionDown;
double normDiff = Math.Abs(ups[0] - downs[0]);
double normSum = ups[0] + downs[0];
double normFraction = 0.0;
if (normSum > double.Epsilon)
normFraction = normDiff / normSum;
index[0] = (1 - k) * index[1] + k * normFraction;
if (IsFirstTickOfBar)
{
epsilon = 0.1 * volatility[1];
hhp = MAX(index, period)[1];
llp = MIN(index, period)[1];
}
hhv = Math.Max(index[0], hhp);
llv = Math.Min(index[0], llp);
double vDiff = hhv - llv;
double vIndex = 0;
if (vDiff > double.Epsilon)
vIndex = (index[0] - llv) / vDiff;
ADXVMA[0] = (1 - k * vIndex) * ADXVMA[1] + k * vIndex * Input[0];
if (trend[1] > -1 && ADXVMA[0] > ADXVMA[1] + epsilon)
{
trend[0] = 1;
// PlotBrushes[0][0] = upColor;
}
else if (trend[1] < 1 && ADXVMA[0] < ADXVMA[1] - epsilon)
{
trend[0] = -1;
// PlotBrushes[0][0] = downColor;
}
else
{
trend[0] = 0;
// PlotBrushes[0][0] = neutralColor;
}
}
if (CurrentBars[0] <EMASlowPeriod)
return;
if (Bars.IsFirstBarOfSession)
{
//currentPnL = 0;
TradeSwitch = true;
}
if ( IsFirstTickOfBar == true
&& BarsInProgress == 0
&& (BarsSinceEntryExecution(0,"Long",0) == 0
|| BarsSinceEntryExecution(0, "Short",0) == 0))
{
TradeSwitch = false;
}
if (IsFirstTickOfBar == true && BarsInProgress == 0)
{
SetStopLoss("Long", CalculationMode.Price,Swing(5).SwingLow[1], false);
// if (Position.MarketPosition == MarketPosition.Long)
// {
// SetStopLoss("Long", CalculationMode.Ticks,Math.Min((Position.AveragePrice - ATRTrailingStop(Close, 5, 10)[1])/TickSize, UpLoss), false);
//}
SetStopLoss("Short", CalculationMode.Price,Swing(5).SwingHigh[1], false);
// if (Position.MarketPosition == MarketPosition.Short)
// {
// SetStopLoss("Short", CalculationMode.Ticks,Math.Min( (ATRTrailingStop(Close, 5, 10)[1] - Position.AveragePrice)/TickSize, DownLoss), false);
//}
SetProfitTarget("Long",CalculationMode.Ticks,UpProfit);
SetProfitTarget("Short",CalculationMode.Ticks,DownProfit);
}
#region Time
// Time
if (((ToTime(Time[0]) >= 124500))
&& (Position.MarketPosition != MarketPosition.Flat)
&& BarsInProgress == 0)
{
if (Position.MarketPosition == MarketPosition.Long)
{
ExitLong(0, Position.Quantity, "time", "");
}
else if (Position.MarketPosition == MarketPosition.Short)
{
ExitShort(0, Position.Quantity, "time", "");
}
}
#endregion
// if (PositionAccount.MarketPosition == MarketPosition.Flat && Position.MarketPosition == MarketPosition.Flat && BarsSinceExitExecution(0, "", 0) == 1 && IsFirstTickOfBar == true)
// {
// Account.CancelAllOrders(Instrument);
// }
// if (IsFirstTickOfBar == true && BarsSinceEntryExecution(0, "Short", 0) == DownExit)
// {
// ExitShort("ShortX", "Short");
// }
//
// if (IsFirstTickOfBar == true && BarsSinceEntryExecution(0, "Long", 0) == UpExit)
// {
// ExitLong("LongX", "Long");
// }
if ( ((ToTime(Time[0]) >= 53000
&& ToTime(Time[0]) < 70000))
//
// && Close[1] < OR1.RangeHighSeries[1]
//&& SMA1[1] > SMA2[1]
// && OR1.RangeHighSeries[1] > 0
&& trend[1] == 1
// && Slope(SMA(OBV(),1000), 5, 0) > 0
// && (Time[0].DayOfWeek == DayOfWeek.Thursday
// || Time[0].DayOfWeek == DayOfWeek.Tuesday
// || Time[0].DayOfWeek == DayOfWeek.Wednesday
//|| Time[0].DayOfWeek == DayOfWeek.Friday)
&& Position.MarketPosition == MarketPosition.Flat
&& BarsInProgress == 0
&& TradeSwitch == true
&& IsFirstTickOfBar == true
// && currentPnL > -LossLimit
// && currentPnL < ProfitLimit
)
// && (BarsSinceEntryExecution(0, "Long", 0) > 1 || BarsSinceEntryExecution(0, "Long", 0) == -1))
{
// EnterLong(0, 1, "Long");
// EnterLong(0, 1, "Long2");
EnterLongStopLimit(0,false, Convert.ToInt32(DefaultQuantity) ,High[1] + TickSize, High[1] + TickSize, "Long");
// EnterLongStopLimit(0,false, Convert.ToInt32(DefaultQuantity),High[1] + TickSize, High[1] + TickSize, "Long2");
Draw.ArrowUp(this, "tag1", true, 0, Low[0] - TickSize, Brushes.Green);
}
if (BarsInProgress == 0 && Position.MarketPosition == MarketPosition.Long)
{
if (IsFirstTickOfBar == true
&& (SMA1[1] < SMA2[1] && ToTime(Time[0]) > 64500)
|| CrossBelow(Close, SMA1, 1)
)
{
ExitLong("Long");
}
}
Announcement
Collapse
No announcement yet.
Partner 728x90
Collapse
NinjaTrader
Error Calling 'OnBarUpdate' Index outside bounds of array
Collapse
X
-
Error Calling 'OnBarUpdate' Index outside bounds of array
I am trying to incorporate some language from an indicator to a strategy. I added all the neccessary variables and added any applicable series, but for the life of me I cannot figure out how to get it to quit throwing either "outside bounds of array" or "accesssing an index with a value that is invalid." Any suggestions on where I'm going wrong would be greatly appreciated. Through some troubleshooting steps I am fairly confident the errors are being cause by the first language in OnBarUpdate before "if (CurrentBars[0] <EMASlowPeriod) return;" Thanks. (I did delete my properties at the bottom of the code so I'd be within the character limit)
Code:Tags: None
-
Hello zrobfrank,
Thanks for your post.
When working with any issue, it is important to take steps to isolate the issue so that the exact line causing the behavior can be found.
This is a process of elimination and a process of debugging by adding prints.
First, its great to create a copy of the script so that the original work is kept safe. To create a copy of a script, right-click within the scripts code, select 'Save as', and name the copy.
Once the copy is created, the copy can be modified in any way without losing the original work.
The next step is to start commenting out code. Comment out sections of code in the script and then test to see if the error persists. If at any point you comment out a section of code and the error stops, the commented-out section of code likely causing the error.
You could then further comment/un-comment lines of code within that section and add debugging prints to the script that print out all the logic being used along with the CurrentBar/CurrentBars to see how your logic is evaluating.
Below is a link to a forum post that demonstrates how to use prints to understand behavior.
https://ninjatrader.com/support/foru...121#post791121<span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>
Latest Posts
Collapse
| Topics | Statistics | Last Post | ||
|---|---|---|---|---|
|
Started by NullPointStrategies, Today, 05:17 AM
|
0 responses
52 views
0 likes
|
Last Post
|
||
|
Started by argusthome, 03-08-2026, 10:06 AM
|
0 responses
130 views
0 likes
|
Last Post
by argusthome
03-08-2026, 10:06 AM
|
||
|
Started by NabilKhattabi, 03-06-2026, 11:18 AM
|
0 responses
70 views
0 likes
|
Last Post
|
||
|
Started by Deep42, 03-06-2026, 12:28 AM
|
0 responses
44 views
0 likes
|
Last Post
by Deep42
03-06-2026, 12:28 AM
|
||
|
Started by TheRealMorford, 03-05-2026, 06:15 PM
|
0 responses
49 views
0 likes
|
Last Post
|

Comment