Go Back   NinjaTrader Support Forum > NinjaTrader 7 > Indicator Development

Indicator Development Support for the development of custom indicators using NinjaScript.

NinjaTrader
Reply
 
Thread Tools Display Modes
Old 06-11-2018, 05:38 AM   #1
NewCode
Junior Member
 
Join Date: Jan 2017
Posts: 8
Thanks: 0
Thanked 0 times in 0 posts
Default Data Series Subtract Previous Price from Current

In the future i am looking to build a complex indicator but would like to first start with being able to store and use values within a data series. The problem is, the documentation links confuse me quite a bit when going through them as i am not quite sure how to implement them in the standard start script given.


https://ninjatrader.com/support/help...ries_class.htm


I don't understand how to apply this within the code.



Ultimately, what i would like to do is take the current candles close price and subtract it from the Open price of 4 candles ago, store the answer, then apply it as the profit target. As for working code examples i made a simply entry code below for examples to be displayed with. Again i would greatly appreciate your help if possible.





namespace NinjaTrader.Strategy
{
/// <summary>
/// Enter the description of your strategy here
/// </summary>
[Description("Enter the description of your strategy here")]
public class DataHelp : Strategy
{
#region Variables
// Wizard generated variables
private int myInput0 = 1; // Default setting for MyInput0
// User defined variables (add any user defined variables below)
private int ProfitTarget = 5; // Define Profit Target
private DataSeries myCalculation; // Define a DataSeries variable

#endregion

/// <summary>
/// This method is used to configure the strategy and is called once before any strategy method is called.
/// </summary>
protected override void Initialize()
{
CalculateOnBarClose = true;
myCalculation = new DataSeries(this, MaximumBarsLookBack.Infinite);

}

/// <summary>
/// Called on each bar update event (incoming tick)
/// </summary>
protected override void OnBarUpdate()
{


if( CrossAbove(DM(14).DiMinus, DM(14).DiPlus, 1))
{
myCalculation.Set(Open[4] - Close[0])= ProfitTarget; // Not sure how to place this

EnterShort(DefaultQuantity, "");
SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
}
}

#region Properties
[Description("")]
[GridCategory("Parameters")]
public int MyInput0
{
get { return myInput0; }
set { myInput0 = Math.Max(1, value); }
}

public int ProfitTarget
{
get { return ProfitTarget; }
set { ProfitTarget = Math.Max(1, value); }
}
#endregion
}
}
NewCode is offline  
Reply With Quote
Old 06-11-2018, 06:45 AM   #2
NinjaTrader_Paul
NinjaTrader Customer Service
 
NinjaTrader_Paul's Avatar
 
Join Date: May 2014
Posts: 3,984
Thanks: 418
Thanked 1,029 times in 987 posts
Default

Hello NewCode,

Thanks for your post.

As presented your code would likely generate an error of trying to access an index before the bar is available. When you load an indicator, the code of the indicator will load the very first bar of data available (historically, so if the chart has 5 days of data loaded, the first bar would be from 5 days ago).

On that first bar loaded when you code hits this line: myCalculation.Set(Open[4] - Close[0])= ProfitTarget; it would error out because the bars ago reference of [4] does not exist at that time. To work around this, you add a check of the CurrentBar property which holds the bar number of the bar being processed. Typically you would perform this check at the top of the OnBarUpdate() method, here is an example:

if (CurrentBar < 4) return; // you would adjust the value (4 in the example) depending on the bars ago reference. Other considerations may be for any moving averages to have their period of bars before accessing them (mainly for accuracy considerations).
Reference: https://ninjatrader.com/support/help...currentbar.htm

On this line: myCalculation.Set(Open[4] - Close[0])= ProfitTarget; I'm not entire certain what you want to do. The Open[4] - Close[0] will set the value of the data series with the difference in price. The assignment of ProfitTarget would not work.

I suspect you would want to check to see if the price difference is greater than or equal to the profit target? If, as I suspect the profit target is in Ticks, you would need to convert the price difference to ticks by dividing by the tick size of the instrument, for example myCalculation.Set((Open[4] - Close[0]) / TickSize ); Here is the helpguide link to the "TickSize" property: https://ninjatrader.com/support/help.../?ticksize.htm

Here is an example of the logical statement to ask if the ticks are >= profit target:
if (myCalculation[0] >= ProfitTarget)
{
SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
EnterShort(DefaultQuantity, "");
}


Note that the index of [0] would represent the calculation just performed above. Note that I moved the setting of the profit target prior to the EnterShort, this is the recommended practice when setting the profit target dynamically. (You are using the same profit target of 5 ticks so this coding really is not needed in the example but if you decide to change the profit target value while running, then for sure this is the correct order of setting the target before placing the order because the Set methods will retain and apply the last set value immediately upon entry order filling).

