Go Back   NinjaTrader Support Forum > NinjaScript Educational Resources > Tips

Tips Official NinjaScript tips and tricks

NinjaTrader
Reply
 
Thread Tools Display Modes
Old 09-24-2007, 08:51 PM   #1
NinjaTrader_JoshP
NinjaTrader Product Manager
 
NinjaTrader_JoshP's Avatar
 
Join Date: May 2007
Location: Denver, CO
Posts: 17,459
Thanks: 1
Thanked 381 times in 106 posts
Default Debugging your NinjaScript Code

Applies to NinjaTrader 7

Debugging can be a frustrating and time-consuming task. In order to make the most of your time, it is best to proceed in a methodical manner. The first step you should do is to strip your code down into simple code segments. You want to start your debugging at a point where you know the code works as expected. From there you can then add more layers of complexity. With each additional layer, you want to ensure it works as expected before adding more layers.

To begin the process of stripping down your code you can either make a new temporary NinjaScript and copy over only the key relevant code segments or you can comment out segments that are not vital to the test.

To comment out code segments you can either press the "Comment selection" button on the top toolbar in the NinjaScript editor or type "//" in front of the line. To mass comment code segments, you can use your mouse cursor and select multiple lines and press the "Comment selection" button as well. To uncomment code, remove the "//" or select the line and press the "Uncomment selection" button.

Commenting code segments is also useful if you wanted to just temporarily check if your code compiles. When your NinjaScript editor pops up with errors you can click on the error message and it will bring you to the erroneous line. After you comment out the erroneous lines you should be able to compile.

The most common method you can use to ensure your code works as expected is through the use of the Print() command.

Example:
Code:
if (Close[0] > Open[0])
{
     Print("Code has entered If statement. Close: "+ Close[0] + " Open: " + Open[0]);
     // Do something
}
Placing Print() commands throughout your code logic allows you to trace where you are exactly. You can see where your code goes and where it does not go by viewing the output from the Output Window. Coupled with reading the error log from the Log tab in the Control Center, you can pinpoint where your code is crashing or locking up and make changes accordingly.

Debugging orders can be a bit harder though because you cannot discern the behavior state of your orders through the Print() command easily. In addition to Print(), you can use TraceOrders to help you decipher what is happening under the hood for orders. TraceOrders will print information into the Output Window that will contain details about your orders.

Code:
protected override void Initialize()
{
     TraceOrders = true;
}
When debugging stop or limit orders it can also be extremely useful to draw dots along your chart of the actual stop/limit prices. This way you can visually see where your orders are at and if they should have been filled or not.
Code:
DrawDot("Stop" + CurrentBar, true, 0, stopPrice, Color.Orange);
Sometimes your code will compile and run fine, but it will produce inaccurate results. To check for accuracy, you can use Print() along with the Data Box to compare values. If you are doing a complex mathematical calculation, you can print the value at every step to ensure the calculations are as expected.

External references can also be very useful when debugging. They are great for gaining insight into syntax and usage of various methods. Searching Google or MSDN can provide useful examples and code snippets you can adapt to use with your own code.

Some useful resources:
C# Station
Microsoft Developer Network
The Code Project
Last edited by NinjaTrader_Jesse; 06-03-2015 at 08:27 AM.
NinjaTrader_JoshP is offline  
Reply With Quote
The following 6 users say thank you to NinjaTrader_JoshP for this post:
Old 06-03-2015, 11:47 AM   #2
NinjaTrader_Jesse
NinjaTrader Customer Service
 
NinjaTrader_Jesse's Avatar
 
Join Date: Mar 2014
Location: Denver, CO
Posts: 4,789
Thanks: 30
Thanked 1,217 times in 1,138 posts
Default

Applies to NinjaTrader 8

Debugging can be a frustrating and time-consuming task. In order to make the most of your time, it is best to proceed in a methodical manner. The first step you should do is to strip your code down into simple code segments. You want to start your debugging at a point where you know the code works as expected. From there you can then add more layers of complexity. With each additional layer, you want to ensure it works as expected before adding more layers.

To begin the process of stripping down your code you can either make a new temporary NinjaScript and copy over only the key relevant code segments or you can comment out segments that are not vital to the test.

To comment out code segments you can either press the "Comment selection" button on the top toolbar in the NinjaScript editor or type "//" in front of the line. To mass comment code segments, you can use your mouse cursor and select multiple lines and press the "Comment selection" button as well. To uncomment code, remove the "//" or select the line and press the "Uncomment selection" button.

Code:
double limitPrice = 0; //You can comment after working code
// double stopPrice = 0; 
// you can also comment out whole lines to prevent it from being used by using //
Commenting code segments is also useful if you wanted to just temporarily check if your code compiles. When your NinjaScript editor pops up with errors you can click on the error message and it will bring you to the erroneous line. After you comment out the erroneous lines you should be able to compile.

The most common method you can use to ensure your code works as expected is through the use of the Print() command. The Print command will print the supplied value to the New -> NinjaScript Output window.

Example:
Code:
if (Close[0] > Open[0])
{
     Print("Code has entered If statement. Close: "+ Close[0] + " Open: " + Open[0]);
     // Do something
}
Placing Print() commands throughout your code logic allows you to trace where you are exactly. You can see where your code goes and where it does not go by viewing the output from the Output Window. Coupled with reading the error log from the Log tab in the Control Center, you can pinpoint where your code is crashing or locking up and make changes accordingly.

Debugging orders can be a bit harder though because you cannot discern the behavior state of your orders through the Print() command easily. In addition to Print(), you can use TraceOrders to help you decipher what is happening under the hood for orders. TraceOrders will print information into the Output Window that will contain details about your orders.

Code:
protected override void OnStateChange()
{
     if (State == State.SetDefaults)
     {
          TraceOrders = true;
     }
}
When debugging stop or limit orders it can also be extremely useful to draw dots along your chart of the actual stop/limit prices. This way you can visually see where your orders are at and if they should have been filled or not. Draw.Dot

Code:
Draw.Dot(this, "tag1", true, 0, Low[0] - TickSize, Brushes.Red);
Sometimes your code will compile and run fine, but it will produce inaccurate results. To check for accuracy, you can use Print() along with the Data Box to compare values. If you are doing a complex mathematical calculation, you can print the value at every step to ensure the calculations are as expected.

External references can also be very useful when debugging. They are great for gaining insight into syntax and usage of various methods. Searching Google or MSDN can provide useful examples and code snippets you can adapt to use with your own code.

Some useful resources:
NinjaScript Debugging
CSharp Essentials
C# Station
Microsoft Developer Network
The Code Project
Last edited by NinjaTrader_Jesse; 06-03-2015 at 12:58 PM.
NinjaTrader_Jesse 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
SMA code maxpi Indicator Development 5 07-29-2010 06:21 AM
Code->test/debug->change code->retest ... cycle process bbarroux Strategy Development 3 10-02-2007 12:44 PM
code question abikambic General Development 2 05-03-2007 06:03 AM
Code snippet library for Ninjascript ct Indicator Development 4 04-08-2007 08:48 AM
Debugging using Visual Studio guym Indicator Development 2 11-28-2006 01:41 AM


All times are GMT -6. The time now is 07:10 AM.

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.