While I understand you are working through the learning process just for clarification in the example you are showing a data series that is not needed as you can store the calculation results in a double variable, for example, double myCalc = (Open[4] - Close[0]) / TickSize;
NinjaTrader_Paul is online now  
Reply With Quote
Old 06-12-2018, 09:06 PM   #3
NewCode
Junior Member
 
Join Date: Jan 2017
Posts: 8
Thanks: 0
Thanked 0 times in 0 posts
Default

i am still confused as where to position a few things. I am getting 2 errors

Error: } expected
Error: already contains a definition for ProfitTarget



protected override void OnBarUpdate()
{
if (CurrentBar < 4)

return;



myCalculation.Set((Open[4] - Close[0]) / TickSize ); // Not sure how to place this


if( CrossAbove(DM(14).DiMinus, DM(14).DiPlus, 1) && myCalculation[0] >= ProfitTarget)

{

SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
EnterShort(DefaultQuantity, "");
}
}



looks like the area 2 is coming from here


public int ProfitTarget
{
get { return ProfitTarget; }
set { ProfitTarget = Math.Max(1, value); }
}
NewCode is offline  
Reply With Quote
Old 06-13-2018, 07:36 AM   #4
NinjaTrader_Paul
NinjaTrader Customer Service
 
NinjaTrader_Paul's Avatar
 
Join Date: May 2014
Posts: 3,984
Thanks: 418
Thanked 1,029 times in 987 posts
Default

Hello NewCode,

Thanks for your reply.

In the case of the error "already contains a definition for ProfitTarget", going back to your first post you have this line that creates the error: private int ProfitTarget = 5; // Define Profit Target
Please remove or comment out that line.

Regarding the error, "Error: } expected" It is hard to see based on what you have posted. Each "{" must have a closing "}". The "braces" are used to encapsulate the code section that relates. In C#/Ninjascript, you can have many layers of embedded {}.

If you are unable to determine where the braces should be, please repost your entire source code or attach the .CS file to your post.
NinjaTrader_Paul is online now  
Reply With Quote
Old 06-13-2018, 08:52 PM   #5
NewCode
Junior Member
 
Join Date: Jan 2017
Posts: 8
Thanks: 0
Thanked 0 times in 0 posts
Default

namespace NinjaTrader.Strategy
{
/// <summary>
/// Enter the description of your strategy here
/// </summary>
[Description("Enter the description of your strategy here")]
public class DataHelp : Strategy
{
#region Variables
// Wizard generated variables
private int myInput0 = 1; // Default setting for MyInput0
// User defined variables (add any user defined variables below)
private int ProfitTarget = 5; // Define Profit Target
private DataSeries myCalculation; // Define a DataSeries variable
// private double myCalculation;

#endregion

/// <summary>
/// This method is used to configure the strategy and is called once before any strategy method is called.
/// </summary>
protected override void Initialize()
{
CalculateOnBarClose = true;
//SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
myCalculation = new DataSeries(this, MaximumBarsLookBack.Infinite);

}

/// <summary>
/// Called on each bar update event (incoming tick)
/// </summary>
protected override void OnBarUpdate()
{

if (CurrentBar < 4)

return;

myCalculation.Set((Open[4] - Close[0]) / TickSize );// Not sure how to place this


if( CrossAbove(DM(14).DiMinus, DM(14).DiPlus, 1) )

{
//myCalculation.Set((Open[4] - Close[0]) / TickSize );// Not sure how to place this

if(myCalculation[0] >= ProfitTarget)
{
SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
EnterShort(DefaultQuantity, "");

}
}
}

#region Properties
[Description("")]
[GridCategory("Parameters")]
public int MyInput0
{
get { return myInput0; }
set { myInput0 = Math.Max(1, value); }
}


#endregion
}
}
NewCode is offline  
Reply With Quote
Old 06-14-2018, 08:05 AM   #6
NinjaTrader_Paul
NinjaTrader Customer Service
 
NinjaTrader_Paul's Avatar
 
Join Date: May 2014
Posts: 3,984
Thanks: 418
Thanked 1,029 times in 987 posts
Default

Hello NewCode,

Thanks for your reply.

I do not see any issues with the braces {}. Please compile your code again and look carefully at the left column of the error message. The left column is "Ninjascript File", it may be that the error is actually in another file which would also need to be corrected before you can successfully compile. NinjaTrader will compile every source code file at once to provide you with the fastest execution possible however an error in any file will prevent a successful compilation.
NinjaTrader_Paul is online now  
Reply With Quote
Old 06-18-2018, 04:53 AM   #7
NewCode
Junior Member
 
Join Date: Jan 2017
Posts: 8
Thanks: 0
Thanked 0 times in 0 posts
Default

All other strategies are good now but i am still getting the same error. It is almost as if i have calculation.set in the wrong place but i an not entirely sure. How do i download the .cs file to send to you?
NewCode is offline  
Reply With Quote
Old 06-18-2018, 06:46 AM   #8
NinjaTrader_Paul
NinjaTrader Customer Service
 
NinjaTrader_Paul's Avatar
 
Join Date: May 2014
Posts: 3,984
Thanks: 418
Thanked 1,029 times in 987 posts
Default

Hello NewCode,

Thanks for your reply.

You can send the source code file to PlatformSupport[at]NinjaTrader[dot]Com (replace the [at] with @ and [dot] with . ) Mark the e-mail subject as Atten:Paul and please include a link to this forum for reference in the e-mail.

The file would be found in Documents>NinjaTrader8>bin>Custom>Strategies> it will have the name of your strategy with .CS extension
NinjaTrader_Paul is online now  
Reply With Quote
Old 06-22-2018, 05:17 AM   #9
NewCode
Junior Member
 
Join Date: Jan 2017
Posts: 8
Thanks: 0
Thanked 0 times in 0 posts
Default Source Code

Did you get the source code?
NewCode is offline  
Reply With Quote
Old 06-22-2018, 05:42 AM   #10
NinjaTrader_Paul
NinjaTrader Customer Service
 
NinjaTrader_Paul's Avatar
 
Join Date: May 2014
Posts: 3,984
Thanks: 418
Thanked 1,029 times in 987 posts
Default

Hello NewCode,

Thanks for your reply.

Yes, we received your first e-mail on June 19th and I replied on June 19th. Please check your junk or spam e-mail as you would have gotten an immediate automated e-mail advising we received your e-mail and then my response was sent a short time later, perhaps they are both in your junk/spam.

I also have the e-mail you just sent, I will reply to that with the same answer as was previously sent.
NinjaTrader_Paul is online now  
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
CurrentBar of current Price Vs previous Price akvevo Indicator Development 8 12-12-2017 09:20 AM
Current price < Previous bar's low = exit position Jebelle Platform Technical Support 18 01-30-2012 08:39 AM
Can't subtract 10 minutes from current time. freeway General Development 11 11-18-2011 04:04 PM
How do I compare the current ask price with previous ask price? johnnyebegoode Strategy Development 1 12-03-2010 05:35 AM
Startegy involving previous day close price and current open price kirankksimon General Development 3 03-11-2009 08:59 AM


All times are GMT -6. The time now is 01:28 PM.

Futures, foreign currency and options trading contains substantial risk and is not for every investor. An investor could potentially lose all or more than the initial investment. Risk capital is money that can be lost without jeopardizing ones financial security or lifestyle. Only risk capital should be used for trading and only those with sufficient risk capital should consider trading. Past performance is not necessarily indicative of future results. View Full Risk Disclosure.

CFTC Rules 4.41 - Hypothetical or Simulated performance results have certain limitations, unlike an actual performance record, simulated results do not represent actual trading. Also, since the trades have not been executed, the results may have under-or-over compensated for the impact, if any, of certain market factors, such as lack of liquidity. Simulated trading programs in general are also subject to the fact that they are designed with the benefit of hindsight. No representation is being made that any account will or is likely to achieve profit or losses similar to those shown.

This website is hosted and operated by NinjaTrader, LLC (“NT”), a software development company which owns and supports all proprietary technology relating to and including the NinjaTrader trading platform. NT is an affiliated company to NinjaTrader Brokerage (“NTB”), which is a NFA registered introducing broker (NFA #0339976) providing brokerage services to traders of futures and foreign exchange products. This website is intended for educational and informational purposes only and should not be viewed as a solicitation or recommendation of any product, service or trading strategy. No offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, is made, given, or in any manner endorsed by any NT affiliate and the information made available on this Web site is not an offer or solicitation of any kind. Specific questions related to a brokerage account should be sent to your broker directly. The content and opinions expressed on this website are those of the authors and do not necessarily reflect the official policy or position of NT or any of its affiliates. 

Vendors along with their websites, products and services, collectively referred to as (“Vendor Content”), are independent persons or companies that are in no manner affiliated with NT or any if its affiliates. NT or any of its affiliates are not responsible for, do not approve, recommend or endorse any Vendor Content referenced on this website and it’s your sole responsibility to evaluate Vendor Content. Please be aware that any performance information provided by a vendor should be considered hypothetical and must contain the disclosures required by NFA Rule 2-29(c). If you are interested in learning more about, or investigating the quality of, any such Vendor Content you must contact the vendor, provider or seller of such Vendor Content. No person employed by, or associated with, NT or any of its affiliates is authorized to provide any information about any such Vendor Content.