Ninja Trader Version 7 Help Guide
Ninja Trader Version 7 Help Guide
Ninja Trader Version 7 Help Guide
Table of Contents
Part I Welcome to NinjaTrader Version 7 18
Part VI Copyrights 96
1 Account
...................................................................................................................................
Groups 137
Managing Account
..........................................................................................................................................................
Groups 137
2 Advanced
...................................................................................................................................
Trade Management (ATM) 138
ATM Strategy .......................................................................................................................................................... 139
ATM Strategy
.........................................................................................................................................................
Parameters 140
ATM Strategy
.........................................................................................................................................................
Selection Mode 144
Stop Strategy
......................................................................................................................................................... 148
Auto Breakeven......................................................................................................................................... 148
Auto Trail ......................................................................................................................................... 150
Manage ATM .........................................................................................................................................................
Strategy Templates 152
Tutorial: ATM
.........................................................................................................................................................
Strategy Example #1 153
Tutorial: ATM
.........................................................................................................................................................
Strategy Example #2 156
Advanced Options
.......................................................................................................................................................... 160
Auto Chase ......................................................................................................................................................... 160
Auto Reverse
......................................................................................................................................................... 162
Shadow Strategy
......................................................................................................................................................... 163
Close At Tim..........................................................................................................................................................
e 164
FAQ .......................................................................................................................................................... 164
3 Alerts
................................................................................................................................... 167
Using the Alerts
..........................................................................................................................................................
Window 167
Window Linking
.......................................................................................................................................................... 168
4 Automated
...................................................................................................................................
Trading 168
Autom ated Trading
..........................................................................................................................................................
Interface (ATI) 169
What can.........................................................................................................................................................
I do and how ? 169
Commands .........................................................................................................................................................
and Valid Parameters 171
Initialization
......................................................................................................................................................... 173
Trading currencies
.........................................................................................................................................................
(FX) and options 174
File Interface
......................................................................................................................................................... 174
Order Instruction .........................................................................................................................................
Files (OIF) 174
Information Update .........................................................................................................................................
Files 175
Automated Trading .........................................................................................................................................
OIF Builder 176
DLL Interface......................................................................................................................................................... 177
Functions ......................................................................................................................................... 177
eSignal Sample.........................................................................................................................................
Code 180
TradeStation Sample .........................................................................................................................................
Code 186
eSignal Integration
......................................................................................................................................................... 186
Set Up ......................................................................................................................................... 186
Functions ......................................................................................................................................... 187
Sample Code ......................................................................................................................................... 190
Tips ......................................................................................................................................... 196
TradeStation .........................................................................................................................................................
Integration 196
Email Interface ......................................................................................................................................... 196
Symbol Mapping ................................................................................................................................... 197
Running concurrent ...................................................................................................................................
strategies in the same market 197
Set Up ................................................................................................................................... 197
Order Handling...................................................................................................................................
Options 201
Stop Order Handling ................................................................................................................................... 203
Workspace Options ................................................................................................................................... 205
DLL Based Integration ......................................................................................................................................... 206
Set Up ................................................................................................................................... 207
Functions ................................................................................................................................... 207
Sample Code ................................................................................................................................... 210
Running NT on ...................................................................................................................................
a different PC than TS 211
3
4 NinjaTrader Version 7
Working w ith..........................................................................................................................................................
Hot Keys 331
Trading w ith..........................................................................................................................................................
Hot Keys 335
12 Instrument
...................................................................................................................................
Manager 340
Searching for..........................................................................................................................................................
Instrum ents 341
Adding Splits..........................................................................................................................................................
and Dividends 342
Editing Instrum
..........................................................................................................................................................
ents 342
Adding Com..........................................................................................................................................................
m ission Rates 348
Instrum ent Lists
.......................................................................................................................................................... 349
Manage Database
.......................................................................................................................................................... 351
TradeStation..........................................................................................................................................................
Sym bol Mapping 351
Im porting a List
..........................................................................................................................................................
of Stock Sym bols 353
Rolling Over ..........................................................................................................................................................
a Futures Contract 354
13 Level
...................................................................................................................................
II 355
Using the Level
..........................................................................................................................................................
II Window 355
Level II Properties
.......................................................................................................................................................... 357
14 Market
...................................................................................................................................
Analyzer 359
Creating a Market
..........................................................................................................................................................
Analyzer Window 360
Working w ith
..........................................................................................................................................................
Instrum ent Row s 361
Working w ith
..........................................................................................................................................................
Colum ns 366
Creating Alert,
..........................................................................................................................................................
Cell and Filter Conditions 370
Dynam ic Ranking
..........................................................................................................................................................
and Sorting 379
Market Analyzer
..........................................................................................................................................................
Properties 380
Working w ith
..........................................................................................................................................................
Tem plates 382
Perform ance..........................................................................................................................................................
Tips 384
Reloading Indicators
..........................................................................................................................................................
& Colum ns 385
Window Linking
.......................................................................................................................................................... 385
15 Market
...................................................................................................................................
Replay 385
Set Up .......................................................................................................................................................... 385
Replay .......................................................................................................................................................... 387
Data Files .......................................................................................................................................................... 389
16 News
...................................................................................................................................
& RSS 390
New s Window
.......................................................................................................................................................... 390
Window Linking
.......................................................................................................................................................... 394
17 Order
...................................................................................................................................
Entry 394
Sim ulated Stop
..........................................................................................................................................................
Orders 394
FIFO Optim ization
.......................................................................................................................................................... 396
Closing a Position
..........................................................................................................................................................
or ATM Strategy Position 397
Window Linking.......................................................................................................................................................... 398
Order State Definitions
.......................................................................................................................................................... 398
Basic Entry .......................................................................................................................................................... 399
Market Display
......................................................................................................................................................... 399
Order Grid.........................................................................................................................................................
Display 400
Selecting.........................................................................................................................................................
Instruments and Accounts 400
Submitting.........................................................................................................................................................
Orders 401
Modifying.........................................................................................................................................................
and Cancelling Orders 405
Action Buttons
......................................................................................................................................................... 405
Adding or.........................................................................................................................................................
Removing Targets 406
Window Linking
......................................................................................................................................................... 407
Basic Entry
.........................................................................................................................................................
Properties 408
Chart Trader.......................................................................................................................................................... 409
Order & Position
.........................................................................................................................................................
Display 410
Collapsed.........................................................................................................................................................
View 412
5
6 NinjaTrader Version 7
Submitting.........................................................................................................................................................
Orders 412
Modifying.........................................................................................................................................................
and Cancelling Orders 418
Action Buttons
......................................................................................................................................................... 420
Chart Trader
.........................................................................................................................................................
Properties 420
FX Pro .......................................................................................................................................................... 422
Overview......................................................................................................................................................... 423
Selecting.........................................................................................................................................................
Instruments and Accounts 426
Submitting.........................................................................................................................................................
Orders 427
Modifying.........................................................................................................................................................
and Cancelling Orders 431
Adding and.........................................................................................................................................................
Removing Targets 431
FX Pro Properties
......................................................................................................................................................... 432
SuperDOM .......................................................................................................................................................... 433
Price Ladder
.........................................................................................................................................................
Display 434
Static vs .........................................................................................................................................................
Dynamic Price Ladder Display 439
Selecting.........................................................................................................................................................
Instruments and Accounts 440
Order Display
......................................................................................................................................................... 441
Submitting.........................................................................................................................................................
Orders 444
Modifying.........................................................................................................................................................
Orders 452
Cancelling.........................................................................................................................................................
Orders 455
Adding and.........................................................................................................................................................
Removing Targets 455
Action Buttons
......................................................................................................................................................... 457
Window Linking
......................................................................................................................................................... 457
SuperDOM .........................................................................................................................................................
Properties 457
18 Session
...................................................................................................................................
Manager 460
Using the Session
..........................................................................................................................................................
Manager 460
19 Simulator
................................................................................................................................... 463
The Sim 101 Account
.......................................................................................................................................................... 463
Multiple Sim..........................................................................................................................................................
ulation Accounts 464
Live/Sim ulation
..........................................................................................................................................................
Environm ent 464
Global Sim ulation
..........................................................................................................................................................
Mode 464
Trading in Sim
..........................................................................................................................................................
ulation 465
20 Strategy
...................................................................................................................................
Analyzer 465
Strategy Analyzer
..........................................................................................................................................................
Window 466
Backtest a Strategy
.......................................................................................................................................................... 467
Optim ize a Strategy
.......................................................................................................................................................... 471
Genetic Algorithm
......................................................................................................................................................... 474
Walk Forw ard..........................................................................................................................................................
Optim ize a Strategy 477
Basket Test .......................................................................................................................................................... 478
Review ing Perform
..........................................................................................................................................................
ance Results 479
Saving Perform
..........................................................................................................................................................
ance Results 479
Monte Carlo..........................................................................................................................................................
Sim ulation 481
Running a.........................................................................................................................................................
Monte Carlo Simulation 481
Discrepancies:
..........................................................................................................................................................
Real-Tim e vs Backtest 483
21 Strategy
...................................................................................................................................
Wizard 484
Wizard Screens
.......................................................................................................................................................... 485
Condition Builder
.......................................................................................................................................................... 490
Strategy Actions
.......................................................................................................................................................... 505
22 Time...................................................................................................................................
& Sales 510
Using the Tim..........................................................................................................................................................
e & Sales Window 511
Tim e & Sales..........................................................................................................................................................
Properties 512
Window Linking
.......................................................................................................................................................... 513
23 Window
...................................................................................................................................
Linking 513
Linking Window
..........................................................................................................................................................
s 513
24 Workspaces
................................................................................................................................... 514
Managing Workspaces
.......................................................................................................................................................... 514
7
8 NinjaTrader Version 7
Developing Strategies
.......................................................................................................................................................... 567
The Strategy.........................................................................................................................................................
Development Process 568
Strategy Position
.........................................................................................................................................................
vs. Account Position 569
Syncing Account
.........................................................................................................................................................
Positions 570
Using ATM .........................................................................................................................................................
Strategies 573
Developing Custom
..........................................................................................................................................................
Fill and Optim izer Types 573
Fill Types......................................................................................................................................................... 574
Optimizer.........................................................................................................................................................
Type 574
Reference Sam ..........................................................................................................................................................
ples 574
Tips .......................................................................................................................................................... 575
Best Practices
.........................................................................................................................................................
for 3rd Party Developers 575
C# Method .........................................................................................................................................................
(Functions) Reference 576
Code Breaking
.........................................................................................................................................................
Changes for NinjaTrader 7 577
Multi-Threading
.........................................................................................................................................................
Consideration for NinjaScript 577
Multi-Time.........................................................................................................................................................
Frame & Instruments 578
User Defined.........................................................................................................................................................
Methods 587
Sample 1 ......................................................................................................................................... 588
Sample 2 ......................................................................................................................................... 590
Using 3rd.........................................................................................................................................................
Party Indicators 591
Using Historical
.........................................................................................................................................................
Bid/Ask Series 592
Tutorials .......................................................................................................................................................... 593
Indicators......................................................................................................................................................... 593
Beginner - Using .........................................................................................................................................
price variables 594
Set Up ................................................................................................................................... 594
Entering Calculation ...................................................................................................................................
Logic 599
Compiling ................................................................................................................................... 600
Using ................................................................................................................................... 600
Beginner - Indicator .........................................................................................................................................
on Indicator 602
Set Up ................................................................................................................................... 602
Entering Calculation ...................................................................................................................................
Logic 607
Compiling ................................................................................................................................... 608
Using ................................................................................................................................... 609
Intermediate - Your .........................................................................................................................................
ow n SMA 610
Set Up ................................................................................................................................... 610
Entering Calculation ...................................................................................................................................
Logic 615
Compiling ................................................................................................................................... 618
Using ................................................................................................................................... 618
Intermediate - Historical
.........................................................................................................................................
Custom Data Series 619
Set Up ................................................................................................................................... 619
Entering Calculation ...................................................................................................................................
Logic 624
Compiling ................................................................................................................................... 626
Using ................................................................................................................................... 626
Advanced - Custom .........................................................................................................................................
Plot Colors via Thresholds 628
Set Up ................................................................................................................................... 628
Entering Calculation ...................................................................................................................................
Logic 633
Compiling ................................................................................................................................... 635
Using ................................................................................................................................... 636
Advanced - Custom .........................................................................................................................................
Draw ing 637
Set Up ................................................................................................................................... 637
Entering Calculation ...................................................................................................................................
Logic 642
Compiling ................................................................................................................................... 646
Using ................................................................................................................................... 646
Strategies......................................................................................................................................................... 648
Beginner - Simple .........................................................................................................................................
MA Cross Over 648
9
10 NinjaTrader Version 7
11
12 NinjaTrader Version 7
13
14 NinjaTrader Version 7
On Balance.........................................................................................................................................................
Volume (OBV) 875
Parabolic .........................................................................................................................................................
SAR 876
Percentage.........................................................................................................................................................
Price Oscillator (PPO) 877
Pivots ......................................................................................................................................................... 878
Polarized.........................................................................................................................................................
Fractal Efficiency (PFE) 881
Price Oscillator
......................................................................................................................................................... 882
Prior Day .........................................................................................................................................................
OHLC 883
Range ......................................................................................................................................................... 884
Range Indicator
.........................................................................................................................................................
(RIND) 884
Rate of Change
.........................................................................................................................................................
(ROC) 885
Regression.........................................................................................................................................................
Channel 886
Relative Spread
.........................................................................................................................................................
Strength (RSS) 888
Relative Strength
.........................................................................................................................................................
Index (RSI) 889
Relative Volatility
.........................................................................................................................................................
Index (RVI) 890
R-squared ......................................................................................................................................................... 891
Standard.........................................................................................................................................................
Deviation (StdDev) 892
Standard.........................................................................................................................................................
Error (StdError) 893
Stochastics
......................................................................................................................................................... 894
Stochastics
.........................................................................................................................................................
Fast 895
Stochastics
.........................................................................................................................................................
RSI (StochRSI) 896
Summation .........................................................................................................................................................
(SUM) 897
Sw ing ......................................................................................................................................................... 898
Time Series
.........................................................................................................................................................
Forecast (TSF) 899
True Strength
.........................................................................................................................................................
Index (TSI) 900
Ultimate Oscillator
......................................................................................................................................................... 901
Volume (VOL)
......................................................................................................................................................... 902
Volume Moving
.........................................................................................................................................................
Average (VOLMA) 903
Volume Oscillator
......................................................................................................................................................... 904
Volume Rate
.........................................................................................................................................................
of Change (VROC) 905
Volume Up .........................................................................................................................................................
Dow n 905
Williams %R
......................................................................................................................................................... 906
Woodies .........................................................................................................................................................
CCI 907
Woodies .........................................................................................................................................................
Pivots 909
ZigZag ......................................................................................................................................................... 911
Strategy .......................................................................................................................................................... 912
Advanced .........................................................................................................................................................
Event Driven Programming Concepts 912
AccountSize
......................................................................................................................................................... 913
Add() ......................................................................................................................................................... 913
ATM Strategy
.........................................................................................................................................................
Methods 914
AtmStrategyCancelEntryOrder()
......................................................................................................................................... 914
AtmStrategyChangeEntryOrder()
......................................................................................................................................... 915
AtmStrategyChangeStopTarget()
......................................................................................................................................... 915
AtmStrategyClose() ......................................................................................................................................... 916
AtmStrategyCreate() ......................................................................................................................................... 916
GetAtmStrategyEntryOrderStatus()
......................................................................................................................................... 918
GetAtmStrategyMarketPosition()
......................................................................................................................................... 918
GetAtmStrategyPositionAveragePrice()
......................................................................................................................................... 919
GetAtmStrategyPositionQuantity()
......................................................................................................................................... 919
GetAtmStrategyRealizedProfitLoss()
......................................................................................................................................... 920
GetAtmStrategyStopTargetOrderStatus()
......................................................................................................................................... 920
GetAtmStrategyUniqueId()
......................................................................................................................................... 921
GetAtmStrategyUnrealizedProfitLoss()
......................................................................................................................................... 922
BarsRequired
......................................................................................................................................................... 922
BarsSinceEntry()
......................................................................................................................................................... 923
BarsSinceExit()
......................................................................................................................................................... 924
ConnectionLossHandling
......................................................................................................................................................... 925
DataSeriesConfigurable
......................................................................................................................................................... 926
DefaultQuantity
......................................................................................................................................................... 926
Disable() ......................................................................................................................................................... 926
DisconnectDelaySeconds
......................................................................................................................................................... 927
EntriesPerDirection
......................................................................................................................................................... 927
EntryHandling
......................................................................................................................................................... 928
ExcludeTradeHistoryInBacktest
......................................................................................................................................................... 929
ExitOnClose
......................................................................................................................................................... 930
ExitOnCloseSeconds
......................................................................................................................................................... 930
ForceMaximumBarsLookBack256
......................................................................................................................................................... 931
GetAccountValue()
......................................................................................................................................................... 931
IExecution......................................................................................................................................................... 932
IncludeCommission
......................................................................................................................................................... 933
IOrder ......................................................................................................................................................... 933
IPosition ......................................................................................................................................................... 936
MaxRestartAttempts
......................................................................................................................................................... 936
MaxRestartMinutes
......................................................................................................................................................... 937
OnConnectionStatus()
......................................................................................................................................................... 937
OnExecution()
......................................................................................................................................................... 939
OnFundamentalData()
......................................................................................................................................................... 940
OnMarketData()
......................................................................................................................................................... 940
OnMarketDepth()
......................................................................................................................................................... 940
OnOrderUpdate()
......................................................................................................................................................... 940
OnPositionUpdate()
......................................................................................................................................................... 942
OnStartUp()
......................................................................................................................................................... 942
OnTermination()
......................................................................................................................................................... 942
Order Methods
......................................................................................................................................................... 943
Managed Approach ......................................................................................................................................... 944
Advanced Order ...................................................................................................................................
Handling 949
CancelOrder() ................................................................................................................................... 951
EnterLong() ................................................................................................................................... 952
EnterLongLimit() ................................................................................................................................... 953
EnterLongStop() ................................................................................................................................... 954
EnterLongStopLimit() ................................................................................................................................... 955
EnterShort() ................................................................................................................................... 957
EnterShortLimit() ................................................................................................................................... 958
EnterShortStop() ................................................................................................................................... 959
EnterShortStopLimit() ................................................................................................................................... 960
ExitLong() ................................................................................................................................... 961
ExitLongLimit() ................................................................................................................................... 962
ExitLongStop() ................................................................................................................................... 964
ExitLongStopLimit() ................................................................................................................................... 965
ExitShort() ................................................................................................................................... 967
ExitShortLimit()................................................................................................................................... 968
ExitShortStop()................................................................................................................................... 970
ExitShortStopLimit() ................................................................................................................................... 971
SetProfitTarget() ................................................................................................................................... 973
SetStopLoss() ................................................................................................................................... 974
SetTrailStop() ................................................................................................................................... 975
Unmanaged Approach ......................................................................................................................................... 977
CancelOrder() ................................................................................................................................... 980
ChangeOrder()................................................................................................................................... 980
15
16 NinjaTrader Version 7
I
18 NinjaTrader Version 7
The NinjaTrader Help Guide is your reference to product features descriptions and detailed
instructional content on their use. Instructional content is delivered via text, images and video
where applicable. This Help Guide also serves as a reference to NinjaScript used in the
development of automated trading systems (strategies) and custom indicators.
In addition to this Help Guide, NinjaTrader hosts multiple live on-line training sessions per
week on various aspects of our product.
Good trading,
NinjaTrader Customer Service
II
20 NinjaTrader Version 7
Performance
Significant memory reductions across all areas of the application
Faster application start up and workspace recovery on multi-core machines
Optimized processing of streaming/real-time events
Optimized processing of bar data recording - Lower CPU utilization and smaller memory
footprint
Significant optimization of internal in memory bar management and building processes
Historical data requests are now internally processed down to an increment of one hour if
the connectivity provider supports this level of granularity reducing data download times
Upgrade to Microsoft .NET 3.5 runtime
True 64-bit windows support where possible
Historical data now stored in binary format in file system vs database
Replaced Jet database engine with SQL server compact edition database engine
General
Added new Google adapter
Added support for fundamental data
Added support for historical bid and ask data (most connectivity providers do not support
historical bid/ask data)
Added ability to automatically connect to your broker/market data service on NinjaTrader
start up
Improved search algorithm used in the Instrument Manager
Deprecated OpenTick adapter support
Miscellaneous Enhancements
General
Z-order of application windows are accurately restored on reloading of a workspace
Removed "Default" workspace requirement
ATM strategy generated stop loss orders are no longer hard coded to use "Stop Limit"
orders on Globex
Removed "Loading data..." pop up dialog window for historical data
Start up splash screen is no longer top most
General
Multi-core support for strategy optimization and basket backtesting
Optimized backtesting performance
New Monte Carlo analysis window
New genetic optimization algorithm
New bar interval optimization - In addition to optimizing on strategy parameters you can
General
Added condition element "Session Break"
Added action "Set bar color"
Added action "Set back color"
Added action "Set back color all"
Added action "Candle outline color"
Added drawing action "Regression channel"
Added drawing action "Fixed text"
Added "Compile" button which allows you to compile your strategy at any point in the
wizard vs at the very end
General
Added "Historical Data Manager" which provides the ability to edit historical data records
through addition, exclusion or change
Added "Session Manager" which allows for the creation of session profiles that can be
assigned at the instrument level
Added automatic merging (continuous contracts) by where historical data from an expired
futures contract will be transparently merged into the front month contract
Added "Metastock" data import
Added ability to import data where time stamps are start of bar time stamped
Added ability to generate minute or day bars from imported tick or minute data
Improved flexibility in historical data import format
General
General performance improvements
Added ability to download historical replay files from NinjaTrader servers
New data files are started at midnight ET
All recorded replay data files are now aggregated into a single replay session allowing for
continuous replay across all available days
Draw objects added during replay are now removed on rewind
NinjaScript Enhancements
General
Objects that implement the IDataSeries interface (excluding DataSeries objects that hold
drive indicator plots) now by default only hold the last 256 values but can be overridden to
hold infinite values if required
"Save As" and "Print" menus to the Output window
Historical data import are now implemented as NinjaScript objects - Advanced developers
can program their own custom import formats
Improved File > Utilities > Import NinjaScript to support custom 3rd party assemblies
NinjaScript exceptions are now sent to the Output window in addition to the Log tab
Added "Weighted" and "Weighteds" price type data series
SendMail() method now supports multiple email addresses
Output window can now be launched from a chart
Added new "OnFundamentalData" method that is called on any change in fundamental
data
Changed data type of "int" to "long" for Volume
Indicators
Added support for multi-series indicators
Improved support for multi-color plots
Changed internal logic of how/when OnBarUpdate() is triggered - There were situations
where buried indicators using custom data series did not fire OnBarUpdate() in correct
sequence
Strategies
Added "StdDev" standard deviation to the TradesPerformance class
Added "GetAccountValue()" method
Fixed issue with sequence of OnBarUpdate() calls for multi-series strategies
General
Added ability to add/change instruments by typing the instrument name (symbol) directly
into the grid
Significantly optimized data series loading for indicator based columns
Optionally highlight instrument column if any cell in its row changes value
Added ability to change the text of a cell based on user defined conditions
Added ">=" and "<=" conditions
Added "Cross Above" and "Cross Below" conditions
Added ability to drag and drop rows
Added ability to add user defined label rows
Added new column "Instrument description"
Bars look back property now customizable per indicator column allow for optimized user
set ups resulting in smaller memory footprint
Session definitions can now be defined by instrument row
Clicking in white space or pressing the Esc key now de-selects a row
Added 10+ fundamental data columns
Charting Enhancements
General
Added support for "Ask" and "Bid" charts
Added support for rapidly changing charts for forex and indexes
Alt + F4 key combination now closes chart
Indicators
Added support for indicators on indicators at the user interface level
Infinite nesting of indicators on indicators
Added support to save user defined default settings per indicator
Added new plot styles Block, Cross, HLine, TriangleDown, TriangleUp, TriangleLeft,
TriangleRight
Added "T3" indicator
Added "DEMA" Double Exponential Moving Average indicator
Added "Double Stochastics" indicator
Added "ZLEMA" Zero Lag Exponential Moving Average indicator
Added "Chaikin Volatility" indicator
Added "LinRegIntercept" indicator
Added "LinRegSlopes" indicator
Added "MAEnvelopes" indicator
Added "PFE" Polarized Fractal Efficiency indicator
Added "RSquared" indicator
Drawing Objects
Drawing objects can attach to data series or indicators
Drawing objects can be local to the chart or global to an instrument across all charts
Snap to OHLC now snaps to any valid data point within a panel
Added new "Lock" property
Added new "Triangle" drawing tool
Added new "Arc" drawing tool
Added option to display fibonacci text levels on the left or right
Regression Channel drawing tool now supports selectable price type
Selecting a draw object and right clicking with your mouse shows context menu with
relevant commands
Barchart Adapter
Updated to the latest API
Added support for a divisor parameter in the symbol map to address incorrect price levels
where needed
eSignal Adapter
Updated to eSignal Standard API 152
Added support for a divisor parameter in the symbol map to address incorrect price levels
where needed
Added support for eSignal fundamental data
Fixed issue where timestamps could be inaccurate during pre and post market hours
IQFeed Adapter
Updated to the latest API (you must update the DTN client)
Optimized processing of news and historical data series requests
Fixed issue where daily events were not processed correctly if NinjaTrader was left
connected to IQFeed overnight
Fixed issue where loss of connection during a pending historical data series would cause
NinjaTrader to hang
MB Trading Adapter
Added support for historical data (requires MBT Navigator version 11.1.0.2 or later)
Added option to drive streaming level 1 data from either snap shot data or time & sales
data
Fixed issue where redundant execution events were thrown after recovery on a loss of
connection
Patsystems Adapter
Updated to the latest Patsystems API
Added support for a divisor parameter in the symbol map to address incorrect price levels
where needed
Added support for account values (applicable only if FCM provides this data)
Fixed issue where data streams could abruptly stop
PFGBEST.com Adapter
Added support for block accounts
TD Ameritrade Adapter
Implemented streaming API, slight performance improvement
Yahoo Adapter
Complete performance overhaul
Optimized HTTP request processing
Zen-Fire Adapter
Updated to the latest API
Fixed issue with duplicate execution id's with Eurex
Improved reconnect logic
III
Release Notes 27
3 Release Notes
NinjaTrader Version 7.0.1000.2 Production Release - January 6, 2010
Status Issue # Category Comments
Improved 4264 Vendor Vendor licensing now only allows letters and digits as user
Licensing ID.
Improved 4270 General Removed Help->Search option as it was redundant to Help-
>Help
Changed 4265 Charts Changed @RSI division by zero; Changed Minimum Period
to 1
Changed 4273 Kinetick Due to upcoming changes on tick IDs, Kinetick users
adapter must update to NT 7.0.1000.2
Changed 4245 IB adapter Updated to TWS 911.
Fixed 4247 Charts X axis labels of 'monthly net profit' could display value of
wrong month. X axis labels were also sometimes not
distributed as expected.
Fixed 4248 Charts Chart executions and trade lines were displayed into right
side margin
Fixed 4251 NinjaScript FirstBarOfSession of period type second on last session
indicators could be false under specific circumstances
Fixed 4252 Charts Added support for box chart style when having range bars
type selected in data series dialog
Fixed 4253 PFG adapterData server settings from connection wizard had not been
properly reflected
Fixed 4254 Charts Add to all bar series didn't work as default for regression
channel draw objects
Fixed 4255 Kinetick Minute bars requests had not been properly filtered by From/
adapter To
Fixed 4256 Charts Amended Point and Figure chart style so that Xs and Os
bars are distributed equally and Os are better aligned to grid
lines/session breaks
Fixed 4257 NinjaScript Specific circumstances could cause an overfill position not
strategies to auto close when strategy is stopped. Strategies will now
wait for 5 seconds for inflight executions to come in.
Fixed 4258 Charts Seconds and Seconds based bar series' first bar on chart
could be from the incorrect prior session
Fixed 4263 Kinetick Toggling instrument type on instrument selector while
Free EOD connected to Kinetick Free EOD data could lock up NT
Fixed 4267 General When merging contracts, data for the rollover day could be
missing for time zones that would span across midnight
when converted to the exchange's time zone
Fixed 4268 Charts Trying to move single anchors of multi anchor drawing
objects on equidistant chart before first bar didn't work as
expected
Fixed 4269 Market OnBarUpdate() now is called for non-indicator columns with
Analyzer BarsRequired=true right after historical data has been
pulled.
Fixed 4271 PFG adapterPFG adapter could throw off NT on sending malformed data.
There are now are more detailed consistency checks in
place.
Fixed 4272 Strategy When opening a chart of a Trade in the SA, if there was a
Analyzer default chart template with non-default session definitions
the chart could be of the wrong time range and no
executions were displayed.
Fixed 4274 Charts 'Reload historical data' on chart didn't work properly when
triggered on rollover date
Fixed 4280 Barchat.com Updated Barchart.com API to address an issue where an
adapter invalid timestamp emitted by the API could throw off NT.
Fixed 4281 Charts Chart lines could be a little off the selection marks when
drawn on logarithmic scale
Fixed 4282 NinjaScript NinjaScript multi series indicators hosting a custom series
indicators which is the input of another hosted indicators could crash
NT.
Fixed 4283 NS NinjaScript indicators would not be updated correctly when
indicators hosted my multi series indicators and having a custom data
series as input.
Fixed 4284 DTN adapterDTN adapter could throw off NT as it sent volume=0 events.
Fixed 4285 Strategy SA chart didn't use point and figure chart style as default
Analyzer when backtesting on PnF series
Fixed 4286 General Detection if user needs to add external references on export
of assembly didn't work properly
Fixed 4287 MBT adapterSome exceptions which could occur on requesting historical
data are now trapped
Fixed 4288 Chart TraderChanging order quantity of ATM strategy in Chart Trader
could yield ArgumentNullException in traces
Fixed 4289 Charts Receiving multi-series chart could lose panel height settings
when instrument change was triggered via the Link button
Fixed 4290 PFG adapterRequesting historical data could fail due to an API issue.
Please update to new PFG API 1.0.458 to resolve.
Fixed 4293 General Fixed logic on parsing currency instrument names
Fixed 4294 PFG adapterPFG adapter now properly reconnects on PFG server reset.
Fixed 4295 Charts Opening horizontal line properties dialog on compressed
monthly chart could crash NT.
Fixed 4296 Market Connecting to live feed after being connected to MR when
Replay >1 charts were open could cause a chart to not roll to actual
date.
Fixed 4297 Charts X axis cross hair label could get truncated on left/right edge
of chart.
Fixed 4299 General NT could crash if it internally tried to calculate conversion
rates for currency pairs which are not supported by the NT
database.
Fixed 4300 Strategy Genetic optimizer pops up excessive dialog boxes for bool
Analyzer and enum parameters if walk forward optimization was
used
Fixed 4301 Patsystems Pats adapter could create phantom "External" orders on
adapter partial fills.
Fixed 4302 Market PositionAvgPrice would display an incorrect value even after
Analyzer position was closed.
Fixed 4304 Charts Settings bar and bar outline color from indicator/strategy
didn't work on box chart style
Fixed 4126 NinjaScript Submitting orders that violated the internal order handling
strategies rules could throw off NinjaTrader and result in strategy
exceptions.
Fixed 4127 Charts P&F could display an inconsistent, different chart after
reloading historical data
Fixed 4128 Instrument Downloading rollover data from the server could yield
Manager exceptions.
Fixed 4130 Data grids Persisting grid settings was erroneous in some scenarios
Fixed 4131 Instrument Requesting the merged continuous contract from our server
Manager (e.g. ES ##-##) didn't work properly for daily bar series
Fixed 4132 Charts Pressing 'Home' or 'Left' on keyboard when no bars were
displayed on equidistant chart could cause the chart to
become blank
Fixed 4134 Chart Trader"Manage ATM Strategy templates" was erroneously
selectable even though "<None>" was selected.
Fixed 4135 Import stock "File->Utilities->Import stock lists" could crash when an
list instrument list was selected.
Fixed 4137 NinjaScript Cancelling orders at the end of a session did not work
strategies properly on multi-series strategies
Fixed 4138 Migration Replay101 and Sim accounts were duplicated on migrating
a NT6.5 DB.
Fixed 4139 Charts @Pivots and WoodiesPivots displayed pivots from wrong
days when on sessions from 12:00am - 12:00am and in
calculate from DailyBars method
Fixed 4140 Charts First or first two days of @Pivots or WoodiesPivots were
calculated incorrectly when using calculate from DailyBars
method and using session definitions not confined to a
single calendar day
Fixed 4141 Charts When using StayInDrawMode with an object already
selected, there could be scenarios where the next mouse
click was erroneously registered as a double mouse click
Fixed 4142 Charts Chart objects attached to bar series not on the chart could
be erroneously duplicated when saving/restoring the
workspace
Fixed 4143 PFG adapterOrders could be stuck when trading on block accounts.
Please update to new PFG API 1.0.445 to resolve.
Fixed 4144 Charts Removing bar series on multi-series charts with indicators
attached to several different bar series could crash NT
Fixed 4148 Charts Indicators on higher panel indexes could move panels when
indicators on lower panel indexes were deleted
Fixed 4149 Strategy Adding non-overlay indicators from strategy and optimizing
Analyzer strategy in SA could have erroneously added the indicators
onto Panel 0.
Fixed 4152 Strategy Changing the panel the bar series resides on could have
Analyzer caused on exception when running consecutive backtests
Fixed 4153 Charts Mouse icon could be erroneous under certain situations
when pressing both mouse buttons
Fixed 4154 Charts Bar series on panel index >1 could have disappeared when
skipping around in Market Replay
Fixed 4155 Strategy Opening the indicator dialogue from the Chart tab after
Analyzer consecutive backtests could have erroneously been
hosting indicator on
Fixed 4098 Charts Logic which determines end of last session on chart wasn't
working properly in some situations for historical charts with
several session segments per day
Fixed 4099 Kinetick Pre/after market realtime did not work as expected.
adapter
Fixed 4100 Instrument Rollover offset calculation wasn't working properly for tick
Manager bar series and 24/7 session.
Fixed 4101 NinjaScript GetTradingDayFromLocal was yielding wrong date values
when applied on 24/7 session
Fixed 4102 Charts There could be spikes (or incorrectly calculated merge
offset) on tick charts for days before rollover days under
certain conditions (time zones, etc.) when tick data was
loaded from repository
Fixed 4103 Session Session on rollover date could be missing under specific
Manager time zones/session time zone combination.
Fixed 4105 General Sorting of tiered commission levels was wrong
Fixed 4106 Market Requesting a chart in Market Replay on a future instrument
Replay with a rollover day included yielded more days than
requested
Fixed 4107 Charts Renko Bars could randomly hang NinjaTrader
Fixed 4108 Performanc Sorting column was not reset when changing Period type in
e reports Performance report's Period tab
Fixed 4109 Charts Drawing new objects on panels occupied only by indicators
could have yielded erroneous behavior
Fixed 4111 NinjaScript Prevent order placement of unmanaged orders with qty <=
strategies 0.
Fixed 4112 Charts When chart was set to always on top, the input selector of
the indicator window popped up behind chart
Fixed 4028 Charts TEMA indicator updated to prevent issue where it did not
operate as expected when used in an exported assembly
Fixed 4029 NinjaScript Trades had not been properly visualized on chart if
strategies ExcludeTradeHistoryInBacktest was set
Fixed 4030 Strategy Handled situation where unreasonably high commissions
Analyzer could crash the performance graph
Fixed 4031 Market Using an indicator with incorrectly coded data series could
Analyzer cause a crash.
Fixed 4032 RSS Inconsistent RSS messages could cause a crash
Fixed 4033 Strategy SA -> Trades tab -> Chart was using instrument's default
Analyzer session template instead of session template which was
selected for the backtest
Fixed 4034 Charts Some chart objects (e.g. Ray) could disappear on non-
equidistant charts when anchors were before the first visible
bar
Fixed 4035 Charts Having lots of chart objects and executions on a chart could
yield a collection modified exception when opening the
workspace
Fixed 4036 Charts Pressing middle mouse button on chart with >1 series and 1
indicator on same panel & scale could yield an exception
Fixed 4038 Instrument Rollover offset could calculate wrong for daily series on
Manager rollover date
Fixed 4040 NinjaScript DrawFibonacciRetracement() with time set signature didn't
work properly
Fixed 4041 Charts Arrow part of an arrow line object could be reversed on
some rare occasions
Fixed 4042 Charts Minimizing a chart could yield exceptions in trace
Fixed 4043 NinjaScript Entry signals had not been properly cleared out when
strategies handling TIF=Day on backtest for multi-series strategies
Fixed 4044 NinjaScript Entry signal handling could get out of sync on multi-series
strategies strategies with more than one series on the same
instrument.
Fixed 4045 Charts Pressing 'Apply' in 'Data Series' dialog or in chart strategy
dialog could change scale justification of indicators on chart
Fixed 4047 Charts Objects which were restored from workspace but were
attached to a bar series 'not yet on chart' were included in
AutoScale and could cause a crash when moved
Fixed 4048 NinjaScript Indicators hosting another multi-series indicator as an input
indicators did not always update properly.
Fixed 4049 Strategy Chart objects drawn from strategy were deleted in SA when
Analyzer trades tab was selected before chart tab
Fixed 4050 Charts Bars.FirstBarOfSession and session break lines on chart
didn't work as expected on seconds and seconds based
period types
Fixed 4051 Charts Changed 'seconds' bar building logic to build bars
consistent with how minute bars are built
Fixed 4056 Charts Fixed performance issue when several indicators and many
chart objects were on chart
Fixed 4057 NinjaScript Setting the panel of an indicator added into a strategy wasn't
strategies working properly
Fixed 4058 Market Replay data can only be downloaded when not connected to
strategies DB, but the associated strategies had not been cleared out
properly.
Fixed 4018 Charts Closing a chart with no bars, but had an active strategy
could yield an exception
Fixed 4019 Instrument Removing an instrument while a strategy was still using the
Manager instrument could cause an exception. Removal now
prevented till no strategy is using it.
Fixed 4021 NinjaScript Strategy recovery did not work in all scenarios when
strategies workspace was not saved
Fixed 4022 Charts Historical reload on futures instruments could result in
redundant data requests
Fixed 4023 Instrument Searching for instruments under certain situations could
Manager cause a crash
Fixed 4024 Market Rewinding Market Replay with an indicator that ran into an
Replay exception earlier could cause a crash. Indicator now
removed from chart on rewind
Fixed 4025 Market Rewinding Market Replay with a multi-series indicator could
Replay cause a crash
Fixed 3911 Charts Applying bars settings in Data Series dialog and then
reapplying could cause a crash
Fixed 3912 Charts Adding new series with last selected period type in chart
bars dialog didn't work when charts were already open.
Fixed 3913 Charts Adding additional bar series objects via typing on the chart
could use an unsupported chart style for the new series
Fixed 3914 Charts Multi-series charts could crash when strategy with
indicators on own panels were removed under certain
circumstances
Fixed 3915 Charts Andrew's pitchfork wasn't drawing parallel fork lines on
monthly logarithmic charts
Fixed 3916 Charts Moving anchor points of lines (line, ray, arrow line, ...) with
auto scale true and one anchor point not on the chart's
visible y-axis didn't work properly.
Fixed 3917 NinjaScript Fixed issues regarding being able to use NinjaScript
strategies strategies on live accounts while in Global Simulation Mode.
Fixed 3919 NinjaScript Could not be re-enabled if strategy were halted due to an
strategies error.
Fixed 3920 Charts Reloading historic data on chart while indicators with
CalculateOnBarClose=false are on chart could cause a
crash
Fixed 3921 Historical Fixed "could not delete file, since it's in use by another
Data process" error related to downloading historical data.
Manager
Fixed 3922 IB adapter Auto start did not properly handle failed login due to incorrect
password.
Fixed 3923 Charts Logic which should repair corrupt days back/custom range/
bars back settings on restore didn't work properly
Fixed 3924 Charts Bars' panels could be removed on restore of multi-series
charts
Fixed 3926 Charts Chart data box got stuck when changing days back on chart
bars with bars data dialog
Fixed 3927 Strategy Switching to chart tab could crash NT.
Analyzer
Fixed 3928 Strategy Reduced the likelihood of rounding errors after optimization
Analyzer in parameter result sets
Fixed 3929 Charts Fibonacci retracement and Fibonacci extension didn't keep
the correct price levels when switched between linear and
logarithmic scale.
Fixed 3930 Alerts NT could crash on shutdown as there had been alerts in the
window alert window
Fixed 3931 Charts Changed data box logic to display plot names instead of
indicator names for plots on non-equidistant charts
Fixed 3932 Charts In Data Series dialog, values on 'Ok' are only applied, when
there were changes in bars # or bars properties
Fixed 3933 Charts Some operations on multi-series charts could cause a Key
"x" already inserted exception
Fixed 3934 Order entry Sim stop orders: If there was a sim stop where the price
was amended and NT crashes, the original price was
erroneously restored on next connect instead of the
amended price.
Fixed 3935 Historical Delete operations could conflict with concurrent data
Data recording logic.
Manager
Fixed 3936 SuperDOM Triggering the FlattenEverything logic while establishing or
closing a connection could cause a crash
Fixed 3937 Charts When strategy on chart, manual executions of same
account could be displayed, too.
Fixed 3938 Account Account performance->Trades tab->Right click->Chart did
performance not work properly for trades created by an NS strategy
Fixed 3939 Charts Executions from on same instrument but on different
exchange weren't displayed in chart data box.
Fixed 3940 Charts Prior executions could be erroneously displayed on chart
while strategy was active
Fixed 3941 Charts When several bar series were reloaded on a multi-series
chart, series with AutoScale=false could be switched to
AutoScale=true
Fixed 3942 Charts Heuristics which distributed a strategy's non-overlay
indicators on panels wasn't working properly on multi-series
charts
Fixed 3943 Charts Line break and Renko bar types could add bars with volume
0, which NT doesn't support.
Fixed 3944 Charts Saving defaults for fib. objects didn't work properly when
"Apply" wasn't pressed before "Set default".
Fixed 3945 Charts Chart containing indicator with additional bar series could
yield exception when connecting to market replay
Fixed 3946 Charts Moving auto scale objects on logarithmic scale could make
the scale change very fast.
Fixed 3947 Charts Applying a chart template on existing chart with more panels
than existing chart, and bar series on last panel could yield
error message
Fixed 3948 Charts Disabled strategies weren't removed properly when
underlying bar series was removed.
Fixed 3949 Account Account Performance->Trades tab->Right click->Chart did
Performanc not position executions properly if there were executions
e from multiple accounts.
Fixed 3951 Strategy Strategy Analyzer's From/To backtest properties could
Analyzer erroneously show time components instead of only dates.
Fixed 3952 Charts Data series containing bars which require very large
amounts of memory space (e.g. forex with very high period
value and volume) could cause internal storage logic to be
off.
Fixed 3953 Charts Restoring a multi-series workspace on a chart with less
panels than bar series could cause the x-axis to not be
visible
Fixed 3954 Market Changing from date in MR while indicator is on chart could
Replay yield exception.
Fixed 3955 WorkspacesNT would report "Unable to open workspace..." as there had
been alerts pending on opening a workspace.
Fixed 3956 Vendor Modules with names starting with a digit could corrupt NT's
licensing Config.xml. Modules are now prevented from having names
starting with digits.
Fixed 3895 Charts Requesting bars data on chart during another data request
is already in progress is now ignored. An error message will
pop up.
Fixed 3896 Google Removed configuration page from Tool->Account
adapter connections for Google since the Google adapter does not
support realtime data.
executed.
Fixed 3804 Charts Improved performance of @MIN and @MAX indicators
Fixed 3805 NinjaScript Chart objects on chart attached to a bar series which was
not visible on a chart could be erroneously accessed in
NinjaScript's 'DrawObjects'
Improved 3806 General NinjaTrader now adds 'Version' tag to all template and
workspace files.
Fixed 3808 Instrument Instrument Manager could crash when pressing OK.
Manager
Fixed 3809 Historical Import of minute data with 'import file timestamp represent
Data start time of bar' option was calculating wrong time offset.
Manager
Fixed 3810 Historical Downloading historical data for only bid, ask, or last was
Data deleting already existing data for bid, ask, and last.
Manager
Fixed 3811 Charts Update of rollover offsets on first open of a chart did not
work when done on date after last rollover date in rollover
offset collection.
Fixed 3812 Charts When a draw object tag and time was changed in property
dialog at the same time, object was not removed from
DrawObjects collection
Fixed 3814 Strategy Strategy Analyzer backtest/optimization properties panel
Analyzer could have been erroneously undocked
Fixed 3815 SuperDOM Changing instruments quickly on SuperDOM with a
workspace containing several linked charts to the
SuperDOM resulted in endless requests.
Fixed 3816 Charts Closing chart while bars reload was in progress could crash
NT.
Fixed 3817 NinjaScript Adding indicator based on custom DataSeries yielded
strategy indicator exception
Fixed 3818 Market Instrument column name holding e.g. blanks could cause
Analyzer exceptions when saving the workspace or saving the MA as
template.
Fixed 3819 Instrument Chart crash on editing instrument lists
Manager
Fixed 3820 Charts Crash when disconnecting from PATS while chart data was
loading
Improved 3822 Charts X axis labels for charts with period type week, month and
year uses improved logic
Fixed 3823 Strategy Chart tab->Right click->Indicators erroneously showed
Analyzer indicator properties besides plot properties
Fixed 3824 Strategy Strategy where indicator with custom series as input was
Analyzer added to a chart could crash NT when switching to chart tab
Fixed 3825 Historical Introduced progress bar for MetaStock import when import
Data archive has a lot of unknown master instruments
Manager
Fixed 3826 Charts/ Amended parameters on a disabled strategy were not
Strategies persisted.
tab
Fixed 3827 Strategy Setting focus to "Optimize on" while in optimizer/walk
Analyzer forward mode and then pressing arrow up/down on
from zero.
Fixed 3701 Charts Cross hair label on daily equidistant charts could show
wrong dates on rare situations
Fixed 3702 NinjaScript Indicators added via a strategy were erroneously all added
strategies to panel 2.
Fixed 3703 Charts Indicators with transparent plot colors could have still
painted a price label outline.
Fixed 3704 Charts Global line on chart with anchors far in past (> 20 days)
could have been removed on switching period value of
chart.
Fixed 3705 Sim101 Trading currencies on sim account while connected to
account Barchart.com, IQFeed or eSignal could have shown
incorrect account values.
Fixed 3706 Charts Disabled setter of ChartControl properties BarsPainted,
LastBarTimePainted, TimePainted
Fixed 3707 Market Changing the label of the "Instrument" column could cause
Analyzer NT to crash.
Fixed 3708 Charts Opening mini data box on indicator panel of daily or weekly
chart could crash NT
Fixed 3709 Charts @Pivots indicator could yield exception when on chart while
connecting
Fixed 3712 Charts WoodiesCCI didn't paint zone bars with correct color (> 0
blue, < 0 red, first n bars grey, neutral = yellow).
Improved 3713 Charts When a chart's instrument is changed via link button,
primary series and all series with same instrument are
changed on the chart too instead of only the primary.
Fixed 3714 IB adapter Market data event with unusually large volume could have
been thrown under certain circumstances
Improved 3715 NinjaScript Removed strategy popups on connection loss and made
strategies them regular log entries.
Fixed 3716 MBT adapterRequests for historical minute data could cause NT to hang
if the request went further back than what MBT actually had
data for.
Fixed 3717 NinjaScript Referencing ChartControl.ChartStyle in OnTermination()
indicators produced indicator error in log on closing of chart
Improved 3719 Database Performance improvements on reset simulation account
and reset DB.
Fixed 3720 Charts Extensive use of cross hair on several charts could crash
NT.
Fixed 3721 Market Resolved several scenarios where ATM strategies could
Replay lock up NT.
Fixed 3722 YAHOO Updating splits no longer worked due to YAHOO data format
adapter change.
Fixed 3723 Charts Requesting bars until yesterday (on chart or SA) on a day
without session definition could leave out data for previous
day.
Fixed 3728 General Instrument selector erroneously accepted blank characters
when connected to a data provider.
Fixed 3729 Charts Woodies CCI/Pivots did not get restored with the workspace
when using NT 64-bit.
Fixed 3730 NinjaScript Generating protected assemblies could have had issues
grid restart.
Fixed 3756 Executions Manually adding executions with an execution time in the
tab past could have caused a log error on NT restart.
Fixed 3757 Charts Toggling the time frame where the chart held no historical
bars and a live strategy could crash NT.
Fixed 3758 Charts Performance improvements on drawing of charts while
connected with live feed
Fixed 3759 Charts Indicator with Displacement > 0 could break NT when in
workspace which is opened on chart with no bars.
Fixed 3760 MBT adapterHandle new order rejection reason "Business Reject".
Fixed 3655 General Performance graphs for large backtests could have
displayed with lines pinned to the left edge
Fixed 3656 Level II Quotes grid settings were not persisted
Fixed 3658 General Reloading historical data did not work properly when using a
derivative chart type (LineBreak, PnF, etc.) that was based
on a Minute series
Fixed 3659 Charts Reloading historical data on charts could cause an assert
error
Fixed 3660 Strategy Loading optimizer results did not properly restore the
Analyzer "Settings" tab
Fixed 3661 Charts Z-order of global chart objects could be wrong when viewed
from another chart
Fixed 3662 MBT adapterProperly filter bid/ask/last events generated when using
"Use snapshot data" for when price <= 0
Fixed 3663 NinjaScript SyncAccountPosition=false could have still tried to close a
Strategies historical strategy position
Fixed 3664 General Saving rollover dates pulled from data server could have
caused exception errors
Fixed 3665 General Single or double quotes in a Windows user account name
could cause issues
Fixed 3666 Charts Crosshair on charts could have caused exception errors
Fixed 3667 NinjaScript NinjaScript strategies on charts could cause exceptions
Strategies when switching the charted instrument
Fixed 3668 Charts Building of the first bar of a session was not properly built
independently of prior session for LineBreak charts
Fixed 3669 NinjaScript Very first OnMarketData(), OnMarketDepth(), and
Indicators OnFundamentalData() could have been filtered which could
throw off building L2 price ladders
Fixed 3670 NinjaScript Pivots didn't calculate correctly for monthly/weekly pivots
Indicators based on daily data
Improved 3671 Charts New charts now save last used Period type as default for
subsequent File > New Chart actions
Fixed 3672 NinjaScript CurrentDayOHL didn't notify user when used improperly on
Indicators a non-intra day chart
Fixed 3673 Charts LineBreak and Renko charts could have an improperly built
last bar
Fixed 3674 NinjaScript FirstTickOfBar logic could have been off on multi-series
Indicators indicators
Fixed 3675 Strategy Setting default settings for a strategy could have thrown off
Analyzer the optimizing on a Data Series
Fixed 3676 Charts Charts could have had a gap with missing data of the
previous day if session definition was a 24 hours definition
and prior session's data wasn't loaded completely
Fixed 3677 Charts Live charts could have stopped updating after disconnecting
and then reconnecting with "Get data from server" option set
to false
Fixed 3678 NinjaScript Set() methods could have been inadvertently cancelled on a
Strategies multi-series strategy
Fixed 3679 Backup/ There could have been redundant backup reminders
Restore
Improved 3680 TDA adapter Filtered out "Hdr: 400 Data acquisition failed" messages on
Fixed 3599 Charts Link button didn't work when sending chart was a multi
series chart.
Fixed 3600 Market PositionAvgPrice column would set a background color
Analyzer
Fixed 3601 NinjaScript OnStartup() had not always been triggered on starting a
Strategies strategy.
Fixed 3602 NinjaScript Placing orders in different BIP could cause asserts on
Strategies StopTargert handling.
Fixed 3603 Chart TraderChart trader did place a stop limit on the wrong side of the
market if the price traded through the stop price.
Fixed 3604 General Fixed a couple of minor issues on various UI's like focus
handling, icons etc.
Fixed 3605 DataBase Historical daily data request for more then 10,000 bars back
could corrupt the DB.
Fixed 3606 Basic Entry Orders in basic entry could change rows on pressing '+' or
'-'.
Fixed 3607 Grid Grid header weren't included when grid saved with 'Save
as...'.
Fixed 3608 DTN adapterNT could lock up while connected to DTN, then File->new
L2->Right click->Instrument->Select...
Fixed 3609 Level II L2 did not properly recover on opening a hosting workspace.
This e.g. prevented the selected instrument from being
restored which then would not subscribe upon connect.
Fixed 3610 Charts Fixed bugs related to internal parameter handling for PnF,
LineBreak and Kagi
Fixed 3611 Market Sorting order was not maintained after right click-
Analyzer >Properties->OK/Apply
Fixed 3612 General Moving mouse from active chart to inactive chart (both with
indicators on) while data box was open could bring up
PANIC error message.
Fixed 3613 Performanc X axis labels in performance graph Distribution was
e reporting displayed with uneven gaps or odd labels around 12:00 AM
Fixed 3614 TDA adapter Updated to TDA API V134
Fixed 3615 General Updated ZipLib to latest version
Fixed 3616 Alert window Right click->Always on top was not reflective of actual
"Always on top" state
Fixed 3617 Basic Entry Clicking rapidly on '+' of basic entry order sometimes
changed the price value in the wrong row.
Fixed 3618 Strategy Right click->Performance viewer only would have the tabs
Analyzer which are available on the originating SA.
Fixed 3619 Charts Removing bar series on multi series chart and adding on
different position could crash NT.
Fixed 3620 Charts Many charts open on high virtual screen setup (e.g. 4 x 3
screens of 1920 x 1200 size resolution) could cause
exception clicking on chart.
Fixed 3621 Window T&S, BasicEntry, FxPro and FxEntry did not properly handle
properties default properties and the "reset" option for properties.
Fixed 3622 Indicator Removed the CalculateOnBarClose option.
Wizard
Fixed 3623 Market Indicator columns now format prices using
Analyzer FormatPriceMarker
Fixed 3624 Alerts Mails on alert only would be submitted if the email address
would not end with "@NinjaTrader.com."
Fixed 3625 Market Right click->Reload all historical data did not work as
Analyzer expected.
Fixed 3626 Backup/ Several improvements on backup/restore
Restore
Fixed 3627 Market There now are separate options for download L1 and L2
Replay replay data.
Fixed 3628 General Application could hang when trying to exit while loading data
from provider.
Fixed 3629 Internal Session bars could be missing when merging bar series on
continuous contracts.
Fixed 3630 Charts Adding chart template on multi-series could yield out of
memory exception.
Fixed 3631 TradeStation TradeStation ATI files had bugs which could cause TS 8.8 to
ATI crash
Fixed 3635 Charts Cross hair did not work accurately if Data Series was on
panel 2 and was using logarithmic scale
Fixed 3636 Market Changing instrument name to blank could crash the
Analyzer application
rapid succession.
Fixed 3580 Market Clicking on chart canvas after rewind on MR is triggered
Replay could crash NT.
Fixed 3581 Charts V value of anchors of chart objects could change when
property dialog was opened.
Fixed 3582 Strategy The tab sequence summary->chart->summary->chart
Analyzer would make custom color series ineffective
Fixed 3583 NinjaScript Signal handling etc. still could have been triggered on live
strategies incoming executions although Unmanaged=true.
Fixed 3584 NinjaScript NS strategies did not properly recover their live orders on
strategies restoring after NT restart which caused several issues in
syncing when re-enabling.
Fixed 3585 TDA adapter Updated to latest TDA API V130
Fixed 3586 TDA adapter Changed logic on requesting historical daily data to resolve
issues related to incorrect from/to dates.
Fixed 3587 Strategies Strategy in Strategies grid could have had the Enabled
grid check box be displayed as "Disabled" despite it actually
being "Enabled"
when changed via link button and instrument did not exist in
combo box
Fixed 3535 Strategy Bar width settings in SA were not restored properly on
Analyzer several consecutive backtests.
Fixed 3536 Charts Multi-series indicators has issues when going from historical
to realtime data.
Fixed 3537 Session Spikes or a whole session with wrong offset could be built
Manager on merging contracts for first session of new contract.
Fixed 3538 NinjaScript "Cancel exit/entry orders when strategy is disabled" did not
Strategies work as expected as it could have left orders in
"PendingCancel" and causing issues when reconnecting.
Fixed 3540 NinjaScript Context menu "Save" menu was not disabled on system
Editor indicators
Fixed 3542 Chart Indicators with a transparent plot color could cause an
indicators overflow exception on panels with a very small scale range
Manager
Fixed 3459 MBT adapterAccount values had not been reported property upon
connect.
Fixed 3460 ZenFire account values had not been reported property upon
adapter connect.
Fixed 3461 Chart Chaikin Oscillator had been using SMA instead of EMA.
indicators
Fixed 3462 Charts First bar of session did not work for Renko and not properly
for Line break bars style.
Fixed 3463 Charts Global cross hair on charts could cause 'out of memory'
exception
Fixed 3464 Charts Daily bars didn't fill up when connected before first existing
date in repository.
Fixed 3465 WorkspacesRestoring workspace with multiple bars and indicators on
higher panels could crash NT
Fixed 3466 Internal Reset member cache when last bar is removed.
Fixed 3467 Charts Global horizontal line could disappear from chart when
switching bars on chart or opening new charts
Fixed 3468 Charts Execution could have wrong scale justification, e.g. on
update or when base bars changed panel/scale
Fixed 3469 NinjaScript Fixed various issues related to multi-series handling.
indicators
Fixed 3470 Charts Data box didn't show instrument label when opened before
first bar of chart.
Fixed 3471 Charts Z-order of objects and bar series could change when
switching period type and bar default for new period type
was in place
Fixed 3472 Chart Indicator on bars panel didn't change scale justification
indicators when underlying bar series was dragged & dropped on
different scale on same panel
Fixed 3473 Charts When bar series was dragged and dropped on different
panel and/or different scale and strategy was running on bar
series, related objects weren't moved with bar series.
Fixed 3474 Chart Pivots and WoddiesPivots indicator didn't paint after
indicators pressing F5 under certain circumstances
Fixed 3475 Charts Switching to instrument with typing on chart could change
also period under certain circumstances.
Fixed 3476 Charts Too few x axis label could be displayed on equidistant charts
when sessions displayed where a large bar range was
missing (e.g. on bank holiday).
Fixed 3477 Time and T&S window now has a property to configure the update
Sales interval.
Fixed 3478 Charts CurrentDayOHL didn't work properly for actual day and
session 24/7
Fixed 3479 Chart Indicator's ShowBarsRequired didn't work for indicator's
indicators price label. Indicator on empty chart could crash indicator.
Fixed 3480 External Did not construct daily bars from streaming data
adapter
Fixed 3481 Market Race conditions could cause exceptions on start up if
Analyzer indicator columns were present
Fixed 3482 NinjaScript Fixed issues related to persisting strategies
strategies
Fixed 3483 NinjaScript Export protected assemblies now supports RemoteSoft
assemblies Protector V4
Fixed 3484 NinjaScript Vendor assemblies could have been loaded as there had
assemblies been X86 and X64 versions available.
Fixed 3485 WorkspacesAdded confirmation on save workspace by double click.
Fixed 3486 Strategy Strategy Analayzer could throw exceptions as a non XML
Analyzer serializable strategy was persisted.
Fixed 3487 Charts When a bar series was requested of an already expired
contract spanning from contract before/until contract
afterwards, wrong merge offset was added
Fixed 3489 Chart Fibonacci Retracement can be selected on non diagonal of
objects the object where is no anchor lines.
Fixed 3413 FX Pro FXPro could end up having live account selected even when
in global sim mode by connecting/disconnecting multiple
connections at a time.
Fixed 3415 NinjaScript Having a multi-series indicator as input of an indicator could
indicators cause log errors e.g. on pressing F5.
Fixed 3416 Charts Opening chart object dialog could crash NT when object had
y anchor value of > 99999 or < -99999
Fixed 3301 Historical Selecting "Edit logs" node and pressing "Delete" could
Data cause an exception.
Manager
Fixed 3302 Market Rejected orders on ATM strategies could lock up NT.
Replay
Fixed 3303 General SQL CE DB engine deployed with NT might conflict with
SQL version installed already !!! exported NS assemblies
needed to be exported again !!!
Fixed 3304 IB adapter Bogus TWS data could corrupt NT and result e.g. in spikes
on a chart.
Fixed 3305 Google Added UrlEncoding to instrument names to make sure only
adapter valid URLs would be created.
Fixed 3306 Market Row filter did not work as expected.
Analyzer
Fixed 3307 NinjaScript DrawTextFixed method could cause an exception if
strategy/indicator was not running on a chart.
Fixed 3308 Instrument Instrument manager could crash when adding a stock while
Manager being connected to a provider which does not support
stocks
Fixed 3309 Instrument Setting contract month to 12-99 in roll over definition could
Manager cause an exception.
Fixed 3310 Strategy Chart could be on wrong data series if previously there was
Analyzer a data series optimization running
Fixed 3311 Charts Values of bars with merge settings MergeBackAdjusted
were off when bars loaded from repository.
Fixed 3312 IB adapter Volume on realtime for non US stocks could be off.
Fixed 3313 Charts Request for daily bars could result in too many requests to
provider when requested on a day without session definition
Fixed 3314 Strategy Changing symbol in SA chart while indicator applied causes
Analyzer crash
Fixed 3315 Charts Opening daily chart on day with no session definition build a
daily bar with wrong timestamp.
Fixed 3316 Chart OnMarketData/OnMarketDepth /OnFundamentalData did
indicators not trigger as the chart was recovered in "hidden" state.
Fixed 3317 Chart Fixed several issues on Pivots/Woodies Pivots indicators
indicators
Fixed 3318 Strategy "Period" column had DateTime values instead of Date.
Analyzer
Fixed 3319 Chart Changing the 'attached to' property in chart object properties
objects dialogs didn't change the y values off the anchor points in
the dialog.
Fixed 3320 Chart Double click on ruler didn't select ruler, when 2nd and 3rd
objects anchor were at the same x/y location
Fixed 3321 Chart Chart objects which were on chart 'hidden' (on bar series
objects which is not on chart) were not saved/restored in
workspace.
Fixed 3322 Market Rewinding could throw off indicators
Replay
Fixed 3323 Charts Exception when strategy which is not on chart is drawing
region, regression channel or TextFixed.
Fixed 3324 Chart Drawing object related exceptions on restore, e.g. multi
charts.
Fixed 3378 Historical Downloading historical data server could result in "Index out
Data Server or range" errors.
Fixed 3379 Charts Chart executions' labels could overlap when they were
located on bar which had same timestamp as several other
bars.
Fixed 3380 WorkspacesWorkspaces holding single quote ' in their name could
cause exceptions.
Fixed 3382 IQFeed Realtime and historical volume values for currencies now
are multiples of 100,000
Fixed 3383 Charts Volume values greater than uint.MaxValue (4 ~billion) had
been inaccurate as they internally had been stored as float -
> rounding issues
Fixed 3384 Charts Chart didn't AutoScale to objects drawn from indicator when
indicator only series on chart with AutoScale = true and
indicator had no plot.
Fixed 3385 Charts Fixed several AutoScale issues
Fixed 3386 Charts Added indicator, strategy and chart series defaults to
templates category on Restore/Backup and changed test in
dialog accordingly (to 'Templates')
Fixed 3387 Order entry BasicEntry, FxPro, FxEntry did not maintain their properties
windows (e.g. link color) as there had been default properties.
Fixed 3388 Backup Hot Key settings were not restored until after a restart
Fixed 3390 Market Using multi-series indicators could cause an index out of
Analyzer bounds error
Fixed 3391 Charts Scrolling non-equidistant charts with the keyboard arrow
keys moved the chart crosshairs off the mouse cursor
Fixed 3392 Strategy Chart tab did not use user defined defaults for Chart
Analyzer Properties
Fixed 3393 Chart Chart objects placed on the first bar moved to be before the
objects first bar when switching the chart from non-equidistant to
equidistant
Fixed 3196 Strategy Strategy wizard could produce non-compilable code when
Wizard manipulating int/double on min or default values.
Fixed 3197 PFG AdapterHistorical minute and daily requests did not work as
expected.
Fixed 3199 Charts Opening property dialog for an object attached to custom
indicator with empty result of ToString(...) method could
crash NT.
Fixed 3200 NinjaScript DrawTextFixed methods did draw outline and back
rectangle with an incorrect offset.
Fixed 3201 Historical Made metastock import more error tolerant regarding
Data uppercase/lowercase filenames.
Manager
Fixed 3202 Charts CandleOutlineColor set from script was ignored for the color
of candle wicks when wick color was set in bar series
settings.
Fixed 3203 Charts FisherTransform indicator was not TickSize sensitive.
Fixed 3204 Historical Daily bars built from tick or minute data were not correctly
Data time stamped
Manager
Fixed 3205 Data Server Daily data was incorrectly built.
Fixed 3206 NinjaScript Using custom series on a multi-series indicator/strategy
could cause exceptions.
Fixed 3208 Charts Selecting an bar series or indicator with drawing tool 'ruler'
selected was not possible when chart's bar series selection
property was false.
Fixed 3209 Data box Coloring issues on data box and mini data box.
Fixed 3210 Market Available data" was not updated as data down downloaded
Replay again.
Fixed 3211 Charts PnF charts loaded from cache could hang NT
Fixed 3212 Charts Enabled TickCounter indicator for tick based period types.
Does not work for PnF, Kagi and LineBreak.
Fixed 3213 Charts Applying chart template with less panels than already on
chart could crash NT.
Fixed 3214 Charts Data in display box of ruler has been off when only 2nd ruler
anchor was moved.
Fixed 3215 Charts VolumeUpDown could paint bars with 2 colors and 2 labels
instead of one color per bar and 1 price label.
Fixed 3216 Charts On switch of period type in bars data dialog, if new period
type has no defaults, and new period type supports candle
stick as chart style, take candle stick.
Fixed 3217 Charts If ruler drawing tool is selected, and only one bar series/
indicator is on panel, series is auto selected and ruler starts
drawing immediately, instead of selecting the series only.
Fixed 3218 Charts Trade lines didn't display properly on chart after walk
forward optimizer in strategy analyzer.
Fixed 3219 Drawing Show text in properties did not work for Andrew's pitchfork,
objects Fibonacci time extension, Fibonacci circle and Gann fan.
Fixed 3220 Strategy Switched a couple of currency cells on the grids to fixed '$'.
Analyzer
Fixed 3221 Charts Zooming or panning a chart in x/y-axis didn't work when a
locked and selected drawing object was on chart.
Fixed 3222 Drawing Slope of global chart objects could be off when anchor time
objects are before first bar of chart.
Fixed 3223 Charts Colors of a multi color plot indicator could be wrong when
only color of some parts were set.
Fixed 3224 Data box Chart data box and mini data box displayed indicator values
though if it wasn't defined for that bar
Fixed 3225 Charts Bar color of OHLC chart style could be off when extremely
zoomed out.
Fixed 3226 Drawing Opening properties dialog on global chart object with
objects anchors partially off bars (e.g. before first bar) could crash
NT.
Fixed 3227 SuperDOM SuperDOM PnL did not update properly when market depth
was disabled and PnL was using bid price instead of last
price for calculations
Fixed 3229 Charts New->Chart dialog was not sensitive on the selected
exchange of instruments added to instrument lists.
Fixed 3231 Charts Resizing non equidistant chart with 'show toolbar' set to
false did shrink/expand bars instead of leaving distance
between them constant.
Fixed 3232 Charts Left price markers on bar series or indicators could be
displayed though there was no left y axis.
Fixed 3233 NinjaScript Time/Times property did not return end-of-session
timestamps for daily bars.
Fixed 3234 IB adapter Amended handling on pacing violations
Fixed 3235 NinjaScript Explicit exit orders could cause an "Order quantity has to be
strategies greater than 0" error.
Fixed 3236 ATM ATM strategies had not been properly recovered on
strategies reconnect.
Fixed 3237 General Revised approach to resolve DB.ExecutionUpdate
exceptions.
Fixed 3239 General Default property settings for various UI had not been
maintained across sessions.
Fixed 3240 Strategy Walk forward no longer properly had been using the
Analyzer optimization period as sync up period.
Fixed 3241 Hot Key Hot Key Manager no longer would allow assigning mouse
Manager buttons.
Fixed 3242 Charts Loading bar series before session begin on rollover date of
future with merge settings set to 'merge backadjusted' or
'merge non backadjusted' could hang NT.
Fixed 3243 Charts Chart style default had not been applied correctly.
Fixed 3244 Charts Last session break line on equidistant charts did plot on
second bar of new live session, not on first.
Fixed 3245 Market Infinite historical market data requests
Analyzer
Fixed 3246 Strategy Could crash on compiling a strategy.
Analyzer
Fixed 3247 Charts VolumeProfile indicator: Diamond was missing as it started
recording.
Fixed 3248 Historical Changed warning logic on download in case not for all
Data instruments data could be downloaded.
Manager
Fixed 3114 Yahoo Redundant DailyVolume event could cause charts being off
adapter on the last price.
Fixed 3115 Strategy Results on WalkForward tab did include the optimization
Analyzer period.
Fixed 3116 NinjaScript Amended code snippet by adding AutoScale parameter
Editor where needed.
Fixed 3117 Chart Chart could crash on equidistant non minute charts with
only a few bars, e.g. when reloading historical data
Fixed 3118 Charts Modified sequence, which chart style is used on switching
period types on chart.
Fixed 3119 Charts Added HorizontalGridlinesUnit to panel properties which
switches horizontal grid line interval from points to ticks.
Fixed 3120 Drawing XML for Fibonacci templates takes direct user input causing
objects error as certain characters are saved (dashes, spaces, etc)
Fixed 3122 ATM There was an unwanted delay between placing stop and
Strategies target orders.
Fixed 3123 Charts If left and right scale were on chart, panel properties
displayed properties from other side, even when there was
no series on scale.
Fixed 3125 NinjaScript Restoring on startup caused duplication of parameters in
Strategies StratgeyBase.Parameters collection.
Fixed 3126 Merging Merging contracts on futures: added logic to prevent reload
of last day from provider on one previous expiry.
Fixed 3127 General Link button was not shown on SuperDom, FXEntry,
BasicEntry etc. if those UIs had been AlwaysOnTop
Fixed 3128 General ATI component was not shut down properly
Fixed 3129 Charts Chart objects painted into the future were moving on every
incoming tick on realtime.
Fixed 3130 Charts X-axis labels for space right from last bar changed on
second charts on every incoming bar.
Fixed 3131 Charts Bars.SessionBreak was not working properly on second
charts.
Fixed 3133 Charts Resolved conflict between chart trader minimize/maximize
and right lick-> price offset selector
Fixed 3134 General Avoid null reference exception during connecting while
objects are on chart
Fixed 3136 General Auto scale on global chart objects didn't work properly, when
several bar series with same instrument were on chart.
Fixed 3137 Charts Data Box Error as multi-series chart is scrolled to the first
bar of the series.
Fixed 3138 Monte Carlo Print on Monte Carlo Simulations was printing a blank page.
Simulation
Fixed 3140 General Save as image dialog had caption '<instrument> & date'
instead of 'Save as' and save as indicator set had caption
'save image'.
Fixed 3141 Charts Indicator on left scale on charts with 1 bars only could crash
NT.
Fixed 3142 Performanc Currency symbol is taken from Windows default regional
e tabs setting and does not correspond to trading currency in the
Account Performance Periods, Executions, and Trades
tabs.
Fixed 3143 NinjaScript Not all custom series classes had a constructor where a
MaximumBarsLookBack could be applied.
Fixed 3144 Charts Renamed display name "Candle Stick" to "Candlestick".
Fixed 3145 Charts Added property ShowGlobalChartObjects to bar series
Fixed 3146 Charts Added chart property ChartObjectSelection which defines if
bar series and indicators can be selected with mouse click.
Fixed 3147 Charts Box chart style didn't display bars when chart was extremely
zoomed out.
Fixed 3148 Charts Allow user defined y axis horizontal grid line & label logic
also on scales & panels which contain no bars.
Fixed 3150 NinjaScript You now could access .Instrument in Initialize() again like
NT6.5
Fixed 3151 Charts When using white text on a chart with a black background,
the input text can not be seen in the text entry field of text
properties window. This makes adding text difficult.
Fixed 3153 Order entry Limit and stop price editing precision was off for instruments
with different tick size precisions.
Fixed 3154 Charts CurrentDayOHL didn't reset properly on beginning of actual
session
Fixed 3155 Charts First bar of box chart style was painted without margin,
displaying it larger when bars got scrunched.
Fixed 3156 Drawing Pasted drawing objects didn't get offset on equidistant
objects charts.
Fixed 3157 General Fixed crashes on several properties grids when up/down
key would be pressed
Fixed 3158 Charts Logic which avoids no bar series/indicator with AutoScale
true is on panel didn't work if bar series had AutoScale false.
Fixed 3159 WorkspacesEditing workspaces names in the FileDialog would get
rejected if the new file name held a space.
Fixed 3160 Charts PNF bar type was not building properly when the box size
was set to 1 (1x1, 1x2, 1xn etc)
Fixed 3161 Strategy Monte Carlo sim painting was wrong as it repainted not on
Analyzer thee whole panel but onle the subsection which was
reported by the painting event.
Fixed 3162 Charts If bar series/indicator is last series with AutoScale on panel
& scale with AutoScale true, disable AutoScale in property
grid.
Fixed 3163 Historical Meta Stock import didn't import the last bar.
Data
Manager
Fixed 3164 Drawing Global objects (e.g. lines) with anchor painted in near of last
objects bar could disappear on chart where several bars have same
timestamp (e.g. 1 tick charts)
Fixed 3166 PFG adapterPFG adapter now would reset internal position calcs and
order states on server reset.
Fixed 3167 Monte Carlo Memory Consumption on Monte Carlo form leaks
Fixed 3168 Market The calendar control kept scrolling after pressing the '<' '>'
Replay buttons
Fixed 3169 Drawing Draw object handling on equidistant chart is now index
objects based again, with values between bars possible.
Fixed 3170 Google Google changed their table format for Historical data for
selection process.
Improved 2996 Barchart. Updated to latest API and re-enabled pre/after market data.
com
adapter
Improved 3031 Historical HDM import now has an additional combobox to set the
Data timezone of the imported data.
Manager
Improved 3032 NinjaScript Added back the feature to access hosted indicators in
indicators Initialize().
Improved 3042 NinjaScript Throw exception is the respective methods for HeikenAshi,
LineBreak, Renko, Kagi, PointAndFigure are not used but
the generic Add() method.
Fixed 2904 Account Account performance->Execution tab->Right click on
Performanc execution->Chart did not work as expected.
e
Fixed 2988 MBT adapterSeveral issues related to historical data on MBT.
Fixed 2994 Import stock File->Utilities->Import stock list->Session combobox did not
list properly show session names
Fixed 2995 NinjaScript Issue with BarsDisplayText
Fixed 2997 WorkspacesRestoring a workspace with cross hair on a chart could
crash NT.
Fixed 2998 Charts Added additional description text in the right/left horizontal
grid line properties in chart panel properties.
Fixed 2999 Charts Drag & drop or deletion of bar series or indicators could
cause scaling/scale justification errors.
Fixed 3000 Charts 'Set default' button was displayed on chart panel properties
window
Fixed 3001 Charts Indicators scaled to objects drawn from this indicator even
when on separate panel.
Fixed 3002 Charts Panels did scale to Dots and Text even when they were not
visible on chart.
Fixed 3003 Indicators Indicator VolumeZones, DrawLine parameter did not work
as expected
Fixed 3004 NinjaScript Using TickSize in Initialize() now throws an improved log
message.
Fixed 3005 Data box Data box shows info from two bars while on the same bar
for box style
Fixed 3006 Charts Multi series indicator on multi series chart could crash.
Fixed 3007 Hot Key Set a wider min width to avoid formatting trouble on tool tips.
Manager
Fixed 3008 Connecting AutoConnect did not properly Initialize all UIs
Fixed 3009 General NT could crash on reloading/restoring from xml when
executions were on chart.
Fixed 3010 Chart TraderEntry parameter instrument in chart trader -> ATM strategy
could have been blank on multi series.
Fixed 3011 Indicators ZigZag.HighBar did not work as expected, since an Update()
was missing.
Fixed 3012 Charts X axis labels on equidistant tick charts updated on every
second when ticks came in on realtime.
Fixed 3013 Charts Panel height wasn't maintained in some situations.
Fixed 3014 Drawing Fibonacci objects not working when chart put into
Fixed 2961 Charts BackColor from indicator wasn't drawing properly before
first/after last bar of base bar series on chart.
Fixed 2962 Charts NT could crash on multi series charts with indicators on
when changing period type from toolbar.
Fixed 2963 Charts 'Set Default' button was no longer being displayed on the
Gann Fan and Andrews Pitchfork properties
Fixed 2964 Charts BarTimer indicator no longer working for second charts.
Fixed 2965 Charts Box Style had remnant of a bar when drawing in certain
situations.
Fixed 2967 Charts Timestamp of first bar in session of n-minute/n-minute-
based bars (n > 1) could be off on odd session settings
Fixed 2968 Mail feature NT mail feature now supports having multiple TO and CC
recipients by concatenating them by ";".
Fixed 2969 Charts First line off ZigZag indicator on daily charts could have been
off (to the left edge of the chart).
Fixed 2970 Charts ZigZag indicator wasn't included in AutoScale
Fixed 2971 Market Bar series could disappear on Market Replay
Replay
Fixed 2972 NinjaScript NinjaScript indicator wrappers had been flawed !!! Must
regenerate all indicator scripts individually
Fixed 2973 Charts Extend left/right text not formatting properly for retracements
and other fib objects.
Fixed 2975 Historical Cache not being deleted properly in HDM.
Data
Manager
Fixed 2977 Charts The logic to determine if a tick was in session or not was
flawed.
Fixed 2979 General Several fixes/changes on data server.
Fixed 2980 Charts Panel height changed when interval was selected in toolbar.
Fixed 2981 Charts Mini instrument selector did not work as expected using
NumPad keys.
Fixed 2982 Charts 'F' for fixed panel was not visible when chart trader was
enabled but collapsed.
Fixed 2983 Charts Date timestamps on a axis could be off in case of minute
charts containing data with large gaps in it.
Fixed 2984 Charts X-axis labels and grid lines did not correctly re-size on
equidistant chart
Fixed 2987 Automated COM/DLL interface did not work
Trading
Fixed 2855 Charts OHLC bar Type not reflecting changes in bar Width.
Fixed 2856 Charts PnF, Kagi, LineBreak charts did not have volume
Fixed 2857 Historical When additional data is downloaded for an instrument in the HDM,
Data the newly downloaded data is not being reloaded in the Edit/Export
Manager tabs
Fixed 2863 Historical When an HDM node is expanded, right clicking and deleting a
Data different node will sometimes cause an exception.
Manager
Fixed 2861 Historical Edit Tab in HDM does not match the sorting of the lists on the
Data Control Panel
Manager
Fixed 2865 SuperDOM SuperDOM could have stale bid volumes when "Show market
depth" was disabled
Fixed 2866 Vision Vision connections did not migrate properly and Vision default
Financial settings had not been correct.
adapter
Fixed 2867 Strategies Restoring strategies upon connect could cause a lock up.
Fixed 2868 Grids When grids were being printed/emailed the date showing up was
the day the grid was created, not the day that the grid was printed.
Fixed 2869 General Error message for rejecting restore archive created by older NT
version was incorrect.
Fixed 2870 Indicators BarTimer indicator did not work.
Fixed 2871 TT adapter There could have been redundant connection status events
causing e.g. duplicate account on the NT combo boxes.
Fixed 2873 NinjaScript Replace overwritten .Dispose() in standard indicators by
OnTermination()
Fixed 2877 Charts MultiColored Plots are not working when changing the plot style to
block or triangle.
Fixed 2878 Charts Drawing objects (GannFan, AndrewsPitchfork, and Fibonacci) from
indicators with Overlay set to true threw indicator log error.
Fixed 2879 Charts Negative bar series values would throw off NT and result e.g. in
incorrect values being rendered on chart.
Fixed 2880 NinjaScript OnTermination logic was flawed.
Fixed 2881 Charts NT could crash when deleting indicator with indicator dialog while
having bars on higher panel number.
Fixed 2882 Charts BackColor could be off set from a indicator with overlay true.
Fixed 2883 Charts 3 Line Break chart styles creating incorrect bars.
Fixed 2884 Charts indicator wich plotted an indicator with input series not on chart
could crash NT.
Fixed 2887 NinjaScript NS: Indicator wrapper did not work in MA columns (although not
supported they used to work in NT6.5)
Fixed 2889 Charts Removal of indicators @VolumeCounter.cs, @BarTimer.cs,
@RangeCounter.cs or @TickCounter.cs crashed NT.
Fixed 2890 Charts When switched from MR to realtime, chart stayed historical in
some cases.
Fixed 2891 Charts Chart execution text and trade lines could have been drawn on
wrong panel on multi series charts.
Fixed 2893 Charts Indicator which added 2nd series and had other indicator as input
series could throw indicator exception.
Fixed 2897 Charts Removing of panel with y axis context menu could crash NT
Fixed 2898 Charts Changing panel # of new indicator with other indicator as base
IV
86 NinjaTrader Version 7
4 Video Library
Within the Help Guide are numerous help videos. Below is a shortcut list to all available
videos within the Help Guide.
ATM Strategy Selection Demonstrates the various ATM Strategy selection modes
Mode
ATM Strategy Example #2 Demonstrates how to build an ATM Strategy including auto
breakeven and auto trail stop features
Charts
Creating a Chart
Navigating a Chart
Changing the Horizontal Demonstrates how to adjust the chart horizontal scale and
Scale and Range range
Changing the Vertical Demonstrates how to adjust the chart vertical scale and
Scale and Range range
Chart Zooming Demonstrates how to zoom in and out of a chart
Chart Panels Overview of chart panels
Chart Drag and Drop Demonstrates how to drag and drop chart items
Chart Z-Order Demonstrates how to adjust chart item depth (z-order)
How to Draw on a Chart Demonstrates how to add a drawing object to the chart
Drawing Object Properties Overview of drawing object properties
Removing Drawing Demonstrates how to remove a drawing object from the
Objects chart
Fibonacci Drawing Object Demonstrates how to save Fibonacci drawing object
Templates properties as a template
Local and Global Drawing Overview of using local versus global drawing objects
Objects
Data Box
Working with Hot Keys Overview of the Hot Key Manager, assigning and removing
Hot Keys
Market Analyzer
Working with Instrument Demonstrates how to add and remove various instrument
Rows rows
Working with Columns Demonstrates how to add, customize, and remove columns
Market Replay
Set Up
Replay
SuperDOM
Static vs Dynamic Price Overview of the differences between the Static and Dynamic
Ladder Display SuperDOM
Dynamic Price Ladder Overview of the Dynamic price ladder display
Display
Order Display
Submitting Orders
Modifying Orders
Cancelling Orders
Adding and Removing Overview of adding and removing targets within the
Targets SuperDOM
Adding and Removing Use this interactive review to test your knowledge of adding
Targets Interactive Review and removing targets in the SuperDOM
Basic Entry
Market Display
Submitting Orders
Chart Trader
Order & Positions Display Overview of how orders and positions are displayed in the
Chart Trader window.
Submitting Orders
Session Manager
Strategy Analyzer
Backtest a Strategy
Backtest a Strategy
Optimize a Strategy
Workspaces
Managing Workspaces
V
Risks of Electronic Trading with NinjaTrader 93
OCO does not imply that once one order is filled, related orders in the same
OCO group are guaranteed to be cancelled. It means that once an order is
filled or cancelled, any remaining orders in the same OCO group will try to be
cancelled. It is possible (in rare occasions) that order(s) that are part of the
OCO group will be filled before the cancellation request has been
acknowledged. As an example, let's say you have a stop loss and profit
target order as part of an OCO group. The profit target is filled, the market
rapidly turns around, the OCO cancellation request is submitted, the stop
loss order is filled before the cancellation request is acknowledged. The
narrower the spread between your OCO orders the higher the risk of getting
filled on an order before it is cancelled in fast moving markets.
Local PC held simulated OCO orders are dependant on order status events
returning from your connectivity provider to trigger the cancellation of OCO
orders. If NinjaTrader is offline (internet connection is down or PC crashed)
then the simulated OCO functionality will not be operational.
In Flight Executions
There are several functions within NinjaTrader that are based on the current state of
your account at the moment the function is invoked. These functions are:
Close Position
Flatten Everything
In flight executions are orders that are partially or completely filled between the time that
you invoke one of the above functions and the time your connectivity provider
acknowledges the order submission/modification/cancellation requests submitted by
these functions. Here is an example:
1. You have an open long position for three contracts and several working stop loss and
profit target orders for three contracts each
2. You invoke the command "Flatten Everything" which proceeds to cancel all working
orders and submit a market order to close the three contract position
3. One of your profit target orders is filled before the cancellation request arrives at the
exchange
4. The market order to close the position is also filled for three contracts
This example is generally a rare occurrence. After invoking any of the above commands
it is always prudent to check the Control Center's Positions Tab and Orders Tab to
ensure that all orders were cancelled and positions flattened. To avoid these situations
you should be cautious of using the "Close Position" function when you have orders that
are working within a few ticks of the inside market.
VI
96 NinjaTrader Version 7
6 Copyrights
NinjaTrader, LLC acknowledges the following:
QuickFIX
The QuickFIX Software License, Version 1.0
Copyright (c) 2001-2005 quickfixengine.org All rights reserved.
NinjaTrader includes software developed by quickfixengine.org http://www.quickfixengine.org/
OpenSSL
Copyright (c) 1998-2004 The OpenSSL Project. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
3. All advertising materials mentioning features or use of this software must display the
following acknowledgment:
"This product includes software developed by the OpenSSL Project for use in the
OpenSSL Toolkit. (http://www.openssl.org/)"
4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to endorse or
promote products derived from this software without prior written permission. For written
permission, please contact [email protected].
5. Products derived from this software may not be called "OpenSSL" nor may "OpenSSL"
appear in their names without prior written permission of the OpenSSL Project.
6. Redistributions of any form whatsoever must retain the following acknowledgment:
"This product includes software developed by the OpenSSL Project for use in the
OpenSSL Toolkit (http://www.openssl.org/)"
THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT "AS IS'' AND ANY
EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR ITS
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===================================================================
=
This product includes cryptographic software written by Eric Young ([email protected]).
This product includes software written by Tim Hudson ([email protected]).
Original SSLeay License
-----------------------
This library is free for commercial and non-commercial use as long as the following
conditions are adhered to. The following conditions apply to all code found in this distribution,
be it the RC4, RSA, lhash, DES, etc., code; not just the SSL code. The SSL documentation
included with this distribution is covered by the same copyright terms except that the holder is
Tim Hudson ([email protected]).
Copyright remains Eric Young's, and as such any Copyright notices in the code are not to be
removed.
If this package is used in a product, Eric Young should be given attribution as the author of
the parts of the library used.
This can be in the form of a textual message at program startup or in documentation (online
or textual) provided with the package.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the copyright notice, this list of conditions and
the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
3. All advertising materials mentioning features or use of this software must display the
following acknowledgement:
"This product includes cryptographic software written by Eric Young ([email protected])"
The word 'cryptographic' can be left out if the routines from the library being used are not
cryptographic related :-).
4. If you include any Windows specific code (or a derivative thereof) from the apps directory
(application code) you must include an acknowledgement:
"This product includes software written by Tim Hudson ([email protected])"
THIS SOFTWARE IS PROVIDED BY ERIC YOUNG "AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The licence and distribution terms for any publicly available version or derivative of this code
cannot be changed. i.e. this code cannot simply be copied and put under another distribution
licence [including the GNU Public Licence.]
VII
100 NinjaTrader Version 7
7 Introduction
This section of the Help Guide provides basic information about the NinjaTrader support and
education resources available to you as well as helpful information on getting started with
NinjaTrader.
Support Priority
It is preferred that you send us a support email from the "Mail To Support" sub menu under
the Help menu of the NinjaTrader application since it provides us with additional trouble
shooting information, however, when sending an email to support, please provide the
following information:
Operating system
Current NinjaTrader version (Can be accessed by selecting the Help menu from the
Control Center followed by the About menu item)
License code (Can be accessed by selecting the Help menu from the Control Center
Current subscribers (evident by providing a license code) will receive priority support.
NinjaTrader, LLC
1236 Clarkson Street
Denver, CO 80218 USA
Send us an email
Help Guides
Installation Guide
The installation guide outlines the installation steps and provides the minimum PC
requirements for NinjaTrader.
If you have questions about your installation click here to send a support request to the
NinjaTrader support team.
Take me to the Installation Guide!
Connection Guides
NinjaTrader is supported by hundreds of brokers around the globe as well as a variety
of data feeds.
You can create a connection to your broker or data feed by following the steps outlined
in the connection guide for your broker or data feed.
If you have questions about your connection or whether your broker is supported click
here to send a support request to the NinjaTrader support team.
Take me to the Connection Guides!
guide.
There is an internal version of this help guide in every install of NinjaTrader. You can
press the F1 key on your keyboard to pull up this guide at anytime. The guide will
automatically open to the content relating to the window you are working with and does
not require an internet connection.
Video Library
Video Library
The NinjaTrader video library contains a variety of videos on various features within the
NinjaTrader software.
These videos require an internet connection, and can be viewed at anytime.
Take me to the video library!
VIII
104 NinjaTrader Version 7
8 Configuration
8.1 Connecting
You must establish an account connection to either a NinjaTrader provided connection, your
broker or a data feed in order to receive market data and trade either live or in simulation.
NinjaTrader comes with the following default installed connections:
You must configure your own broker or data feed accounts using the Connection Wizard.
Once a connection is created, you can establish a connection from the Control Center by
selecting the File menu followed by the menu item Connect and then selecting your account
connection.
Instructions and an interactive video for connecting to all supported connectivity providers can
be found in the NinjaTrader Connection Guide
Account Connections
Within the NinjaTrader Control Center window, select the Tools menu followed by the
Account Connections... menu item. This will launch the Account Connection Set Up
window. A connection is where you set up your user name, password and any relevant
information that allows you to establish a connection to your connectivity provider which
is your broker and/or data feed service.
You can access broker/technology specific connection help information via the
NinjaTrader Connection Guide.
1. Open the Account Connection Set Up window by going to the Tools menu within
the Control Center and selecting the menu item Account Connections...
User defined connection name (Only use alphanumeric characters in the connection
name)
Select the connectivity provider
Optional back up data feed connection
Historical Data Options (visibility of these options are dependent on the provider and
your license)
Optionally select "Connect on startup" to automatically connect to this connection
when NinjaTrader is started.
Note: Please test and ensure your connection is working as expected before using this
option as it is possible to input incorrect credentials which could prevent the startup of
NinjaTrader.
4. After pressing the Next button, you will be presented with provider specific
parameters that you must enter in order to establish a connection. Each different
provider may have different options. For specific information relative to your connectivity
provider, please see the Connection Guide.
5. Once you have entered in all of the required connectivity information and pressed the
Next button, your set up information will be presented to you at which time you must
press the Finish button.
The newly created connection will be displayed in the Account Connection Set Up
window and can be connected to by selecting the File menu from the Control Center
then selecting the Connect menu item and left mouse clicking on the account
connection you have created.
8.1.2 Multiple Connections
Multiple Connections
NinjaTrader supports multiple simultaneous connections to different connectivity providers
and in some cases, to the same connectivity provider allowing you to:
connection is connected.
For example:
If you connect to BrokerA first and BrokerB second, when requesting market data NinjaTrader
will request the data stream for both real-time and historical data from BrokerA even if you
trade against BrokerB. It is possible you want to use the real-time market data from BrokerB
(you perceive it to be faster) then you should connect to BrokerB first and BrokerA second.
NinjaTrader is smart enough to realize that although it uses BrokerB for real-time data it will
request historical data from BrokerA.
8.1.3 External Data Feed Connection
External Data Feed Connection
The External Data Feed connection is a default connection installed with NinjaTrader. In
combination with the DLL Interface, it provides 3rd party applications the ability to drive
NinjaTrader with market data.
This connection targets those traders who have programming experience and wish to create
a market data link between their charting or custom application and NinjaTrader which allows
them to use the full functionality of NinjaTrader simulator. Please refer to the Ask and Bid
functions of the DLL Interface.
8.1.4 Market Replay Connection
Market Replay Connection
The Market Replay connection is a default connection installed with NinjaTrader. Its purpose
is for replaying NinjaTrader recorded data files. See the Market Replay section of the Help
Guide for further details.
8.1.5 Simulated Data Feed Connection
Simulated Data Feed Connection
The Simulated Data Feed connection is a default connection installed with NinjaTrader. Its
purpose is to play internally generated market data for simulation.
1. Left mouse click on the Tools menu in the Control Center and select the Instrument
Manager menu item
2. Search for the desired instrument
3. Press the Edit button and set a Sim feed start price value
Once you are connected to the Simulated Data Feed connection, the instrument will begin
simulated trading at the Sim feed start price value.
Trend Slider
The Trend slider control will appear once connected to the Simulated Data Feed. Left
mouse click on the slider and drag it up or down to cause the Simulated Data Feed to move
in that direction.
What is Kinetick?
Kinetick is the preferred market data service for NinjaTrader 7. Kinetick provides FREE
end of day data for stocks, futures and forex. Real-time data service starts as low as
$50 per month and you can qualify to have your CME Globex exchange fees waived with
a qualified brokerage account. Please visit www.kinetick.com for more detailed
information.
Connecting to Kinetick
The Kinetick - End Of Day (Free) connection provides FREE end of day data for
stocks, futures and forex. It is built into NinjaTrader 7 and can be used directly out of the
box with no additional steps. (Kinetick is not available for older versions of NinjaTrader)
Initial Set Up
To set up the TradeStation connection:
Connecting
To connect to TradeStation's real-time data feed:
1. Start NinjaTrader and connect to the External Data Feed connection via the Control
Center window by selecting the File menu followed by the Connect menu.
2. Start TradeStation
3. Within TradeSation, open a chart window (@ES for example). Right mouse click and
select the menu item Insert Strategy...
4. From the dialog window Insert Strategies select the item NTExternalFeed strategy and
press the OK button
5. A new window will appear called Format Analysis Techniques & Strategies. Press the
CLOSE button
6. Within NinjaTrader, select the current ES contract from the instrument list (ES 03-09 for
the March 2009 contract as an example) from any of the order entry or chart window
You will now receive real-time data from TradeStation in NinjaTrader.
* Only level one data will be transmitted. Market depth is not supported.
8.1.8 Connecting to Collective2
You can use NinjaTrader to automatically submit orders to your C2 (Collective2) account.
Collective2
Real-time orders generated and submitted to any account (live brokerage or simulation)
by NinjaTrader can be enabled to have a market order submitted to C2 servers.
The interface supports futures, forex and equities (options are NOT supported)
A single market order is submitted upon an order of any type (market, limit, stop or
stop limit) has been reported as filled or part filled
A single market order is submitted for the full order quantity amount (even if it was only
part filled)
A market order quantity can be offset based on an optional quantity multiplier
Orders generated while connected to the Market Replay, Simulated Data Feed or
External Data Feed connections will NOT be transmitted to C2
Users of the NinjaTrader Multi-Broker Version are able to have their NinjaTrader
generated C2 orders distributed as trade signals to your C2 subscribers
In the event that C2 servers are not responding, NinjaTrader will queue orders and
submit them in the correct sequence
NinjaTrader will attempt to resubmit queued orders 5 times over a 2.5 minute period, if
this threshold is breached, a notification window will pop up and inform you of all
orders that have not been submitted and prompt you to synchronize you C2 account
via their web interface. Further C2 communicated will cease until NinjaTrader is
restarted.
* If your C2 system has paying subscribers, you MUST use the paid for NinjaTrader
Multi-Broker Version otherwise you will NOT be able to send trade signals from
NinjaTrader to your C2 account.
Please see the NinjaTrader website for more information on purchasing a live license.
Collective 2 Setup Up
You must set up an Account Group(s) to instruct NinjaTrader to submit market orders to
Determines if real-time orders for a specific live or simulation account should replicate
orders to C2 servers
Determines what C2 strategy ID an order is associated to
Determines if the real-time order quantity should be offset by a multiplier amount
1. From the NinjaTrader Control Center window, select the Tools menu and select the
Options menu item.
2. Within the Options window, select the Data tab and press the Account Groups
button to bring up the Account Groups dialog window
3. Type in a name for the Account Group based on the strict naming convention outlined
below
4. Assign an account(s) from the list of available accounts
5. Press the "Save" button to save the Account Group
6. Press the "Close" button to close the "Account Groups" dialog window
C2;Strategyid;YourPassword;QuantityMultiplier
StrategyId
Your C2 strategy id used for tracking a C2 strategy.
YourPassword
Your C2 account password.
QuantityMultiplier (Optional)
A factor that will be multiplied by the order quantity to derive the quantity of the market
order submitted to C2. For example: If you are trading 10 lots in your account and you
specify a value of "0.5", the C2 order will be submitted at a quantity of 5. If the result is an
uneven number, NinjaTrader will round up to the nearest whole number.
Example #1
StrategyId = 1982131
YourPassword = candle
No quantity multiplier
Example #2
StrategyId = 98761
YourPassword = jump
Quantity multiplier of 0.5
Enabling an Instrument
You must enable an instrument by 'tagging' the C2 symbol with an asterisk (*) prefix.
This ensures that only orders for those instruments you have enabled will be routed to
C2.
1. From the NinjaTrader Control Center window, select the Tools menu then the menu
item Instrument Manager to bring up the Instrument Manager window
2. Search for the instrument you wish to enable, highlight it and pres the Edit button to
bring up the Instrument Editor
3. In the Instrument Editor window, select the Misc tab and scroll down to the Symbol
Map section
4. Next to Collective2, add an asterisk (*) in front of the C2 symbol map name (MSFT
would be *MSFT)
5. Press the OK button
6. Press the OK button once more
The image below depicts the ES (S&P Emini) instrument enabled (asterisk prefix)
You are now set for NinjaTrader to submit orders to C2. Keep in mind the following:
C2 orders will be placed when you execute a real-time order within an account that is
assigned to a C2 Account Group and the traded instrument has been enabled
You MUST disable an instrument (by removing the asterisk in the symbol mapping) if
you do not want C2 orders to be generated
Understanding synchronization
Synchronization
It is possible for various reasons that the communication between NinjaTrader and C2
can be disrupted resulting in the potential of unsubmitted orders. In this event (excluding
an unexpected application or computer crash) a notification box will pop up. It is your
responsibility to logon to your C2 account via (www.collective2.com) and manually
synchronize your C2 account to your actual live trading account position size.
8.2 Installation
Please visit the online installation guide for detailed information on how to install NinjaTrader.
Installing NinjaTrader may require you to clear your browser cache if instructed by a
8.3 Options
Various options can be configured inside the Options menu. To access the Options menu,
select the Tools menu within the NinjaTrader Control Center and select the menu item
Options.
General Tab
Strategies Tab
Simulator Tab
Log Tab
Commission Tab
ATI Tab
Data Tab
RSS Tab
Misc Tab
ATM Strategy
This section sets ATM strategy handling options.
Modify inner bracket When enabled and scaling into a position strategy, the inner
bracket (stop loss and profit target orders) quantities will be
modified to reflect the increased position strategy size else the
outer bracket is modified
Modify nearest bracket When enabled, the nearest bracket (stop loss and profit target
orders) quantities are modified when changing the quantity of a
stop loss or target order in a multi target strategy. This property
is used in conjunction with "Modify inner bracket". For example, if
both "Modify inner..." and "Modify nearest..." are enabled and you
modify target 2 from 1 contract to 2 contracts, target 1 order size
will be reduced by 1. If you had "Modify inner..." disabled, target 3
order size will be reduced by 1.
Use last price for auto When enabled, the last trade price is used to trigger auto trail or
trail and auto auto breakeven functions. When disabled, the bid is used for long
breakeven positions, the ask is used for short positions.
Wait until flat before When starting a NinjaScript strategy that relies on historical data
executing live for calculating its current positions and order states, it will wait
until the strategy position has reached or crossed a flat position
before executing any live orders. All trading done before this
condition will be virtual, simulated trades.
Immediately submit When starting a NinjaScript strategy that relies on historical data
live working historical for calculating its current position and orders states, it will
orders immediately submit live any working orders that reflect the current
strategy's overall order state. It is IMPORTANT to understand
that the position of the strategy reported in the Strategies tab may
not reflect the actual account-based position reported in the
Accounts tab at the time the strategy is started. In this scenario, it
is highly recommend that the account position be synced to the
strategy position.
On Connection Loss
Disconnect delay Sets the number of seconds a disconnect must exceed before it
seconds is determined as a disconnect in regards to the Handling options
(see below).
Number of restart Sets the number of times NinjaTrader will attempt to restart a
attempts strategy within the "Restarts within x minutes" time span. The
Order Handling
Account
The Account section sets account options.
Delay comm. Simulated delay of sending an order from your PC to a virtual exchange
(msec)* server
Delay exchange Simulated delay of a virtual exchange server processing an order
(msec)*
Initial cash: Starting cash value of your simulation account
Margin: Simulated margin applied to your simulated account cash balance
Maintenance Sets the minimum required level of margin as a percent of the total
margin: market value of securities in the Sim account.
Wait for data Sets the time that the simulator will wait for market data. If wait time
(secs): exceeds set value, the simulated order will be rejected.
Margin/unit: Sets the minimum amount of margin required to trade one unit
For more information on how the margin parameters impact simulated trading please see the
"How the Margin parameters impact Account values" section below.
Misc
The Misc section sets miscellaneous simulator options.
Always start in Enables or disables the application always starting in global simulation
simulation mode as default.
Enforce partial fills Enables or disables the forcing of partial fills on each order. If enabled,
orders will always get filled with partial fills. When disabled orders are
filled completely or partially depending on trade volume.
Enforce immediate Enables or disables limit orders to fill immediately instead of using
fills NinjaTrader advanced simulation fill engine
Accounts... Add/remove simulation accounts (See the "Multiple Simulation Accounts"
section of the Help Guide for more information)
Reset... Resets the Simulation account to the Account values
Margin
This parameter only impacts the Initial Margin value of your simulation account as
shown in the Accounts tab of the Control Center. It is only used when calculating the
initial margin of stock positions and has no impact on your trade capability.
Maintenance Margin
This parameter impacts the calculation of Excess Equity. Based on how many positions
you currently hold, the maintenance margin is applied per position and reduces your
Excess Equity. If you do not want to use this, setting it to 0 means no maintenance
margin will be assessed in the Excess Equity calculations. If the order being placed is
an entry order and you do not have enough Excess Equity, the order will be rejected.
Margin / unit
This parameter impacts the Cash Value calculations when trading currencies or futures;
it has no relation to trades done on stocks. The Cash Value then in turn impacts the
Excess Equity calculations which determines if you can successfully place your entry
order or not. Note that the "Margin value" parameter in the Instrument Manager per
instrument overwrites the "Margin / unit" parameter here if it is set to anything besides 0.
Cash Value
This Account value will either be increased or decreased based on the order quantity of
trades placed against the simulation account. For currencies and futures, the order's
quantity will be margin adjusted based on the "Margin / unit" parameter. They will also be
weight adjusted based on the connection/brokerage being used since different quantities
means different things on some providers. For stocks, the order's quantity will be price
adjusted.
Buying Power
This Account value on a simulation account is always 2x the account's Cash Value.
Excess Equity
This Account value on a simulation account is calculated by the following math:
Excess Equity = Cash Value + (value of position) - (lower of the two values: 0 or value of
position subtracted by Cash Value) - (maintenance margin of the position)
"Value of position" is determined by applying weights to the quantity of the position and
then subtracting commissions from it if the user opts for including commissions in
PnL calculations. The weights are determined by the "Margin / unit" parameter for
currencies and futures. For stocks, it is determined by the average position price.
"Maintenance margin of the position" is determined by weighting the "value of position"
by the "Maintenance Margin" parameter.
Informatio Sets the background color for information level log events
n
Warning Sets the background color for warning level log events
Error Sets the background color for error level log events
Alert Sets the background color for alert level log events
# entries Sets the max number of historical log events loaded upon application start up
loaded
Days Sets the number of days that historical log information is maintained on your PC
maintaine
d
To set commissions for backtesting purposes, set commissions for the "Simulator"
connectivity provider.
In the following example we will add a global flat commission for trading futures on our
Market Replay connection. This means whenever we connect to our Market Replay
connection and trade against it, commission costs will be calculated against the values
we will enter below.
1. Locate the Futures - Replay connection and expand the options branch by clicking
on the "+" icon. You will see a "Commission levels" property (none defined) and a
"Minimum commission" property.
2. Insert your commission per side next to "Minimum commission" and press the OK
button. For this example, we will assume a $2.50 commission rate per side. The
image below displays this configuration.
Once commissions have been entered, they must be enabled. Please select the Tools
menu within the Control Center. Select the Options menu item and check "Apply
commissions to PnL calculations."
whenever we connect to our Market Replay connection and trade against it,
commission costs will be calculated against the values we will enter below:
1. Locate the Stocks - Replay connection and expand the options branch by clicking on
the "+" icon. You will see a "Commission levels" property (none defined) and a
"Minimum commission" property.
2. Many brokers who support trading equities have a minimum commission rate. Let's
assume that our Market Replay connection minimum commission is $1.00 by
setting that value in the property. Then put your mouse cursor in the "Commission
levels" property. The "..." button will become visible which allows us to add multiple
commission levels.
3. Once you click on the "..." button, a commission level collection editor will appear. We
are going to add (press the "New" button) two commission rate levels. $0.01/share for
the first 500 shares and then $0.005/share for every share after that until 9,999
shares. The image below displays this configuration.
Once commissions have been entered, they must be enabled. Please select the Tools
menu within the Control Center. Select the Options menu item and check "Apply
commissions to PnL calculations."
8.3.6 ATI Tab
The ATI tab sets options for the Automated Trading Interface.
ATI server port Default port number for communicating with NinjaTrader via the
COM or DLL interface
Default account Sets the default account for automated trading. If no account is
specified in an OIF file or function, the default account is used.
Enable SMTP Enables or disables the local NinjaTrader SMTP server used with the
server TradeStation Email interface
Ignore duplicate Enables or disables ignoring duplicate OIF files. If enabled, any OIF
OIF files files with the same name during the current NinjaTrader session will
be ignored.
OIF Builder... Opens the Automated Trading OIF Builder window
Order Handling
Submit market orders Enables or disables the submission of market orders when
on TS fill NinjaTrader receives a strategy order filled email notification from
TradeStation
Submit "as-is" When enabled, NinjaTrader will submit the specified order type
(market, limit and stop) when a strategy active order email
notification is received from TradeStation and then wait to convert
it to market based on ...
Convert unfilled... Number of seconds NinjaTrader will wait after receiving a strategy
order filled email notification to convert any unfilled contracts/
shares to market
Submit and forget When enabled, NinjaTrader will submit the specified order type
(market, limit and stop) when a strategy active order email
notification is received from TradeStation
seconds Number of seconds NinjaTrader will provide a pop up notification
synchronization if order are out of synchronization (For example; TS reports a fill
timeout but NinjaTrader live order is not filled)
Stop Orders
Submit "as-is" When enabled, submits the specified stop order when
NinjaTrader receives a strategy active order email notification
from TradeStation
Convert to stop limit When enabled, submits a stop limit order when NinjaTrader
receives a strategy active order email notification from
TradeStation for any stop order type
Limit price offset as Sets the amount of ticks the limit price is offset from the stop
ticks price
Convert to simulated When enabled, submits a local PC held simulated stop market
stop market order when NinjaTrader receives a strategy active order email
notification from TradeStation for any stop order type
Submit market order ifIf a stop order is rejected for any reason, a market order will be
stop order was immediately sent. Please see the following section for disclaimer
rejected and risks of this feature.
8.3.7 Data Tab
The Data tab sets options related to market data and database management.
Adjust for splits Enables or disables split adjusting historical data for use with any
function that requires historical market data
Adjust for dividends Enables or disables dividend adjusting historical data for use with any
function that requires historical market data
Get data from server Enables or disables retrieving of historical data from the data provider's
(if available) server
Real-Time Data
This section sets real-time data handling procedures within NinjaTrader.
Save chart data as Enables or disables the storage of incoming real-time Chart data to
historical your local PC for future historical data requests. If you are connected to
a provider that supports historical data, disable this feature.
Record for Market Enables or disables market data recording for use with the market
Replay replay connection
Filter bad ticks % off Sets the real-time tick filter offset percentage (0.1 equals 1/10 of a
market percent)
Database Management
This section pertains to database management and account grouping.
Reset DB Removes historical trade data from the database. Should only be used
at the request of a NinjaTrader technical support representative.
Repair DB Repairs the database. Should only be used at the request of a
NinjaTrader technical support representative.
Account Grps. Manage account groups
Reset Instruments Reset instrument settings to installation default
Available news is sent from the enabled RSS feeds to the News window in NinjaTrader for
any instrument assigned to the RSS instrument list.
8.3.9 Misc Tab
The Misc tab sets miscellaneous NinjaTrader options.
Mail Setup
This section sets email configuration options
Server Sets the server address (if left blank, the NinjaTrader server will be used)
Port Sets the server port
SSL Check only if your email server uses Secure Sockets Layer (SSL) security
User Sets the server user name
Password Sets the server password
Test Sends a test message through the server
Mail alert Sets the email address alerts messages will be sent to
messages to
Flatten Positions
This section sets a time to automatically flatten positions
Time to flatten Sets the time (local PC time) where a position will be flattened and working
orders cancelled. This feature can be enabled per position from the right
mouse click menu of any Order Entry windows. "12:00:00 AM" setting
disables this feature.
Flatten all Enables or disables the flattening of all positions and cancelling of working
orders across all positions and accounts
Different connectivity providers (market data vendors and broker technologies) that
NinjaTrader supports vary in their level of real-time data service. For example, providers
who deliver unfiltered tick data (submit all market ticks) will impose heavier processing load
than a vendor that provides throttled market data.
The load you place on the NinjaTrader application (running 200 charts will consume more
processing power than running only 20 charts)
The capability of your PC hardware (are you running a brand new state of the art machine
or a 4 year old PC with limited RAM)
The following are some suggestions that can help you fine tune your NinjaTrader installation
to run optimally.
Charting
Market Analyzer
it will take to load data and the more memory (RAM) NinjaTrader will use to hold the
data in memory.
Miscellaneous
Within the Control Center window, select Tools > Options > Data and uncheck "
Record for market replay"
Within the Control Center window, select Tools > Options > Data and uncheck *"
Save chart data as historical"
Reduce the number of applications running on your PC
* "Save chart data as historical" should only be checked if are using a connectivity
provider that does NOT provide historical data
NinjaScript
Debug Mode
Please also ensure you do not have Debug Mode enabled as it can lead to lower
performance. To disable, right mouse click in any NinjaScript Editor and uncheck the
"Debug Mode" menu item. After doing so, press F5 to recompile.
Workspaces
Hidden Workspaces
Hidden workspaces consume CPU cycles so check under File > Workspaces to see
all of the workspaces that are open and close any that you seldom or never use.
IX
Operations 137
9 Operations
NOTE: Subsequent cancellations and or order modifications will NOT be replicated against
each order, you must manage each replicated order individually.
1. From within the Control Center window select the Tools menu and then select the menu
item Options. Once in the Options window select the "Data" tab and press the button "
Account Groups"
2. Select an account that you wish to add to your Account group from the "Available
accounts" list
3. Press the "left arrow" button to move this account to the "Assigned accounts" list
4. Give the Account Group a name
5. Press the "Save" button
The "My Group" (in image above) account will now be available in all account selection lists in
all order entry interfaces.
1. Select an Account Group in the Account group selection list (icon #4 in the image
above)
2. Press the "Remove" button (icon #6 in the image above)
"A collection of user defined rules/conditions that create and manage a set of Stop Loss and
Profit Target orders that are used to govern a portion or an entire open position."
We just defined a set of conditions for the management of a 5 contract long position, or in
other words, we just defined an ATM Strategy. The ATM Strategy is the foundation for how
positions (or partial positions) can be managed within NinjaTrader. ATM Strategies can be
defined on the fly or you can pre-define them using templates that can be recalled for later
use in a split second.
All of NinjaTrader's order entry interfaces house the same control for defining an ATM
Strategy.
1. The ATM Strategy Control list
2. The Stop Loss and Profit Target parameters
3. The Advanced Options
<None>
When this option is selected, any orders placed in the entry window will not be applied to
an active ATM Strategy nor will it initiate a new ATM strategy.
order submitted will be applied to the selected active ATM Strategy. For example, if you
have an active ATM Strategy with a stop and target bracket for 1 contract, if you are
filled on another contract, the fill is applied to this ATM Strategy and the stop and target
bracket is automatically updated from 1 contract to 2 contracts.
When it comes to the automatic submission of Stop Loss and Profit Targets and how
subsequent order fills are handled, there are two approaches:
1. Scaling into a position or out of a position should automatically update the order sizes
of existing stop and target brackets
2. Scaling into a position should create a new set of stop and target brackets based on
the new order fill price
If you always want to operate with approach number 1, then you will always want to have
the ATM Strategy control list set to your active ATM Strategy when one exists. This is
accomplished by setting the ATM Strategy Selection Mode to "
SelectActiveATMStrategyOnOrderSubmission". If you would rather have new stop
and target brackets submitted on a new fill, then set the ATM Strategy Selection Mode
to "KeepSelectedATMStrategyTemplateOnOrderSubmission" and the strategy
control list will not automatically set to an active strategy when one is created.
Understanding Stop Loss and Profit Target parameters (how to set your stop and
target values)
Qty Sets the quantity for the Stop Loss and Profit Target orders
Stop Loss Sets the value that determines the Stop Loss price. If the value is set
to 4 (ticks) and your average entry for the initiating order is 1000 and
you are long, your Stop Loss would be submitted at AvgEntry - Stop
Loss = 1000 - 4 ticks = stop price of 999. This assumes each tick is
valued at 0.25.
Profit Target Sets the value that determines the Profit Target price. If the value is
set to 4 (ticks) and your average entry for initiating the order is 1000
and you are long, your Profit Target would be submitted at
AvgEntry + Profit Target = 1000 + 4 ticks = 1001 Profit Target. This
assumes that each tick is valued at 0.25.
Stop Strategy Sets the Stop Strategy
For further reference, please look at the Strategy Examples located within the "ATM
Strategy" section of the user help guide.
Advanced Options
To access the Advanced options right mouse click in the order entry window and select
the menu name Advanced Options.
From the Advanced Options section you can enable the Shadow Strategy, Auto Reverse
, or Auto Chase features.
Most of the NinjaTrader order entry screens have three modes that you can set to determine
the behavior of the ATM Strategy selection control list upon submission of an order that
enters the market/initiates an ATM Strategy. You can set this mode via the order entry
screen's Properties dialog window that is accessible via the right mouse click context menu.
Before reviewing this section you should have a thorough understanding of how the strategy
control list determines what actions (if any) to take when a submitted order is filled. Please
review the video and content in the preceding page ATM Strategy Parameters.
When you select <None> in the strategy list, all working orders and ATM Strategies
will be displayed
The position display will display the number of contracts being managed by the ATM
Strategy and then your net position size. The box is color coded to the ATM
Strategy's market position. So if your ATM Strategy is long, the box will be colored
green. Using the first image on the right as an example, it shows "3 - 4L" in a green
box. Green indicates the ATM Strategy is long, the number 3 indicates that there are
3 contracts being managed by that ATM Strategy and 4L indicates the account
actually holds 4 contracts long. What it is saying is; that we are running a long ATM
Strategy that is managing 3 of 4 contracts that are held long in my account. The
image on the right is managing 1 of the 4 long contracts.
When you do not have any active ATM Strategies selected, the SuperDOM position
display will display your net account position
Pressing the "CLOSE" button while an active ATM Strategy is selected will close only
that ATM Strategy. If anything else is selected, it will close the entire account position
including all other working ATM Strategies.
are other orders working in the selected market that are not associated to the ATM
Strategy, you will not see them displayed. The risk is that you could have orders
working, you forget about them or did not even know they were still working, they are
filled and you could damage your trading account. Please fully understand how to use
this powerful feature before putting it to use.
9.2.1.3 Stop Strategy
When setting up an ATM Strategy, you can select either <Custom>, <None>, or any pre-
defined Stop Strategy template from the Stop Strategy control list.
If <Custom> or any template is selected ("Stop1" in the image below is a template) a Stop
Strategy Dialog window will appear.
You can enter the appropriate values to enable any of the Stop Loss automation strategies.
You can also save commonly used parameters as a Stop Strategy template.
The Auto Breakeven feature will adjust your Stop Loss order to breakeven (average entry
price for the ATM Strategy position) once a user defined Profit Trigger has been reached.
If you move your mouse over an active Stop Loss order in the buy cell for a buy order or
sell cell for a sell order and press down on your right mouse button, you will see a menu
of all working orders. Each working order menu has a sub menu that displays any
applicable strategies that can be enabled or disabled. In the image below, you can see
that Auto Breakeven is currently enabled. By selecting the "Auto Breakeven" menu
item, you can enable or in this example disable the Auto Breakeven. You can change
the parameters by selecting the "Auto Breakeven Properties" menu when Auto
Breakeven is disabled.
ticks = 10190) NinjaTrader will move the Stop Loss order to 10,198 (Average Entry -
Plus = 10200 - 2 ticks = 10198) and enter a log event in the Log tab.
9.2.1.3.2 Auto Trail
Auto Trail is a powerful stop strategy that allows you to be more liberal with your Stop Loss
at the early stage of your trade and tighten your Stop Loss as your profits in your trade
increase.
There are 3 available steps for Auto Trail parameters. Each step can have unique
parameters providing you with the flexibility to tighten your Stop Loss automatically as
your profits increase. Auto Trail can be set before entering a position as part of a Stop
Strategy. You can also enable or disable it on a working Stop Loss order.
If you move your mouse over an active Stop Loss order in the buy cell for a buy order or
sell cell for a sell order and press down on your right mouse button, you will see a menu
of all working orders. Each working order menu has a sub menu that displays any
applicable strategies that can be enabled or disabled. In the image below, you can see
that Auto Trail is currently enabled. By selecting the "Auto Trail" menu item, you can
enable or in this example disable the Auto Trail. You can change the parameters by
selecting the "Auto Trail Properties" menu item when Auto Trail is disabled.
"Once our trade has 4 ticks in profit, move our Stop Loss back 6 ticks and move it up
for every additional 2 ticks in profit."
The market moves up to 1001 and the Auto Trail is triggered (Average Entry + Profit
Trigger = 1000 + 4 ticks = 1001) and the Stop Loss is adjusted to 999.50 (1001 - Stop
Loss = 1001 - 6 ticks = 999.50). For every additional 2 ticks (Frequency of 2 ticks) the
Stop Loss will be adjusted by 2 ticks.
"Once our trade has 4 ticks in profit, move our Stop Loss back 6 ticks and move it up
for every additional 2 ticks in profit then; once our trade has 10 ticks in profit, tighten and
move our Stop Loss back 3 ticks and increase the rate at which the Stop Loss is
adjusted and move it up for every additional 1 tick in profit"
The market moves up to 1001 and the Auto Trail is triggered (Average Entry + Profit
Trigger = 1000 + 4 ticks = 1001) and the Stop Loss is adjusted to 999.50 (1001 - Stop
Loss = 1001 - 6 ticks = 999.50). For every additional 2 ticks (Frequency of 2 ticks) the
Stop Loss will be adjusted by 2 ticks (same as Example #1). Then the market moves to
1002.50 and the 2nd step of the Auto Trail strategy is triggered and the Stop Loss is
adjusted to 1001.75 and moves up by 1 tick with every additional tick in profit.
9.2.1.4 Manage ATM Strategy Templates
An ATM Strategy is defined by the parameters you enter into the ATM Strategy parameters
section on any of the order entry screens. The collection of parameters that make up a
strategy can be saved as a template that you can recall at a later date to automatically
populate all of the ATM Strategy parameters.
Via right mouse clicking in any of the following windows, you can access a menu for saving
and removing ATM Strategy Templates:
Basic Entry
SuperDOM
Stop Strategy window in FX Pro and Chart Trader
Any Stop Strategy dialog window
See ATM Strategy Example #1 and ATM Strategy Example #2 for further reference on how to
create and save an ATM Strategy template.
This simple ATM Strategy will automatically submit a Stop Loss order 4 ticks from entry
and a Profit Target order 8 ticks from entry.
You can save this ATM Strategy as a template by clicking on your right mouse button within
the background of the SuperDOM or Basic Entry windows or within the ATM Strategy
parameters box of the FX Pro or Chart Trader windows, and selecting the menu name "
Manage ATM Strategy Templates..."
Once you press the save button, a template is created for this ATM Strategy and it will
become available in the strategy control list of all order entry windows. You can now place an
order which once filled will automatically trigger the ATM Strategy to submit the Stop Loss
and Profit Target. In the image below, an order was submitted and filled at 1311.00 as
depicted by the brown colored cell.
7. A Profit Target was submitted at 1313.00 which is 8 ticks from our entry price of 1311.00
8. A Stop Loss was submitted at 1310.00 which is 4 ticks from our entry price of 1311.00
9. An active strategy named "* Active Strategy" is created and listed under the ATM
Strategy control list.
If under SuperDOM Properties you have the "ATM Strategy selection mode" set to "
SelectActiveATMStrategyOnOrderSubmission", NinjaTrader will automatically set the
ATM Strategy control list to the newly created ATM Strategy. The importance of this is if
you place another order, any fills resulting from the order will be applied to the existing Stop
Loss and Profit Target orders. As an example, if we were filled on an additional contract,
our Stop Loss and Profit Target would automatically be modified from 1 contract to 2
contracts. Both Stop Loss and Profit Target orders are tied via OCO which means if one of
the orders is filled, the other will automatically be cancelled. If the option in the first sentence
was not checked, the ATM Strategy control list would be set to the "8 Tick 1 Target" ATM
Strategy template we just created. Any subsequent orders would create an additional ATM
Strategy that would submit another set of Stop Loss and Profit Target orders.
7. Select <Custom> from the Stop Strategy control list under the first target.
A Stop Strategy parameters dialog window will appear. This is where you will define the
automation strategies for automatic Stop Loss adjustment.
8. Set the Auto Breakeven "Profit trigger" value to 6 ticks. This will automatically adjust
our Stop Loss order to breakeven once the ATM Strategy has 6 ticks in profit.
9. Set the Auto Trail "Profit trigger" to 8 ticks
10. Set the Auto Trail "Stop loss" to 4 ticks
11. Set the Auto Trail "Frequency" to 1 tick
The auto trail parameters will automatically start adjusting our Stop Loss order once we have
8 ticks in profit (9) to 4 ticks back (10) and adjust it for every 1 tick (11) in profit gain.
You can save the Stop Strategy as a template by pressing down on your right mouse button
within the Stop Strategy parameters box and selecting the menu name "Manage Stop
Strategy Templates..."
Once you press the Save button, a template is created for this Stop Strategy and it will
become available in all Stop Strategy control lists. Press the "OK" button on the Stop
Strategy parameters dialog window to exit.
14. Select the Stop Strategy we just created (Basic Stop) in the 1st and 2nd Stop Strategy
control lists. This sets the 1st and 2nd Stop Loss orders to the same Stop Strategy so that
Stop Loss 1 and Stop Loss 2 will adjust in unison.
You can now save this ATM Strategy (Stop Strategies included) as a template by pressing
down on your right mouse button within the background of the SuperDOM or Basic Entry
windows or within the ATM Strategy parameters box of the FX Pro or Chart Trader
windows, and selecting the menu name "Manage ATM Strategy Templates..."
Type in the Name "2 Target" and click the "Save" button. We now have a 2 target strategy
template that can be selected from the ATM Strategy control list at any time. Doing so will
update all of the parameter fields automatically based on the information we have entered in
this example.
You can now place an order which once filled will automatically trigger the ATM Strategy to
submit the Stop Loss and Profit Target brackets. In the image below, an order was
submitted and filled at 1461.25 as depicted by the brown colored cell.
15. The first Profit Target order was submitted at 1463.25 which is 8 ticks from our entry,
the 2nd Profit Target was submitted at 1464.25 which is 12 ticks from our entry and finally,
our 2 Stop Loss orders were submitted at 1460.00 which is 5 ticks from our entry. You can
tell we have 2 orders at the Stop Loss level because the Size Marker has the "s" suffix
indicating that we have multiple orders consolidated at the price 1460.00.
16. An active ATM Strategy named "* Active Strategy 8" is created and listed under the
ATM Strategy control list. The significance of 8 is that we had 7 active ATM Strategies
created before.
If under SuperDOM properties you have "ATM Strategy selection mode" set to "
SelectActiveATMStrategyOnOrderSubmission", NinjaTrader will automatically set the
ATM Strategy control list to the newly created ATM Strategy. The importance of this is if
you place another order, any fills resulting from the order will be applied to the existing Stop
Loss and Profit Target orders. As an example, if we were filled on an additional contract,
our Stop Loss and Profit Target orders would automatically be modified from 1 contract to
2 contracts. Both Stop Loss and Profit Target orders are tied via OCO which means if one
of the orders is filled, the other will automatically be cancelled. If the option in the first
sentence was not checked, the ATM Strategy control list would be set to the original ATM
Strategy template we created. Any subsequent orders would create an additional ATM
Strategy that would submit another set of Stop Loss and Profit Target orders.
9.2.2 Advanced Options
All NinjaTrader order entry windows that offer ATM Strategies also include the Advanced
Options. The Advanced Options include: Shadow Strategy, Auto Chase, and Auto
Reverse features. To access the Advanced Options in the SuperDOM or Basic Entry
windows press down on your right mouse button in the background of the window and select
the menu name Advanced Options. To access the Advanced Options in the Chart
Trader or FX Pro windows press down on your right mouse button in the background of the
ATM Strategy parameters window (accessible with the "..." button) and select the menu
name Advanced Options.
Auto Chase will automatically adjust the price of a limit order as the market moves away
from it.
The difference between Chase and Chase if touched is that Chase if touched does
not start chasing until your limit price has been touched. This works well for Profit
Target orders. Your Profit Targets will rest at their respective limit price, if the market
moves to the target and backs off but the target order does not fill, NinjaTrader would
then start adjusting the target order to chase the market up until the Chase Limit
amount.
Auto Chase can be set as part of an ATM Strategy (set the parameters you want use
before entering the ATM Strategy). However, you can also enable or disable Auto
Chase on working limit orders.
If you move your mouse over an active limit or Profit Target order in the buy cell for a
buy order or sell cell for a sell order and press down on your right mouse button, you will
see a menu of all working orders. Each working order menu has a sub menu that
displays any applicable strategies that can be enabled or disabled. In the image below,
you can see that Auto Chase is currently disabled. By selecting the "Auto Chase"
menu, you can enable or disable it. You can change the parameters by selecting the "
Auto Chase Properties" menu when Auto Chase is disabled.
In this example, if the bid moves up to 1000.50, Auto Chase will adjust the buy limit
price to 1000.25, subsequently each additional tick rise in price on the bid will adjust the
buy limit price accordingly to a maximum price of 1001.25 which is Buy Limit Price +
Chase Limit = 1000 + 5 ticks = 1001.25.
This example works in the same manner as example #1 with the exception that chasing
does not start until the bid has touched the limit price of 1000.
9.2.2.2 Auto Reverse
Auto Reverse simply reverses your position at either your Stop Loss or Profit Target. You
can optionally enable "Reverse at stop" or "Reverse at target" with any ATM Strategy.
The reverse ATM Strategy used will be the same as the position ATM Strategy you are
reversing from.
When Auto Reverse is enabled, entry orders for the reverse ATM Strategy will be placed at
either your Stop Loss or Profit Target orders. The image below shows a 1 stop/1 target
ATM Strategy with Auto Reverse enabled for both the stop and target.
Modifying the price of either your Stop Loss or Profit Target will result in the modification of
the reverse order as well. You can also enable or disable Auto Reverse of an active ATM
Strategy at any time by selecting the "Reverse At Stop" or "Reverse At Target" menus via
the right mouse click context menu in either the SuperDOM or Basic Entry windows.
Tips
Intelligently name Shadow Strategies by including a prefix such as "Shadow - My
Strategy"
When using the Performance Tab, you can filter your reports to include or exclude your
Shadow Strategy
9.2.3 Close At Time
Close At Time is a strategy that will automatically close your position at a user defined time.
A position will be closed using the NinjaTrader close algorithm. The user defined close time
can be set via the "Time to flatten" property located in the Misc tab. You can enable or
disable this strategy via any NinjaTrader order entry screen's right mouse click context menu.
9.2.4 FAQ
Listed below are some common questions concerning building and implementing ATM
Strategies.
See the Modifying Orders section for more information on Single Click order
Modification and scaling in and out of an active ATM Strategy. Click here for a full
schedule of our free live training events!
Please see the Submitting Orders section for more information and examples of the
OCO function, or attend one of our free live training events to see further examples.
Is it possible to run concurrent ATM Strategies in the same market and the same
account?
Absolutely, NinjaTrader's Strategy Selection Modes allow you to limit the display in
the SuperDOM so that you can run concurrent ATM Strategies. One of the great
features of NinjaTrader is its ability to manage multiple virtual positions in the same
market. For example, this allows you to manage a long and short position in the same
market simultaneously.
For more information please see the ATM Strategy Selection Mode section of the user
help guide, or attend one of our free live training events.
Example:
If the first step of your Auto Trail has the Stop Loss trailing by 5 ticks and then the
second step of the Auto Trail tells the Stop Loss to trail by 10 ticks the Stop Loss will
simply stay at its current price point until there is a 10 tick spread between the Stop
Loss and the current trading price and then begin to trail by 10 ticks. The Stop Loss will
not move backwards when the second step of the Auto Trail is activated.
For more information on the Auto Trail feature please see the Auto Trail section of the
user help guide or attend one of our free live training events.
When building an ATM Strategy each Profit Target must be greater than the Profit
Target before it. Example: The Profit Target for 1 Target must be less than the Profit
Target for 2 Target. Also each Stop Loss must be must be equal to or greater than
the Stop Loss before it. Example: The Stop Loss for 1 Target must be equal to or
less than the Stop Loss for 2 Target. The Parameters listed below show the correct
way to enter the values listed above.
Please see the ATM Strategy Parameters section of the user help guide for further
information.
Can I use the Auto Breakeven and Auto Trail strategies together?
Absolutely, NinjaTrader gives you the flexibility to use these strategies alone or to
combine them. However, when using these features together please be aware of the
following:
The Stop Strategy will not move your Stop Loss backward it will only move it closer
The Profit Trigger for your Auto Trail must be higher then the Profit Trigger for
your Auto Breakeven
If you have an open position without an ATM Strategy attached, and you wish to add
limit and stop orders to protect the position follow these steps:
Set the ATM strategy in the ATM Strategy selection drop down box to a value of
<None>
Right click in the SuperDOM and enable OCO order placement by selecting the
menu name "OCO Order"
Then place a limit order where you want to exit at a profit
Then place a stop order where you want to exit at a loss
Lastly, right click again and select the menu item "OCO Order" to disable the OCO
order placement
Now you have a target and a stop placed protecting your open position, and when one of
these orders is filled the other will be cancelled automatically.
How do I make one target a "runner" so that it has a Stop Loss only and no Profit
Target?
If you want a target in your ATM Strategy to have a Stop Loss only then set the Profit
Target to zero.
9.3 Alerts
The Alerts window displays triggered user defined alerts. Alert conditions can be defined
within the Market Analyzer window, News window or alerts can be triggered within a custom
NinjaScript indicator or strategy. The Alerts window can be opened by left mouse clicking on
the File menu within the NinjaTrader Control Center and selecting the menu item New
followed by the menu item Alerts...
1. Instrument name
2. Alert Priority
3. Time of the alert
4. User defined message
Always On Top Sets the Alerts window to always be on top of other windows
Reset Clears the Alerts window and resets alerts
Filter By Priority Filters alerts by user defined priority
Send To Loads the selected instrument into another NinjaTrader window
Grid Sets various grid options
ATI Interface
File Interface
DLL Interface
eSignal Integration
TradeStation Integration
Running NinjaScript Strategies
NOTE: This interface is ONLY used for processing trade signals generated from
external applications and is not a full blown brokerage/market data API. If you are
interested in automated trading using native NinjaScript strategies please proceed to
the following help guide section.
NinjaTrader provides TradeStation and eSignal integration, File Interface, DLL Interface, and
a .NET Interface which ensures that you can communicate with NinjaTrader from any
application such as but not limited to:
Popular charting applications such as but not limited to TradeStation, eSignal, NeoTicker,
and Investor RT
Custom applications written in but not limited to Visual Studio .NET, Visual Basic, Delphi,
and MS Excel
Black box trading systems
The Automated Trading Interface is bi-directional. You can enable automated trading by left
mouse clicking on the Control Center's File menu and selecting the Automated Trading (AT
Interface) menu item
Place orders
Initiate a NinjaTrader ATM Strategy
Change orders
Cancel orders
Close ATM Strategies and positions
Flatten accounts
Cancel all orders
Retrieve information on positions and orders
File Interface
The File interface uses standard text files as input. These files are called order
instruction files (OIF) and have specific format requirements. NinjaTrader processes the
OIF the instant the file is written to the hard drive and subsequently deletes the file once
the processing operation is complete.
DLL Interface
NinjaTrader provides a DLL named NtDirect.dll that supports various functions for
automated trading.
TradeStation Systems
If you are not running your own strategies or you have limited or no programming
experience you should use the TradeStation Email Interface
If you are running your own system and you are comfortable with EasyLanguage and
want to have bi-directional control of your real-time order processing you should use
the pre-configured TradeStation NinjaTrader functions that use the DLL interface.
eSignal Systems
You should use the pre-configured eSignal NinjaTrader functions that use the DLL
interface
You should use the DLL if your charting application supports that interface type or use
the File Interface
Custom Applications
You should use the DLL interface
9.4.1.2 Commands and Valid Parameters
The following section is only relevant for the File and DLL interfaces. Both interfaces share
common interface functions/methods that take as arguments the parameters defined in the
tables below. You can automate your trading through eight different commands. Command
definitions are also provided below.
Available Commands
The following table displays required (R) and optional (O) values for each different
command value.
COMMAN ACCO INSTR ACT Q ORDE LIMIT STOP TI OC ORD STR STRA
D UNT UMEN ION TY R PRICE PRICE F O ID ER ID ATE TEGY
T TYPE GY ID
CANCEL R O
CANCELA
LLORDER
S
CHANGE O O O R O
CLOSEP R R
OSITION
CLOSEST R
RATEGY
FLATTEN
EVERYTHI
NG
PLACE R R R R R O O R O O O O
REVERSE R R R R R O O R O O O O
POSITION
CANCEL COMMAND
This command will cancel an order and requires an order ID value and an optional
strategy ID value. The order ID value must match either the order ID value given to an
order placed through the PLACE command or, an order name such as ENTRY*, EXIT*,
STOP*, SIMSTOP* or TARGET*. The star (*) represents an integer value such as
TARGET1 or TARGET2. Order names are only valid if a valid strategy ID value is
passed. The strategy ID value must match a strategy ID value given to a strategy in the
PLACE command.
CANCELALLORDERS COMMAND
This command will cancel all active orders across all accounts and broker connections.
CHANGE COMMAND
This command will change the parameters of an order and requires an order ID value,
optional price and quantity values and an optional strategy ID value. The order ID value
must match either the order ID value given to an order placed through the PLACE
command or, an order name such as ENTRY*, EXIT*, STOP*, SIMSTOP* or TARGET*.
The star (*) represents an integer value such as TARGET1 or TARGET2. Order names
are only valid if a valid strategy ID value is passed. Pass in zero (0) values for price and
quantity if you do not wish to change these order parameters. Price values must be in
US decimal format (1212.25 is correct while 1212,25 is not).
CLOSEPOSITION COMMAND
This command will close a position and requires an account name value and an
instrument name value. The instrument name value is the name of the NinjaTrader
instrument including the exchange name. For equities, the symbol is sufficient. This
command will cancel any working orders and flatten the position.
CLOSESTRATEGY COMMAND
This command will close an ATM Strategy and requires a strategy ID value. The
strategy ID value must match a strategy ID given to a strategy in the PLACE command.
This command will close the specified strategy.
FLATTENEVERYTHING COMMAND
This command will cancel all active orders and flatten all positions across all accounts
and broker connections.
PLACE COMMAND
This command will place orders, place orders that initiate a NinjaTrader ATM Strategy,
or place orders that are applied to an active NinjaTrader position ATM Strategy.
Providing the optional strategy name field with a valid ATM Strategy template name will
result in execution of that ATM Strategy once the order is partially or completely filled.
Pass in an optional unique string value for the strategy ID in order to reference that ATM
Strategy via other commands. To apply an order to an active ATM Strategy (existing
strategies Stop Loss and Profit Target orders are amended) pass in the active
strategy ID value and leave the strategy name field blank. Pass in an optional unique
string value for the order ID in order to reference that order via other commands. If
specifying an ATM Strategy template name, there is no need to pass in an order ID as
the strategy based orders can be referenced by their internally generated names such
as TARGET1, STOP1 and so on.
REVERSEPOSITION COMMAND
This command will close the current position and place an order in the opposite
direction. The field requirements are identical to the PLACE command.
9.4.1.3 Initialization
If using the DLL based interface, it is important to understand how the ATI is initialized with
respect to referencing account names. The ATI is initialized to the first account name used in
the first calling function.
Some functions accept an account name as a parameter. In most if not all functions, these
parameters can be left blank in which case the "Default" account will be used. You can set
the Default account by left mouse clicking on the File menu in the NinjaTrader Control
Center and selecting the menu item Options, once in the Options window select the ATI
tab and select the account you want to use from the Default account menu. If your default
account is set to 'Sim101' and you call functions and leave the account parameter blank, the
Sim101 account will be automatically used.
Example:
To trade currencies (FOREX) and/or options through the ATI you must explicity reference the
NinjaTrader instrument name in any functions that accept an instrument name as an
argument from the calling application.
9.4.1.5 File Interface
The File interface is an easy way you can instruct NinjaTrader to place and manage orders.
To use this interface, just create Order Instruction Files (OIFs) in "My
Documents\<NinjaTrader Folder>\incoming" and when NinjaTrader sees the instructions they
will be processed immediately. This interface allows you the flexibility to create order
instructions to NinjaTrader from any application that allows you to create text files.
Each file must also contain correctly formatted line(s) of parameters. You may stack the
instruction lines so that each file contains as many instruction lines as you desire. The
delimiter required is the semicolon. Although this section is a good reference for generating
correctly formatted OIF, it is highly suggested that you use the Automated Trading OIF
Builder to generate OIF strings for comparison to your OIF generation. Files are processed
the instant they are written to the hard disk without delay.
Please reference the Commands and Valid Parameters section for detailed information on
available commands and parameters.
The following are examples of the required format for each of the available commands.
Required fields are embraced by <> where optional fields are embraced by [].
CANCEL COMMAND
CANCEL;;;;;;;;;;<ORDER ID>;;[STRATEGY ID]
CANCELALLORDERS COMMAND
CANCELALLORDERS;;;;;;;;;;;;
CHANGE COMMAND
CHANGE;;;;<QUANTITY>;;<LIMIT PRICE>;<STOP PRICE>;;;<ORDER ID>;;
[STRATEGY ID]
CLOSEPOSITION COMMAND
CLOSEPOSITION;<ACCOUNT>;<INSTRUMENT>;;;;;;;;;;
CLOSESTRATEGY COMMAND
CLOSESTRATEGY;;;;;;;;;;;;<STRATEGY ID>
FLATTENEVERYTHING COMMAND
FLATTENEVERYTHING;;;;;;;;;;;;
PLACE COMMAND
PLACE;<ACCOUNT>;<INSTRUMENT>;<ACTION>;<QTY>;<ORDER TYPE>;[LIMIT
PRICE];[STOP PRICE];<TIF>;[OCO ID];[ORDER ID];[STRATEGY];[STRATEGY
ID]
REVERSEPOSITION COMMAND
REVERSEPOSITION;<ACCOUNT>;<INSTRUMENT>;<ACTION>;<QTY>;<ORDER TYPE>;
[LIMIT PRICE];[STOP PRICE];<TIF>;[OCO ID];[ORDER ID];[STRATEGY];
[STRATEGY ID]
9.4.1.5.2 Information Update Files
NinjaTrader provides update information files that are written to the folder "My
Documents\<NinjaTrader Folder>\outgoing". The contents of this folder will be deleted when
either Automated Trading is disabled or the NinjaTrader application is restarted.
Position update files are generated on every update of a position. The name of the file is
Instrument Name + Instrument Exchange_AccountName_Position.txt. An example
would be ES 0909 Globex_Sim101_Position.txt. The format of the file is:
Connection State
The Automated Trading OIF Builder is a utility that will generate correctly formatted OIF
based on user input. This utility will help you become familiar with the OIF formats that
NinjaTrader expects to see. You can also test these files in real-time by doing the following:
1. Ensure that "AT Interface" is enabled via the Control Center's File menu
2. Check "Write file" in the Automated Trading OIF builder window.
You can access the Automated Trading OIF Builder from the NinjaTrader Control Center
by clicking your left mouse button on the Tools menu and selecting the menu item Options.
Once in the Options window select the ATI tab and then left mouse click on the OIF
builder... button.
DLL Functions
Functions
Sample Code
eSignal Sample Code
TradeStation Sample Code
9.4.1.6.1 Functions
Sets the ask price and size for the specified instrument for use when synchronizing
NinjaTrader playback with an external application playback. A return value of 0 indicates
success and -1 indicates an error. The timestamp parameter format is "yyyyMMddhhmmss".
value of 1 = show message box, any other value = don't show message box.
string NewOrderId()
Gets a new unique order ID value.
Gets a string of strategy ID's of all ATM Strategies of an account separated by '|'. Duplicate ID
values can be returned if strategies were initiated outside of the ATI.
int TearDown()
Disconnects the DLL from the NinjaTrader server. A return value of 0 indicates success and -
1 indicates an error.
The eSignal sample code below illustrates the use of the NinjaTrader NtDirect.dll within an
eSignal EFS script. The function preMain() loads the various DLL functions. The function
main() places an order. There is also additional wrapper samples created as examples. The
sample is also saved as an EFS file located at <NinjaTrader Installation
Folder>\bin\AutoTrade\NTSample.efs.
Sample Code
/* Copyright (c) 2005, NinjaTrader LLC
[email protected]. All rights reserved. */
var dll = new DLL("NtDirect.dll");
var orderPlaced = false;
var printDone = false;
function preMain()
{
setPriceStudy(true);
setStudyTitle("NT Sample");
dll.addFunction("AvgEntryPrice", DLL.DOUBLE, DLL.
STDCALL, "AvgEntryPrice", DLL.STRING, DLL.STRING);
dll.addFunction("AvgFillPrice", DLL.DOUBLE, DLL.
STDCALL, "AvgFillPrice", DLL.STRING, DLL.STRING);
dll.addFunction("BuyingPower", DLL.String, DLL.
STDCALL, "BuyingPower", DLL.DOUBLE);
dll.addFunction("CashValue", DLL.String, DLL.
function main()
{
if (isLastBarOnChart() && NTConnected(1))
{
if (!orderPlaced)
{
if (NTBuyMarket("MyOrderId", 1) == 0) //
buy 1 unit at market, assign order id (optionally)
orderPlaced = true;
}
else
{
// print some information on the current
position and order
debugPrint("Position size: " +
NTMarketPosition("") + "\r\n");
debugPrint("AvgEntryPrice: " +
NTAvgEntryPrice("") + "\r\n");
debugPrint("OrderStatus: " +
NTOrderStatus("MyOrderId") + "\r\n");
debugPrint("Filled #: " + NTFilled
("MyOrderId") + "\r\n");
debugPrint("AvgFillPrice: " +
NTAvgFillPrice("MyOrderId") + "\r\n");
debugPrint("RealizedPnL: " +
NTRealizedPnL("") + "\r\n");
}
}
}
return (dll.call("Connected") == 0)
}
The TradeStation sample code below illustrates the use of the NinjaTrader NtDirect.dll within
an TradeStation Easy Language function script.
Sample Code
{ Copyright (c) 2005, NinjaTrader LLC
[email protected] }
NinjaTrader installs an EFS script that contains a set of convenience functions that uses the
DLL interface for trade automation. These functions provide order submission, modification
and cancellation capabilities, global operation capabilities, and strategy initiation and
management capabilities. You can execute trades from within an eSignal indicator/formula on
the tick that the trade signal occurred.
Set Up
Functions
Sample Code
Tips
9.4.1.7.1 Set Up
Sample Script
You can view the sample script by following the instructions below.
string NTNewOrderId()
Gets a unique order ID.
Global Functions
int NTCancelAllOrders()
Cancels all orders across all connections across all accounts. A return value of 0
indicates success and -1 indicates an error. Success indicates success in submitting
the command NOT that all orders are in fact cancelled.
int NTFlattenEverything()
Closes all positions and cancels all orders across all connections across all accounts. A
return value of 0 indicates success and -1 indicates an error. Success indicates
success in submitting the command NOT that all orders are in fact cancelled and all
positions are in fact closed.
The following EFS sample strategy "NTSample" is located in the <NinjaTrader installation
folder>\bin\AutoTrade\NTSample.efs folder. This sample is intended demonstrate the use of
NinjaTrader functions in EFS and NOT to illustrate any best practice or approach in function
implementations.
function preMain()
{
setPriceStudy(true);
setStudyTitle("NT Sample");
dll.addFunction("AvgEntryPrice", DLL.DOUBLE, DLL.
STDCALL, "AvgEntryPrice", DLL.STRING, DLL.STRING);
dll.addFunction("AvgFillPrice", DLL.DOUBLE, DLL.
STDCALL, "AvgFillPrice", DLL.STRING, DLL.STRING);
dll.addFunction("BuyingPower", DLL.String, DLL.
STDCALL, "BuyingPower", DLL.DOUBLE);
dll.addFunction("CashValue", DLL.String, DLL.
STDCALL, "CashValue", DLL.DOUBLE);
dll.addFunction("Command", DLL.INT, DLL.STDCALL,
"Command", DLL.STRING, DLL.STRING, DLL.STRING, DLL.
STRING, DLL.INT, DLL.STRING, DLL.DOUBLE,
DLL.DOUBLE, DLL.STRING,
DLL.STRING, DLL.STRING, DLL.STRING, DLL.STRING);
dll.addFunction("ConfirmOrders", DLL.INT, DLL.
STDCALL, "ConfirmOrders", DLL.INT);
dll.addFunction("Connected", DLL.INT, DLL.
STDCALL, "Connected", DLL.INT);
dll.addFunction("Filled", DLL.INT, DLL.STDCALL,
function main()
{
if (isLastBarOnChart() && NTConnected(1))
{
if (!orderPlaced)
{
if (NTBuyMarket("MyOrderId", 1) == 0) //
buy 1 unit at market, assign order id (optionally)
orderPlaced = true;
}
else
{
// print some information on the current
position and order
debugPrint("Position size: " +
NTMarketPosition("") + "\r\n");
debugPrint("AvgEntryPrice: " +
NTAvgEntryPrice("") + "\r\n");
debugPrint("OrderStatus: " +
NTOrderStatus("MyOrderId") + "\r\n");
debugPrint("Filled #: " + NTFilled
("MyOrderId") + "\r\n");
debugPrint("AvgFillPrice: " +
NTAvgFillPrice("MyOrderId") + "\r\n");
debugPrint("RealizedPnL: " +
NTRealizedPnL("") + "\r\n");
}
}
}
function NTRealizedPnL(account) {
return dll.call("RealizedPnL", account);
}
function NTStrategyPosition(strategyId) {
return dll.call("StrategyPosition", strategyId);
}
9.4.1.7.4 Tips
1. You can optionally leave the account parameters empty in any of the eSignal NinjaTrader
functions and NinjaTrader will use the default account. You can set the Default account by
left mouse clicking on the File menu in the NinjaTrader Control Center and selecting the
menu item Options, once in the Options window select the ATI tab and select the account
you want to use from the Default account menu.
2. To ensure you do not place duplicate orders in the event that an eSignal chart reloads you
can check for the condition "isLastBarOnChart()"
3. You can check NTMarketPosition for a flat position before placing an order
4. You can create an orderId using the current bar time stamp + instrument name. Before
placing an order, call NTOrderStatus and see if you get a valid return value. If yes, then the
signal has already been processed.
9.4.1.8 TradeStation Integration
There are two options to execute your TradeStation strategies through NinjaTrader to one or
more of NinjaTrader's hundreds of supported brokers. If you do not have programming
experience you can use the Email Interface to send your trade signals to NinjaTrader, or if
you are familiar with Easy Language and have basic programming experience you can use
the DLL Based Integration.
The TradeStation Email Interface is targeted toward individuals who are not familiar with
programming in EasyLanguage and want to run TradeStation strategies and automate order
flow to any supported NinjaTrader broker.
If you are running concurrent strategies on the same market you should ensure
that you either
Make all signal names unique or
Run the concurrent strategies in different TradeStation workspaces
The following set up is for TradeStation Version 8.XX. This section will walk you through the
set up in both NinjaTrader and TradeStation as well as allow you to send a test email through
the Email Interface you have created.
Setting up NinjaTrader
1. Start NinjaTrader
2. Select the Tools menu and then the menu item Options from the Control Center
window
3. Once in the Options window select the ATI tab
4. Set the default account to Sim101 (you can always set this to your live brokerage account
later but we recommend leaving it to Sim101)
5. Check the "Enable SMTP server" option
6. Set your Order Handling options
7. Set your Stop Order Handling options
6. Connect to your broker by selecting the File menu and then the menu item Connect within
the Control Center window (make sure you have set up a connection to your broker)
7. Enable the Automated Trading Interface by selecting the File menu and then the menu
item AT Interface within the Control Center window (a pale green "ATI" will light up in lower
right hand corner of the Control Center window)
Symbol Mapping for Futures Contracts (Stocks and Forex traders may skip this
step)
8. Set your symbol mapping for futures contracts
13. Click once on the TradeManager window that appears then select the TradeStation main
menu View and the menu name TradeManager preferences
14. Select the "Notification" tab as per the image below and then select "Strategy Active
Order"
16. Enter the information exactly as shown above in items 1 through 4; you can press the "
Test" button which will send a test message to NinjaTrader and show up in the Control
Center Log tab. If you receive an error when attempting to send a test message, please
ensure that you have no other SMTP server running on your PC and make sure that any
competitive products are uninstalled.
17. Press "OK"
18. Repeat steps 15 through 17 for "Strategy Canceled Order", "Strategy Filled Order"
and "Strategy Replaced Order"
21. Your strategy will appear in the "Format Analysis Techniques & Strategies" window as
shown above
22. Check the "Generate strategy orders for display in TradeManager's Strategy
Orders tab" box and press "Close"
* Following this set up procedure, orders will NOT be sent to any live TS brokerage account,
only to NinjaTrader.
That's it! Your strategy will now be automated for execution through NinjaTrader!
9.4.1.8.1.4 Order Handling Options
There are several Order Handling options available for the signals sent from TradeStation.
All Order Handling options are available by selecting the Tools menu in the Control Center
, selecting the menu name Options, and then selecting the ATI tab. Please review all of the
following Order Handling options to ensure your orders are managed as expected.
Submit "as-is"
Submits orders as specified (limit, market, stop, stop limit) when NinjaTrader receives a
"strategy active order" notification email from TradeStation. Upon receiving the
subsequent "strategy filled order" notification email from TradeStation, NinjaTrader will
convert any unfilled shares/contracts to either market order or marketable limit order
(substantially higher than inside market if buying or below market if selling) depending on
the instrument type after a user defined number of seconds.
NOTE: If trading currencies (Forex) it is advised to start a market data stream (any
order entry window) for the market you are trading. Since limit buy orders above the offer
or limit sell below the bid are invalid orders that are rejected from your broker,
NinjaTrader will check the TradeStation requested limit price against the current market
price and if it would result in a rejected order, it will convert to a market order.
Order Confirmation
You can choose to have NinjaTrader prompt you for approval before submitting your
order to your brokerage account. To enable this feature start in the NinjaTrader Control
Center and select the Tools menu, then select the menu name Options, once in the
Options window check "Confirm order placement" under the General tab.
There are several Stop Order Handling options available for the signals sent from
TradeStation. All Stop Order Handling options are available by selecting the Tools menu in
the Control Center, selecting the menu name Options, and then selecting the ATI tab.
Please review all of the following Stop Order Handling options to ensure your stop orders
are managed as expected.
If you have "Submit market order on TS fill" enabled via Order Handling Options, the
following Stop Order Handling is ignored.
Submit "as-is"
Submits the stop order as specified.
Behavior as follows:
1. Stop order worse than current last traded price --> Market order submitted (desired
outcome)
2. Stop order rejected due to insufficient funds --> Market order submitted and also
rejected (not desired but no risk)
3. Stop order rejected due to price outside of range --> Market order submitted and likely
filled (risky)
4. Stop order rejected due to limit price worse than stop price --> Market order submitted
and likely filled (risky)
Creating a workspace within TradeStation with the correct naming convention is critical to
enabling TradeStation to properly communicate with NinjaTrader.
*Please note you may have multiple charts/strategies running in a single workspace
Account Name
You can optionally add your brokerage account name(s) to the workspace name to
identify an account that NinjaTrader will route orders to. If the account name is missing
NinjaTrader will route orders to the default account (to set the default account from
NinjaTrader left mouse click on the Tools menu, select the menu name Options, left
click on the ATI tab, and then select the General tab). The account name must be
specified as "Account=YourAccount" (without quotations) and where "YourAccount" is
the name/number of your brokerage account.
Multiple Accounts
You can add multiple accounts in the workspace name to inform NinjaTrader to replicate
the TradeStation order across more than one account. To do this add a comma ",
" (without the quotations) after each account name. For example; "Account=Account1,
Account2"
Quantity Multiplier
You can optionally associate a quantity multiplier with each account that you have
specified in the workspace name. This optional value will be multiplied by the
TradeStation's strategy quantity amount. For example; if your TradeStation strategy has
a quantity amount of 1 contract and you want to trade 2 contracts and you do not want to
modify this amount in the strategy itself you can add "=2" after the account name in the
workspace which would multiple the strategy contract amount by a factor of 2. The text
would look like "Account=YourAccount=2"
The following workspace name routes orders to the Default account specified under
Tools --> Options --> ATI tab
NinjaTrader
The following workspace name routes an order to account #7777 and another order to
account #1311 with the original strategy quantity multiplied by a factor of 2
NinjaTrader;Account=7777,1311=2
The following workspace name routes orders to account #123 and maps trade signals
generated by the $SPX.X chart to the S&P Emini March 2009 contract
NinjaTrader;Account=123;Map=$SPX.X,ESH09
Multiple Workspaces
You may create multiple workspaces provided that they each contain
"NinjaTrader;" (without the quotations) in their name. For example, you could have two
workspaces named "NinjaTrader1;" and "NinjaTrader2;"
9.4.1.8.2 DLL Based Integration
DLL based integration is targeted for system developers who are familiar with EasyLanguage
and have basic programming experience. NinjaTrader installs an EasyLanguage script that
contains a set of convenience functions that uses the DLL interface for trade automation.
These functions provide order submission, modification and cancellation capabilities, global
operation capabilities and strategy initiation and management capabilities. You can execute
trades from within a TradeStation indicator on the tick that the trade signal occurred.
NinjaTrader also provides a script for driving TradeStation market data to NinjaTrader. See
the Connecting to TradeStation Data Feed for more details.
9.4.1.8.2.1 Set Up
string NTNewOrderId
Gets a unique order ID.
Global Functions
int NTCancelAllOrders
Cancels all orders across all connections across all accounts. A return value of 0
indicates success and -1 indicates an error. Success indicates success in submitting
the command NOT that all orders are in fact cancelled.
Enables order confirmation dialog box. 0 = false, 1 = true. This is a global NinjaTrader
setting that can be also set via the Control Center window by selecting the Tools
menu and then selecting the menu name Options.
int NTFlattenEverything
Closes all positions and cancels all orders across all connections across all accounts. A
return value of 0 indicates success and -1 indicates an error. Success indicates
success in submitting the command NOT that all orders are in fact cancelled and all
positions are in fact closed.
The following EasyLanguage sample strategy "NTSample" is installed during the set up
procedure. This sample is intended to demonstrate the use of NinjaTrader functions in
EasyLanguage and NOT to illustrate any best practice or approach in function
implementations.
Sample Code
{ Copyright (c) 2005, NinjaTrader LLC
[email protected] }
Success = NTBuyMarket("MyOrderId",
1); { buy 1 unit at market, assign order id
(optionally) }
end else begin
Success = NTSellMarket("MyOrderId",
1); { sell 1 unit at market, assign order id
(optionally) }
end;
end else begin
{ print some information on the current
position and order }
Print("Position size: " + NumToStr
(NTMarketPosition(""), 0));
Print("AvgEntryPrice: " + NumToStr
(NTAvgEntryPrice(""), 2));
Print("OrderStatus: " + NTOrderStatus
("MyOrderId"));
Print("Filled #: " + NumToStr(NTFilled
("MyOrderId"), 0));
Print("AvgFillPrice: " + NumToStr
(NTAvgFillPrice("MyOrderId"), 2));
end;
end;
You can run NinjaTrader on a different PC than where TradeStation is running via the DLL
interface only.
1. Define the SetUp function by adding the following line to your EL script:
2. You must call the SetUp function before calling any other DLL function. Following is
sample code on how to accomplish this.
Once you have a default account setup you can optionally leave the account parameters
empty in any of the TradeStation NinjaTrader functions and NinjaTrader will use the default
account set here.
2. To ensure you do not place duplicate orders in the event that a TradeStation chart reloads
you can check for the condition "LastBarOnChart"
3. You can check NTMarketPosition for a flat position before placing an order
4. You can create an order ID using the current bar time stamp + instrument name. Before
placing an order, call NTOrderStatus and see if you get a valid return value. If yes, then the
signal has already been processed.
9.4.2 Running NinjaScript Strategies
The following section explains how to automate a NinjaScript strategy. Please keep in mind
that a strategies real-time performance can and will vary from your backtested results.
Prior to running a NinjaScript strategy against a live account, you must first understand and
set the real-time handling options for a NinjaScript strategy. These options can be found in
the Control Center under Tools > Options > Strategies Tab.
9.4.2.2 Running a NinjaScriptStrategy from a Chart
You can run a NinjaScript strategy in real-time in a live or simulation account within a
NinjaTrader chart.
Setup Tips
Following are some key points and instructions on on how to run a NinjaScript strategy
from a chart.
NinjaTrader MUST be connected to a live brokerage or market data vendor. You can
also use the Market Replay or Simulated Data Feed connections as well.
Strategy menu options will NOT appear if not connected live
You can not run Chart Trader on a chart while you have a running strategy applied to
the chart
On terminating (stop running) a strategy, all strategy generated trade markers or draw
objects will be removed from the chart
A NinjaScript strategy is a self contained automated trading system and orders
generated are live and not virtual. Cancelling strategy generated orders manually can
cause your strategy to stop executing as you designed it. If you want to manually
cancel an order, terminate the strategy itself.
Running and disabled strategies are also displayed in the Control Center window
Strategies tab
If running an FX strategy, please review the "Running FX Strategies" section for critical
information
1. Within an open chart, either select the Strategies... menu from within the right mouse
button click context menu, the Strategies icon from the tool bar or press the default
CTRL + S Hot Key on your keyboard to bring up the Strategies dialog window
2. You can add/remove and set up live strategies from within the Strategies dialog
window pictured to the right:
3. From the list of available strategies (section 1 in the image below) select a strategy
and either press the New button or double click on the strategy
4. Once added to the list of applied strategies (section 2 in the image below), you can
now edit the strategy's properties
5. Set the strategies properties (section 3 in the image below). You must set the
property Enabled to True to actually turn on the strategy.
7. To terminate (stop running) a strategy, you can highlight a running strategy and press
the Remove button within the Strategy dialog window which would completely
remove the strategy from the chart and Control Center's Strategies tab. Alternatively
you can set the Enabled property to False to simply disable the strategy and allow
you to re-enable the strategy at a later point in time without needing to reparameterize
it.
Strategy Properties
The image below shows the adjustable properties for a strategy available in the
Strategies dialog window (see the "How to run a NinjaScript strategy in a chart" section
above):
You can run a NinjaScript strategy in real-time in a live or simulation account via the
Strategies tab of the Control Center.
Setup Tips
Following are some key points and instructions on on how to run a NinjaScript strategy
from the Strategies tab of the Control Center window:
1. Left mouse click on the Strategies tab found in the NinjaTrader Control Center
2. Right mouse click within the Strategies tab. The right click menu will appear.
3. Select the menu item New Strategy... The New Strategy window will appear.
4. Choose the strategy you wish to run from the Strategy drop down menu.
5. Set the instrument, interval, and other optional strategy properties (see the "
Understanding strategy properties section below") and press the OK button
6. Check the box in the Enable column of the Strategies tab next to the strategy you
wish to enable.
CRITICAL
Based on the above information, if you are backtesting in the Strategy Analyzer using order
quantities of 100,000 and you now wish to trade live in your brokerage account where 1 lot is
equal to 100,000 MAKE SURE that you adjust your strategy's order quantity from 100,000 to
1 to ensure you are trading the correct quantity.
1. Disconnect from all connectivity providers (if connected) and from within the Control
Center window select the File menu. Then select the menu Utilities and the menu item
Backup...
1. From within the Control Center window select the File menu. Then select the menu
Utilities and the Restore... menu item
2. Select the backup archive to restore from the "Restore" file dialog window
3. Press the "Open" button
9.6 Charts
NinjaTrader charts support a multitude of intervals, indicators and drawing tools as well as
discretionary trading using Chart Trader and automated trading using NinjaScript strategies.
The chart window itself is highly customizable and supports a wide range of user definable
options.
Management Trading
Creating a Features
Chart Trading from a
Navigating a Chart
Chart Working with
Working with Automated
Price Data Strategies
Working with
Indicators Misc
NinjaTrader does not limit the number of chart windows that can be opened, however
more open windows will require more PC resources. Please see the Performance Tips
page for more information on improving PC performance.
Selecting an Instrument
Once inside the Data Series window, there are multiple ways to choose an instrument.
You can select an instrument from the available instrument lists, type the instrument
symbol into the empty instrument field and press the Enter key, or use the Instrument
Lookup window by pressing the "..." button next to the instrument field. Please see the "
Working with Price Data section of the Help Guide for more information on selecting
instruments.
The chart image below displays some of the common features you will see inside a
NinjaTrader chart window:
6. Chart tool bar Access to chart features. Can be enabled or disabled via chart
properties.
7. Price markers Displays current price and indicator values in the left or right scale.
Can be enabled or disabled on a per chart object basis through
the Data Series or Indicators window. Drawing tool objects do not
have price markers.
8. Caption Displays the chart Data Series, interval and date at the top of the
chart window. The Data Series caption can be edited via the Label
parameter in the Data Series window.
9. Horizontal scroll Scrolls the horizontal axis left and right. (See the "Navigating a
bar Chart" section of the Help Guide for more information.) Can be
enabled or disabled via chart properties.
A solid "return" icon means the last visible bar is to the right of the viewable area
A hollow "return" icon means the chart is horizontally scrolled to the left
Horizontal Scaling
To compress or decompress the horizontal axis, left mouse click in the x- axis margin
and move the mouse cursor to the left or right. Alternatively, use the Hot Keys CTRL +
CTRL + Left mouse click and hold on chart margin and drag up or down as depicted in
the images below:
A box with an "F" (Fixed) will appear in the upper right corner of the chart margin anytime
the vertical chart axis is manually adjusted. This signifies the chart axis is set to a "fixed"
scale. Left mouse click this button to return to auto scale.
Vertical Scaling
There are two methods to shrink or grow the vertical axis of the chart:
1. Double click in the right or left margin to open the Chart Panel Properties window, or
right mouse click in the price scale and select the menu Properties... Set the Range
to Fixed and enter a Maximum and Minimum for the chart scale.
2. Left mouse click in the x-axis margin and move the mouse cursor up or down as
shown in the images below:
Zoom In
To create a zoom frame around a chart area you want to focus in on:
1. Right mouse click on the Zoom In icon in the tool bar, select the Zoom In menu item
within the right mouse button click context menu, or use the zoom in Hot Key CTRL+Z
2. Left mouse click and while holding down the left mouse button, draw a zoom frame
region and release the button.
The chart display area will zoom in to the selected frame area.
Zoom Out
Each zoom in can be undone to the prior zoom level with a zoom out. To zoom out, left
mouse click on the Zoom Out icon in the chart tool bar, select the Zoom Out menu item
within the right mouse button click context menu, or use the zoom out Hot Key
CTRL+O.
Bar Spacing
To change the spacing between bars:
Bar Width
To change the width of bars:
Alternatively, left mouse click on the "Bar style" chart toolbar icon to access bar spacing
and width functions
Understanding panels
Panels
A chart is comprised of Panels that contain chart objects such as Data Series,
Indicators and Drawing Objects. Panels are added to a chart during the process of
adding/editing a Data Series or Indicator. Every Panel has three independent scales to
which you can associate a chart object to. Each scale can be uniquely customized via
the panel properties (see "Panel Properties" sub-section below for more information):
Panel Scales
When adding a Data Series or Indicator to a chart, you can set the Scale justification
property to align the chart object to any of the following scales within the Panel:
Left
Right
Overlay
With the exception of the Overlay scale, a price scale will only be displayed in a Panel if
there is one or more chart objects justified to it. The Overlay scale does not have a
visible price scale however, any chart objects justified to this scale will display their price
markers first on the Right scale if one exists otherwise they are displayed on the Left
scale. All scales can be shared by multiple chart objects.
In addition to changing a chart objects scale justification property via the Data Series
window or Indicators window, you can drag and drop a chart object onto different scales.
Please see the sub-section ("How to drag and drop chart objects") lower down within
this topic page.
The image above depicts the ES 12-09 futures contract justified to the Right scale and a
Stochastics indicator justified to the Left scale within the same Panel.
Panel Properties
The Panel Properties menu can be opened by double left mouse clicking within the
price scale or selecting the Properties menu via the Panel Context menu discussed
above. The Panel Properties window will list the properties below grouped by each
scale that is currently active on the Panel.
Range Sets the range to "Automatic" or "Fixed." Fixed allows the manual
setting of the upper and lower boundary of the chart. The range can
also be manually defined via the mouse. Please see the section above
"How to change the vertical scale and range of a chart".
Based on Sets a value indicating how the automatic scale range is calculated.
When set to “EntireDateRangeSeriesOnly”, Data Series and Indicator
values for the entire date range of the chart (draw objects are ignored)
are used to calculate the vertical scale range. When set to
“ScreenDateRange”, all visible objects on the screen are used.
Horizontal grid Sets a value of either "Ticks" or "Points" which is used to calculate the
lines interval interval between grid lines and labels
type
Horizontal grid Sets the vertical interval of the horizontal axis. A value of 0 (zero) will
lines interval enable the automatic generation of grid line intervals. The Right scale
value will always take precedence over the left scale if both are set to user
defined custom grid line intervals.
Margin type Sets the calculation mode for determining the upper and lower panel
margins. ("Percent" values are whole percents. For example, entering
a value of "1" equals 1%.)
Margin lower Sets the lower margin value
Margin upper Sets the upper margin value
Maximum Sets the scale's upper boundary when using "Fixed" range
Minimum Sets the scale's lower boundary when using "Fixed" range
Type Sets the scaling type to "Linear" or "Logarithmic"
Left mouse click on a chart object within a chart and drag and drop to any of the
following areas of the chart:
When you drag a selected object to a valid region on the chart, a blue band will appear
acknowledging you that by dropping the object at this particular location, a new panel will
be created.
Z-Order
Objects within a panel can be adjusted by paint order to appear behind or in front of
another chart object.
You can change the z-order (paint order) of all chart objects within each individual
panel. Each chart object is assigned a level value which informs you where in the paint
order the particular object resides. As a rule of thumb, there are as many levels on a
panel as there are chart objects on it. For example, if you had a Data Series and a
simple moving average indicator on a panel, there would be two painting levels. Level 1
is the top most level which means that any chart object on Level 1 would be painted
above all others. Continuing our example, if the Data Series was on Level 1 of 2 and the
simple moving average was on Level 2 of 2, that would mean the Data Series would be
painted on top of the Data Series.
The image below depicts a "Rectangle" drawing object set at z-order Level 3 of 3,
which is behind both the Stochastics indicator (Level 2 of 3) and the ES 12-09 Data
Series (Level 1 of 3).
Note: Draw objects originating from a NinjaScript indicator or strategy will all generally
share the same z-order as the script. To have the objects on a separate z-order would
have to be set programmatically.
Cursor Type
You can have either the standard windows pointer, cross hair or Global Cross Hair for
chart navigation. You can toggle between cursor modes via the right mouse click context
menu cursor sub menu, the "Cursor" chart toolbar icon or via the following shortcut
keys:
CTRL + R Pointer
CTRL + Q Cross Hair
CTRL + G Global Cross Hair (links crosshairs when enabled on two or more
charts)
The Data Series window is used to configure the Data Series within the chart, edit
Data Series parameters, and save default values for the Period Type.
Select the File menu from the NinjaTrader Control Center, left mouse click the menu
item New and select the menu item Chart...
Right mouse click in the chart background and select the menu Data Series...
Use the default CTRL+F Hot Key from an open chart
Double left mouse click on a Data Series within the chart
Right mouse click on a selected Data Series within a chart and select the menu
Properties
1. Left mouse click on the instrument you want to add as a Data Series and press the
New button or simply double left mouse click on it
2. Type the instrument symbol, including front month for futures instruments, in the
empty search field above the Data Series list and press the "Enter" key. For example,
"ES 12-09"
3. Left mouse click on the "..." button next to the search field. The Instrument Lookup
window appears. Use the name or description field to search available instruments
and double left mouse click on the desired instrument. (See "Instrument Lookup
Window" topic below.)
The added Data Series will now be visible in the list of applied Data Series objects. (4)
A Data Series can also be added by typing directly into an open chart. Type the plus
symbol (+) followed by the instrument symbol, front month for Futures, and appropriate
interval value. Typing "+ES 12-09 5M" will add a 5 minute ES 12-09 Data Series to the
selected chart. (See the "How to change a Data Series" section below for more
information)
The Data Series parameters will now be editable on the right side of the Data Series
window when you have an applied Data Series selected. (see the "How to edit Data
Series parameters" sub-section below)
1. Open the Data Series window (see the "Understanding the Data Series window"
section above)
2. Select the Data Series you would like to edit in the list of applied Data Series (as
shown in the image below).
3. Once selected, the Data Series parameters will be available to edit on the right hand
side.
The section of the Data Series window below the parameters will display a description
of the selected parameter. Left mouse click in a parameter row to edit the property.
Select an option from the drop down menu or if one does not appear, type in the desired
value.
Price based on Sets the type of market data used to drive the Data Series.
Type Sets the bar type of the Data Series. See the Bar Types section
of the Help Guide for more information.
Value Sets the Data Series value.
Base period type Sets the underlying Data Series type used. (Kagi,
PointAndFigure, and LineBreak only)
Base period value Sets the underlying Data Series value used. (Kagi,
PointAndFigure, and LineBreak only)
Reversal Sets the reversal value. (Kagi and PointAndFigure only)
Reversal type Sets the type of reversal calculation used. (Kagi only)
Brick size Sets the brick size value. (Renko only)
Box size Sets the box size value. (PointAndFigure only)
Price Sets the price type used for Data Series calculations.
(PointAndFigure only)
Line Breaks Sets the number of lines used to determine a line break.
(LineBreak only)
Chart style Sets the style of the bars.
Bar width Sets the width of the bar.
Candle outline Sets the visual properties of the candle outline.
Color for down bars Sets the color for the down bars.
Color for up bars Sets the color for the up bars.
Load data based on Determines how much data is loaded based on number of bars,
number of days, or a custom date range.
Days to load Sets the number of days to load data.
Start date Sets the start date of the chart. *If the specified start date is
within a session (part of a Session Template definition) whose
start time falls on a prior date then the Chart will start on that prior
date.
End date Sets the end date of the chart. *If the specified end date is within
a session (part of a Session Template definition) whose end time
falls on a future date then the Chart will end on that future date.
Session template Sets the session time template for the Data Series. (See the "
Session Manager" section of the Help Guide for more
information)
Auto scale When true, the Data Series is part of the chart auto scaling
Display in Data Box When true, the Data Series values will display in the chart Data
Box.
Label Sets the label display text of the chart window (can be left blank
to remove label)
Panel Sets the panel the Data Series is displayed on.
Plot session break When true, will plot the session break line in the chart.
line
Price marker When true, the Data Series value will plot in the Y-axis.
Price marker color Sets the color of the price marker.
Scale justification Sets the scale the Data Series will be displayed on.
Session break line Sets the visual properties of the session break line.
Show global draw Enables or disables a global drawing object to be shown in this
objects chart. (See the "Understanding local vs. global drawing
objects" section of the Working with Drawing Tools & Objects
section of the Help Guide for more information.
Color for executions - Sets the color of the plotted buy executions.
buy
Color for executions - Sets the color of the plotted sell executions.
sell
NinjaScript strategy Sets the visual properties of profitable strategy position lines.
profitable trade
NinjaScript strategy Sets the visual properties of the unprofitable strategy position
unprofitable trade lines.
Plot executions Sets the plotting style of the trade executions.
Before changing the instrument or interval, you must select the Data Series you wish to
change. If none is selected, any instance of the primary Data Series is changed.
1. Left mouse click on the instrument drop down menu in the chart toolbar
2. Select an instrument from the list (for more information about editing this list, please
see the Instrument Lists section of the Help Guide for more information.)
1. Left mouse click on the Data Series drop down menu from the chart toolbar
2. Left mouse click on any of the minute, daily, weekly, monthly or yearly menu items.
To change an Type the instrument symbol. (Add the front month for futures
instrument: instruments) Examples: "ES 12-09" for E-mini S&P 500, "AAPL"
for Apple stock or "EURUSD" for Euro/U.S. dollar Forex pair.
To change bar Type interval value plus the interval suffix (Value +suffix).
series: Examples: "5M" for 5 minute bars, "100T" for 100 tick bars, etc.
Available Suffix interval:
suffixes:
M Minute
T Tick
V Volume
R Range
S Second
D Day
W Week
MO Month
Y Year
RE Renko
To change Type the symbol + interval. Example: "AAPL 5M" will change chart
instrument and to a 5 minute chart of Apple stock.
interval
To add additional Type a plus sign (+) + the interval. Example: "+5M" will add a 5
Equities can be added to the NinjaTrader instrument database by typing the instrument
symbol followed by the exchange into an open chart and pressing the "Enter" key on
your keyboard. For example, you can type "YYY NYSE" to add stock "YYY" mapped to
the Nyse. Just typing "YYY" without the exchange will map to the Default exchange and
will use the "Default 24/7" session template.
Open the Data Series window (see the "Understanding the Indicators window" section
above), select a Data Series from the applied Data Series list, press the Remove
button, and then press the OK button to exit the Data Series window
Left mouse click to select the Data Series on your chart and then press the Delete
button on your keyboard.
Left mouse click to select the Data Series on your chart, then right mouse click and
select the menu item Remove.
The primary Data Series in the applied Data Series list CANNOT be removed once a
chart is created.
The image below shows two Data Series plotted within one chart window:
1. ES 12-09 (1 Min)
Each instrument is placed in its own panel by default with the scale shown in the right
margin of the chart. A maximum of 10 separate panels can be displayed within a single
chart window. Instruments and indicators can alternatively be plotted within one panel.
The scale of each can be justified to the right, left or overlayed on the panel. Please see
the "Understand panels" section of the "Navigating a Chart" page of the Help Guide for
more information.
Please note: The last bar of a session may be built as an incomplete bar due to the session
ending before the bar could be completed. Each new session will have bars freshly built
beginning from the first tick of the session. For example, the last bar of a session in a 10,000
Volume chart may contain a volume less than 10,000, while the next bar which builds on a
new session would contain 10,000 volume. This is to ensure that your charts are accurate
and consistent regardless of how many historical dates you decide to load. Otherwise
depending on when exactly the chart begins, the bars may look different since each session
is impacted by all prior sessions.
Tick Bars
A Tick bar is based on a specific number of trades (ticks). A bar will build until the
specified number of ticks is reached. The next tick will then result in a new bar being
created. For example, each historical bar in the the 500 Tick ES 09-10 chart shown
below plots 500 ticks at a time.
Volume Bars
A Volume bar is based on a specific number of units (volume) traded. A bar will build
until the specified volume is reached and once surpassed, a new bar will be created. For
example, each historical bar in the 10,000 Volume ES 09-10 chart shown below
contains a volume of 10,000 contracts as verified by the "VOL" indicator plotted below
the price bars.
Range Bars
A Range bar is based on a specified tick* price range. The bar will plot until the price
range is broken. A new bar will then start plotting. For example, each historical bar in the
4 Range ES 09-10 chart shown below is exactly 4 ticks (1 point) as measured from
hight to low as displayed by the vertical line of the Ruler drawing tool. (The "Y value" of
1.00 shown in the Ruler's display box is equivalent to 4 ticks.)
*A tick in this instance is different from a tick in a Tick bar described in the sub-section
above. A tick in a Tick bar represents when an actual trade occurred, whereas a tick in
a Range bar is a price increment. This increment is the smallest price movement the
instrument can make and may differ by instrument. For example, a tick on the e-mini
S&P 500 (ES) is 0.25, while a tick on AAPL stock is 0.01. More information on setting the
instruments Tick size can be found in the Editing Instruments section of the Help Guide.
Time Bars
Second, Minute, Day, Week, Month, and Year bars are all built based on the passage
of time. The bar will plot for a specified amount of time. Once this time is exceeded, a
new bar will begin. For example, each historical bar in the 1 Min ES 09-10 chart shown
below represents price movement for one minute in time.
Kagi Bars
Kagi bars are built based solely on price movement with no regard to time or volume. A
Kagi bar will plot in the direction of price until price reverses in a specified amount set as
the Reversal. The bar will then change direction, but stay the same color until the last
bar's high or low is surpassed. The length of time the bar will plot depends on the Base
period.
For example, suppose the price of an instrument is heading down and the Reversal is
set to 2 ticks. The line will continue to plot downward only until price reverses more than
2 ticks. At this point, the line will change direction, but stay red. Once the last Kagi bar
high is exceeded, the line will change to a thick green color and the same rules will apply
to the upside. The chart below displays 1 Min Kagi bars with a Reversal set to 2 ticks.
Renko Bars
Renko bars are built based solely on price movement with no regard to time or volume.
Each bar is known as a "brick" and a brick is plotted as green when price is moving up
and red when price is moving down. A new brick is plotted when price exceeds the high
or low of the previous brick by a specified amount set as the Brick size.
PointAndFigure Bars
PointAndFigure bars are built based solely on price movement with no regard to time
or volume. Each bar is a column made up of only X's representing rising price or only
O's representing decreasing price. Each X or O is referred to as a "box" and represents
the price distance defined by the Box size (set in number of ticks). A new X or O box
will be added to the bar when price moves more than the Box size to warrant adding
another box.
Another setting called the Reversal sets the amount of price movement needed from
the high/low to change from X's to O's or visa versa. A column will continue indefinitely
until price reverses equal to the Reversal amount (set in number of boxes). There can
never be two columns of X's or O's next to each other for a given session as any
additional X's or O's would just be added to the current column. When a reversal
occurs, the new column starts one box size above the last low for X's and one box size
below the last high for O's.
For example, the chart below shows PointAndFigure bars based on a 1 Minute ES 09-
10 Data Series. The Box size is set to 1 and the Reversal is set to 3. Starting from the
left, price went from a low of 1042.75 to a high of 1046 without reversing 3 ticks. Since
the Box size is set to 1 tick, anytime price goes higher than the last high by 1 tick, a new
X is drawn at the top. (If the Box size was set to 2, an X would not be drawn until price
exceeded the last X by 2 ticks.) Once it reversed 3 ticks, an O was drawn one box size
below the last high of the X column at a price of 1045.75. Price then went down to
1044.25 without going up 3 ticks. Once it retraced 3 ticks an X was drawn one box size
above the low of the previous O column. This same process is repeated resulting in the
full PointAndFigure bar series.
Note: The prices of the X's and O's are represented exactly in the middle of the X and O,
not at the top or bottom of them.
LineBreak bars
LineBreak bars are built based solely on price movement with no regard to time or
volume. The Line Breaks parameter sets the number of previous bar's high or low that
price must break to draw a new bar.
For example, if the Line Breaks parameter is set to 2 as shown in the chart below, the
first bar is drawn based on whether the close was above or below the open. The second
bar in the chart is drawn as green if price exceeds the first bar's high and red if price
drops below the low of the first bar's low. No new bar is drawn if price does not exceed
the high or low of the previous bar. The third bar is only plotted once price breaks the
high/low of the last 2 bars since the LineBreaks parameter is set to 2. A color change
occurs when price breaks the last 2 lows instead of highs or visa versa.
The Indicators window is used to add, remove and edit all indicators within a chart.
Adding an Indicator
To add an indicator to a chart:
1. Open the Indicators window (see the "Understanding the Indicators window" section
above)
2. Left mouse click on the indicator you want to add and press the New button or simply
double click on it
3. The indicator will now be visible in the list of applied indicators
4. The indicator's parameters will now be editable on the right side of the Indicators
window (see the "How to edit an indicator" section below)
Editing an Indicator
You can customize any indicator from the Indicators window.
1. Open the Indicators window (see the "Understanding the Indicators window" section
above)
2. Highlight the indicator you would like to edit from the list of applied indicators (as
shown in the image below).
3. Once highlighted this indicator's parameters will be available to edit on the right hand
side.
Indicator Parameters
The following parameters are common to all indicators:
Calculate on bar If true, will only calculate the indicator's value on the close of a bar. If
close false, NinjaTrader will calculate the indicator's value with each
incoming tick
Input Series Please see the Input series section for further information.
Maximum bars Max number of bars used for calculating an indicator's value. The
look back TwoHundredFiftySix setting is the most memory friendly.
Auto Scale If true, the indicator is part of the chart panel's vertical automatic
scaling
Displacement Displaces the plot back by this value (value of 2 would plot the current
indicator value two bars ago)
Display in Data If true, will display the indicator values in the chart Data Box
Box
Label The label displayed on the chart. Leaving the field blank will remove
the label from being displayed on the chart. Enclosing a label in
quotations ("MyEMA" for example) will display what's within the
quotations and exclude the system added trailing series information.
Panel The panel the indicator is plotted on. If you select Same as input
series the indicator will be linked to the input series and automatically
move with the input series if it is modified to a different panel.
Price marker(s) If true, the indicator value is plotted in the axis selected under the
Scale justification parameter.
Scale Sets the scale axis the indicator will be plotted on within its selected
justification panel. Please see the Navigating a chart user help guide section for
additional information.
Lines Allows you to customize the appearance of editable lines that are
Please see the Saving Chart Defaults section of the Help Guide for more information.
Removing an Indicator
There are three ways to remove an indicator from your NinjaTrader chart:
Open the Indicators window (see the "Understanding the Indicators window" section
above), select an indicator from the applied indicators list, press the Remove button,
and then press the OK button to exit the Indicators window.
Left mouse click to select the indicator on your chart and then press the Delete button
on your keyboard.
Left mouse click to select the indicator on your chart, then right mouse click and select
the menu Remove to remove the indicator from your chart.
For more information on using NinjaScript to build custom indicators please see the
NinjaScript section of the user help guide. Click here to view NinjaScript tutorials.
The option to hire a NinjaScript Consultant to build your custom indicators is also
available.
Drawing on a Chart
Various drawing tools are available and customizable within a chart. The image below
shows an example of several drawing tools applied to the chart.
1. Right mouse click within the chart and select the Drawing Tools menu
2. Left mouse click on the Drawing Tools button in the toolbar at the top of the chart
3. Via Hot Key
Ruler
The Ruler measures the number of bars, amount of time, and Y-axis distance between
the first two Ruler anchor points for a Data Series. The measurement data is attached
as a flag to a third, independent anchor point.
1. Select the Ruler drawing object from the Drawing Tools menu
2. Select the Data Series or Indicator you wish to measure by left mouse clicking on it
(you can skip this step if the series you wish to measure is the only series on the
specific chart panel)
3. Left mouse click on the chart where you wish to place the first anchor point
4. Left mouse click a second time on the chart where you wish to place the second
anchor point
5. Left mouse click a final time to set the anchor point for the Ruler display flag.
The anchor points can be relocated after setting by left mouse clicking on the anchor
point and dragging to a new location.
Drawing Objects
The following are the available drawing objects with default Hot Keys found within the
Drawing Tools menu:
Ruler Ctrl + F3
Line F2
Ray F3
Extended Line F4
Arrow Line Ctrl+F2
Horizontal Line F6
Vertical Line F7
Fibonacci F8
Retracements
Fibonacci F9
Extensions
Fibonacci F10
Time
Extensions
Fibonacci F11
Circle
Andrew's Ctrl + F8
Pitchfork
Gann Fan Ctrl + F9
Regression Ctrl + F10
Channel
Ellipse Ctrl + F11
Rectangle Ctrl+ F12
Triangle Ctrl + F6
Arc Ctrl + F7
Text F12
Chart Marker:
Arrow Up Alt+F2
Arrow Down Alt +F3
Diamond Alt +F5
Dot Alt +F6
Square Alt +F7
Triangle Up Alt +F8
Triangle Down Alt +F9
1. Select the drawing object from the Drawing Tools menu. The cursor will change to
resemble a pen. (Right clicking or pressing the "Esc" key will cancel the operation)
2. Left mouse click on the chart where you want the first anchor point set
3. Left mouse click again on the chart for any other necessary anchor points. Once all
anchor points are set, the cursor will change back to the cursor type you had
previously selected.
Once the drawing object is applied to the chart, it can be selected by left mouse clicking
on it. Once selected, the object can be moved throughout the chart and the anchor
points can be moved by left mouse clicking and dragging to a new location.
Snap Mode
Drawing objects can be attached to price and/or time data within the chart by using any
of the Snap Mode options:
Disabled Disables "Snap Mode" and allows the drawing object anchor point(s)
to be placed anywhere on the chart
Bar Sets the x-axis value of drawing object anchor point(s) to the bar
interval values only
Price Sets the y-axis value of drawing object anchor point(s) to the Data
Series OHLC and indicator price values only
Bar and Price Sets the x and y-axis of drawing object anchor point(s) to be aligned
with bar interval values, Data Series OHLC and indicator price
values only
Each drawing tool can be customized using the Drawing Object Properties menu.
1. Left mouse click on the drawing object to select it (once selected, the anchor points
will be visible)
2. Either double left mouse click on the drawing object, or right mouse click and select
the Properties... menu item
The general properties of the drawing object are located in the General tab. The image
below shows the General tab properties for the Line drawing object.
The Data tab displays the data locations of the drawing object anchor points in the chart.
These fields can be modified to change the location of the drawing object within the
chart.
Tag The Tag property is a naming convention used to access the drawing object
via NinjaScript. Any Tag values generated via NinjaScript are grayed out and
cannot be changed. Each drawing object must have a unique Tag value.
Start Sets the x-axis start value of the drawing object
Time
Start Y Sets the y-axis start value of the drawing object
End TimeSets the x-axis end value of the drawing object
End Y Sets the y-axis end value of the drawing object
Drawing object properties can be saved as default using the Set Default button. Please
see the "Saving Chart Defaults" section of the Help Guide for more information.
1. Left mouse click on the drawing object to select it (when selected, the anchor points
will appear)
2. Press the Delete key on the keyboard or right mouse click on the drawing object and
select the Remove menu item
1. Select the Drawing Tools menu via right mouse clicking in chart or via left mouse
clicking the Drawing Tools icon in the chart toolbar
2. Left mouse click on the Remove Drawing Objects menu item
3. The Remove Drawing Objects window will appear (image below).
4. Select either the group of drawing objects you wish to remove, or choose the "Select
All" option and press the OK button to remove the selected drawing objects from the
chart.
Removing a global drawing object will remove the object from all charts.
The properties for all Fibonacci drawing objects can be saved within templates. This
allows multiple property setups to be saved and applied to any Fibonacci drawing object
on a chart.
1. Open the Fibonacci drawing object Properties window (See the "Understanding
drawing object properties" section above)
2. Configure properties within the General tab to the desired settings
3. Right click within the Fibonacci drawing object Properties window and select the
menu item Manage Templates.
4. Enter a name for the template and press the Save button.
Note: Saving a new Fibonacci template as "Default" will make it the new default
template.
Once a template is saved, it can be applied to any Fibonacci drawing object on the
chart by selecting the template name from the Template drop down menu found in the
Fibonacci drawing object properties window.
Drawing objects can be applied to a specific chart (local), or to all charts of the same
instrument (global). You can optionally exclude any Data Series to NOT display a global
draw object by setting the property "Show global draw objects" to false in the Format
Data Series window.
1. Apply a drawing object to the chart (see the "How to draw on chart" section above)
2. Access the drawing object's properties (see the "Understanding drawing object
properties" section above)
3. Locate the "Attach to" drop down menu and select "Instrument name" (All charts)
The drawing object will now be applied to all charts for that specific instrument as well
as any new charts opened for that instrument. Global drawing objects are stored even
when a chart of the instrument is not open
Global drawing objects will be automatically deleted after 20 days of not being viewed.
Strategy Persistence
Automated strategies are always persisted on a chart whenever it is open, even if
Enabled is set to false inside the chart Strategies window. For example, if you shut
down NinjaTrader with an enabled strategy in a chart then reopen NinjaTrader, the strategy
will still be applied to the chart with the property Enabled being set to false. This allows
you to enable the strategy without having to reconfigure the parameters. When the chart
containing the automated strategy is closed though, the strategy will not be persisted
(stopped and removed).
Reloading NinjaScript
An automated strategy can be reloaded by right mouse clicking in the chart and selecting
the menu item Reload NinjaScript. Reloading of an automated strategy will remove the
old instance of the strategy and add a new one in the chart.
Executions
Automated strategy trade executions will be displayed in the chart. The chart below shows
several executions from orders placed by an automated strategy. (Only executions
pertaining to the strategy on the chart will be visible. Any manual executions or executions
from strategies not applied to the chart will NOT be shown.) Execution markers are
configured for each Data Series by selecting the parameter named Plot executions from
the Data Series window.
Strategy Performance
Real-time, Historical, or Historical & Real-time executions for the automated strategy
can be accessed within the open chart by right mouse clicking in the chart and selecting
the menu item Strategy Performance. Then hover the mouse over the desired
automated strategy and select the type of executions you wish to view from the menu that
appears. A Performance window will appear where you can view and analyze the trade
data.
Chart Template
Chart properties, chart panel properties, and indicator settings can be saved as a Chart
Template. A Chart Template can be applied to a new chart or an open chart for quick
loading of customized chart settings provided the template and chart share the same
number of Data Series objects.
1. Once you have a chart set up to your liking, right mouse click and select the menu
item Templates followed by the Save As... menu item
2. The Save Chart Template window will appear. Enter a name for your template and
press the OK button.
1. Right mouse click within an open chart and select the Templates menu
2. Select the menu item Save as Default
1. Right mouse click and select the menu item Templates followed by the Load... menu
item
2. The Load Chart Template window will appear. Select the template to load from the
list of templates and press the OK button.
1. Right mouse click and select the menu item Templates followed by the Save As...
menu item
2. The Save Chart Template window will appear. Select the template for removal from
the list of templates and press the Remove button.
What is Saved
All parameter settings are saved with the following exceptions:
In the image below, the parameters will be saved for the 'Minute' Period Type. Anytime
the 'Minute' Period Type is selected, the saved parameters will load.
What is Saved
All parameter settings are saved with the following exceptions:
Input series will default to the first Data Series applied to the chart
Panel will use the default NinjaTrader settings
In the image below, the parameters will be saved for the selected 'SMA' indicator.
Anytime the 'SMA' indicator is applied to the chart, the saved parameters will load.
What is Saved
All parameter settings are saved with the following exceptions:
In the image below, the parameters will be saved for the 'SampleMACrossOver'
strategy. Anytime the 'SampleMACrossOver' strategy is applied to the chart, the saved
parameters will load.
What is Saved
All parameter settings are saved.
(The chart property parameters can be restored to NinjaTrader default settings by left
mouse clicking on the Reset button within the Chart Properties window.)
If you change your settings and later wish to go back to the original settings, you can left
mouse click on the "Reset" button to return to the original settings.
What is Saved
The following properties are saved in the General tab:
Color
Width
Dash Style
Lock
Auto scale
Attach to will default to the Data Series where the object is drawn.
1. Open the Drawing Object Properties window by either double left mouse clicking on
the drawing object or right mouse clicking and selecting Properties...
2. Set desired property settings
3. Press the Set Default button
The next time the drawing object is drawn, the saved properties will be automatically
applied.
Please see the Working with Drawing Tools & Objects page for more information on
saving Fibonacci drawing object templates.
9.6.10 Data Box
The Mini Data Box and Data Box are excellent tools that allow you to access both bar and
indicator values on your chart. The Mini Data Box provides a compressed view of your chart
data while the Data Box provides a comprehensive view of the data.
If you open the Mini Data Box in a panel that has indicators applied you will see the
indicator values for the bar as well. The display order of data in the Mini Data Box is
displayed as follows:
If a panel contains more than one Data Series, each Data Series will be displayed with
its own shade of black or gray and these shades will repeat after the fourth Data Series.
The display order of data in the Data Box is first grouped and sorted by panel number
and then within each panel it is displayed as follows:
Indicators whose underlying input Data Series is NOT on the same panel will be listed
first and sorted based on the vertical scale they reside on (Left, Right, then Overlay).
Data Series will be listed next and sorted based on the vertical scale they reside on
(Left, Right, then Overlay).
Underneath each Data Series, any associated indicators will be listed and sorted
based on the vertical scale they reside on (Left, Right, then Overlay).
As shown in the image below, Panel 1 shows the Data Series label as well as the Data
Series values. The Data Series information is followed by the Indicator label, plot
names, and values. Panel 2 lists the Indicator label, plot name, and indicator plot value.
Please note plots set to transparent, and Indicators or Data Series with the "Display in
Data Box" parameter set to false will NOT be displayed in the Data Box.
The second image on the right shows a one minute Data Series in Panel 1 and a five
minute Data Series in Panel 2. However, the 14 period SMA (Simple Moving Average)
of the five minute Data Series is being plotted on top of the one minute Data Series in
Panel 1. Since the underlying Data Series of the SMA does NOT reside in Panel 1, the
SMA value is not associated to the one minute time stamp and thus the correct time
stamp is automatically added to the SMA plot name.
Show Indicator Labels Enables or Disables the display of the Indicator labels
Show Panel Numbers Enables or Disables the display of the Panel numbers
Font Sets the Data Box text font
The column splitter can be re-sized by hovering your cursor until the sizing arrows
appear. Once the sizing arrows are showing you can press down on your left mouse
button and drag the column splitter to the desired location and then release the left
mouse button.
9.6.11 Global Cross Hair
The Global Cross Hair allows you to link cross hairs from multiple chart windows. This
means that as you move the cross hair in one chart, all other cross hairs will move together
by automatically staying on the same time and price.
1. Left mouse click on the Cursor icon in the chart toolbar and select the Global Cross
Hair menu item.
2. Right mouse click within the chart and select the Cursor menu, then select the
Global Cross Hair menu item.
3. Use the default CTRL +G Hot Key
The cursor icon within the chart toolbar will change to the globe icon letting you know
that Global Cross Hair is enabled in the chart.
The images below show two ES charts, a 1 Min and 5 Min, both with Global Cross Hair
enabled. Notice the cross hair values in each chart are the same. The active cursor is
shown by diagonal dash marks around the cursor intersection as shown in the image
below left. When the cursor is moved, all cursors in charts with Global Cross Hair
enabled will move as well to stay on the same time and price.
If the the active Global Cross Hair moves outside the viewable horizontal range of
any other chart with Global Cross Hair enabled, the horizontal axis in the inactive
charts will automatically scroll to keep aligned with the active cursor. This can be
enabled/disabled in the Chart Properties window by setting the property "Global cross
hair time axis scrolling" to True or False.
Global Cross Hair may not be as useful when it is enabled in charts with large time
frame differences like a 1 Min and 60 Min chart. For each bar that is scrolled in the 60
Min chart, the 1 Min chart cursor will scroll 60 bars making it hard to follow.
The following chart properties are available for configuration within the Chart Properties
window:
Color for axis Sets the color for both vertical and horizontal chart axis
Color for Price markers display the current price of bars and indicators on the Y-
inactive price axis. When looking at the current bar, the price markers will take the
markers color of the data series. When scrolling back through historical bar
data, the markers are inactive (not real-time) and will be displayed by
the color set on this property
Date label Sets the format for displaying the date in the X-axis for daily bars
format for daily
bars
Date label Sets the format for displaying the date in the X-axis for monthly bars
format for
monthly bars
Date label Sets the format for displaying the date in the X-axis for yearly bars
format for yearly
bars
Equidistant bar Enables or disables plotting bars an equal distance from each other.
spacing Please see the "Working with Price Data" section of the Help Guide for
more information.
Horizontal grid Sets the drawing properties of the horizontal grid lines
lines
Plot horizontal Enables or disables the plotting of horizontal grid lines
grid lines
Plot vertical grid Enables or disables the plotting of vertical grid lines
lines
Vertical grid Sets the drawing properties of vertical grid lines
lines
Allow the Enables or disables the selection of Data Series and indicators for
selection or drag and drop
drag/drop of
chart series
Color for Sets the chart background color
background
Color for Sets the color for the cross hair label
crosshair label
Display update Sets the frequency the chart display is updated (A value of 200 ms or
interval (sec) less (0.2) will be CPU intensive and can adversely affect performance
especially in high volatile market activity.)
Global cross When true and global cross hair is enabled on multiple charts, the non-
hair time axis active chart will automatically scroll the horizontal axis to stay aligned
scrolling with the X-axis value of the active chart.
Label font Sets the font display properties for the chart
Right side Sets the spacing between the Y-axis and the current bar in pixels
margin
Show chart Enables or disables the Chart Trader order entry window for direct
trader trading from within a chart
Show scrollbar Enables or disables showing the horizontal chart scroll bar
Show toolbar Enables or disabled showing the chart tool bar
Defaults for the Chart Properties window can be saved by left mouse click on the "Set
Default" button. Please see the "Saving Chart Defaults" section of the Help Guide for
more information.
9.6.14 Power Volume Indicators
NinjaTrader includes several powerful real-time volume based indicators that give traders a
profile where trades are executing relative to the bid or ask.
BuySellPressure Indicator
The BuySellPressure indicator displays both the current bar's buying and selling pressure
as percentage values based on the categorization of trades as buy or sell trades. Trades are
categorized in real-time as a buy (at the ask or above) or as a sell (at the bid or below)....
Trades in between the market are ignored. This is a real-time indicator only. It functions only
on real-time data and therefore does not plot any values on historical data. If you change any
property, interval or instrument on a chart, this indicator will restart and any accumulated real-
time data plots will be lost.
BuySellVolume Indicator
The BuySellVolume indicator displays a real-time horizontal histogram of volume
categorized as buy or sell trades. Trades are categorized in real-time as a buy (at the ask or
above) or as a sell (at the bid or below) and then color coded .... Trades in between the
market are ignored. This is a real-time indicator only. It functions only on real-time data and
therefore does not plot any values on historical data. If you change any property, interval or
instrument on a chart, this indicator will restart and any accumulated real-time data plots will
be lost.
Data can also be reloaded by pressing the Reload All button in the Reload tab of the
Historical Data Manager. This will reload data from your data provider's servers for the active
instruments only, not the entire historical database in NinjaTrader.
Time Settings
Different session templates as well as the date range of data being plotted can affect the
chart display and indicator values.
Understanding the underlying base data type required for constructing various chart
bars
Tick
Volume
Range
Second
Renko
Minute
Day
Week
Month
Year
The base data is important to understand. If you are connected to a market data vendor
that does NOT support "tick data," you will NOT be able to build chart bars that use "tick
data" as its base data such as tick, volume, range or second charts. A matrix of
supported data vendors and their varying levels of service is located here.
Understanding why a chart can look different after reloading historical data from the
server
As ticks come into NinjaTrader in real-time, they are time stamped based on your local
PC time if they do not already have an associated time stamp that is provided from the
real-time data source. The majority of our supported brokerage feeds DO NOT time
stamp ticks, where most of our supported market data vendor feeds do provide time
stamped ticks. NinjaTrader then builds bars based on the time stamp of the incoming
tick and displays these bars in your chart in real-time.
Let's say you have a tick (tick "A") with a time stamp of 10:31:00 AM which gets
packaged into the 10:32:00 AM bar and happens to be the high of that bar. An hour later,
you reload historical data from your historical data provider into NinjaTrader. This
process will overwrite the existing data. The 10:32:00 AM bar now looks different since
the high made by TICK "A" is now part of the prior bar, 10:31:00 AM. How is this
possible?
Your PC clock could have been off so the time stamp is delayed
Your internet may have been lagging so the tick came in slightly delayed and therefore
the time stamp is delayed
Due to standard latency, even 50ms delay (which is normal) could be the difference
between a 10:30:59 and 10:31:00 time stamp
There is no way of knowing how the historical data provider packages their bars
The only way to ensure that data always looks the same is if every connectivity provider
sent ticks with time stamps AND that all vendors synchronized on time stamps.
Unfortunately, this is just not a reality nor plausible scenario.
Example: Data feed bar is currently timestamped as 4:26PM. Local PC clock is 4:21PM.
When a market order is placed under the above situation, the trade execution will occur at
4:26PM prices, but be shown on the chart at 4:21PM.
To prevent these types of issues please ensure your local PC clock is in sync with your data
feed. Please reference the Historical & Real-Time Data chart to see if your data provider
timestamps their data or if the data is timestamped locally by your PC clock. It is important to
maintain a sync between your PC clock and the data feed's timestamping.
Example: Many ticks occurred on the 16:35:54 timestamp seen in the x-axis below the chart.
Trade execution was at price 1058.75 on 16:35:54.
Since the execution occurred on 16:35:54 it is plotted on the first bar with the same
timestamp. In this particular case, the first bar was not at the same price as the execution
price so it would appear to be filled outside of the bar. Checking bars being plotted later on we
find that 1058.75 was a valid price for timestamp 16:35:54 and that this execution was in fact
on a valid price.
The Control Center can be broken down into three sections. The menu system, the
information tabs, and the status bar.
New Creates new function windows such as charts and order entry windows
Workspace Creates and manages workspaces
s
Connect Establish a connection to a connectivity provider
Disconnect Disconnects an established connection
Flatten Flattens all open positions and cancels all working orders across all connected
Everything accounts
The "Flatten Everything" function is not guaranteed. (See the "Risks of Electronic
Trading with NinjaTrader" section of the Help Guide)
The "Flatten Everything" function is also accessible via the right mouse click
context menu of all order entry windows
AT Interface Enables or disables the automated trading interface
Global Enables or disables global simulation mode
Simulation
Mode
Utilities Utility functions such as import and export of NinjaScript files
Order Grid
The order grid displays detailed information regarding the current day's orders. The grid
is also active in that you can modify an order directly in it. The active order's State cell
will be color coded for ease of use.
1. You can modify the quantity and/or price of an order by double left clicking your
mouse in either the Qty, Limit or Stop value fields of an active order and either
pressing the Enter key or clicking in another cell.
2. You can increase the price of an order by one tick by pressing the "+' button. Holding
the CTRL key down will modify the order by 5 ticks, ALT key by 10 ticks.
3. You can decrease the price of an order by one tick by pressing on the "-" button.
Holding the CTRL key down will modify the order by 5 ticks, ALT key by 10 ticks.
4. You can cancel an order by pressing on the "X" button.
Order Entry
The order entry section allows you to submit orders. The image below shows the order
entry section which shows a different background color when a simulation account is
selected than a live account.
Submitting Orders
To submit an order:
Order Parameters
* OCO is an order property that groups orders together by a common user defined id. If
one order in the group is either filled, cancelled or rejected, all orders in the group with
the same OCO id will be cancelled.
Market Display
The market display section shows market data for the currently selected instrument
from the order entry section. (See the section above).
Strategy Display
Active and stopped strategies are listed as a grid and can be started/stopped by left
Strategy Performance
While the Account Performance tab will generate performance report against your
account's trade history, the Strategy Performance menu allows you to generate a
performance report against the trades generated by the selected strategy.
Real-time - Generates performance data for your real-time trades only (since the
strategy started running) and will exclude historical trades. If your strategy held a virtual
position (calculated against historical data) upon starting, a virtual execution
representing the average price of this position will be injected into the real-time results to
ensure that a trade pair can be created with the executions resulting from the closing of
this position.
Historical & Real-time - Generates performance data for both historical and real-time
trade data.
Forex Executions
Executions done on currency pairs that do not contain USD will try to grab a conversion
rate in real-time shown in the "Rate" column from your data provider. Should a suitable
USD conversion rate not be available, a rate of 1 will be used. This rate will be used in
determining the PnL in USD for the forex trade in other areas like the Account
Performance tabs. The approach NinjaTrader follows is the GAIN Capital approach, but
may differ from what GFT and banks do since they base their conversion rates off of the
prior session's closing price of the currency pair. This means that our calculation
approach may result in slightly different PnL values than the ones reported from your
brokerage.
Adding Executions
There may be situations where you will want to manually add a historical execution to
the database. Historical executions are used to generate performance data in the
Account Performance tab. If an execution is missing, the performance data will be
incorrect. This could happen since not all brokers provide historical execution. Let's say
you placed a good till cancelled (GTC) order on Monday, did not connect on Tuesday at
which time your order filled, then connected NinjaTrader on Wednesday, NinjaTrader
would never receive the execution report for Tuesday's order fill. You would then have to
add this historical execution to the database if you want your performance reporting to
be accurate.
1. Right mouse click in the Executions tab and select the Add... menu item. The Add
Execution window appears.
The execution is now added to the database and will be used in performance reporting.
Positions Display
Open positions are displayed in the data grid.
Close Flattens the currently selected position in the grid and cancels any working
Position* orders associated to the position's instrument
Flatten Flattens all open positions and cancels all working orders
Everything*
Filter By Sets which positions to display by account
Account
Grid Sets the grid properties
*The Close Position and Flatten Everything functions are not guaranteed. (See the "Risks
of Electronic Trading with NinjaTrader" section for more information)
9.7.8 Accounts Tab
The Accounts tab displays current account information in a data grid. The account values
that are displayed or not displayed is dependant on your connectivity provider. Not all
connectivity providers transmit complete account data. Some transmit partial account data
while others do not transmit anything.
Performance Report
To generate a performance report:
Performance data is generated and displayed in the various Performance Data Tabs.
Note: It is possible to have trades before the From date being listed in your report.
NinjaTrader generates reports from the last time you were flat. If a particular instrument
was already in the middle of a position at the beginning of the From date, NinjaTrader will
report all trades prior to this date up to the point where the position was flat. This will
ensure you have a complete picture in terms of your performance on any specific date
instead of "jumping" into the middle of a position which may cause inaccurate overall
performance.
Advanced menu
Pressing the Advanced button will expand the Performance tab to include advanced
parameters that you can filter your performance reports by. Unchecking any of the items
will activate the filtering of your Performance Report. This filtering is done on an
executions basis and not a trades basis.
Comparison examples:
Time frame based (current week compared to last week)
Account based (simulation account compared to live account)
Instrument based (S&P Emini compared to Dow Mini)
Instrument type based (equities compared to futures)
Template based (strategy x compared to strategy y)
The performance data tabs display historical trade performance data. This performance data
can be accessed from the following locations:
Summary Tab
The Summary tab displays performance statistics.
Chart Tab
The Chart tab is visible in the Strategy Analyzer and via the Strategies tab menu
Strategy Performance. It is used to display historical backtested trade data in the
Strategy Analyzer and historical and/or real-time trades in the Performance window.
Strategy trades are connected by lines that can be configured via Chart properties. You
can quickly jump to the next trade in time by pressing the CTRL + Arrow Right key
combination. CTRL + Arrow Left key combination will jump in the other direction.
Graphs Tab
The Graphs tab displays graphs of various trade statistics which are found under the
Graph drop down menu. Graphs can be filtered by Long/Short trades and Winning/
Losing trades using the respective drop down menus.
Executions Tab
The Executions tab displays all historical executions in a data grid. You can go to the
exact chart location of an execution by doing the following:
NinjaTrader will open a chart to the location of the execution. This will only work if you
have access to historical data via a connection or in your local database.
Trades Tab
The Trades tab displays all historical executions in a data grid. You can go to the exact
chart location of an execution by doing the following:
NinjaTrader will open a chart to the location of the trade. This will only work if you have
access to historical data via a connection or in your local database.
From the Trades tab you can also run Monte Carlo simulations by right mouse clicking
on a trade and selecting the menu item Monte Carlo Simulation...
Periods Tab
The Periods tab displays performance data in a data grid based on various time
periods.
Orders Tab
The Orders tab displays all historical orders in a data grid.
Journal Tab
The Journal tab is only visible in the Performance tab of the Control Center window.
The Journal tab allows you to keep journal entries on your trading activities. Enter your
comments in the text area and press the OK button. The data grid will display your
journal entries.
Following are the formulas for the calculation of some of the efficiency performance graphs.
(maximum price seen - entry price) / (maximum price seen - minimum price seen)
= (130 - 100) / (130 - 90)
= 75%
(exit price - minimum price seen) / (maximum price seen - minimum price seen)
= (110 - 90) / (130 - 90)
= 50%
= The exit took 50% of the available trade range
(exit price - entry price) / (maximum price seen - minimum price seen)
= (110 - 100) / (130 - 90)
= 25%
= The trade represented only 25% of the trade range
The following are definitions and formulas used for Account Performance statistics:
Average ETD
This statistic returns a value that is useful in giving you a measure of how effective your
exit conditions capture the price movements after your strategy enters a position. It
shows you how much you give back from the best price reached before you exit the
trade. A small number here is generally desirable since it would imply highly optimized
exit conditions that capture most of the price movement you were after.
Average MAE
This statistic returns a value representing the average maximum run-down your strategy
experiences. This information helps you gauge how poorly your strategy’s entry
conditions predict upcoming price movement directions. A low percentage here is
desirable since it would imply that the price movement after you enter a position follows
the direction of your intended trade.
Average MFE
This statistic returns a value representing the average maximum run-up your strategy
experiences. This information helps you gauge how well your strategy’s entry conditions
predict upcoming price movements. A high percentage here is desirable since it would
imply high profitability opportunities.
Average Trade
This statistic returns a value representing the average profit you experience from all of
your trades. It is useful for getting an idea of how much you could expect to earn on
future trades.
Understanding Commission
Commission
This statistic returns a value that is the sum of all the commission fees associated with
the trades executed by the strategy.
cumulative profit
This statistic returns a value representing a summation of all the profits earned by all
your trades. It can be interpreted as a performance measure for your strategy.
Gross Loss
This statistic returns a monetary value representing a summation of all the money lost
across all your trades with your strategy.
Gross Profit
This statistic returns a monetary value representing a summation of all the money
earned across all your trades with your strategy.
Max. Drawdown
The maximum drawdown statistic provides you with information regarding the biggest
decrease (drawdown) in account size experienced by your strategy. Drawdown is often
used as an indicator of risk.
size
Max Drawdown = single largest Drawdown
As an example, your account rises from $25,000 to $50,000. It then subsequently drops
to $40,000 but rises again to $60,000. The drawdown in this case would be $10,000 or -
20%. Take note that drawdown does not necessarily have to correspond with a loss in
your original account principal.
Profit Factor
This statistic returns a ratio that can be used as a performance measure for your
strategy. It gives you an idea of how much more money your strategy earns then it
loses. A higher ratio can be considered characteristic of a high performing strategy. A
ratio less than one indicates your strategy loses more money than it earns.
Sharpe Ratio
This statistic returns a ratio that measures the risk premium per unit of risk of your
strategy. It can help you make decisions based on the excess risk of your strategies.
You may have a high-return strategy, but the high returns may come at a cost of excess
risk. The Sharpe ratio will help you determine if it is an appropriate increase in risk for the
higher return or not. Generally, a ratio of 1 or greater is good, 2 or greater is very good,
and 3 and up is great.
Note:
NinjaTrader presets "risk free Rate of Return" to a value of zero
In the event that there is only 1 month of trade history or less, there is insufficient data
to calculate the monthly standard deviation of profits in which event, the Sharpe Ratio
is set to a value of 1
(See the Profit Per Month statistic above for its definition.)
9.7.10 Log Tab
The Log tab displays historical application and trading events for the current day in a data
grid.
Log Display
There are various options for displaying log information that can be set via Log tab of the
Options menu of the Control Center window. Log events are categorized and color coded
based on four distinct alert levels; Information, Warning, Error and Alert.
Each log event is displayed by date, category and message. In some cases, the length of the
message may be larger than the width of the "Message" column. In this situation, you can
hover your mouse above the message in order to have it display in a pop-up type window.
Data Grids
With a data grid you can:
Moving Columns
To adjust the order of columns within a data gird, left mouse click on the column title and drag
it to the location you wish to place the selected column. Two red arrows will appear above
and below the column title (see image below) showing where the column will now be located.
Release the mouse button to place the column in the new location.
Note: Dragging a column outside of the window will remove the column from the data grid.
Grid Properties
Selecting the Properties menu item of the right mouse click menu will open a grid properties
window. In this window you can choose which columns you wish to show (make visible). Any
column name with a check-mark next to it will be visible and un-checking a column name will
take the column out of the data grid.
Real
Instr
Historic Historic Historic - Real
Connec Historic ume
Real- Historic al Bid/ al Bid/ al Bid/ Historic Tim -
tivity al nts
Time al Tick Ask Ask Ask al Daily e Time
Provide Minute Sup
Data Data Minute Daily Tick Data Tim New
r Data port
Data Data Data esta s
ed
mp
Kinetick YES YES YES
www. (subscri (subscri (subscri Nativ E, F,
NO NO YES YES YES
kinetick. ption ption ption e FX, I
com only) only) only)
BarChar YES YES NO NO NO YES YES Nativ E, F, NO
t e FX, I
Nativ E, F,
eSignal YES YES NO NO YES YES YES YES
e FX, I
YES YES YES
GAIN (With (With (With
YES (24 YES (24
Capital/ NT NT NT Loca
YES hours hours NO FX NO
FOREX. server server server l
back) back)
COM selected selected selected
) ) )
Google NO NO NO NO NO NO YES --- E NO
YES YES
Interacti
(live (live Loca E, F,
ve YES NO NO NO NO NO
account account l FX, I
Brokers
only) only)
Nativ E, F,
IQFeed YES YES NO NO NO YES YES YES
e FX, I
MB Loca E, F,
YES YES NO NO NO YES YES NO
Trading l FX, I
Patsyste Loca
YES NO NO NO NO NO NO F NO
ms l
Nativ
PFG YES YES NO NO NO YES YES F, FX NO
e
TD
Loca
Ameritra YES NO NO NO NO YES YES E, I YES
l
de
TrackDa Loca E, F,
YES YES NO NO NO YES YES NO
ta l I
TradeSt E, F,
YES NO NO NO NO YES NO --- NO
ation FX, I
Trading
Loca
Technol YES YES YES YES YES YES YES F NO
l
ogies
Vision
Nativ
Financia YES YES YES YES YES YES YES F NO
e
l
Loca
YAHOO NO NO NO NO NO NO YES E NO
l
Nativ
Zen-Fire YES YES YES YES YES YES YES F NO
e
E = Equities
F = Futures
FX = Forex
I = Indexes
1. The End date parameter of the Data Series window contains the current day
2. The End date parameter of the Data Series window contains the last day of data
available in your data repository
3. The data repository contains no data within 3 days of the first day loaded in the chart
Examples of when NinjaTrader will fetch data if the data repository contains data from
1/3/08 to 1/6/08 and the current date is 1/7/08:
1. Chart of 1/3/08 to 1/7/08 -> load data request for 1/7/08, use data stored in data
repository/cache for other dates
2. Chart of 1/3/08 to 1/6/08 -> load data request for 1/6/08, use data stored in data
repository/cache for other dates
3. Chart of 1/3/08 to 1/5/08 -> use data stored in data repository/cache for all dates
4. Chart of 12/28/07 to 1/5/08 -> load data request for all dates
To minimize the need to load data and to speed up chart load times, NinjaTrader
maintains an internal cache of your prior accessed data. When data is in this cache,
NinjaTrader will use it to populate your charts instead of loading from your data provider.
There are two ways to ensure that the internal cache contains data for your instrument
of interest:
1. Open and maintain a chart of any time frame containing the instrument
2. Load the instrument into a Market Analyzer window along with an indicator column
The Market Analyzer option is not as viable since it only maintains a 100 bar cache as
a default setting that can be changed. Since 99% of all charting requests consist of
much more than 100 bars, they will most likely incur a data load.
Note: The internal cache is managed by the .NET framework so it is unpredictable when
the .NET runtime will clear it. In most cases, as long as you have at least one chart of
your instrument open, the instrument’s data cache will persist.
If you are using a market data vendor where you often see data spikes come in
If you trade primarily equities
If you are running automated strategies where data spikes have implications
For example:
Day 1: $9.25
Day 2: $9.75
Day 3: $10.50
Day 4: $10.50 (the ex-day is not adjusted)
NinjaTrader stores historical data in it's local data repository in an unadjusted state
If the data provider provides adjusted data, NinjaTrader will convert the data into it's
unadjusted state prior to local storage
Merge Policy
The Merge policy option can be found in the Data tab of the Options menu and sets
how NinjaTrader handles the merging of historical data for futures contracts.
MergeBackAdjusted
Selecting this option uses data from each individual expiry month across the time span
of the historical data requested. Offset* values will also be used to back adjust the
historical data to match the next front month.
For example: If requesting a chart of the ES 09-10 from June 1st through July 1st, two
contract months were the front month during that time span (06-10 and 09-10). The 06-
10 data will be merged with the 09-10 data and an Offset value will be used to connect
the last 06-10 contract data point with the first 09-10 contract point. The result is a
continuous chart of ES front month data for the dates selected.
*More information on Offsets can be found in the Editing Instruments section of the Help
Guide.
MergeNonBackAdjusted
Selecting this option uses data from each individual expiry month across the time span
of the historical data requested. Offset values are NOT used and leaves historical data
as raw data.
For example: If requesting a chart of the ES 09-10 from June 1st through July 1st, two
contract month were the front month during that time span (06-10 and 09-10). The 06-10
data will be merged with the 09-10 data; however, NO Offset value will be applied. The
result is a continuous chart of ES front month data for the dates selected.Significant
price gaps in the chart may be present due to changes in contract values that were NOT
Offset.
DoNotMerge
Selecting this option will not merge any data and only show historical data for the front
month selected.
For example: If requesting a chart of the ES 09-10 from June 1st through July 1st, two
contract month were the front month during that time span (06-10 and 09-10). The 06-10
data will NOT be merged and only data for the 09-10 contract will be used. The result is
a chart that goes as far back as there is data for the selected front month, which may be
less than the requested date range.
Importing
Exporting
Editing
Download
9.10.1 Importing
Historical data can be imported from a text file with a ".txt" extension within the Import tab of
the Historical Data Manager. Several formats and data types are supported and
NinjaTrader can optionally build 'Minute' bars from tick data as well as 'Day' bars from tick
or minute data.
The following formats and options are available when importing a text file:
Format:
Select one of three options available in the Format drop down menu:
1. MetaStock - Select this option if importing a MetaStock historical data text file
2. NinjaTrader (timestamps in import file(s) represent end of bar time)
3. NinjaTrader (timestamps in import file(s) represent start of bar time)
Data Type:
Select one of three options available for the data type:
1. Ask - Data values in the text file represent historical Ask prices
2. Bid - Data values in the text file represent historical Bid prices
3. Last - Data values in the text file represent historical Last prices (trades)
File Name
When using the NinjaTrader format, the name of the text file to be imported must be the
NinjaTrader instrument name followed by a period and "Last", "Bid", or "Ask" depending
on the data type. For example:
Tick Format
Each tick must be on its own line and fields must be separated by semicolon (;).
Sample data:
20061107 000431;1383.00;1
20061107 000456;1383.25;25
20061107 000456;1383.25;36
20061107 000537;1383.25;14
Sample data:
20061023 004400;1377.25;1377.25;1377.25;1377.25;86
20061023 004500;1377.25;1377.25;1377.25;1377.25;27
20061023 004600;1377.25;1377.25;1377.25;1377.25;24
20061023 004700;1377.50;1377.50;1377.25;1377.25;82
Sample data:
20061023;1377.25;1377.25;1377.25;1377.25;86
20061024;1377.25;1377.25;1377.25;1377.25;27
20061025;1377.25;1377.25;1377.25;1377.25;24
20061026;1377.50;1377.50;1377.25;1377.25;82
Importing Tips
Please review the following before importing:
If you are importing historical data for a futures or forex instrument, the instrument
MUST exist in the Instrument Manager. If it does not, you must add it first
Any data imported where the instrument does not exist in the Instrument Manager
will automatically be imported as a "Stock" instrument type
Data points will be rounded to the instruments tick size as it is imported if the price is
not evenly divisible by the instrument's tick size
Imported data, regardless of time zone, will be converted to the local time zone.
1. Choose the Format and Data type that correctly represent the data in the import file
(see the "Understanding the import options" section above)
2. Optionally select any of the Generate... choices to have NinjaTrader create other bar
types from the import data
3. Select the Time zone of imported data
4. Press the Start Import button
5. Select the text file from your PC to import and press the "Open" button.
NinjaTrader will attempt to import the text file. If successful, a window will appear
confirming this. If unsuccessful, an error window will appear and you should check the
Log tab of the Control Center to view the error.
To download historical data from TradeStation for import into NinjaTrader, open a chart
in TradeStation and open the Format Symbol window.
Futures Note: If you want to download historical futures data, use the TradeStation
continuous contract such as "@ES". Once imported into NinjaTrader, it will be mapped
to the closest individual contract. If the current month is November, 2009, data would be
mapped to the December contract which is "ES 12-09".
This import procedure will allow you to construct charts in NinjaTrader that use minute
bars. Tick or daily bars can not be constructed from this procedure.
9.10.2 Exporting
Historical data stored within NinjaTrader can be exported to a text ".txt" file. This is done within
the Export tab of the Historical Data Manager window.
1. Left mouse click on the plus "+" button to the left of the Data Series you wish to export data
from. The data type(s) "Ask," "Bid," or "Last" are displayed if that type of data is available.
2. Left mouse click on the plus "+" button to the left of the "Ask," "Bid," or "Last" data type you
wish to export. The data type(s) "Tick," "Minute," or "Day" are displayed if that type of data
is available. The date range of the data is displayed to the right of the data type.
3. Left mouse click to select the "Tick," "Minute," or "Day" data type you wish to export.
4. In the right pane, select the desired Start date and End date for the export file and press
the Export button.
5. Select a location to create the export file and press the Save button.
The historical data is exported with End of Bar time stamps to the chosen folder as a text file
in the same format specified in the "Understanding import file and data formats" section of
the Importing page.
9.10.3 Editing
Historical data saved in NinjaTrader can be edited via the Edit tab of the Historical Data
Manager.
Left mouse click the plus "+" button to select the Instrument node, "Ask," "Bid," or "Last
," the data type, and the data date. The bar data appears in the right section. (Marker #1
in the image below)
Changing data - Double left mouse click on a cell in the Open, High, Low, Close or
Volume column to edit the data value. (Marker #2 in the image above)
Adding data - Left mouse click on a row to select it. Then right mouse click to access
the options to Add a new data row. (Marker #3 in the image above)
Excluding data - Right mouse click on the desired row and select the menu item
Exclude to exclude the data. Excluded data is data that is intentionally ignored and not
used. NinjaTrader will remember this excluded data on a historical data reload.
(Marker #3 in the image above)
Grid properties are also available at the bottom of the right click context menu.
Any changes that are made are both color coded as well as shown in the Status
column. (Marker #4 in the image above)
Once the desired changes are made, press the Save button to save the changes within
NinjaTrader.
Note: If more than one row contains the same Date, Time and price values, all similar
rows will be edited.
Excluding Data
The image below shows what happens when the selecting the row is Excluded. Since
the two rows above the selected row have the same value in the Date, Time, and Price
columns, they were automatically Excluded by NinjaTrader.
The Edit Logs node contains all edits made to historical data for a specific instrument.
Edits can be undone by right mouse clicking on the change you wish to undue and
selecting the menu item Remove (change). All edits can be removed by right mouse
clicking over the edit node and selecting the menu item Remove All Edits.
Historical & Real-Time Data" section of the Help Guide for more information. If you do
not have data, it can be downloaded from your data provider if they offer it by using the
Download tab of the Historical Data Manager.
1. Left mouse click on any node available in the Edit tab of the Historical Data
Manager to select it.
2. Right mouse click and select the menu item Delete or press the 'Delete' key on your
keyboard to delete all data contained in the node.
Note: Deleted historical data will be replaced when data is reloaded from the connectivity
provider. Please see the "Excluding Data" sub-section of the "How to edit historical data"
section above for more information on excluding data, which will remain excluded when
reloading data from the data provider.
9.10.4 Download
Historical data can be downloaded from the data provider via the Download tab.
1. Make sure NinjaTrader is connected and historical data is available from your data
provider
2. Left mouse click the plus "+" button to select the instrument from the available instrument
lists
3. Select the desired Start and End date range of the data to be downloaded
4. Select the desired Intervals and Data Types of the data to be downloaded
5. Press the Download button to begin the download
A message in the right section of the Download tab will appear saying, "Download in
progress... Please see the Control Center Status Bar for progress update." The download
progress will be shown in the lower right hand corner of the Control Center.
NOTE: If you already have historical data for an instrument, please be sure to only select a
date range in which your data provider offers historical data. If you choose a range older than
what your data provider offers you may lose any data you had stored on those dates in that
range outside of what your data provider offers.
Active Window
The Active Window section displays a list of NinjaTrader windows where Hot Keys can
be assigned. Please see the "Understanding when Hot Keys are active" section of this
page for more information on the active window.
Available Actions
The Available Actions section displays the actions available for Hot Key assignment
within the selected active window.
1. Left mouse click in the action field where you want your Hot Key assigned.
2. Left mouse click on the drop down arrow that appears in this field.
3. Select a Modifier.
4. Select a Key and press the OK button.
Note
Make sure you are not assigning the same Hot Key to two different actions that can be
invoked simultaneously. You will be asked to reassign the Hot Key if you do.
1. Left mouse click in the action field where you wish to remove the Hot Key and select
the drop down arrow. Then left mouse click on the Remove button.
2. Select the action field where you wish to remove the Hot Key then right mouse click
and select the Remove Hot Key menu item.
Hot Keys are window sensitive. This means that Hot Keys will only work when the
active window is selected. The name of the window that needs to be active is located in
the left column of the Hot Key Manager.
Global
Hot Keys assigned under the Global section are always active regardless of the active
NinjaTrader window with the exception of the modal form having focus. See the "
Understanding the risks in using Hot Keys for order entry" section of the Trading with
Hot Keys page of the Help Guide for more information on the modal form exception.
Grid
Hot Keys assigned under the Grid section are active whenever a window with a grid is
selected. Examples of these are Market Analyzer or the Orders tab of the Control
Center.
Order Entry
Hot Keys assigned under the Order Entry section are active whenever an order entry
window is selected. Please see the Trading with Hot Keys section of the Help Guide for
more information on this topic.
Active Window
You must always be aware of the current active window when using Hot Keys for order
entry. Order entry Hot Keys are window sensitive and will only execute an action to the
active order entry window. Please see the "Understanding where Hot Key order entry is
active" section on this page for more information on this topic.
The screen capture below to the left shows the SuperDOM as the active window
whereas the screen capture in the lower right shows the Chart with Chart Trader as
the active window. If you had placed an order using a Hot Key when the SuperDOM
was active, you would have placed an order to the ES 09-09. If you had placed an order
using a Hot Key when Chart Trader was active, you would have placed an order to the
NQ 03-10. It is important to always be aware of the active window when using Hot Keys
to submit orders.
Buy Ask Submits a buy limit order at the current ask price
Buy Bid Submits a buy limit order at the current bid price
Buy Market Submits a buy market order
Sell Ask Submits a sell limit order at the current ask price
Sell Bid Submits a sell limit order at the current bid price
Sell Market Submits a sell market order
Breakeven Modifies your stop loss order to your break-even price for the ATM Strategy
ATM on the active window
Strategy
Breakeven Modifies any stops to your break-even price for any open position.
Position
Cancel last Cancels the last submitted order
Order
Close ATM Cancels any pending orders and exits any open positions activated by an
Strategy ATM Strategy
Close Closes any open position on the active order entry window
Position
Decrease Decreases the price of the last submitted pending order by one tick
Last Order
Price
Increase Increases the price of the last submitted pending order by one tick
Last Order
Price
Modify Last Modifies the price of the last submitted pending order by 15 ticks past the
Order to Fill last traded price in order to fill the order.
Reverse Closes your open position and any related ATM orders and submits a
market order in the opposite direction to reverse your open position.
Searching Instruments
To search for an instrument within the database:
1. From the Instrument Manager, select an available instrument type using the Type drop
down menu.
3. Left mouse click on the Search button. All instruments that match the search parameters
will appear in the instrument data field.
The image below displays the results of searching for any Futures beginning with the letter
"E" as inputted in the Name search field.
You can double left mouse click on any search result to bring up the Instrument Editor
window for the selected instrument. Please see the Editing Instruments page for more
information on how to edit instruments.
1. Create a connection to Yahoo. See the Connection Guide for more information on creating
a free Yahoo account connection.
2. Connect to Yahoo by left mouse clicking on the menu File and selecting the menu item
Connect. Then select your Yahoo connection.
3. Open the Instrument Manager by left mouse clicking on the menu Tools and select the
menu item Instrument Manager
4. Select the stock that you wish to update with historical split and dividend data
5. Press the Edit button to bring up the Instrument Editor window
6. Select the Misc tab and scroll down to the bottom section Splits & Dividends
7. Press the Update splits & dividends button
NinjaTrader will now request historical splits and dividend information from Yahoo! Finance
and populate the information in your local database.
NOTE: The Update splits & dividends button only appears when connected to a provider
(Yahoo) that supports historical splits and dividend data.
9.12.3 Editing Instruments
The Instrument Editor displays all parameters that define an instrument including symbol
mappings to your connectivity provider and symbol level commission values. The editor
allows you to change or add parameters to an instrument's profile. In general, instruments
that are installed with NinjaTrader do not require any parameter modification. However, you
may want to override your global commission settings if a particular symbol has a unique
commission structure.
In the Instrument Manager, once an instrument is selected in the instrument grid, you can
double left mouse click or press the Edit button to open the Instrument Editor.
Definition Tab
The Definition tab displays parameters that uniquely define an instrument.
value
Margin The margin required for backtesting this instrument
value
Sim feed The starting price for the internally generated data feed (Simulated Data Feed
start priceconnection)
Merge The merge settings applied to historical data. (See the Data Tab section of
policy the Help Guide for more information on merge policies and to set the global
merge policy)
Session Sets the default session template for the instrument. (See the Session
template Manager section of the Help Guide for more information)
Descriptio Description of the instrument
n
URL The website address of the instrument definition
Exchange Sets the exchange that the instrument is traded on
s
Misc Tab
The Misc tab allows you to set instrument level commission settings, symbol mappings,
and split and dividend information
Commission Section
Instrument level commission values override global commission settings. An example
would be if you have a standard commission rate from your broker for most instruments
but there may be an exception where your rate is different for the DOW Emini contract.
You would then set the custom DOW Emini contract commission rate at the instrument
level. Please see the Commission Tab section of the Help Guide for more information on
setting up commission levels.
Symbol Mapping
If you add a new instrument that is not already in the NinjaTrader instrument database,
you will need to map the new instrument to the symbol used for the connectivity provider
(broker or data feed) that you will be requesting data from. Most instruments in the
database are already mapped.
Contract Months
The Contract months section shows the contract months with associated rollover
dates. This information is automatically downloaded from the NinjaTrader server
whenever you are connected to your live data feed or the Simulated Data Feed. The
Contract month, Rollover date, and Offset values are used when NinjaTrader
automatically merges historical data.
You can open up the defined contract months by left mouse clicking in the Contract
months field and selecting the "..." button that appears. The Contract month and
Rollover date can be set.
Offset Value
The Offset value is used to connect the last value of a contract month with the next
one.
Although NinjaTrader will attempt to download the Offset values from the data server, if
they do not exist on the data server, they will be calculated locally. Offsets are only
downloaded when the "Offset" field is left blank and the rollover date matches the date
defined on the server.
Use the old and new expiry’s daily price data for calculations
If daily data does not exist, use minute data
If minute data does not exist, default Offset value will be 0
One day prior to the rollover date, calculate the difference between the close price of
the new expiry and the close price of the old expiry. This is the Offset value.
If you wish to overwrite the calculated Offset value you can input in your own
When using minute data, the close price at the ending time as defined in the
default session template for the instrument will be used
Note: If you inputted your own Offset value, it will be overwritten by values downloaded
from the data server if it exists there. To prevent this you will need to ensure that your
rollover date is not the same as the ones coming from the data server.
Note: The rollover date is the date to roll into the selected contract month and NOT out
of.
Manager. Please see the Commission Tab section of the Options menu for more
information on setting up commissions.
9.12.5 Instrument Lists
There are several uses for an instrument list:
Instrument Lists
The collection of instruments that comprise a list is displayed in the left pane of the
Instrument Manager.
Adding an Instrument
To add an instrument to an instrument list:
The instrument is added to the instrument list and will now be available throughout the
NinjaTrader application.
Removing an Instrument
To remove an instrument from an instrument list:
1. Left mouse click on the instrument you wish to remove from the instrument list in the
left pane of the Instrument Manager.
2. Press the right arrow button
9.12.6 Manage Database
NinjaTrader installs with a predefined database of commonly traded instruments. There will
be rare occasions where you may need to add a new instrument to the database.
Adding an Instrument
Equities can be alternatively added by typing the symbol name into an open chart or Market
Analyzer and pressing the "Enter" key on your keyboard. Please see the "How to change a
Data Series" section of the Working with Price Data page of the Help Guide for more
information.
Deleting an Instrument
1. From the NinjaTrader Control Center window select the menu Tools and select the
Instrument Manager menu item.
2. Highlight the 6E contract from the main grid which is the NinjaTrader Euro FX contract
* The symbol map name "EC" in the image below needs to be the TradeStation symbol
base name.
This procedure would be repeated for any other symbols you wish to map between
TradeStation and NinjaTrader.
For automatic mapping, follow the instructions above for "How to map an individual
futures contract" otherwise follow the instructions below.
If you run the TradeStation Automated Trading Interface through the email protocol or
want to use the NTExternalFeed strategy to drive NinjaTrader Simulation Edition with a
TradeStation continuous contract, follow the instructions below. We will use the "@ES"
continuous contract symbol and front month of March 2009 for example purposes.
1. From the NinjaTrader Control Center window select the menu Tools and select the
Instrument Manager menu item.
2. Highlight the 6E contract from the main grid which is the NinjaTrader Euro FX contract
3. Press the Edit button to bring up the Instrument Editor window
4. Select the Misc tab
5. Next to External set the value to "ES|03-09"
6. Press the OK button
* The symbol map name "ES|03-09" in the image below needs to be the TradeStation
symbol base name.
Automated Trading Interface - Orders generated for "@ES" will now be routed to the
NinjaTrader "ES 03-09" contract.
NTExternalFeed strategy - Data from your "@ES" chart will be sent to the NinjaTrader
"ES 03-09" contract.
Please remember to change this when the contract rolls over. If your system is trading
on the "ESH09" symbol you could just leave the symbol mapping in NinjaTrader to "ES"
instead of the "ES|03-09" as shown above.
1. Within the Control Center window select the File menu. Then select the menu item
Utilities and left mouse click on the menu item Import Stock Symbol List...
2. Press the Load button to open a text file that contains your symbol list or type each symbol
into the editor manually
1. Select the Tools menu within the Control Center followed by the Instrument Manager
menu item
2. Left mouse click on the expired contract in the list to the left within the Instrument
Manager window
3. Press the > button to remove the expired contract from the instrument list
4. Press the < button to add the current contract to the instrument list
NOTE: You must select the current contract within a chart for the new contract data to load
9.13 Level II
The Level II window displays bid and ask data color coded by price. It is used to gauge
strength and depth on either side of the market. Each price row in the Details section shows
a Market Maker or ECN for that price level. For non-Nasdaq stocks, market depth is displayed
for the regional exchange the market is traded.
Quotes
The Quotes section displays various market data items. You can add or remove items
by clicking on your right mouse button within the Quotes section and selecting the
menu Grid > Properties... You can disable the Quotes section by clicking on your right
mouse button and deselecting the menu item Show Quotes.
Summary
The Summary section displays total size per price level.
You can change the graph type via the Level II properties dialog window. You can disable
the Summary section by clicking on your right mouse button and selecting the menu
Show Summary.
Details
The Details section displays bid data on the left and ask data on the right.
You can disable the Details section by clicking on your right mouse button and de-
selecting the menu item Show Details.
The following properties are available for configuration within the Level II Properties
window:
Property Definitions
# of price levels (Details) Sets the number of visible price levels in the details
section of the Level II window
# of price levels (Summary) Sets the number of visible price levels in the summary
section of the Level II window
Font Sets the font options
Graph Graphs the total size at a price level or depth which is
number of market participants
Size divided by 100 Displays the the size column values divided by 100
Color for price level X Sets the back ground color for a specific price level
Back color for tracked market Sets the back color for tracked market makers
makers
Fore color for tracked market Sets the fore color for tracked market makers
makers
If you change your settings and later wish to go back to the original settings, you can left
mouse click on the "Reset" button to return to the original settings.
Management Conditions
Creating Alert Conditions
Working with Instrument Rows Cell Conditions
Working with Columns Filter Conditions
Dynamic Ranking and Sorting
Templates Performance
Properties Tips
Reloading Indicators & Columns
NinjaTrader does not limit the number of Market Analyzer windows that can be opened,
however more open windows will require more PC resources. Please see the
Performance Tips page for more information on improving PC performance.
The image below shows some of the common features of a Market Analyzer window:
All functions of the Market Analyzer can be accessed by pressing on your right mouse
button within the Market Analyzer window to bring up the right click menu.
9.14.2 Working with Instrument Rows
The Market Analyzer window allows you to display a variety of real-time quotes, indicator
values, and position information on multiple instruments. You can add, remove, and organize
individual instrument rows, Instrument Lists, Label rows, Blank rows, and a Total row with
the instructions listed below.
Adding an Instrument
You can add an instrument to the Market Analyzer through one of the techniques
below:
Press down on your right mouse button in the Market Analyzer window and select
the menu item Add Instrument. Select the instrument you want to add inside the
Select Instrument window and press the OK button to add the instrument.
Double left mouse click in a row under the Instrument column to get a flashing text
cursor. After the cursor is showing in the row you can type in the symbol of your
choice and press enter to add the instrument.
Press down on your right mouse button in the Market Analyzer window and select
the menu Add Instrument List. Then select the Instrument list you would like to add
to the Market Analyzer. Please see the Instrument Manager section of the user help
guide for additional information on creating, editing, and deleting Instrument lists.
NOTE: It is more efficient to add instruments after defining the columns of your Market
Analyzer window. This will minimize NinjaTrader re-loading historical data into the
Market Analyzer window.
A Total row can total any column of values and is displayed at the top of the Market
Analyzer window. For example, you could choose to display your total Realized PnL
and total Traded Contracts for all instruments displayed in the Market Analyzer.
1. Press down on your right mouse button in the Market Analyzer window and select
the menu Properties.
2. In the Properties menu scroll down to the Total Row section and set the property
Enabled to True. You can also choose to customize the color of this row with the
Color for background property.
3. Press the Apply button to apply the changes or press the OK button to apply the
changes and exit the Properties menu.
4. To show each column’s total in the Total row press down on your right mouse button
inside the Market Analyzer window and select the menu Columns.
5. Set the Show in Total row property to True for each column you want totaled in the
Total row.
6. Press the Apply button to apply the changes or press the OK button to apply the
changes and exit the Columns window.
Row Filtering allows you to filter out (hide) rows from the Market Analyzer grid display
based on a cell's value. Filter conditions can be setup for any column applied to the
Market Analyzer.
For more information on Row Filtering see the Creating Filter Conditions section of the
user help guide.
9.14.3 Working with Columns
The Market Analyzer allows you to add a variety of columns ranging from indicators to
position information. To add, remove, and customize columns in your Market Analyzer
window please review the information below.
1. Open the Columns window (see the "Understanding the Columns window" section
above)
2. Select the column you want to add from the list of available columns
3. Press the New button or simply double click on the column you want to add
4. The column will now be visible in the list of applied columns
5. The column's parameters will be editable on the right side of the Columns window
when the column is selected from the applied columns list (see the "How to
customize columns" section below)
6. Press the OK button to apply the column(s) to your Market Analyzer, and exit the
Columns window
1. Open the Columns window (see the "Understanding the Columns window" section
above)
2. Left mouse click on the Indicator column and press the New button or simply double
click on it
3. The column will now be visible in the list of applied columns and listed as "ADL on 1
Min data"
4. You can now select the indicator of your choice from the Indicator parameter
1. Open the Columns window (see the "Understanding the Columns window" section
above)
2. Highlight the column you would like to edit in the list of applied columns (as shown by
the image below).
3. Once highlighted this column's parameters will be editable on the right hand side.
4. You can choose to display the column Type as Regular or as a BarGraph
5. When editing an Indicator column, the indicator's parameters will also be editable
6. You can set Alert, Cell or Filter conditions for any column from the Special
parameters section
Left mouse click the up arrow to move the selected applied column left in the Market
Analyzer window
Left mouse click the down arrow to move the selected applied column right in the
Market Analyzer window
Please see the Data Grids section of the user help guide for information on sizing and
ordering columns.
Columns can be removed from the Columns window or from the Market Analyzer
directly.
1. From the Market Analyzer window left mouse click on the column header and hold
down the left mouse button to drag the column outside the Market Analyzer window,
once the cursor changes to a black X release the left mouse button to remove the
column.
2. Open the Columns window (see the "Understanding the Columns window" section
above). Highlight the column you would like to remove in the list of applied columns
(as shown in the image below) then press the Remove button.
Alert Conditions
Alert Conditions allow you to define a custom alert based on the cell's value. Alert
Conditions are defined per column, and the Alert notifications they create are displayed
in the Alert Window. To enable/disable Alert Conditions press down on your right
mouse button inside the Market Analyzer window select the menu "Alerts".
4. Press the New button to add a new Alert Condition to the list of Alert Conditions
displayed in the left side of the Alert Conditions window
5. Set the Alert Condition properties in the right side of the Alert Conditions window
Please note setting the "Re-arm after secs" property to a value of zero means the alert
will not re-arm once triggered.
In this example, if the value of the cell was greater than 100, the first condition of "greater
than 30" would trigger the alert since its first in the list of conditions to be evaluated. The
"greater than 100" condition would never trigger in this example since "greater than 30"
will always trigger the alert first. To ensure that both conditions trigger an alert so that
you get the desired alerting behavior you want, you have to list the conditions in this
order:
This will guarantee that a cell value over 100 will fall in the "greater than 100" condition
and cell values between 30 and 100 will be triggered by the "greater than 30" condition.
Cell Conditions
Cell Conditions allow you to define the display behavior of a cell based on the cell's
value, and are defined per column. You can choose to alter both the color and text of a
cell with Cell Conditions.
4. Press the New button to add a new Cell Condition to the list of Cell Conditions
displayed in the left side of the Cell Conditions window
5. Set the Cell Condition properties in the right side of the Cell Conditions window
In this example, if the value of the cell was greater than 100, the first condition of "greater
than 30" would change the cell's color since its first in the list of conditions to be
evaluated. The "greater than 100" condition would never trigger in this example since
"greater than 30" will always trigger the color change first. To ensure that both conditions
trigger a color change so that you get the desired alerting behavior you want, you have to
list the conditions in this order:
This will guarantee that a cell value over 100 will fall in the "greater than 100" condition
and cell values between 30 and 100 will be triggered by the "greater than 30" condition.
Filter Conditions
Filter Conditions allow you to define conditions that filter out rows from the Market
Analyzer grid display based on the cell's value and are defined per column.
4. Press the New button to add a new Filter Condition to the list of Filter Conditions
displayed in the left side of the Filter Conditions window
5. Set the Filter Condition properties in the right side of the Filter Conditions window
Filter out the row from the Market Analyzer grid display when the cell value is less
than 30
The row will be displayed in the Market Analyzer grid display when the cell value is
greater than or equal to 30
To enable/disable filtering press down on your right mouse button in the Market
Analyzer window and select the menu Row Filter. When enabled, the Market
Analyzer will filter out rows from the grid display based on the Filter Conditions of the
columns.
9.14.5 Dynamic Ranking and Sorting
The Market Analyzer window can automatically rank and sort the data rows.
1. To set the column you wish to sort press down on your left mouse button in the column
header. You can set the column to sort in either descending (down arrow) or ascending (up
arrow) order.
2. You can enable dynamic sorting by pressing down on our right mouse button inside the
Market Analyzer and selecting the menu Auto Sort.
3. You can set the auto sort interval within the Market Analyzer Properties window.
Property Definitions
General
# of bars to look Sets the number of bars of historical data to use for indicator column
back calculations
Auto sort Sets the interval time in seconds between automatic resorting of rows
seconds
Color for Sets the default color for the row background
background
Color for Sets the default color for the text in a cell
foreground
Color for grid Sets the color of grid lines
lines
Font Sets the font
Session template Sets the session template
Label Row
Alignment Sets the alignment for the label
Color for Sets the default color for the Label row background
background
Color for Sets the default color for the Label row foreground
foreground
Row change
highlight
Color for Sets the color for the row change highlight background
background
Color for Sets the color for the text in the row change highlight
foreground
Duration in Sets the duration (in seconds) the instrument cell will remain
seconds highlighted. A value of zero will disable highlighting.
Total row
Color for Sets the color of the Total row background
background
Enabled Enables (True) or disables (False) the Total row in the Market
Analyzer window display grid
What is Saved
The following are saved within a Market Analyzer template:
Column layout
Column parameters and conditions
Market Analyzer properties
1. Configure your desired Market Analyzer columns and properties ( see the "Working
with Columns" and "Market Analyzer Properties" sections of the Help Guide for more
information)
2. Right mouse click within the Market Analyzer
3. Select the menu item Templates
4. Select the menu item Save As...
(You can optionally select the menu item Save As Default to save the current settings
as default. Any new Market Analyzer will load with these new default settings)
5. Enter a name for your Market Analyzer template and press the OK button.
4. Select the template you wish to load from the drop down menu and press the OK
button
Indicator Columns
Each indicator has a # of bars to look back parameter in the Columns window that
overrides the one in the Market Analyzer Properties window noted above. The higher the
number, the longer it will take to load data and the more memory (RAM) NinjaTrader will
use to hold the data in memory.
Each indicator has a Maximum bars look back parameter in the Columns window that
determines how many historical indicator values are stored for access. It is set to
TwoHundredFiftySix by default for optimal performance. Setting this to Infinite will take
longer to calculate and NinjaTrader will use more memory (RAM) to hold the extra values in
memory.
Set Up
Replay
Data Files
9.15.1 Set Up
In order to record live market data for use with Market Replay, you must first turn on the
replay recorder.
1. Left mouse click on the Tools menu and select the menu item Options.
2. Left mouse click on the Data tab and select Record for market replay
All live data from instruments that are active in any NinjaTrader window will now be
recorded for replay. (See the "How to record live market data" section below)
Recording Data
Once Record for market replay is enabled (see the "How to enable the Market Replay
recorder" section above for how to enable), data is recorded for any instrument in any
NinjaTrader window that is receiving live market data. Level II (market depth) data is only
recorded if a Level II, SuperDOM, or FX Pro window is open and receiving data for the
instrument. The Market Analyzer window is the recommended recording window as
multiple instruments can be added to one Market Analyzer window and all recorded at
the same time.
Notes:
Record for market replay must be disabled from the Data tab of the Options menu
before downloading replay data.
NOT available when connected to the Market Replay connection.
1. Select the File menu in the Control Center, select the menu item Utilities and select
Download Replay Data... The Download Replay Data window appears.
2. Select the instrument and date of the desired replay data and press the OK button to
begin the download.
The status of the download will appear in the lower right hand corner of the Control
Center.
9.15.2 Replay
Once replay data is available by either recording or downloading (See the "Set Up" page of
the Help Guide), it can be replayed in all NinjaTrader windows.
"Connected - Replay" should now show in the lower left hand corner of the NinjaTrader
Control Center.
Replay Control
Once connected to the Market Replay data (see the "How to connect to Market Replay
data" section above for how to connect), the Replay control window will appear.
At the top of the Replay control window, the replay speed and current replay date and
time are shown. Below that title bar you can select the replay From and To dates.
Controls
The Replay control is set up much like a DVD player. The following controls are
available:
Available Brings up the Available Data window. Instruments with replay data will
Data... be displayed with the level 1 (L1) and level 2 (L2) Begin and End dates
and times. Left mouse click on the "+" icon to view a more detailed
report for instruments with multiple replay dates as shown in the image
to the right for the ES 03-10.
Go To... Brings up the Go To window where you can specify a date and time to
jump the replay file to. There must be recorded data available for the
selected time.
Tips
1. Should you be using the Market Replay for testing a NinjaScript strategy, please be
sure the chart you apply the strategy onto has bars populating it prior to the start time
of your replay.
The following outlines how the Market Replay works in syncing the Level I and Level II
data together. The same concept applies to syncing events between different
instruments being played back at the same time.
NinjaTrader's Market Replay feature uses two separate files for Level I and Level II
data.
When replaying, the Level I sequence is guaranteed to be in the correct sequence in
relation to all Level I events for that instrument.
The Level II sequence is also guaranteed to be in the correct sequence in relation to all
Level II events for that instrument.
When both Level I and Level II data streams are played in conjunction, the Level I and
the Level II events are still guaranteed to be in the correct sequence in relation to their
individual streams. So L1 is still correctly sequenced for all L1 and L2 is correctly
sequenced for all L2s.
What is not guaranteed though is the sequence of events between L1 and L2 greater
than that of a one second granularity.
What the NinjaTrader Market Replay does is increment the replay in seconds
intervals (00:00:00 to 00:00:01) <-- HH:mm:ss
When the second moves up by one, NinjaTrader will gather all the L1 information
that happened within that second and then gather all the L2 information within that
second. Then they are meshed together.
There is no guarantee as to how the L1 and L2 data will mesh together at this point.
What this means is that it is possible to have L1 events timestamped as seemingly
after a L2 event yet still played first and the vice versa as well.
Ex:
L1 data between 00:00:00 and 00:00:01. We have a L1 event of 00:00:01:00 (HH:mm:ss:
ff)
L2 data between 00:00:00 and 00:00:01. We have a L2 event of 00:00:00:90 (HH:mm:ss:
ff)
Notice how both of these events with a seemingly 00:00:00 and 00:00:01 seconds
granular timestamp were gathered together for replaying for the same 1 second time
increment on the replay file. The meshing of these two events could result in the L1
event of 00:00:01 being shown first followed by the L2 event of 00:00:00:90.
This would appear to be out of chronological order, but because the meshing is simply
not done with a granularity higher than 1 second this can occur. For this reason, L1 and
L2 sequencing should not be relied on in Market Replay if that sequencing is needed at a
more granular level than 1 second.
9.15.3 Data Files
Market Replay data is recorded and stored in compressed files located in the <Installation
Folder>\db\data folder. These files can be shared by copying the contents of this folder to
another NinjaTrader installation, or by using the Backup & Restore utilities to create a backup
News Window
1. Enable the desired RSS feed(s) in the RSS Tab of the Options menu
2. Add the instrument(s) you want to receive news for to the RSS instrument list within
the Instrument Manager
RSS news will now stream into the News window for any instrument added to the RSS
instrument list as long as you are connected to a data provider.
Keyword
Filtering on a specified instrument list
Filtering on a specified set of news providers
1. Right mouse click in the upper left hand corner of the News window
2. Select the menu item Add Filter...
3. Set the filter properties and conditions (see the "Alert Window" sub-section of the "
How to create an alert condition" section below for more information)
4. Press the OK button and use the Filter drop down menu in the upper left hand corner
of the News window to select the filter.
Keyword
Filtered on a specific instrument list
Filtered on a specified set of news providers
1. Right mouse click in the upper left hand corner of the News window
2. Select the menu item Add Alert...
3. Set the alert properties and conditions (see the "Alert Window" sub-section below)
4. Press the OK button and check the alert to activate it.
Alert Window
The Alert window can be opened by right mouse clicking in the upper left hand corner of
the News window and selecting the menu item Add Alert... This is where you define the
alert keyword and other properties.
price and satisfies a user defined volume trigger. SS orders are very powerful and can be
misused if not fully understood. Please take the time to review this section in it's entirety prior
to using this order type.
NOTE: Simulated Stop (SS) orders are not supported in the NinjaTrader Direct Edition.
Benefits
Hide your order from the market place
Delay the triggering of a stop market or stop limit order (prevent having your position
stopped out prematurely due to a quick drop and pop into your stop loss price level)
Execute a limit order at an improved price from the stop price trigger (for example, you
wish to trigger a buy limit order at 999 once the market price reaches 1000)
Risks
SS orders are held and simulated locally on your PC and are therefore subject to
issues such as loss of internet connection and computer crashes
SS orders require stable and reliable market data since they are simulated; if market
data stops flowing the SS order stops simulating
SS market order types can experience slippage during high volume periods and/or
highly volatile markets
Since SS orders are held on your PC and submitted live when they trigger, it is
possible that the order is rejected should you not have available margin to place this
order. PLEASE BE AWARE OF YOUR ACCOUNT MARGIN LIMITATIONS.
Volume Trigger
A SS order requires a Volume Trigger value to be set. This is the number of shares/
contracts that represents a floor that once penetrated will trigger the SS order. SS
orders trigger once the market price is trading at the SS order price and the Volume
Trigger condition is breached. Volume Triggers for Stop Loss orders are set as part
of a Stop Strategy, Volume Triggers for all other stop orders are set via the properties
dialog window of any order entry window.
SS orders are set to Initialized state (!!! see Appendix A) and are color coded yellow in
all of the NinjaTrader order display windows. Once triggered, either a limit order or a
market order is submitted.
This example will trigger once the market trades at a price of 1000 and the ask volume is
less than 500 contracts. Once triggered, a market order is submitted. If this was a sell
order, the bid volume would be monitored.
This example will trigger once the market trades at a price of 1000 and the ask volume is
less than 500000 contracts. The Volume Trigger is set to a ridiculous high number
because the intent is for the order to trigger right away. Once triggered, a limit order is
submitted to buy at a price of 1001 or better. If this was a sell order, the bid volume
would be monitored.
This example will trigger once the market trades at a price of 999 and the bid volume is
less than 600 contracts. The interesting thing about this set up is that what we are doing
is triggering a limit order at a higher price in order to try and get a better fill. This order
strategy is not possible with standard order types and can only be done using
NinjaTrader SS technology. Once triggered, a limit order is submitted to sell at a price of
1000 or better. If this was a buy order, the ask volume would be monitored.
Avoid SS Orders
During high volume and trade rate periods such as the first five minutes of trading
During major economic events that can substantially affect volatility
Markets that consistently trade with a large spread between the ask and bid price
Markets that trade where the ask or bid price can consistently change by more than
one tick
9.17.2 FIFO Optimization
All of the NinjaTrader order entry interfaces preserve FIFO (First In First Out) status with the
exchanges when possible.
FIFO is important since getting your orders filled is dependant on a FIFO algorithm
which basically means orders submitted ahead of yours at your order's price level will
get filled ahead of you. Think of it like a long line at the grocery store. You are checked
out only when those in line ahead of you have been checked out. NinjaTrader preserves
your place in line when possible giving you the best possible advantage of getting your
orders filled.
When a position or ATM Strategy position is closed, NinjaTrader goes through the following
process: (Assume we are long on the S&P E-mini contract at an entry price of 1000.)
1. Identifies any working sell limit orders
2. Cancel all other orders
3. Modifies the price of the identified working sell limit orders below the market so that they
get filled instantly
4. Submit a sell market order if necessary for any left over contracts that are not covered by
the identified working sell limit orders
The exception are currencies (FOREX) where all working orders are cancelled and then a
market order is submitted to close the position. (Does not apply to currencies with MB
Trading and Interactive Brokers where the previously described process is used.)
This approach essentially guarantees the most efficient way to exit a position.
9.17.4 Window Linking
Please see the Window Linking section of the Help Guide for more information on linking
order entry windows.
9.17.5 Order State Definitions
The table below describes the various order States your orders can be in as well as the color
that represents this state in NinjaTrader. The colors can be seen when submitting,modifying
or cancelling orders in the Order Entry windows as well as the Orders tab of the Control
Center.
Column Definitions
Name Order name such as Stop1 or Target1
Action Buy or sell
Type Order type
Price Order price
Remaining Number of contracts/shares remaining to be filled
Increase (+) Increases the order price
Decrease (-) Decreases the order price
Cancel (X) Cancels the order(s)
By moving your mouse cursor over an order and pressing down on your right mouse button,
you will see a context menu listing all individual orders consolidated at the corresponding
price and any relevant actions that you can perform on those orders.
NinjaTrader makes changing instruments and accounts quick and easy with separate menus
located directly within the Basic Entry window.
Submitting orders within the Basic Entry order entry window is both easy and efficient. In
addition to entry and exit orders the Basic Entry window also offers access to NinjaTrader's
ATM Strategies. For more information on ATM Strategies please see the ATM section of
the user help guide or attend one of our free live training events.
To submit an order
1. Set the "Order qty" field
2. Set the "TIF" (Time in Force) field
3. Set the ATM Strategy option
a) <None> : Orders are submitted independent of a strategy
b) <Custom> : Stop Loss and Profit Target orders are created "on the fly" using
the selected strategy parameters. A more thorough explanation of these concepts
can be found under the Advanced Trade Management section of the user help guide.
c) * Active Strategy X: Apply this order to this selected strategy, the selected
strategy's stops and targets are automatically updated
d) User Defined Strategy Template: Stop Loss and Profit Target orders are
submitted from a predefined user template
4. Enter an order with any of the methods described below
Quick Buttons
You can enter orders rapidly by pressing on any one of the quick order buttons.
BUY ASK Places a buy limit order at the best ask price
BUY MARKET Places a buy market order
BUY BID Places a buy limit order at the best bid price
SELL ASK Places a sell limit order at the best ask price
SELL MARKET Places a sell market order
SELL BID Places a sell limit order at the best bid price
Custom Orders
You can place a custom order by setting order parameters.
The "oc" (OCO indicator) will light up green. All orders placed while this indicator is lit
will be part of the same OCO group. Once any order of this group is either filled or
cancelled, all other orders that belong to this group will be cancelled. If you want each
OCO order to create it's own set of Stop Loss and Profit Target orders ensure that
the ATM Strategy control list is set to either "<Custom>" or a strategy template name
before you submit each OCO order.
Right clicking in the Basic Entry window and selecting the menu item "OCO Order"
to enable the OCO function
For your first order, select the desired option from the "ATM Strategy" drop down list
Submit your stop order to buy above the market
For your second order, select the desired option from the "ATM Strategy" drop down
list
Submit your stop order to sell below the market
CRITICAL: Right click in the Basic Entry window and select the menu item "OCO
Order" to disable OCO for future orders.
For a market fade approach just substitute limit orders for stop orders.
To submit a Simulated Stop Order (entry and exit NOT Stop Loss; simulated Stop
Loss orders are enabled via an ATM stop strategy) you must enable Simulated Order
mode via the right mouse click context menu by selecting the "Simulated Order" menu
item or use the shortcut key CTRL+A. The "so" (Simulated Order indicator) will light up
green. All stop orders placed while this indicator is lit will be submitted as a Simulated
Stop Orders.
9.17.6.5 Modifying and Cancelling Orders
2. You can decrease the price of an order in one tick increments by left mouse clicking on the
"-" button. Holding the CTRL key down while pressing the "-" button will modify the order by 5
tick increments, and holding the ALT key will modify the order by 10 tick increments.
3. You can cancel an order by left mouse clicking on the "X" button.
4. You can change the size of an order by left clicking in the "Remaining" column, typing in a
new quantity value and pressing the "Enter" key on your keyboard.
2. Clicking on the "REVERSE" button will close the current open position and open a reverse
position.
3. Clicking on the "CLOSE" button with your left mouse button will close the current position
and cancel any working orders associated to the instrument/account combination. Clicking
on this button with your middle mouse button (scroll wheel) will close the selected active
ATM Strategy only. This means that the position size of the ATM Strategy will be closed
and any working orders associated to that ATM Strategy will be cancelled.
In NinjaTrader the Chart, SuperDOM, Alerts, FX Pro, Level II, Market Analyzer, News,
Time and Sales, and Basic Entry windows all have link buttons in the top right hand corner("
L" - see the image below). Any window that is linked by color (each link button is set to the
same color) will receive the same change of instrument request. That means, change an
instrument in one window and the instrument in all linked windows will also change.
Also if you link any two order entry windows (ex. Chart Trader and SuperDOM) the orders
you enter in one window will automatically show on the other window allowing you to use the
two windows interchangeably.
The Basic Entry order entry window is highly efficient by design but can also be customized
to your preferences through the Basic Entry Properties menu.
Property Definitions
Action buttons Sets the color for action buttons (CLOSE, BE etc...)
color
Buy buttons Sets the color for all the buy buttons
color
Highlight color Sets the color for button highlighting
Sell buttons Sets the color for all the sell buttons
color
Simulation color Sets the color of the Basic Entry window background when a
simulation account (Sim101) is selected
Set Default
Once you have your Basic Entry window properties set up to your liking, you can press
the "Set Default" button which will save these settings as the default settings used
every time you open a new Basic Entry window.
If you change your settings and later wish to go back to the original factory settings you
can press the "Reset" button.
9.17.7 Chart Trader
When enabled, the Chart Trader control will be visible on the right side of chart window. You
will be able to submit, modify and cancel orders directly from within the chart.
Chart Trader can be enabled within any chart window via the chart properties dialog window
or by left mouse clicking on the Chart Trader chart toolbar icon.
Orders and positions within Chart Trader are displayed in a highly visual manner.
Order Display
An order is visualized as a color coded line with the order price label in the right margin
and a label indicating the order qty, action and either order type or name.
Chart trading color properties can be set via the Chart Trader properties window.
The image below displays how orders are visualized in a NinjaTrader chart.
Position Display
A position is displayed with the quantity, average entry price and unrealized profit/loss on
the chart. The quantity is also color coded green representing a long position and red
representing a short position.
The image below displays the chart with an active position managed by an Advanced
Trade Management strategy.
* The stop loss order is actually comprised of two orders as indicated by the letter "s"
next to the qty number "2".
You can collapse the Chart Trader control by pressing the arrow button in the top right hand
corner of the chart. This will hide/unhide the right side Chart Trader control from view.
There are several methods to submit orders through a chart using Chart Trader.
It is highly recommended that you review the section regarding Position Strategy Parameters
for a complete understanding of order submission and subsequent actions that you can have
NinjaTrader automate.
Submitting Orders
To submit an order using Chart Trader:
3. Clicking the "..." button will display the strategy parameters window
You can then enter an order with any of the methods described in the sections below.
*A more thorough explanation of these concepts are found under the Position Strategy
section.
Order Menus
Order menus will appear via the right mouse click context menu as per the image below
when you have Chart Trader enabled. The menus are filled with pre-defined order types
and prices based on the location of your mouse cursor. Click on the desired order menu
to submit an order.
The numeric field also supports negative values. By selecting a negative value, you
automatically submit a simulated stop order. This allows you to place orders that trigger
at a break out price but try to fill you at a better price. You can also enable simulated stop
order by putting the Chart Trader control into simulated order mode. You can enable
this via right mouse clicking in Chart Trader and selecting the menu item Simulated
Order or via the shortcut key CTRL+A.
Quick Buttons
You can quickly submit orders via the Chart Trader control's Quick Buttons.
Button Actions
Trader properties window. As an example, your initial strategy may call for opening a
position of four contracts but you want subsequent scale orders to be only one contract.
If the Chart Trader's Scale quantity property is set to a value of one, when an active
strategy is selected in the strategy control list, the Qty (Quantity) field will be set to a
value of one automatically.
To place OCO orders, right mouse click in your entry window and select the menu item
OCO Order or use the shortcut key CTRL+Z.
All orders placed while OCO is enabled will be part of the same OCO group. Once any
order of this group is either filled or cancelled, all other orders that belong to this group
will be cancelled. If you want each OCO order to create it's own set of stop loss and
profit target brackets, ensure that the ATM Strategy drop down menu is set to either
<Custom> or a strategy template name before you submit each OCO order.
NOTE: It is important to reset the OCO by disabling and re-enabling it after the
completion of submitting an OCO order group; otherwise, you may run into problems
where orders are rejected due to usage of duplicate OCO id values.
Example:
Below are steps for submitting a sell limit and a buy limit order via OCO.
1. Enable OCO
2. Place buy limit
3. If initiating two orders to enter a new strategy then re-select the strategy in the
strategy selection list
4. Place sell limit
5. Disable OCO (this is critical that you disable OCO before submitting another OCO
group)
One of the powerful features of simulated stop orders is that you can submit a "negative
limit stop limit" order. This means that you can place an order where the limit price is
better than the stop price. As an example, you may want to buy on strength indicated by
a move up to a particular price. Once that occurs, you want to enter at a better price
using a limit order several ticks below (if you are buying) the stop price. Any stop limit
order submitted with a negative limit offset is automatically a simulated order and will be
held on your PC until the stop is triggered or cancelled.
9.17.7.4 Modifying and Cancelling Orders
An order can be modified or cancelled inside a chart with Chart Trader enabled.
When above the ask the label will display a positive value, below the bid the label (in the
image below we are 2 ticks below the bid) will display a negative value. At the ask the
label will display @Ask and at the bid the label will display @Bid.
Once you have the ghost order at the price you desire, left click with your mouse to
complete the modification. This is a click and click method, you do NOT click and drag.
To cancel a pending order price modification press the "Esc" key on your keyboard.
Left mouse click on the area of the order label that displays the order quantity. An order
size modification control will appear. Modify the quantity in the quantity field by using
either the up/down arrows, the mouse scroll wheel, or by typing the desired quantity.
Press the "check mark" to accept the modification, or press the X to cancel the
modification.
Cancelling an Order
To cancel an order:
Action Buttons
There are two action buttons in Chart Trader, the REV button and the CLOSE button.
REV
The REV button stands for "reverse." When pressed, it will reverse your open position by
closing out the open position and entering into the opposite position maintaining your ATM
Strategy if one is applied.
CLOSE
Left mouse clicking on the CLOSE button will close the current position and cancel any
working orders associated to the instrument/account combination. Clicking on this button with
your middle mouse button (scroll wheel) will close the selected active ATM strategy only. This
means that the position size of the strategy will be closed and any working orders associated
to that strategy will be cancelled.
Many of the visual display settings of Chart Trader can be customized using the Chart
Trader Properties window.
1. Right mouse click within the Chart Trader Window (Make sure your mouse is
hovering over the Chart Trader control window when right mouse clicking, otherwise
you will access the chart menu)
2. Select the menu item Chart Trader Properties...
The following Chart Trader properties are available for configuration within the Chart
Trader Properties window:
Action buttons Sets the color for action buttons (CLOSE, BE etc...)
color
Buy buttons color Sets the color for all the buy buttons
Highlight color Sets the color for button highlighting
Limit orders Sets the drawing properties for limit orders
Order display bar Sets the length an order bar is displayed horizontally across the chart
length (% of in %
chart)
Position entry Sets the drawing properties for average position
price
Profit target Sets the drawing properties for profit target orders
Sell buttons colorSets the color for all sell buttons
Simulation color Sets the color of the Chart Trader window background when a
simulation account (Sim101) is selected
Stop limit orders Sets the drawing properties for stop limit orders
Stop loss Sets the drawing properties for stop loss orders
Stop market Sets the drawing properties for stop market orders
orders
ATM Strategy Sets the behavior mode of the price ladder display and strategy
selection mode selector (see the ATM Strategy Selection Mode section of the Help
Guide for more information)
Auto scale Enables or disables the orders and positions to be included in the
chart auto scaling
Parameter type Sets the parameter type used for entering strategy information. *Price
parameter type is absolute price, NOT an offset value (Example: Stop
Loss = 1 will submit an order at a price of 1, NOT 1 point away from
entry)
PnL display unit Sets the display unit for profit loss in currency, percent or points
Scale quantity Sets the scale order quantity amount
Show realized Displays realized profit and loss for the selected account when flat
PnL when flat
Simulated order Sets the value for a simulated order volume trigger (for entry and exit
volume trigger orders and NOT used for stop loss)
Stop limit offset Sets the offset the limit price is away from the stop price for entry/exit
stop limit orders. Set to 'Off' to disable single click stop limit order
submission.
Use stop market When true, a stop market order will be submitted for automatic
for stop loss submission of stop loss orders are part of a position strategy. By
orders default, when selecting any instruments that trade on Eurex, CBOT
and CME this setting is set to true.
If you change your settings and later wish to go back to the original settings, you can left
mouse click on the Reset button to return to the original settings.
9.17.8 FX Pro
The FX Pro order entry window is comprised of several components: the Order Grid, the
Level II panel (optional), position and level 1 display, as well as order entry and ATM
Strategy management.
9.17.8.1 Overview
The FX Pro order entry window is comprised of several components designed to give the
Forex trader every advantage.
The image below shows each of the four sections in the FX Pro window:
1. Order Grid
2. Optional Level II panel that is displayed *only* for brokerages that support ECN style FX
trading. If your brokerage does not support ECN FX then you will not see this panel on your
FX Pro window.
3. Position and level 1 (current inside market) display
4. Order entry and ATM Strategy management
* If your FX provider supports sub pip display you must enable sub pip support via the Misc
tab. The various brokerage technology connection guides will state clearly if the brokerage
technology offers sub pip support.
Please see the sections below for more information on: Order Grid display, Level II, and
Market Display.
Column Definitions
Name Order name such as Stop1 or Target1
Action Buy or Sell
Type Order type
Price Order price
Remaining Number of contracts/shares remaining to be filled
Increase (+) Increases the order price
Decrease (-) Decreases the order price
Cancel (X) Cancels the order(s)
By moving your mouse cursor over an order and pressing down on your right mouse
button, you will see a context menu listing all individual orders consolidated at the
corresponding price and any relevant actions that you can perform on those orders.
Column Definitions
Price The bid or ask price. The bid data is shown in the left section and the ask in
the right.
Size The number of lots at that price level available for buy or sell (represented
in short hand notation where M represents 1,000,000)
Time The last time the bid/ask was refreshed
* If a price is at a sub pip level, the sub pip value is displayed as a value after an
apostrophe as per the following example where the sub pip is highlighted in red.
Example: 1.4115'5 (The price is at 1.4115 pips plus 5 sub pips which is 5/10 of a pip)
Understanding the display of inside bid and ask as well as current position
Market Display
The Market Display panel shows the inside bid and ask along with current position
information.
* FX brokerage technologies that do not support an ECN model will NOT display sub
pips nor will bid/ask size be displayed.
9.17.8.2 Selecting Instruments and Accounts
NinjaTrader makes changing instruments and accounts quick and easy with separate menus
located directly within the FX Pro window.
Submitting orders within the FX Pro order entry window is both easy and efficient. In addition
to entry and exit orders the FX Pro window also offers access to NinjaTrader's ATM
Strategies. For more information on Advanced Trade Management (ATM) Strategies please
see the ATM section of the user help guide or attend one of our free live training events.
To submit an order
1. Set the Qty field
2. Set the ATM Strategy option
a) <None> : Orders are submitted independent of a strategy
b) <Custom> : Stop Loss and Profit Target orders are created "on the fly" using the
selected strategy parameters. Left mouse click the "..." button will display the strategy
parameters window. A more thorough explanation of these concepts can be found
Custom Orders
You can place a custom order by setting the following custom order parameters.
1. Select the order type
2. Set the limit price if applicable (press down on your middle mouse button in the field to
retrieve the last traded price)
3. Set the stop price if applicable (press down on your middle mouse button in the field
to retrieve the last traded price)
4. Press either the BUY or SELL button
Tips
1. Hold down the CTRL key when increasing/decreasing limit/stop prices to change the
price in steps of 10 tick increments.
2. Left clicking on a price in the Level II panel will load that price into the limit and stop
price fields automatically.
OCO Orders
Stop Loss and Profit Target orders (submitted automatically via an ATM Strategy) are
always sent as OCO however, you can submit entry or exit orders as OCO orders as
well. Why? The market may be trading in a channel and you wish to sell at resistance or
buy at support, whichever comes first by placing two limit orders at either end of the
channel. To place OCO orders, press down on your right mouse button inside the FX
Pro window and select the menu name OCO Order.
The "oc" (OCO indicator) will light up green. All orders placed while this indicator is lit will
be part of the same OCO group. Once any order of this group is either filled or
cancelled, all other orders that belong to this group will be cancelled. If you want each
OCO order to create it's own set of Stop Loss and Profit Target orders ensure that
the ATM Strategy control list is set to either <Custom> or a strategy template name
before you submit each OCO order.
NOTE: It is important to reset the OCO indicator after submitting an OCO order group
otherwise you may run into problems where orders are rejected due to usage of
duplicate OCO id values.
Right clicking in the FX Pro window and selecting the menu item OCO Order to
enable the OCO function
For your first order, select the desired option from the ATM Strategy drop down list
Submit your stop order to buy above the market
For your second order, select the desired option from the ATM Strategy drop down
list
Submit your stop order to sell below the market
CRITICAL: Right click in the FX Pro window and select the menu item OCO Order to
disable OCO from being applied to subsequent orders.
For a market fade approach just substitute limit orders for stop orders.
1. You can increase the price of an order in one tick increments by left mouse clicking on the
"+" button. Holding the CTRL key down while pressing the "+" button will modify the order
by 5 tick increments, and holding the ALT key will modify the order by 10 tick increments.
2. You can decrease the price of an order in one tick increments by left mouse clicking on
the "-" button. Holding the CTRL key down while pressing the "-" button will modify the
order by 5 tick increments, and holding the ALT key will modify the order by 10 tick
increments.
3. You can cancel an order by left mouse clicking on the "X" button.
4. You can change the size of an order by clicking in the "Remaining" column, typing in a
new quantity value and pressing the "Enter" key on your keyboard.
* A tick increment for a brokerage that supports sub pips (ECN model) is equal to 1/10 of a
pip also known as a sub pip. Otherwise a tick increment is one pip value.
9.17.8.5 Adding and Removing Targets
If you have 1 target and you remove a target, you will be left with a Stop Loss order only
New targets are added 4 pips from your current outside target
The FX Pro order entry window is highly visual by design but can also be customized to your
preferences through the FX Pro Properties menu.
You can access the FX Pro properties dialog window by clicking on your right mouse
button within the FX Pro window and selecting the menu Properties.
Property Definitions
Action buttons Sets the color for action buttons (CLOSE, BE etc...)
color
Buy buttons Sets the color for all the buy buttons
color
Highlight color Sets the color for button highlighting
Sell buttons Sets the color for all the sell buttons
color
Simulation Sets the color of the FX Pro window background when a simulation
color account (Sim101) is selected
ATM Strategy Sets the behavior mode of the price ladder display and strategy selector
Selection Mode (see more)
Caption bar Sets the text displayed in the caption bar of the Basic Entry
display
Level II font Sets the font style for the Level II display
Parameter type Sets the parameter type used for entering strategy information. *Price
parameter type is absolute price NOT an offset value (Example: Stop
Loss = 1 will submit an order at a price of 1 NOT 1 point away from
entry)
PnL display unit Sets the display unit for profit and loss
Scale quantity Sets the scale order quantity amount.
Show realized Displays realized profit and loss for the selected account when flat
PnL when flat
Simulated Sets the value for a simulated order volume trigger (for entry and exit
order volume orders and NOT used for stop loss)
trigger
Set Default
Once you have your FX Pro window properties set up to your liking, you can press the "
Set Default" button which will save these settings as the default settings used every
time you open a new FX Pro window. If you change your settings and later wish to go
back to the original factory settings you can press the "Reset" button.
9.17.9 SuperDOM
The SuperDOM provides complete functionality for the management of orders, positions,
and discretionary exit and stop strategies in a highly visual and efficient manner. The DOM at
the end of SuperDOM stands for Depth of Market which you can see displayed in the Buy
and Sell columns of the NinjaTrader SuperDOM.
The SuperDOM is designed to allow the trader to view market prices, market depth, current
inside market, PnL, current positions, and pending orders at a glance. The unique display of
each item within the SuperDOM Price Ladder display makes managing open orders and
positions easy and efficient.
BUY Column
The left column is the BUY column which is used to:
PRICE Column
The center column, known as the PRICE column, is used to:
SELL Column
The right column is the SELL column which is used to:
Best ask
Best bid
Last traded price and size (yellow cell in the image below)
Ask depth
Bid depth
Cumulative ask depth
Cumulative bid depth
How to use the quick buttons at the bottom of the Price Ladder display
The bottom row of the price ladder contains three functions: Buy MARKET, PnL, and
Sell MARKET.
You can change the type of order the MARKET cells submit by holding down the SHIFT
key to place limit orders at the ask, or by holding down the CTRL key to place limit
orders at the bid. Clicking with your left mouse button on the PnL cell will change the
display between points, currency, and percent.
You can set this option and customize the color of the markers in the SuperDOM
Properties dialog window.
PnL Display
The PnL field in the bottom of the Price column will show the current unrealized profit/
loss for your current open position, and read as PnL when you are FLAT.
You can optionally enable "Show PnL when flat" in the SuperDOM Properties to view
your daily account PnL when FLAT
When long the field will show as green and list the number of contracts, and when short
field will show as red and list the number of contracts. When you do not have an open
position the field will say FLAT.
Move your cursor into the Price Ladder region and use your mouse scroll wheel to
adjust market prices up or down.
You can also left mouse click on the "C" button at anytime to center the inside market.
Optionally, the Auto Center property will automatically center the inside market price
should the last traded price trade outside the visible range on the Price Ladder. You
can enable or disable Auto Center at anytime by clicking on your right mouse button in
the border of the SuperDOM and selecting the menu name Auto Center.
The number of visible price rows can be adjusted at anytime in the SuperDOM
Properties window.
Test Yourself!
Play the video above to review and test yourself on the topics discussed on this page of
the Help Guide.
You may have the option of using either a static (original SuperDOM) or dynamic price
ladder display depending on your FCM or broker. The difference between these options is
how the inside market is displayed in the Price Ladder.
Static
The inside market (ask/bid and last price) climb up and down the Price Ladder in
response to a change in market price.
Dynamic
The inside market (ask/bid and last price) is in a fixed location in the Price Ladder
display.
The price rows are dynamic in that each row's price changes in response to a change in
market price.
Hold Button
To assist with submitting and modifying orders in the Dynamic Price Ladder display
during volatile market activity you can choose to suspend (freeze) the Price Ladder
display by pressing the HOLD button with your left mouse button or by pressing the
'Space' bar of your keyboard.
Once suspended, the button will highlight red in color and display 'HELD'. You can now
safely submit or modify an order without the price of the underlying row changing. Be
sure to enable the dynamic updating of the price action in the price ladder display after
you have completed your order submission or modification by pressing on the HELD
button or your keyboard 'Space' bar. In addition, the inside market will be displayed in the
top row of the SuperDOM while the price ladder is frozen.
1. Best bid
2. Net change (last traded price) from the time the display was suspended
3. Best ask
NinjaTrader makes changing instruments and accounts quick and easy with separate menus
located directly within the SuperDOM.
The "Instrument" drop down menu contains the instruments from the Default
Instrument List that you have set up in the Instrument Manager. To change an
instrument select a different instrument from this list.
Orders are displayed in a highly visual manner. Different order types and order objectives
(stop loss or profit target orders) are uniquely color coded.
Order Display
All orders are displayed by coloring a cell or group of cells within the Price Ladder
The image below shows a working limit, stop market, and stop limit order for one
contract each.
contracts for all orders resting at that price. The image to the right depicts a
consolidated display of two limit orders for 1 contract each.
By moving your mouse cursor over the order (cyan colored cell) and pressing down on
your right mouse button, you will see a context menu listing all individual orders
consolidated at the corresponding price and any relevant actions that you can perform
on those orders.
Understanding how Stop Loss and Profit Target orders are displayed
The image below displays an image of a Stop Loss and Profit Target pair, notice that
the Size Marker colors on the right side reflect the current state of the orders and that
they are sell orders since they are displayed on the sell side of the Price Ladder. Also
note the brown colored cell at price level 1256.50, this represents the average entry
price for the open position.
How to view out of range Stop Loss and Profit Target orders
Displaying Stop Loss and Profit Target orders outside the visible range
There maybe times when your Stop Loss or Profit Target orders are outside of the
visible price range of the SuperDOM price ladder. You can easily bring these orders in
range by clicking with your middle mouse button in the Price column. Clicking on the bid
or above with your middle mouse button will bring into visible range the first stop loss or
profit target order above the highest displayed price of the price ladder. Clicking below
the bid with your middle mouse button will bring into visible range the first stop loss or
profit target order below the lowest displayed price of the Price Ladder.
NOTE: This function only works if "Single Click Order Modification" is set to False in
the SuperDOM Properties window. If set to true, middle click will instantly modify your
Stop Loss or Profit Target orders.
Test Yourself!
Play the video above to review and test yourself on the topics discussed on this page of
the Help Guide.
9.17.9.5 Submitting Orders
Orders are submitted in the NinjaTrader SuperDOM using different combinations of mouse
clicks and keyboard keys. Limit, stop market, and stop limit orders are placed with the
following conventions: limit orders are placed with the left mouse button, stop market orders
are placed with the Ctrl key and middle mouse button, and stop limit orders are placed with
the middle mouse button. However, you can set the middle mouse button to submit stop
market orders as default by setting "Middle mouse button is stop market" to True in
SuperDOM Properties.
* It is highly recommended that you review the Advanced Trade Management (ATM) section
for a complete understanding of order submission and subsequent actions that you can have
NinjaTrader automate.
To Submit an Order
B. <Custom> : Stop loss and profit target orders are created "on the fly" using the
selected strategy parameters
C.* Active Strategy X: Apply this order to this selected strategy, the selected
strategy's stops and targets are automatically updated
D.User Defined Strategy Template: Stops and targets are submitted from a
predefined user template. A more thorough explanation of these concepts are found
under the Advanced Trade Management (ATM) section.
4. Submit your desired order type based on the instructions in the sub-sections below.
To submit a limit order, select either the BUY column for buy orders or the SELL
column for sell orders and press down on your left mouse button in the cell that
corresponds to the price you wish the limit order to be submitted at. Clicking at the
location marked in the image below would submit a buy limit order at the price 889.25.
To submit a stop market order, select either the BUY column for buy orders or the
SELL column for sell orders and press down on your middle mouse button (scroll
wheel) while holding the CTRL key down in the cell that corresponds to the price you
wish the stop market order to be submitted at.
In the image below, holding down the CTRL key on your keyboard and middle mouse
clicking on the price point would enter a buy stop market order at 891.25.
When you have an active strategy selected in the strategy control list (see image below)
orders submitted scale into or out of the strategy. Once filled or partially filled, existing
stop loss and profit target orders are modified to reflect the new position strategy size.
You can preset a default scale in or out quantity via the "Scale quantity" property
accessible via the SuperDOM properties window. As an example, your initial strategy
may call for opening a position of four contracts but you want subsequent scale orders
to be only one contract. If the SuperDOM "Scale quantity" property is set to a value of
one, when an active strategy is selected in the strategy control list, the SuperDOM
"Order qty" field will be set to a value of one automatically.
channel. To place OCO orders, via the right mouse click context menu select the menu
name "OCO Order" or use the shortcut key CTRL + Z.
The "oc" (OCO indicator) will light up green. All orders placed while this indicator is lit will
be part of the same OCO group. Once any order of this group is either filled or
cancelled, all other orders that belong to this group will be cancelled. If you want each
OCO order to create it's own set of stop loss and profit target brackets ensure that the
Strategy Control List is set to either "<Custom>" or a strategy template name before you
submit each OCO order.
NOTE: It is important to reset the OCO indicator after the completion of submitting an
OCO order group otherwise you may run into problems where orders are rejected due
to usage of duplicate OCO id values.
Right click in the SuperDOM and select the menu item "OCO Order" to enable the
OCO function
For your first order, select the desired option from the "ATM Strategy" drop down list
Submit your stop order to buy above the market
For your second order, select the desired option from the "ATM Strategy" drop down
list
Submit your stop order to sell below the market
CRITICAL: Right click in the SuperDOM and select the menu item OCO Order to
disable OCO from being applied to subsequent orders.
For a market fade approach just substitute limit orders for stop orders.
Set the ATM strategy in the ATM Strategy selection drop down box to a value of
<None>
Right click in the SuperDOM and enable OCO order placement by selecting the
menu name "OCO Order"
Then place a limit order where you want to exit at a profit
Then place a stop order where you want to exit at a loss
Lastly, right click again and select the menu item "OCO Order" to disable the OCO
order placement
Now you have a target and a stop placed protecting your open position, and when one of
these orders is filled the other will be cancelled automatically.
To submit a Simulated Stop Order (entry and exit NOT stop loss; simulated stop loss
orders are enabled via an ATM stop strategy) you must enable Simulated Order mode
via the right mouse click context menu by selecting the "Simulated Order" menu item
or use the shortcut key CTRL + A. The "so" (Simulated Order indicator) will light up
green. All stop orders placed while this indicator is lit will be submitted as a Simulated
Stop Orders.
One of the powerful features of Simulated Stop Orders is that you can submit a
"negative limit stop limit" order. This means that you can place an order where the limit
price is better than the stop price. As an example, you may want to buy on strength
indicated by a move up to a particular price. Once that occurs, you want to enter at a
better price using a limit order several ticks below (if you are buying) the stop price.
For more information please visit the Simulated Stop Orders section of the user Help
Guide.
Setting “Show Quick Buttons” to true in the SuperDOM Properties enables: ASK and
BID buttons in the Buy and Sell Columns, a Plus Target button, and a Remove
Target button.
When enabled, pressing an "ASK" button with the left mouse button will submit a limit
order at the ask price, pressing a "BID" button will submit a limit order at the bid price.
For more information on adding and removing targets please view the Adding and
Test Yourself!
Play the video above to review and test yourself on the topics discussed on this page of
the Help Guide.
9.17.9.6 Modifying Orders
Orders are modified within the SuperDOM by selecting the order and clicking on the new
price cell. Optionally you can also enable Single Click Order Modification of your Profit
Target and Stop Loss orders within the SuperDOM Properties.
2. Once selected, you will see the cursor change to a hand from an arrow, then choose
the price you are modifying the order to and click using your left mouse button to
complete the modify process.
The left mouse button is used to modify the price of limit, stop market and stop limit
orders. You can cancel out of a price modification (remove the hand cursor) by pressing
the ESC key.
How to modify the price of Stop Loss and Profit Target orders
2. Once selected, you will see the cursor change to a hand from an arrow, then choose
the price you are modifying the order to and click using your left mouse button to
complete the modify process.
*If there are multiple orders consolidated at a price level, modifying the price will modify
all orders at that price level.
The quantity field will appear which allows you to set the new order quantity by either
entering a new quantity or using the mouse wheel to scroll the value higher or lower.
Either press the "Check mark" button to submit the change or the "X" button to cancel
the operation. Order size changes are handled according to NinjaTrader's advanced
FIFO optimization capabilities.
How to modify Stop Loss and Profit Target orders with a single click
Once enabled, to modify Stop Loss and Profit Target orders click in the center/PRICE
column. Clicking in the PRICE column on the BID or above when long will adjust your
Profit Target order prices, below the BID will adjust Stop Loss order prices. Clicking in
the PRICE column on the ASK or below when short will adjust your Profit Target order
prices, above the ASK will adjust your Stop Loss order prices.
Left Mouse Modifies the closest Stop Loss or Profit Target order
Click
Middle Modifies the second closest Stop Loss or Profit Target order
Mouse Click
Middle Modifies the third closest Stop Loss or Profit Target order
Mouse
Click +
CTRL Key
* If you have more than one active strategy working in the market, single click
modification will be applied to the stops and targets associated to the selected strategy
as indicated in the strategy control list (drop down list) in the lower portion of the
SuperDOM window.
NOTE: This advanced mode DOES NOT provide single click access to working orders
(Entry/Exit) that reside in either the BUY or SELL columns.
Test Yourself!
Play the video above to review and test yourself on the topics discussed on this page of
the Help Guide.
There are several options for cancelling orders within the NinjaTrader SuperDOM.
Cancelling Orders
1. Pressing down on the left mouse button on the red "X" will cancel all orders
consolidated at the corresponding price level.
2. Pressing down on the right mouse button with the mouse cursor hovering over the
order will display all orders consolidated at that price. You can then select any
individual order for cancellation.
3. Pressing on the large red "X" will cancel all orders on either the "BUY" side (in this
example) or the sell side.
You can also cancel "ALL" orders by right mouse clicking inside the SuperDOM and
selecting the menu item Cancel All Orders.
Test Yourself!
Play the video above to review and test yourself on the topics discussed on this page of
the Help Guide.
9.17.9.8 Adding and Removing Targets
If you have an active ATM strategy displayed in the SuperDOM, you can add or remove
targets. For example, you may have a 2 contract position with 1 Stop Loss and Profit
Target for 2 contracts each. You may decide to split this target (add target) so you can exit
the final contract at a higher price.
Test Yourself!
Play the video above to review and test yourself on the topics discussed on this page of
the Help Guide.
9.17.9.9 Action Buttons
The SuperDOM has action buttons that allow you to quickly: reduce the size of the
SuperDOM, close open positions, reverse positions, and center the inside market.
Left mouse clicking on the "<" button collapses or expands the lower portion of the
SuperDOM.
Left mouse clicking on the "REV" will close the current open position and open a reverse
position.
Left mouse clicking on the "CLOSE" will close the current position and cancel any working
orders associated with the instrument/account combination. Clicking on this button with
your middle mouse button (scroll wheel) will close the selected active strategy only. This
means that the position size of the strategy will be closed and any working orders
associated to that strategy will be cancelled.
Left mouse clicking on the "C" will center the last traded price in the Price Ladder.
9.17.9.10 Window Linking
Please see the Window Linking section of the Help Guide for more information on linking
order entry windows.
9.17.9.11 SuperDOM Properties
The SuperDOM is highly visual by design but can also be customized to each trader's
preferences.
Ask price color Sets the color of the ask price font
Bid price color Sets the color of the bid price font
Buy column Sets the color of the buy column
color
Daily high price Sets the color of the daily high price marker
color
Daily low price Sets the color of the daily low price marker
color
Entry price Sets the color of the average entry price marker
color
Font color Sets the color of the font
Highlight color Sets the color for row and button highlighting
markers
Show market Enables or disables market depth
depth
Show quick Enables or disables the quick buttons rapid order entry section
buttons
Show realized Displays realized profit and loss for the selected account when flat
PnL when flat
Simulated Sets the value for a simulated order volume trigger (for entry and exit
order volume orders and NOT used for stop loss)
trigger
Single click Enables or disables single click stop loss and profit target order
order modification
modification
Stop limit offset Sets the offset the limit price is away from the stop price for entry/exit
stop limit orders. Set to 'Off' to disable single click stop limit order
submission.
Use stop When true, a stop market order will be submitted for automatic
market for stop submission of stop loss orders are part of a position strategy. By
loss orders default, when selecting any instruments that trade on Eurex, CBOT and
CME this setting is set to true.
If you change your settings and later wish to go back to the original factory settings, you
can left mouse click on the Reset button to return to the factory settings.
Session Templates
A Session Template is a collection of session definitions that can be used anywhere
NinjaTrader utilizes data. (See the "Where Session Templates can be Applied" sub-
section below). When a template is applied, any data outside of the times in the session
definitions will be ignored. NinjaTrader comes pre-loaded with the most common
Session Templates; however, custom Session Templates can also be created to suit
your needs.
1. Left mouse click on the New... button. Enter a name for the Session Template and
press the OK button.
2. Left mouse click on the Add... button. The Session Definition window appears.
3. Select the Start day, Start time, End day and End time for the instrument session
and press the OK button to add it to the Session Template. Repeat for as many
sessions as required.*
4. Left mouse click on the time zone drop down menu and select the time zone that
represents the time inputted in the session definitions.
5. Press the Save button to save the configured session times in the Session
Template.
*For convenience, you can right mouse click on the first session added and select the
menu item Add Monday through Friday to have NinjaTrader automatically add
sessions for Monday through Friday with session definitions based on the selected row.
Left mouse click the Copy button and insert a new template name to copy the current
Session Template.
Left mouse click the upper most Delete button to delete the selected Session
Template.
Left mouse click on a session definition and press the Edit button to edit the session
Start day, Start time, End day and End time.
Left mouse click on the lower most Delete button to delete the selected session
definition.
9.19 Simulator
NinjaTrader provides a state of the art internal simulation engine that can be used to test
trading ideas and hone your skills. The simulation engine is not a simple algorithm that fills
your order once the market trades at your order price. The engine uses a scientific approach
to determine fill probability by including a number of variables including: ask/bid volume, trade
volume, time (to simulate order queue position), and random time delays for switching
between order states.
The account will be active the next time you connect to a data provider.
active, and when the check mark is not showing Global Simulation Mode is disabled.
Free license users are not able to disable Global Simulation Mode.
4. In addition, you can set NinjaTrader to always start in simulation mode via the Simulator
Tab in the Options window.
1. Toolbar
The Strategy Analyzer toolbar contains the following items (in order from left to right):
2. <On the fly> - Run a historical test on an instrument not in an instrument list
3. Individual instruments
4. Instrument lists
5. Strategies
6. Performance results
7. Strategy menu - Automatically slides into view when mouse cursor is hovered over it. Left
mouse click the thumbtack icon to pin it to the Strategy Analyzer window.
A backtest allows you to analyze the historical performance of a strategy. In order to run a
backtest you will need:
*There are several pre-defined sample strategies that are installed with NinjaTrader that you
can explore.
Start a Backtest
To run a Backtest of a strategy:
1. Left mouse click on an instrument or instrument list (to backtest the entire list of
instruments) and right mouse click to bring up the right mouse click menu. Select the
menu item Backtest... Alternatively left mouse click on the "b" icon in the Strategy
Analyzer toolbar. The default Hot Key CTRL + B can also be used.
2. Select a strategy from the Strategy slide out menu
3. Set the backtest properties (See the "Understanding backtest properties" section
below for property definitions) and press the OK button.
The backtest progress will be shown in the Status Bar of the Control Center.
Default
An algorithm that takes a conservative and more realistic approach to filling limit and
stop limit orders.
Limit orders only fill if the limit price was penetrated
Limit orders are always filled at the limit price specified never better (for example, if a
limit order is submitted on bar n, NinjaTrader will check if the order is filled on bar n+1,
if this bar gaps down and the limit order was a buy, the order would be filled at the limit
price and NOT the high of bar n+1)
Liberal
An algorithm that takes a liberal approach to filling limit and stop limit orders.
Limit orders fill if the limit price was touched
On gap down bars, buy limit orders will fill at the high of the gap down bar
On gap up bars, sell limit orders will fill at the low of the gap up bar
Slippage can also be set to mimic market conditions. The value is expressed in "ticks",
the minimum value of fluctuation for an instrument, and is only applied to market and
stop market orders since slippage is not possible when using a limit order.
Backtest Properties
The following properties are available within the Backtest window:
Min. bars Sets the minimum number of bars required before the backtest will start
required processing
Fill type Sets the algorithm for processing and filling orders during backtest
Slippage Sets the slippage amount in ticks per execution
Entries per Sets the maximum number of entries allowed per direction while a position
direction is active based on the "Entry handling" property
Entry Sets the manner in how entry orders are handled. If set to "AllEntries", the
handling strategy will process all entry orders until the maximum allowable entries
set by the "Entries per direction" property has been reached while in an
open position. If set to "UniqueEntries", strategy will process entry orders
until the maximum allowable entries set by the "Entries per direction"
property per each uniquely named entry.
Exit on close When enabled, open positions are closed on the last bar of a session
Set order Sets how the order size is determined, options are:
quantity "by default quantity" - User defined order size
"by strategy" - Takes the order size specified programmatically within the
strategy
"by account" - Allows you to set a virtual account value that is used to
determine maximum order size based on margin settings per instrument
set in the Instrument Manager
Time in forceSets the order's time in force
9.20.3 Optimize a Strategy
You can fine tune the input parameters of a strategy through optimization. Optimization is the
process of testing a range of values through iterative backtests to determine the optimal input
values over the historical test period based on your best result criterion. To run an
optimization you will need:
*There are several pre-defined sample strategies that are installed with NinjaTrader that you
can explore.
Start an Optimization
To run an Optimization:
1. Left mouse click on an instrument or instrument list (to run optimization on the entire
list of instruments) and right mouse click to bring up the right mouse click menu.
Select the menu item Optimize... Alternatively left mouse click on the "o" icon in the
Strategy Analyzer toolbar. The default Hot Key CTRL + O can also be used.
2. Select a strategy from the Strategy slide out menu
3. Set the backtest properties (See the "Understanding optimization properties" section
below for property definitions) and press the OK button.
The optimization progress will be shown in the Status Bar of the Control Center.
In the image above, the input "Fast" has a starting (initial) value of 10 and an ending
value of 30 with an increment of 1. This means that the first value tested will be 10, then
11, then 12 all the way through 30. The input "Slow" has a starting value of 6, ending
value of 16 with an increment of 1. Based on these settings, a total of 200 (20 unique
values for "Fast" multiplied by 10 unique values for "Slow") backtest iterations will be
processed in order to find the optimal combination of input values based on the best
result criterion.
1. The optimal value for the "Fast" input for the demonstration strategy used for this
optimization
2. The optimal value for the "Slow" input for the demonstration strategy used for this
optimization
Optimization Properties
Apart from the optimization specific properties described below, the properties are
identical to the ones found in the backtest properties window. Please see the "
Understanding backtest properties" section of the Backtest a Strategy page of the Help
Guide for more information.
Aggregate If set to True, NinjaTrader attempts to find the optimal results for the whole
d basket of instruments. The COMBINED row in the results tab will show an
aggregation of results across the basket of instruments. (This parameter is
only available when an Instrument List is selected for optimization.)
Keep best Sets the number of best results to display
# results
Optimize If set to true, the Data Series Value property will be available for optimization
data series (Not supported for Kagi, PointAndFigure, and Line Break period Types)
Optimize Sets the optimization criterion to base the optimization results on
on...
Optimizer Sets the optimization algorithm that is used. NinjaTrader comes with
"Default" and "Genetic" optimizer algorithms. When the "Genetic" option is
selected, the genetic algorithm's optimization properties fields will appear
above "Keep best # results." You can program your own optimization
algorithm using NinjaScript.
9.20.3.1 Genetic Algorithm
Genetic algorithm (GA) is another optimization technique that can be used to optimize your
NinjaScript strategy parameters with. The Default optimization algorithm tests every single
combination of parameters within the optimization range to find the best result possible, but
since it is testing every combination possible, this requires a lot of computing power and time
to complete. The GA can be more suited for these extensive optimizations because it is able
to approximate best solutions without testing every combination through the evolutionary
theory borrowed from biology.
Overview
The general idea of how the GA solves an optimization problem is analogous to the
concept of how evolution via natural selection adapts a species to the environment. In
biology, only the strongest individuals will be able to reproduce and pass on their
superior genes to the next generation. Assuming each generation can only pass on the
strongest genes, after several iterations we would be left with the optimal attributes for
the environment. Through this same mechanism, the GA will test a random preset of
your parameters. Through multiple generations of testing, the parameters will zero in on
an optimum solution.
When you select the Genetic optimizer you will see the following optimization properties:
*There are several pre-defined sample strategies that are installed with NinjaTrader that you
can explore.
1. Left mouse click on an instrument or instrument list and right mouse click to bring up
the right mouse click menu. Select the menu item Walk Forward... Alternatively left
mouse click on the "w" icon in the Strategy Analyzer toolbar. The default Hot Key
CTRL + W can also be used.
2. Select a strategy from the Strategy slide out menu
3. Set the Walk Forward properties (See the "Understanding Walk Forward properties"
section below for property definitions) and press the OK button.
The Walk Forward progress will be shown in the Status Bar of the Control Center.
Apart from the walk forward optimization specific properties described below, the
properties are identical to the ones found in the Optimization properties window. Please
see the "Understanding optimization properties" section of the Optimize a Strategy page
of the Help Guide for more information.
1. Optimization period (days) - Sets the number of days used for the "in sample"
optimization data set
2. Test period (days) - Sets the number of days used for the "out of sample" real
backtest using the optimized input values generated from the "in sample" period
9.20.5 Basket Test
You can Backtest, Optimize or Walk Forward optimize a basket of instruments by highlighting
an instrument list (such as the "Default" instrument list shown in the image below) and right
mouse clicking. This will bring up the right mouse menu where you can choose to Backtest,
Optimize or Walk Forward test the basket of instruments.
Once the test is complete, a listing of all the results will be displayed. Select an individual row
to display in the Performance tabs individual performance results.
2. The combined backtest results of ALL instruments are shown at the bottom of the results
9.20.6 Reviewing Performance Results
Strategy Analyzer generates performance data that can be viewed in Performance Data
tabs in a new window by right mouse clicking in the desired instrument strategy results and
selecting the menu item Performance Viewer...
1. Left mouse click on the save results icon in the Strategy Analyzer window
2. Enter a name for the results data and press the OK button
1. Left mouse click on the load results icon in the Strategy Analyzer window
2. Left mouse click on the saved test results file and press the OK button.
The following page covers how to set up and run NinjaTrader's Monte Carlo Simulation
1. Open the Monte Carlo Simulation window (see sub-section above for how to open)
2. Set desired simulation parameters and press the Generate button.
X-Axis
The horizontal axis of the Monte Carlo Simulation graph shows the percentage of
simulations that have fallen below the Y - axis value. For example, if you run a Monte
Carlo Simulation setting the # of Simulations to "100" and using the Cumulative
Profit graph, the intersection of the 50% X - value and the associated Y value means
that 50 of your simulations will be below that cumulative profit/loss value, and oppositely
the remaining 50 simulations will have a greater cumulative profit/loss. The above
screenshot shows an example of a worst case scenario of the strategy losing $5602.50
and a best case scenario with the strategy making $2801.25. This type of report allows
you to analyze if the risk/reward ratio between worst and best case scenarios is
acceptable or not.
Y-Axis
The vertical axis of the Monte Carlo Simulation graph displays the measured unit for
the Graph item selected such as Profit/Loss, statistical information, or time.
9.20.9 Discrepancies: Real-Time vs Backtest
You should expect that a strategy running real-time (live brokerage account, live market
simulation, Market Replay etc...) will produce different results than the performance results
generated during a backtest.
As you can see, there are three distinctly different models for how and when an order may be
filled. This is why you may see orders NOT fill in real-time that you may otherwise expect to
see filled based on your backtesting results.
As you can see, there are three different models on what price an order can be filled at.
In conjunction with understanding how to build strategies using the Strategy Wizard, it is
imperative that you:
Understand the overall concepts of developing strategies and how they work
Understand the backtesting options available in the Strategy Analyzer
Once you have developed a NinjaScript strategy you can run it live in full automation
Wizard Screens
Condition Builder
Strategy Actions
5. Press the <Back or Next> buttons to move back or forth between wizard screens
6. Press the Cancel button to leave the Strategy Wizard
Note: Should you want to make a copy of your strategy you can press the View Code...
button and then right click in the NinjaScript Editor and select "Save As...".
average. This then allows you to change the values of the moving averages at run time.
Inputs are also required if you plan to use the Strategy Optimizer or the Walk Forward
Optimization.
Via the wizard, you can have up to ten different condition sets with related actions. If you
require more than ten condition sets, then you should self code your strategy via the
NinjaScript Editor. Conditions are created using the Condition Builder. Actions are
specified by the Strategy Action window.
You can copy and paste conditions from one set to another and you can even save a
condition set as a template and load for future use via the right mouse button click
context menu as show in the image below. You can also save a condition set as a
template (selecting the Save As... menu item) and then re-use it in another strategy at a
later time by selecting the Load... menu item.
Finish Screen
Once you reach this screen you are finished with developing your strategy. Press the
Finish button to compile your strategy which will then be ready for testing or live
execution.
Condition Builder
Most if not all automated trading system code wizards are limited in scope in that they
provide canned pre-defined expressions and only allow you to change a few parameters
on those expressions. The NinjaTrader Condition Builder is advanced in that you can
develop powerful expressions without limitations. Due to its power and flexibility, it is
extremely important that you read through and understand its capabilities.
The Condition Builder is also a very powerful aid for those of you learning NinjaScript
or learning how to program. You can build your conditions within the Condition Builder
and instantly see NinjaScript code generated by having the NinjaScript Editor open ( by
pressing the View Code... button in the wizard screen). You can also use the
Condition Builder from within the NinjaScript Editor directly. By doing so, NinjaScript
code is automatically generated and inserted into your code.
The Condition Builder can be accessed via the Conditions and Actions wizard screen
or the right mouse button click menu of the NinjaScript Editor.
Basic Operation
The general concept of the Condition Builder to generate a Boolean expression also
known as comparison expressions or conditional expressions. What does that mean? It
is simply an expression that results in a value of either TRUE or FALSE. For example,
the expression
is a Boolean expression because the result is TRUE. All expressions that contain
relational operators are Boolean. Boolean expressions or "Conditions" as they are
known in NinjaTrader is used to determine when to take a specified action such as
submitting an order or drawing on the chart.
Looking at the image below, you can instantly see that the Condition Builder is set up
like a Boolean expression. Select an item from the left window, select the relational
operator (2) and compare it to a selected item in the right window.
1. Available items such as indicators, price data, etc. to use for the comparison
2. List of relational operators
Once the OK button is pressed, a condition is created that would translate to the
following:
"Current closing price is greater than the closing price of 1 bar ago"
Percent Adds or subtracts a percentage value of the item's value. A value of 1 is equal
to 100% where a value of 0.1 is equal to 10%.
Price Adds or subtracts an absolute value
Ticks Adds or subtracts the number of ticks (0.01 for stocks and the tick size for
futures or currencies) from the item's value
Once the Offset type is selected, you must set the value Offset. In addition to the
example below, you can see the "Checking for Volume Expansion" section below for
another example that uses the Percent Offset type.
Once the OK button is pressed, a condition is created that would translate to the
following:
"Current closing price is greater than the high price of 1 bar ago + 1 tick"
Once the OK button is pressed, a condition is created that would translate to the
following:
Once the OK button is pressed, a condition is created that would translate to the
following:
"Current K plot value of a Stochastics indicator is greater than the current D plot
value of the same Stochastics indicator"
SMA(9) is how you express a 9 period simple moving average in NinjaScript. If you run a
strategy, you would always be using a 9 period simple moving average. At run time, you
might want to change this value to 10. User defined inputs accomplish this. If you
created an input named "MyInput", you could express the simple moving average as
SMA(MyInput). At run time, you can then configure your strategy by setting the value of
"MyInput" to whatever value you like. In addition, user defined inputs are required when
optimizing a strategy.
User variables (not to be confused with inputs) behave in the same manner with the
exception that they can not be configured when starting a strategy but can only be set
programmatically during run time.
The following is an an example and represents one of many possible combinations. The
example demonstrates the user of a user defined input however the sample approach
applies to user variables.
6. The Condition Builder will look as per the image below with the user defined input
"MAPeriod" assigned to the parameter Period. When you apply this strategy to a
chart, you will be able to set the value for the user defined input which will then be
used to drive the SMA indicator.
Once the OK button is pressed, a condition is created that would translate to the
following:
"Current closing price is greater than the user defined Period simple moving
average"
Once the OK button is pressed, a condition is created that would translate to the
following:
"9 period exponential moving average crosses above the 20 period exponential
moving average in the last bar"
Indicator on Indicator
You can use indicators as input for other indicators... actually, you can nest indicators
within indicators infinitely if you really wanted to!
5. Once you have pressed the OK button, you will notice on the left lower window, the
"Input series" parameters has now been set to the ADX(14) which is the 14 period
ADX indicator.
Once the OK button is pressed, a condition is created that would translate to the
following:
Once the OK button is pressed, a condition is created that would translate to the
following:
"Current value of Volume is greater than or equal to the value of Volume of 1 bar
ago + 300%"
Once the OK button is pressed, a condition is created that would translate to the
following:
Note: Time series represents a collection of bar Date/Time values of a bar series
Once the OK button is pressed, a condition is created that would translate to the
following:
Within a NinjaScript strategy you can invoke miscellaneous actions, submit various
order types for entering and exiting market positions, and have access to various
drawing methods as shown in the images below.
1. Expand the Order management category and select Enter a long position by a
limit order
2. You can set the number of contracts/shares for the order or leave the
DefaultQuantity value which allows you set the quantity when starting a strategy
3. Set the *Signal name property to any user defined value to identify the entry (you can
also leave this name blank)
4. We can set the limit price dynamically by setting it to another item's value, press the "
..." button to open the Value window
*Signal names are important in that they are used as unique identifiers if you have more
than one unique entry in a strategy. By providing unique entry signal names for each
entry on a strategy, you can then identify which position you want closed via the exit
position methods. Signals names are also used to identify executions on a chart.
Once the OK button is pressed, an action is created that would translate to the
following:
"Enter a buy limit order at a price 1 tick below the current bid price to enter a
long position"
1. Expand the Order management category and select Exit long position (exits via
market order)
2. Set the Signal name property to any user defined value to identify the entry (you can
also leave this name blank)
3. Set the From entry signal property to a named entry signal within the strategy.
Providing a value will exit only the quantity associated to the position created by the
named signal. Leaving it blank will exit the total net position.
Once the OK button is pressed, an action is created that would translate to the
following:
"Enter a sell market order to exit from entry signal 'Long Entry'."
Drawing on a Chart
Using the various Drawing methods, you can draw lines, text, squares and more on a
chart. You can review detailed information on supported drawing methods in the
NinjaScript Language Reference section of this Help Guide.
scaling.
4. Set the Bars ago parameter to "0" which will draw the diamond on the current bar x
location
5. Set the Y parameter to the "High" of the current bar plus one tick by pressing the "..."
button to display the Value window
6. Set the Color parameter to any user defined color
Once the OK button is pressed, an action is created that would translate to the
following:
"Draw a red diamond above the high of the current bar plus one tick"
The Time and Sales window can also be customized to meet your trading preferences
through the Time and Sales Properties menu.
9.22.2 Time & Sales Properties
Many of the Time & Sales visual display settings can be customized using the Time &
Sales Properties window.
Property Definitions
Above ask color Sets the text color trades above the ask price
At ask color Sets the text color trades at the ask price
At bid color Sets the text color trades at the bid price
Below bid color Sets the text color for trades below the bid price
Between color Sets the text color for trades between the bid and ask price
Block alert color Sets the back color for block alerts
Color for Sets the back color of the display rows
background
Daily high color Sets the row color for trades at the daily high
Daily low color Sets the row color for trades at the daily low
Block alert trade Sets a value indicating the minimum trade size required to register a
size block trader alert
Display update Sets the interval for updating the display. (Setting to zero will update
interval (sec) tick by tick, but is CPU intensive.)
Rows Sets the number of display rows
Size filter Sets a value indicating the minimum trade size (trades less than this
size are filtered out)
If you change your settings and later wish to go back to the original factory settings, you
can left mouse click on the "Reset" button to return to the factory settings.
9.22.3 Window Linking
Please see the Window Linking section of the Help Guide for more information on linking the
Time & Sales window.
Linking Windows
9.24 Workspaces
Workspaces provide a way for you to manage, organize, and group together windows (such
as charts and order entry windows) in manner that makes sense for the way you work and
trade. These workspaces can be opened, closed, and changed, easily making your daily
setup quick and efficient.
Managing Workspaces
To access all workspace management functions, open the NinjaTrader Control Center,
select the File menu, and then the menu name Workspaces.
A workspace named "Untitled1" will load automatically and cannot be deleted or closed
until a new workspace is created
You can have multiple workspaces open simultaneously
Open workspaces are listed in the caption bar of the Control Center window with a check
mark next to the active workspace (the image above shows two open workspaces,
"Default" and "My Workspace")
The currently displayed workspace has a check mark beside it in the Workspaces menu
(see image right, the workspace "My Workspace" is checked)
You can toggle the currently displayed workspace by selecting the workspace you wish to
display from the Workspaces menu or using the Hot Key SHIFT + F3
On application shut down you will be given the opportunity to save changes in all open
workspaces
Create a Workspace
1. From the NinjaTrader Control Center select the menu File
2. From the File menu select the menu item Workspaces
3. In the Workspaces menu select the menu item New Workspace
4. A new workspace will be created (unsaved) with a generic title such as "Untitled2"
5. Once you have customized the workspace to your liking, you must then save the
workspace (File menu > Workspaces > Save Workspace As... -See the "How to
save a workspace" section listed below for further instructions)
Save a Workspace
1. From the NinjaTrader Control Center select the menu File
2. From the File menu select the menu item Workspaces
3. In the Workspaces menu select the menu item Save Workspace or Save
Workspace As...
4. Any changes made to the currently displayed workspace will be saved
Open a Workspace
1. From the NinjaTrader Control Center select the menu File
2. From the File menu select the menu item Workspaces
3. In the Workspaces menu select the menu item Open Workspace...
4. Within the dialog window "Open Workspace" select the workspace you wish to open
and press the "OK" button
5. The selected workspace will open, a menu item representing the workspace will be
displayed in the Workspaces menu (see "My Workspace" in above image), and the
selected workspace will be set as the currently displayed workspace
Close a Workspace
1. From the NinjaTrader Control Center select the menu File
2. From the File menu select the menu item Workspaces
3. In the Workspaces menu select the menu item Close Workspace
4. The currently displayed workspace will be closed
At least one workspace must remain open, therefore the last workspace cannot be
closed.
Delete a Workspace
1. From the NinjaTrader Control Center select the menu File
2. From the File menu select the menu item Workspaces
3. In the Workspaces menu select the menu item Open Workspace...
4. Within the dialog window "Open Workspace" select the workspace you wish to
delete and press the "Delete" button
X
518 NinjaTrader Version 7
10 NinjaScript
10.1 Distribution
You can distribute custom indicators and strategies to any user of NinjaTrader. The following
section discusses how you can create and share your scripts. If you are a 3rd party
developer, please see the Commercial Distribution section.
Import
Export
Export Problems
Protection/DLL Security
Commercial Distribution
10.1.1 Import
You should only import NinjaScript Archive files (.zip) that you have obtained from a trusted
source.
To import:
1. From the Control Center window select the menu File > Utilities > Import NinjaScript to
open the Import NinjaScript dialog window
2. Select the file you want to import
3. Press the "Open" button
10.1.2 Export
You can export NinjaScript indicators and strategies for others to import in several formats:
Source files - NinjaScript indicator and strategy source files that can be imported and
edited by others
Assemblies - A compiled assembly (DLL) of NinjaScript indicators and strategies that
"hides" your source code. This can be further protected by SecureTeam's CliSecure to
prevent theft of your intellectual property.
Exporting NinjaScript Indicators or Strategies for use in both NinjaTrader 6.5 and 7
Should you wish to create one script file that can be used in both NinjaTrader 6.5 and 7
instead of having one version for 6.5 and another for 7 you can use the following pre-
compiler directive to tag NinjaTrader 7 specific code. When the script is compiled in 7, it
will compile any lines within the tag. When 6.5 is used, the 7 specific code will be
ignored when compiling.
Syntax
#if NT7
Examples
protected override void Initialize()
{
// When NT7 is used to compile this script,
it will compile with the following line. When
NT6.5 is used, the line will be ignored when
compiling.
#if NT7
MaximumBarsLookBack = MaximumBarsLookBack.
Infinite;
#endif
}
10.1.3 Export Problems
If you are having difficulties exporting NinjaScript it could be due to one of the following
reasons:
If you receive the above error, you will need to compile your NinjaScript error-free before
you can export. To see if your NinjaScript file is error free, open the NinjaScript Editor
(Tool > Edit NinjaScript) and press F5 to compile. If you are trying to check a NinjaScript
Strategy created from the Strategy Wizard you can do the same by finishing the wizard
and seeing if you receive the “Strategy successfully generated” message.
If you receive any errors when compiling you will need to address them before exporting.
For more information on compile errors please see this article.
.NET Referencing
If you are able to compile without errors and still experience exporting difficulties like the
one above, check to see if you receive an error similar to this in the Control Center logs:
Note: This error may have a different error code and message depending on which
variant of .NET you have installed. An error message indicative of this issue would
include an indicator name without quotation marks.
1. Take note of which indicator is referenced by the error. In the above example, it is the
SMA
2. Go to your NinjaScript Export utility. (New > Utilities > Export NinjaScript...)
3. Under “Export objects”, select “System indicators”
4. Add the indicator that was referenced in the error to the export list along with your
custom NinjaScript by pressing the > button
5. Press the “Export” button to create your NinjaScript Archive File. If you receive the
same error again, repeat this procedure until you add all the referenced system
indicators and are able to successfully export your custom NinjaScript.
Note: If the indicator referenced in the error is another custom indicator you will need to
follow the same procedure to add the custom indicator.
10.1.4 Protection/DLL Security
NOTE: The information discussed on this page is for a forthcoming version of NinjaTrader 7
and some links may not currently work. Should you have requirements to protect NinjaScript
assemblies in the meantime, please send a note into sales [at] ninjatrader [dot] com.
Although .NET DLL files are compiled which prevents users from being able to see your
proprietary source code, they are still subject to decompilation and reverse engineering
attempts. If you want a higher level of security, you can select the "Protect compiled
assemblies" option (step #3 when exporting as an assembly) which adds an additional layer
of protection. This additional protection layer is provided by SecureTeam's CliSecure product
which has been licensed by NinjaTraderand available for your use free of charge. This
product claims to completely stop MSIL disassembly and decompilation. We use it ourselves
and are extremely happy with it.
Should you wish to use CliSecure for protecting your NinjaScript assemblies you will first
need to go here to download and install it. Once installed, when you select the "Protect
compiled assemblies" option and then export, it will automatically protect your NinjaScript
assembly with CliSecure.
Please note that this version of CliSecure will only work for protecting NinjaScript assemblies
within NinjaTrader. If you would like to protect other files outside of NinjaTrader please
consider purchasing the full version of CliSecure from SecureTeam directly here. NinjaScript
assemblies protected with the full version of CliSecure will also work in NinjaTrader.
10.1.5 Commercial Distribution
As a commercial developer, you can distribute your proprietary indicators and and strategies
to the growing universe of NinjaTrader users. This section contains information you should
understand before distributing your work to the public.
Licensing/User Authentication
Best Practices
Distribution Procedure
NinjaTrader provides a free vendor license management service for user authentication to
qualified 3rd party developers.
One method call within your NinjaScript indicator or strategy will enable the authentication
process
GUI for license management
Licenses are exclusively tied to a combination of user-defined prefix + PC machine id value
ensuring that licenses can't be shared
Create unique module names
Licenses have time based expirations
Create free trial periods
Qualifications include:
You must be a commercial 3rd party developer
Have a website
Promote NinjaTrader on your website and meet our minimum advertising requirements
For more information please contact sales [at] ninjatrader dot com.
10.1.5.2 Best Practices
NinjaTrader makes it easy to distribute complete packages for your clients. Not only can you
distribute your indicators and strategies, but you can also seamlessly deploy your own
custom assemblies, native DLLs, chart templates, and Market Analyzer templates to your
clients.
It is strongly recommended that you export your scripts as an assembly and use
SecureTeam's CliSecure. Only this process will provide you with the highest level of security
possible in order to protect your intellectual property. For more information on using
SecureTeam's CliSecure please see the Protection/DLL Security section.
After you finish using the Export utility you will find the distribution package as a .zip file
located in My Documents\NinjaTrader 7\bin\Custom\ExportNinjaScript. If you only wanted to
distribute your NinjaScript files then providing your customers with this .zip and having them
go through the Import process would install it on their machines. If you wish to add more
custom files to your distribution package, please see the sections below.
Critical: It is important to let your customers know that NinjaTrader Version 7 indicators and
For custom assemblies, you will also need to add to the root of the .zip a .txt file called
AdditionalReferences.txt
Note: If you have multiple custom assemblies to add you can append each of the
assembly's names into the same AdditionalReferences.txt file on new lines
5. Navigate into the "MarketAnalyzer" directory. Copy the .xml Market Analyzer templates
you wish to distribute from My Documents\NinjaTrader 7\templates\MarketAnalyzer to
this directory in the .zip
Note: When modifying the .zip archives, if your zip utility application has an option for storing
or recreating relative paths please be sure to turn this off as it will cause problems when
importing the archive to NinjaTrader.
10.2 Editor
The NinjaScript Editor is a powerful scripting editor that allows you to create custom
indicators and strategies efficiently. The NinjaScript Editor includes powerful coding
assistance and advanced debugging tools to help you custom build your indicator or strategy.
10.2.2 Intellisense
What is Intellisense?
Intellisense is a form of automated autocompletion popularized by the Microsoft Visual
Studio Integrated Development Environment. It also serves as documentation and
disambiguation for variable names, functions and methods. Intellisense is built into the
NinjaScript Editor resulting in an efficient environment to code your custom indicators and
strategies.
If you know that you want to access the Simple Moving Average indicator method which
is SMA(), and you think it starts with "SM" enter "SM" and press CTRL-Space Bar which
would display the Intellisense list box below.
Automatically insert code if the text can uniquely identify a method or property
DMI(int period)
DMI(IDataSeries inputData, int period)
You can quickly add commonly used methods and code structures via
Arithmetic
abs Math.Abs(value)
min Math.Min(value1, value2)
max Math.Max(value1, value2)
Control Statements
if if (expression)
{
}
else
{
break;
case value2:
break;
default:
break;
}
Drawing
dd DrawArrowDown("MyArrowDown", 0, High[0], Color.Red);
du DrawArrowUp("MyArrowUp", 0, Low[0], Color.Red);
ddi DrawDiamond("MyDiamond", 0, High[0] + 2 * TickSize, Color.Blue);
dt DrawDot("MyDot", High[0] + 2 * TickSize, Color.Blue);
de DrawEllipse("MyEllipse", 10, Low[10], 0, High[0], Color.Blue);
di DrawExtendedLine("MyExtendedLine", 10, Close[10], 0, Close[0], Color.Blue);
df DrawFibonacciLevels("MyFibonacciLevels", 10, Close[10], 0, Close[0]);
dh DrawHorizontalLine("MyHorizontalLine", Close[0], Color.Blue);
dl DrawLine("MyLine", 10, Close[10], 0, Close[0], Color.Blue);
dy DrawRay("MyRay", 10, Close[10], 0, Close[0], Color.Blue);
dr DrawRectangle("MyRectangle", 10, Low[10], 0, High[0], Color.Blue);
ds DrawSquare("MySquare", 0, High[0] + 2 * TickSize, Color.Blue);
dx DrawText("MyText", "Sample text ", 0, High[0] + 2 * TickSize, Color.Blue);
dtd DrawTriangleDown("MyTriangleDown", 0, High[0] + 2 * TickSize, Color.Red);
dtu DrawTriangleUp("MyTriangleUp", 0, Low[0] - 2 * TickSize, Color.Blue);
dv DrawVerticalLine("MyVerticalLine", 0, Color.Blue);
The error highlighted by icon (6) below shows that the expression is not closed with a
semicolon. The expression should be:
1. In the NinjaScript Editor enable "Debug Mode". Be sure to compile the NinjaScript
assembly afterwards by pressing "F5" on your keyboard.
2. From within Microsoft Visual Studio select Debug and then select the menu name Attach
to Process.... Now you will select NinjaTrader from the process list and press the "Attach"
button
Note: Please be sure the "Attach to" field is set to "Automatic: Managed code" or "Managed
code".
3. Open the NinjaScript source file within Microsoft Visual Studio and set your break point(s)
4. Run your NinjaScript object in NinjaTrader and it should stop at your break points and all
the debugging tools and information should be available to inspect the current state of the
code.
10.2.7 Compile Error Codes
The following error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
CS0019
CS0021
CS0029
CS0103
CS0117
CS0118
CS0200
CS0201
CS0234
CS0246
CS0428
CS0443
CS0665
CS1002
CS1501
CS1502
CS1503
CS1513
NT0019
NT0029
NT1503
NoDoc
10.2.7.1 CS0019
The following CS0019 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Error Description #1
Operator '==' cannot be applied to operands of type 'string' and 'int'
Error Description #2
Operator ‘<’ cannot be applied to operands of type ‘string’ and ‘double’
Error Description #3
Operator ‘>’ cannot be applied to operands of type ‘string’ and ‘string’
The following CS0021 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
To fix this error you will need to first pass to the indicator method all the necessary parameter
arguments. You can do this with '()' after the indicator name. Please note that you will still
need to pass an empty parameter argument list even if your indicator requires no arguments.
Error Description #1
Cannot apply indexing with [] to an expression of type 'method group'
Example #1
// Erroneous Sample Code - SMA is an indicator and requires
parameter arguments
double value = SMA[0];
Example #2
// Erroneous Sample Code - EMA is an indicator and requires
parameter arguments
double maDelta = EMA[0] - EMA[1];
10.2.7.3 CS0029
The following CS0029 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
To fix this error, ensure that you are assigning the correct value type.
Error Description #1
Cannot implicitly convert type 'int' to 'bool'
Error Description #2
Cannot implicitly convert type 'double' to 'bool'
Error Description #3
Cannot implicitly convert type 'NinjaTrader.Indicator.SMA' to 'double'
The following CS0103 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Please ensure that you have declared your variables prior to using them. If variables are
declared or properties already exist, please check for typos.
Error Description #1
The name 'identifier' does not exist in the current context
Example #1
// Erroneous Sample Code - 'CurentBar' does not exist since it has
been spelled incorrectly (missing an 'r')
if (CurentBar < 10)
Example #2
// Erroneous Sample Code - 'newVariable' is not declared
newVariable = 10;
The following CS0117 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error's code may reflect.
In any case, the examples below provide a reference of coding flaw possibilities.
Please check the methods and exposed property available for your particular object.
Error Description #1
'double' does not contain a definition for 'Set'
// Erroneous Sample Code - DataSeries object’s value does not have
a Set() method. Only a DataSeries object does
SMA(5)[0].Set(5);
Error Description #2
'NinjaTrader.Indicator.CurrentDayOHL' does not contain a definition for 'CurentOpen'
// Erroneous Sample Code - CurrentDayOHL()’s property is
10.2.7.6 CS0118
The following CS0118 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
To fix this error, please replace the round brackets '()' with the proper square brackets '[]'.
Error Description #1
'NinjaTrader.Indicator.IndicatorBase.Close' is a 'property' but is used like a 'method'
10.2.7.7 CS0200
The following CS0200 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
DataSeries indexed values are read only and cannot be changed through assignment
operators. If you wish to set the latest value of the DataSeries please use the Set() method.
Error Description
Property or indexer 'NinjaTrader.Data.IDataSeries.this[int]' cannot be assigned to -- it is read
only
Example #1
Example #2
// Erroneous Sample Code - Cannot reassign values to DataSeries
indexed value and cannot have an if statement based // on an
assignment operator
if (Close[0] = Open[0])
The following CS0201 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
You will need to do something with the value you called for the statement to be complete.
Error Description #1
Only assignment, call, increment, decrement, and new object expressions can be used as a
statement
The following CS0234 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Error Descriptions
The type or namespace name '<name>' could not be found (are you missing a using
directive or an assembly reference?)
The type or namespace name '<name>' does not exist in the namespace 'NinjaTrader.
Indicator' (are you missing an assembly reference?)
10.2.7.10 CS0246
See CS0234.
10.2.7.11 CS0428
The following CS0428 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
If you are calling an indicator please ensure that you have both the parameters '()' and the
indexing value '[]' set. For other methods please ensure you pass all required parameters
through the parameters set '()'.
Error Description #1
Cannot convert method group 'SMA' to non-delegate type 'double'. Did you intend to invoke
the method?
Example #1
// Erroneous Sample Code - SMA() indicator method is improperly
called
double myValue = SMA;
Example #2
// Erroneous Sample Code - ToString is a method and requires round
brackets () to be properly called
string str = Close[5].ToString;
The following CS0443 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Error Description #1
Syntax error, value expected
The following CS0665 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Please ensure that you use (==) when checking if two objects are equal.
Error Description #1
Assignment in conditional expression is always constant; did you mean to use == instead of
=?
10.2.7.14 CS1002
The following CS1002 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Error Description #1
; expected
The following CS1501 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
You can cycle through the available overloads with the use of the up and down arrows on the
Intellisense when you call an indicator method or any other method.
Error Description #1
No overload for method 'SMA' takes '0' arguments
Example #1
// Erroneous Sample Code - SMA() does not contain an overload that
has 3 arguments
double myValue = SMA(Close, 5, 2)[0];
Example #2
// Erroneous Sample Code - EMA() does not contain an overload that
has 0 arguments
10.2.7.16 CS1502
The following CS1502 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Please check the overload methods for the proper parameter object types and pass in the
proper object. You can check the overload methods with NinjaScript editor’s Intellisense
when you call a method.
Error Description #1
The best overloaded method match for 'NinjaTrader.Data.DataSeries.Set(double)' has some
invalid arguments
Error Description #2
The best overloaded method match for 'NinjaTrader.Indicator.Indicator.SMA(NinjaTrader.
Data.IDataSeries, int)' has some invalid arguments
The following CS1503 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Please ensure you are passing in or double in the Set() method. DataSeries objects can only
contain double values.
Error Description #1
Argument '1': cannot convert from 'string' to 'double'
Error Description #2
Argument '1': cannot convert from 'NinjaTrader.Indicator.SMA' to 'double'
The following CS1513 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
Please check all code segments and statements are closed. Every opening curly brace '{'
needs a matching closing curly brace '}' .
Error Description #1
} expected
// Do something
<--- Missing closing curly brace
// Resolution Sample Code - If statement is closed
if (CurrentBar < 1)
{
// Do something
}
10.2.7.19 NT0019
The following NT0019 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
To fix this error ensure that you are actually comparing the values of the DataSeries to
another object. You can do this by adding the index value to the DataSeries call. The index
value is on a zero-based referencing system. [0] references the latest bar while [1]
references one bar ago and [2] references two bars ago.
Error Description #1
Operator '>' cannot be applied to operands of type 'NinjaTrader.Data.IDataSeries' and 'int'
Error Description #2
Operator '==' cannot be applied to operands of type 'int' and 'NinjaTrader.Data.IDataSeries'
Error Description #3
Operator '>' cannot be applied to operands of type 'NinjaTrader.Data.IDataSeries' and
'NinjaTrader.Data.IDataSeries'
// Resolution Sample Code - While the current low is less than the
previous close continue with this code segment
while (Low[0] < Close[1])
10.2.7.20 NT0029
The following NT0029 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
To properly assign the values of a DataSeries to a variable, ensure you have included the
index value to the DataSeries object.
Error Description #1
Cannot implicitly convert type 'NinjaTrader.Data.IDataSeries' to 'double'
The following NT1503 error code information is provided within the context of NinjaScript. The
examples provided are only a subset of potential problems that this error code may reflect. In
any case, the examples below provide a reference of coding flaw possibilities.
DataSeries. DataSeries objects can only take on values that are integers or doubles.
To ensure you are not setting the value of your DataSeries object to another DataSeries
object, use an index value on the DataSeries object that contains the value you want.
Error Description #1
Argument '1': cannot convert from 'NinjaTrader.Data.IDataSeries' to 'double'
Unfortunately we do not have NinjaScript context based Help information on this specific error
code. You can check the Microsoft MSDN site section on error codes for futher information.
Development Tutorials
Basic Programming Concepts Indicators
Developing Indicators Strategies
Developing Strategies
Reference
Reference Samples
Tips
This section will cover some of the basics of C# programming. For an excellent set of more
indepth C# tutorials please see Soft Steel C# Tutorials.
Basic Syntax
Branching Commands
Looping Commands
Functions and Methods Explained
NinjaScript is an extension to the powerful Microsoft C# language. The following syntax guide
is a subset of the capabilities of the C# language. For tutorials and an online reference to the
C# language visit the overview page.
Statements
A statement is analogous to a complete sentence in the English language.
Example:
I like trading.
I like.
Anyone reading this would not know what you like. This is not a complete sentence. The
same logic applies to a C# statement, it forms a complete instruction that can be interpreted
by the compiler.
sum = 10 + 10;
The above statement is complete since we are saying that the variable sum is equal to 10
plus 10. Notice that the statement ends with a semicolon ";" and not a period. In English
sentences end in periods, in C#, statements end with a semicolon.
Building Blocks
Building blocks are analogous to paragraphs in the English language in that they group
statements together. In the programming world we call this a "Block of code". These blocks
are delimited with curly braces "{}" like the following example:
if (x == 5)
{
Print("NinjaTrader");
Print("NinjaScript");
Example:
/* These are comments to illustrate a multi line
comment
block within NinjaScript */
Case Sensitivity
C# is a case-sensitive language which means that "NinjaTrader" with a capital "N" is not the
same as "ninjaTrader" with a lower-case "n".
string
Stores textual data
double
Stores floating point values
integer
Stores whole number values
bool
Stores either true or false
object
Stores objects such as NinjaTrader indicators (in these cases, you would declare the variable
type as the object type itself)
Declaring Variables
To declare a variable in C# you must first declare its data type and then provide a unique
name and optionally assign a value.
In each of the above examples you will notice that the equals character "=" is used to assign
a value to the declared variable.
Operators
C# provides a large set of operators, which are symbols that specify which operations to
perform in a statement. The following is a subset of common operators.
Arithmetic
+ addition
- subtraction
* multiplication
/ division
Would print a value of 1 to the NinjaTrader output window. See a complete list of the Sytem.
Math methods.
Logical
&& and also
|| or else
The above example will print true to the NinjaTrader output window if the variable myString is
equal to 3 and also (&& operator used) the variable myString is equal to NinjaTrader.
Relational
== is equal to
!= does not equal
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Assignment
= equals
+= x += y is equivalent to x = x + y
-= x -= y is equivalent to x = x - y
*= x *= y is equivalent to x = x * y
/= x /= y is equivalent to x = x / y
Conditional
?:
The above conditional statement says assign the value 3 to the variable myInt if 10 is greater
than 12 else assign the value 4 to the variable myInt. The example will then print the value of 4
to the NinjaTrader output window since 10 is not greater than 12.
String Concatenation
To append one string to another string use the "+" character.
The above example would print out NinjaTrader to the NinjaTrader output window.
10.3.1.2 Branching Commands
Branching controls execution flow of your script. It allows you to branch into separate logical
sequences based on decisions you make.
The if Statement
An if statement allows you to take execute different paths of logic depending on a given
condition.
// Either/Or decision
int x = 1;
if (x == 0)
{
Print("NinjaTrader");
}
else
{
Print("NinjaScript");
}
The above example will print NinjaScript to the NinjaTrader output window.
// Switch example
int x = 2;
switch (x)
{
case 0:
Print("x is equal to zero");
break;
case 1:
Print("x is equal to one");
break;
case 2:
Print("x is equal to two");
break;
}
The above example will print out x is equal to two to the NinjaTrader output window.
10.3.1.3 Looping Commands
Looping commands control execution flow of your script. If you wanted to print the word
NinjaTrader 100 times the you could use 100 lines of code or you could do the same using a
While Loop
Example:
Do Loop
do
{
//Do something here
}
while (Boolean expression)
Example:
For Loop
Example:
Foreach Loop
Example:
Lets say you wanted to count the number of oatmeal cookies in a cookie jar.
You can use the break command to exit a loop at any time. The following example is an
infinite loop but we will break after the first print statement.
The continue command will jump ahead to the next iteration of the loop. The following
example will not print NinjaTrader because the continue command sends control back to the
top of the loop each time.
Functions and methods are used to encapsulate a set of statements. They are given a name
and optionally a set of input parameters. They can be called from any point in your
NinjaScript. Once written, we need only be concerned what the function or method does. In
general, the difference between a function and method is that a function returns a value to the
calling routine. C# has done away with the term function and only uses the term method. A
method can return a value (a function) or return nothing.
Declaring a Method
A method must first be declared before you can use it in your script.
Method Access - Sets the access to the method. This topic can be a little complex so lets
just use the access level "private" which is all you will ever likely need.
Return Data Type - Sets the value type that the method return. If it returns nothing, you will
set the return type to "void".
Name - A user defined name for the method
Optional Parameters - Any optional parameters that you may want to pass into the method
}
The above method returns a value of type double so we use the keyword "double", we provide
a user defined method name "Multiply" and we declare that this method takes a parameter
named "input" which is of value type double. Since this method returns a value, we use the
"return" keyword to return the value of (input * 10) back to the calling routine.
Building on our examples from above, we added a call to the PrintDateTime() method within
our Multiply method.
For example:
Lets say you had a script that needed to calculate the average range of the past three bars in
multiple locations. This is where encapsulating the logic to that calculates the range into one
method comes in handy.
First we declare our method using a return type of double and name it AverageRange. There
is no requirement to pass in any parameters. We then write a statement the calculates and
returns the average range of the past three bars. We end up with the method below.
We can then reference the AverageRange method anywhere else in our script like the
example below shows.
Custom indicators are compiled and run natively within the NinjaTrader application
providing the highest performance possible
Indicator values are calculated at the current bar which ensures that you do not accidentally
include future data in your calculations
You can retain calculations between bar updates
You can retain and share calculation values between bar updates across indicators
Wizard
The wizard allows you to define your overall indicator parameters which include name,
properties, inputs, plots and oscillator lines. The wizard will then generate the necessary
NinjaScript code and open up the NinjaScript Editor.
Initialize() Method
The Initialize() method is called once before any initial calculation triggered by an update bar
event. This method is used to configure the indicators plots, lines and properties. The wizard
will generate the required NinjaScript code for this method for most cases.
OnBarUpdate() Method
The OnBarUpdate() method is called with either with each incoming tick or on the close of
each bar depending on how you deploy the indicator at run time. Your core indicator
Debug
The NinjaScript Editor will perform both syntax and semantic checks and list any errors at the
bottom of the NinjaScript Editor. If there are logic problems with your indicator, they will be
listed in the Log tab of the NinjaTrader Control Center during run time. You can use the Print()
method within your script to help debug your code. Output will be sent to the NinjaTrader
Output window.
Compilation
Once the coding effort is completed, you must then compile the indicator (several second
process) directly from the NinjaScript Editor.
Usage
The completed indicator is now available through any window that can use an indicator such
as a Chart window.
Tutorial Descriptions
All internal NinjaTrader indicators come with full source code and can be viewed within the
NinjaScript Editor. Please review the tutorials within this section for detailed walk throughs of
custom indicator development.
The NinjaScript Editor automatically generates required program code on saving and/or
compiling a custom indicator. If you choose to develop custom indicators outside of the
NinjaScript Editor environment, please ensure that you use the NinjaScript Editor to compile.
Please take the time to review this section including the Strategy Development Process.
Prior to running strategies live, please be sure to review the sections about Strategy Position
vs. Account Position and Syncing Account Positions.
Tutorial Descriptions
All internal NinjaTrader indicators and sample strategies come with full source code and can
be viewed within the NinjaScript Editor. Please review the tutorials within this section for
detailed walk throughs of custom strategy development.
Strategy Wizard with Condition Builder - This is a point and click approach for strategy
description which is ideal for everyone from the non-programmer, novice programmer and
advanced programmer.
NinjaScript Editor - This is a modern scripting editor with full inline syntax checking and
intellisense. This is a great approach for those who want to manually code their strategy
logic. If you are going to self code your strategy, please be familiar with the Initialize() and
OnBarUpdate() methods.
Strategy Analyzer - You can backtest, optimize, and analyze your historical results
At this point in the process you will likely go through an iterative cycle by where you change
your strategy description, backtest, change description and backtest until you have a strategy
that meets your requirements.
Simulated Data Feed Connection - This is an random internally generated market with user
controlled trend and is great for force testing operation of a strategy
Market Replay Connection - Record, replay at user defined speeds multiple markets
simultaneously and run your strategies
Real-time Simulation - Connect to your broker or market data vendor in real-time and run
your strategies through our state of the art simulation engine
You can run your strategy from either a chart or the Strategies tab of the Control Center
window. You can generate real-time strategy performance data from the Strategies tab.
Please make sure you fully understand the live run-time options
Live strategy performance will vary from your backtested results
Please make sure you fully understand Strategy Position vs Account Position... your
strategy position is not a one-to-one relationship with your brokerage account position... you
may need to synchronize if they are not synchronized.
Strategies are automatically terminated (stop running) on NinjaTrader shut down
Automated trading does not mean go fishing while your computer trades for you. We highly
recommend that you are within close proximity to your computer while it is running an
automated trading strategy; you never know what can go wrong
You can run multiple trading strategies at the same time in the same market
10.3.3.2 Strategy Position vs. Account Position
Strategy Position
A Strategy Position is a virtual position that is created by the entry and exit executions
generated by a strategy and is independent from any other running strategy’s position or an
Account Position.
Account Position
An Account Position is the position you actually hold in a real-time trading account, whether
it is a NinjaTrader internal simulation account (Sim101) or your live real-money brokerage
account.
In most cases, a trader would want their Strategy Position’s size and market direction to be
equal (in sync) to their Account Position, but there are situations when this may not be the
case.
For example:
You want to run multiple strategies in the same market simultaneously where strategy A
holds a LONG 1 position, strategy B holds a LONG 2 position resulting in an account that
should hold a LONG 3 position in order to be in sync with both strategies
You want to run a strategy and at the same time trade the same market the strategy is
running on using discretionary tactics through one of NinjaTrader advanced order entry
window such as the SuperDOM or Chart Trader
It is critical to understand the various options available to you that determine how the strategy
will behave on startup. NinjaTrader provides several option combinations that can be used in
different scenarios depending on what your requirements are. Please first review the
information about strategy position vs account positions as this article builds on that concept.
The "Wait until flat before executing live" and "Immediately submit live working historical
orders" settings can be found in the Strategies tab of the Options dialogue.
The "Sync account position" option can be found in the NinjaScript strategy dialogue window
when you are adding a strategy.
Wait until flat before executing live, Sync account position = false
These are the default settings for your strategies and are the least disruptive in terms of
handling your current Account Position. It assumes your Account Position is in a flat
state.
When your strategy starts it will check for any active orders previously generated by the
strategy on your account and cancel those first. Should the strategy be unable to cancel
and receive confirmation on the cancellation of these orders within 40 seconds the
strategy will not start and an alert will be issued.
If the Strategy Position is flat, then the Account Position and Strategy Position are
assumed to be in sync with each other. The next order placed by your strategy would
be placed as a live order to your account.
If the Strategy Position is not flat, the strategy will place all trades in a "virtual" sense
until the Strategy Position reaches or crosses a flat state. Once a flat state is
achieved the Strategy Position will be assumed to be in sync with the Account
Position and all future orders will be placed live.
Should your Account Position not be flat at the point in time the Strategy Position
reaches a flat state your Account Position and Strategy Position will NOT be in sync.
Wait until flat before executing live, Sync account position = true
This combination should be used when you want to begin trading your strategy off a flat
state with minimal user interaction to sync your Account Position prior to start.
When your strategy starts it will check for any active orders previously generated by the
strategy on your account and cancel those first. Should the strategy be unable to cancel
and receive confirmation on the cancellation of these orders within 40 seconds the
strategy will not start and an alert will be issued. After the strategy is successful in
cancelling any orders that required action it will check your current Account Position
and compare it to a flat state. On multi-instrument strategies it will perform this check for
all instruments used by the strategy.
If the Account Position is flat already, no reconciliatory order will be submitted. The
strategy will then wait for the Strategy Position to reach a flat state as well before
submitting any orders live.
If the Account Position is not flat, NinjaTrader will submit a market order(s) to
reconcile the Account Position to a flat state. The strategy will then wait for the
Strategy Position to reach a flat state before submitting live orders.
Note: The reconciliatory market order is submitted outside of the strategy so your
strategy will not be able to manage it from methods like OnOrderUpdate(), OnExecution
(), etc.
Immediately submit live working historical orders, Sync account position = false
This combination should only be used when you are sure your Account Position is the
way you want it to be in relation to the Strategy Position prior to strategy start.
Any active orders on the account previously generated by the strategy that does not
match* an active strategy order will be cancelled. Should the strategy be unable to
cancel and receive confirmation on the cancellation of these orders within 40 seconds
the strategy will not start and an alert will be issued.
The matching active orders on the account will then be mapped to the active strategy
orders
Any remaining active strategy orders that cannot be successfully paired will be
submitted live and the strategy will begin managing your Strategy Position assuming
your Account Position is in sync with it.
* A previously generated order is considered to match an active strategy order when the
order action, order type, quantity, limit price, and stop price are exactly identical.
Immediately submit live working historical orders, Sync account position = true
This combination should be used when you want to begin trading with your strategy
immediately while not worrying about your Account Position prior to start.
Any active orders on the account previously generated by the strategy that does not
match* an active strategy order will be cancelled. Should the strategy be unable to
cancel and receive confirmation on the cancellation of these orders within 40 seconds
the strategy will not start and an alert will be issued.
The matching active orders on the account will then be mapped to the active strategy
orders
Any remaining active strategy orders that cannot be successfully paired will be
submitted live and the strategy will then try to sync your Account Position to your
Strategy Position through the process below.
After the strategy is successful in cancelling and submitting any orders that required
action it will check your current Account Position and compare it to your Strategy
Position. On multi-instrument strategies it will perform this check for all instruments
used by the strategy.
If the Account Position matches your Strategy Position, no reconciliatory order will
be submitted. The strategy will then begin managing your Strategy Position
immediately.
If the Account Position does not match your Strategy Position, NinjaTrader will
submit a market order(s) to reconcile the Account Position to match your Strategy
Position. The strategy will then begin managing your Strategy Position immediately.
Note: The reconciliatory market order is submitted outside of the strategy so your
strategy will not be able to manage it from methods like OnOrderUpdate(), OnExecution
(), etc.
* A previously generated order is considered to match an active strategy order when the
order action, order type, quantity, limit price, and stop price are exactly identical.
Please be aware that these options will only help you sync your Account Position to your
Strategy Position once on startup. These options will not guarantee your Account Position
remains in sync afterwards. Any active orders you may have had on your account prior to
strategy start that was not generated by your strategy would not have been cancelled on start
and can lead to your Account Position being out of sync from your Strategy Position.
Placing manual trades or running multiple strategies on the same instrument can also lead to
your Account Position being out of sync from your Strategy Position.
Note: Using "Sync account position = true" can close or place live trades to your
account.
10.3.3.4 Using ATM Strategies
You can create an automated strategy that generates a trade signal that executes a
NinjaTrader ATM Strategy.
ATM Strategies operate in real-time only and will not execute on historical data thus they
can't be backtested
Executions resulting from an ATM Strategy that is created from within a NinjaScript
automated strategy will not plot on a chart during real-time operation
Strategy set up parameters such as EntriesPerDirection, EntryHandling, ExitOnClose do
not apply when calling the AtmStrategyCreate() method
!!! IMPORTANT: Manually Closing an ATM Strategy from an Order Entry Window
such as the SuperDOM
It is crucial that when running ATM Strategies created by a NinjaScript strategy that you
understand how to properly manually close the ATM Strategy from any of the order entry
windows.
If the order entry window ATM Strategy Selection Mode is NOT in "
DisplaySelectedATMStrategyOnly" click on the "CLOSE" button via your middle mouse
button (scroll wheel)
If the order entry window ATM Strategy Selection Mode is in "
DisplaySelectedATMStrategyOnly" you can click on the "CLOSE" button with your left
mouse button to close the selected active ATM strategy
Following the approaches above will internally close the ATM Strategy. Not following the
approach will close the account/instrument position, terminate all strategies and cancel all
orders. The result is that your NinjaScript strategy will be terminated.
10.3.4 Developing Custom Fill and Optimizer Types
NinjaTrader has the flexibility in allowing you to custom define your own fill algorithms and
optimizer types for use with your NinjaScript strategies.
Fill Types
Optimizer Type
This section is under construction however, if you are an advanced C# programmer you can
see the file Documents\<NinjaTrader
Folder>\bin\Custom\Type\@DefaultOptimizationMethod.cs.
10.3.5 Reference Samples
There is a growing repository of NinjaScript tips and reference samples in the NinjaTrader
Support Forum.
10.3.6 Tips
The following pages provide helpful tips when working with NinjaScript indicators or
automated strategies. More information and tips are available on the NinjaTrader Support
Forum.
Naming Conventions
Please use consistent naming convention with your indicators and strategies. We suggest
adding a prefix to an indicator name. If your company name is "Hyper" you could name your
indicators "HyperTrend" or "HyperOscillator" for example.
In the event that you provide NinjaScript export archives (zip files) as your means of
distribution, NinjaTrader 7 will automatically block incompatible scripts from importing so
there will be no confusion by the user as to whether they are installing 6.5 or 7 scripts to their
NinjaTrader installation. It is advisable to include the NinjaTrader version number in the export
archive which will reduce potential support burden. For example, you could name your
indicators “MyIndicator_65.zip” and “MyIndicator_7.zip”.
on NinjaTrader start up or dialog windows that display available indicators and strategies are
loaded. NinjaTrader, LLC provides a free licensing service for qualified 3rd party developers.
Custom Installer
If you provide a custom installer, the installer should not overwrite any NinjaTrader deployed
files (such as UserDefinedMethods.cs) and you should provide an uninstall option which
removes all installed files.
It is also preferred that you provide one installer that provides the user the option to install
either a version 6.5 or version 7 compatible version of your product(s). Ensure that you only
copy the correct files to the correct NinjaTrader installation folders since if you don’t it is
possible that it could cause compile issues for the customer and it will be extremely difficult
for all involved to isolate the cause.
The Microsoft .NET environment has a rich class library that you can access when
developing custom indicators and strategies. There is a plethora of information available
online and in print that details class libraries in great depth. Below are quick links to the
Microsoft Developers Network for some of the basic classes whose functionality you may
harness when developing in NinjaScript.
System.Math
Provides constants and static methods for trigonometric, logarithmic, and other common
mathematical functions.
Full list of member of the System.Math class.
System.DateTime
Represents an instant in time, typically expressed as a data and time of day.
Full list of members of the Sytem.DateTime structure.
System.String
Represents text; that is, a series of unicode characters.
Full list of members of the System.String class.
See this thread for a PDF that outlines the code breaking changes on supported NinjaScript
methods, properties, etc. that needs to be applied to any older NinjaScript files to make them
NinjaTrader 7 compatible.
10.3.6.4 Multi-Threading Consideration for NinjaScript
With the introduction of multi-threading in NinjaTrader when doing things like optimizations
special considerations should be made when programming your NinjaScript indicators and
strategies. Multi-threading basically allows NinjaTrader to take advantage of multi-core CPUs
commonplace in modern computing to do multiple tasks at the same time. What this means
for an optimization run is that multiple iterations can be tested by utilizing the various cores
available to the computer.
Should you be using custom resources like text files, static members, etc. it is important to
protect your resources from concurrent access. If NinjaTrader tried to use the resource at the
same time you would run into errors similar to this one:
NinjaScript supports multi-time frame and instruments in a single script. This is possible
since you can add additional Bars objects to indicators or strategies. A Bars object
represents all of the bars of data on a chart. If you had a MSFT 1 minute chart with 200
minute bars on it, the 200 minute bars represents a Bars object. You can even execute
trades across all the different instruments in a script. There is extreme flexibility in the
NinjaScript model that NinjaTrader uses for multiple-bars scripts so it is very important that
before you incorporate additional Bars objects in a script, you understand how it all works. An
important fact to understand is that NinjaScript is truly event driven; every Bars object in a
script will call the OnBarUpdate() method. What does this mean? It will become evident as
you read further.
It is also important that you understand the following method and properties:
Add()
BarsArray
BarsInProgress
This section is written in sequential fashion. Example code is re-used and built upon from sub
section to sub section.
For the purpose of demonstration, let's assume that a MSFT 1 minute bar is our primary
Bars (set when the script is applied to a 1 minute MSFT chart) and that the Initialize()
method is adding a 3 minute Bars object of MSFT and then adding a 1 minute Bars
object of AAPL for a total of 3 unique Bars objects.
The "Figure 1" image below demonstrates the concept of bar processing on historical
data or in real-time when CalculateOnBarClose property is set to true. The 1 minute
bars in yellow will only know the OHLCV of the 3 minute bar in yellow. The 1 minute bars
in cyan will only know the OHLCV data of the 3 minute bar in cyan. Take a look at "Bar 5"
which is the 5th one minute bar, if you wanted to know the current high value for on the 3
minute time frame, you would get the value of the 1st 3 minute bar since this is the last
"closed" bar. The 2nd 3 minute bar (cyan) is not known at this time.
Contrast the above image and concept with the image below which demonstrates bar
processing in real-time when CalculateOnBarClose property is set to false (tick by tick
processing) . The 1 minute bars in yellow will know the current OHLCV of the 3 minute
bar in yellow (2nd 3 minute bar) which is still in formation...not yet closed.
The point is if you have a multi-time frame script in real-time and it is processing tick by
tick instead of on the close of each bar, understand that the OHLCV data you access in
real-time is different than on historical data.
Your script has complex logic that changes the bar color on the chart. You are running
tick by tick, as per the above "Figure 2" image, the 5th 1 minute bar is looking at OHLCV
data from the 2nd 3 minute bar. Your script changes the 5th 1 minute bar color to green.
In the future you reload your script into the chart (for whatever reason) and the 5th 1
minute bar is now a historical bar. As per "Figure 1" image, the 5th 1 minute bar now
references the OHLCV data of the 1st 3 minute bar (instead of the 2nd 3 minute bar as
per Figure 2) and as a result, your script logic condition for coloring the bar green is no
longer valid. Now your chart looks different.
Carrying on from the example above, our primary Bars is set from a MSFT 1 minute
chart
In the Initialize() method we added a MSFT 3 minute Bars object and an AAPL 1 minute
Bars object to the script
Index values are given to each Bars object as they are added to a script in an
incremental fashion. If there are 10 Bars objects in a script, then you will have index
values ranging from 0 through 9.
Our script now has 3 Bars objects in the container BarsArray. From this point forward,
we can ask this container to give us the Bars object we want to work with by providing
the index value. The syntax for this is:
BarsArray[index]
This allows us to get the correct Bars object and use it as input for an indicator method.
For example:
If the 14 period ADX of MSFT 1 minute is greater than 30 and the 14 period ADX of
AAPL 1 minute is greater than 30
Before we can apply this concept though we would first want to ensure that our Bars
objects actually contain bars that we can run calculations off of. This can be done by
checking the CurrentBars array which returns the number of the current bar in each
Bars object. Using this in conjunction with BarsRequired would ensure each Bars object
has sufficient data before we begin processing.
Putting it all together now, the following example checks if the current CCI value for all
Bars objects is above 200. You will notice that BarsInProgress is used. This is to check
which Bars object is calling the OnBarUpdate() method. More on this later in this
section.
if (BarsInProgress == 0)
{
Since a NinjaScript is truly event driven, the OnBarUpdate() method is called for every
bar update event for each Bars object added to a script. This model provides the utmost
flexibility. For example, you could have multiple trading systems combined into one
strategy dependent on one another. Specifically, you could have a 1 minute MSFT Bars
object and a 1 minute AAPL Bars object, process different trading rules on each Bars
object and check to see if MSFT is long when AAPL trading logic is being processed.
The BarsInProgress property is used to identify which Bars object is calling the
OnBarUpdate() method. This allows you to filter out the events that you want to or don't
want to process.
Continuing our example above, let's take a look at some code to better understand what
is happening. Remember, we have three Bars objects working in our script, a primary
Bars MSFT 1 minute, MSFT 3 minute and AAPL 1 minute.
What is important to understand in the above sample code is that we have "if" branches
that check to see what Bars object is calling the OnBarUpdate() method in order to
process relevant trading logic. If we only wanted to process the events from the primary
Bars we could write our first statement as follows:
if (BarsInProgress != 0)
return;
What is also important to understand is the concept of context. When the OnBarUpdate
() method is called, it will be called within the context of the calling Bars object. This
means that if the primary Bars triggers the OnBarUpdate() method, all indicator methods
and price data will point to that Bars object's data. Looking at the above example, see
how the statement "if (Close[0] > Open[0]" exists under each "if" branch? The values
returned by Close[0] and Open[0] will be the close and open price values for the calling
Bars object. So when the BarsInProgress == 0 (primary Bars) the close value returned
is the close price of the MSFT 1 minute bar. When the BarsInProgress == 1 the close
value returned is the close price of the MSFT 3 minute Bars object.
Notes
1. A multi-series script only processes bar update events from the primary Bars (the
series the script is applied to) and any additional Bars objects the script adds itself.
Additional Bars objects from a multi-series chart or from other multi-series scripts that
may be running concurrently will not be processed by this multi-series script.
2. If a multi-series script adds an additional Bars object that already exists on the chart,
the script will use the preexisting series instead of creating a new one to conserve
memory. This includes that series' session template as applied from the chart. If the
Bars object does not exist on the chart, the session template of the added Bars object
will be the default one set for that instrument in the Instrument Manager and not the
session template of the primary Bars object.
3. In a multi-series script, real-time bar update events for a particular Bars object are
only received when that Bars object has satisfied the BarsRequired requirement. To
ensure you have satisfied the BarsRequired requirement on all your Bars objects it is
recommend you start your OnBarUpdate() method with CurrentBars checks.
4. A multi-series indicator will hold the same number of data points for plots as the
primary series. Setting values to plots should be done in the primary series in
OnBarUpdate(). If you are using calculations based off of a larger secondary series, it
may plot like a step ladder because there are more data points available than there
Close[0];
You can also access price data such as the close price of other Bars objects at any
time. This is accomplished by accessing the Opens, Highs, Lows, Closes, Volumes,
Medians, Typicals and Times series by index value. These properties hold collections
(containers) that hold their named values for all Bars objects in a script.
Continuing with our example code above, if you wanted to access the high price of the
MSFT 3 min Bars object which is at index 1 you would write:
Highs[1][0];
This is just saying give me the series of high prices for the Bars object at index 1 "Highs
[1]" and return to me the current high value "[0]". Now, if the BarsInProgress index was
equal to 1, the current context is of the MSFT 3 min Bars object so you could just write:
High[0];
As you can see above, orders are submitted for MSFT when BarsInProgress is equal to
0 and for AAPL when BarsInProgress is equal to 2. The orders submitted are within the
context of the Bars object calling the OnBarUpdate() method and the instrument
associated to the calling Bars object. There is one exception which is the order placed
for MSFT within the context of the OnBarUpdate() call for AAPL. Each order method has
a variation that allows you to specify the BarsInProgress index value which enables
submission of orders for any instrument within the context of another instrument.
Note: Should you have multiple Bars objects of the same instrument and are using Set()
methods in your strategy, you should only submit orders for this instrument to the first
Bars context of that instrument. This is to ensure your order logic is processed correctly
and any necessary order amendments are done properly.
The property Position always references the position of the instrument of the current
context. If the BarsInProgress is equal to 2 (AAPL 1 minute Bars), Position would refer to
the position being held for AAPL. The property Positions holds a collection of Position
objects for each instrument in a strategy. Note that there is a critical difference here.
Throughout this entire section we have been dealing with Bars objects. Although in our
sample we have three Bars objects (MSFT 1 and 3 min and AAPL 1 min) we only have
two instruments in the strategy.
In the example below, when the OnBarUpdate() method is called for the primary Bars
we also check if the position held for AAPL is NOT flat and then enter a long position in
MSFT. The net result of this strategy is that a long position is entered for AAPL, and then
once AAPL is long, we go long MSFT.
EnterLong();
}
}
10.3.6.6 User Defined Methods
You can create user defined methods (global methods or functions) that can be accessed by
all custom indicators and strategies. User defined methods should ONLY be created if you
intend to re-use these methods over and over again across different custom indicators or
strategies. Otherwise, just code your method logic directly into your indicator or strategy.
UserDefinedMethods.cs
You can define and manage all of your user defined methods from within one of two available
UserDefinedMethods.cs files.
There is one UserDefinedMethods.cs file that contain your user defined methods for
custom strategies
There is one UserDefinedMethods.cs file that contain your user defined methods for
custom indicators
You can not share user defined methods created for custom strategies with custom
indicators. You can edit and manage the UserDefinedMethods.cs file via Tools-->Edit
NinjaScript-->Indicators or Tools-->Edit NinjaScript-->Strategies menus from within the
NinjaTrader Control Center window.
UserDefinedMethods.cs files have unique icons in the Indicators or Strategy Dialog windows.
The following sample illustrates two user defined methods within the strategy
UserDefinedMethods.cs file. You can add methods or edit methods by:
In the image below, there are two user defined methods as examples:
1. IsMorningSession() method which checks if the bar time is in the morning trading session
2. HigherPrices() method which checks if there are n number of higher prices
The following image illustrates the use of the two user defined methods from above in a
custom strategy.
10.3.6.6.2 Sample 2
The following sample is a user defined method created in a separate file used for a custom
strategy. This method returns true or false depending if the current bar time is in a valid user
define trade time.
5. From within the NinjaScript Editor, right click and select the menu "Compile"
You have now created the user defined method "ValidTradeTime" that can be used within any
custom strategy.
6. From within a custom strategy you can call this user defined method as per the image
below.
You can use 3rd party indicators within your strategies or custom indicators. A 3rd party
indicator is an indicator that was not developed by NinjaTrader. It is important to understand
from the 3rd party developer, the functionality provided or NOT provided in their proprietary
indicators. Just because they provide an indicator that displays a bullish or bearish trend on a
chart does NOT mean that you can access this trend state from their indicator.
3rd party indicators can be provided to you in one of the following ways:
NinjaScript archive file that can be directly imported (!!! link to NS Distribution > Import) into
NinjaTrader
A custom installer
A set of files and instructions for saving them in the correct folders
If you were provided with a NinjaScript archive file that you have successfully imported via the
Control Center window "File > Utilities > Import NinjaScript" menu, you can skip over the
information below since NinjaTrader automatically configures the indicators ready for use.
If you were provided with a custom installer or a compiled assembly (.DLL) file that you had to
manually save in the folder My Documents\NinjaTrader Folder>\bin\Custom then you must
follow the instructions below.
Vendor File
The 3rd party developer should have either installed a "Vendor" file or provided you with one.
Its likely in the format "NinjaTrader.VendorName.cs" where VendorName is the name of the
3rd party vendor. This file allows you to conveniently access their indicators.
If you were provided an installer, you can check with the vendor if this file was included or;
If they provided you this file, save it to "My Documents\NinjaTrader Folder>\bin\Custom"
and restart NinjaTrader
Adding a Reference
1. From within any NinjaTrader indicator or
strategy (Tools > Edit NinjaScript Indicator
and open any indicator in the NinjaScript
Editor), right click on your mouse to bring up
the context menu and select the sub-menu
References... as per the image to the right.
New to NinjaTrader 7 is the ability to use historical bid and ask price series in your NinjaScript
instead of only being able to use a last price series. The following outlines the intricacies of
this capability:
You can have multiple bid/ask/last series in your NinjaScript indicator/strategy. Please use
the Add() method to add these series to your script.
The historical bid/ask series holds all bid/ask events sent out by the exchange. This would
not be equivalent to the bid/ask at a specific time a trade went off.
When processing your NinjaScript, the historical bid/ask series would have the historical
portion triggered in the OnBarUpdate() method only. OnMarketData() method events for the
historical bid/ask series would only be triggered in real-time.
When using a Market Replay, the series are synced by their timestamp. These timestamps
are synced only to a 1-second level of tolerance.
In real-time, the events from the various series would be received in whichever sequence
was sent out by the exchange
Developing Indicators
Level 1 - Demonstrating the use of price variables
Level 2 - Demonstrating the use of indicator on indicator
Level 3 - Demonstrating the use of a "for" loop to build a simple moving average
indicator
Level 4 - Demonstrating the use of IndicatorSeries objects to retain historical custom
calculations data series
Level 5 - Demonstrating the use of custom plot coloring based on threshold values
Level 6 - Demonstrating the use of custom of drawing using bar color, back color
and line colors
Level 7 - Demonstrating the use of custom draw objects such as bar markers
Developing Strategies
Level 1 - Simple MA Cross Over (Demonstrates strategy construction by wizard and
scripting)
Level 2 - RSI with Stop Loss & Profit Target (scripting only)
10.3.7.1 Indicators
The following educational tutorials walk you through the indicator development process from
the beginner level through intermediate to advanced topics. More information as well as
development support can be found on the NinjaTrader Support Forum.
Developing Indicators
Level 1 - Demonstrating the use of price variables
Level 2 - Demonstrating the use of indicator on indicator
Level 3 - Demonstrating the use of a "for" loop to build a simple moving average
indicator
Level 4 - Demonstrating the use of IndicatorSeries objects to retain historical custom
calculations data series
Level 5 - Demonstrating the use of custom plot coloring based on threshold values
Level 6 - Demonstrating the use of custom of drawing using bar color, back color
and line colors
In this beginner level tutorial we are going to build a custom indicator that searches for a bar
pattern where the closing price is equal to the opening price. This indicator will show you how
to access price variables and use a conditional operator.
Set Up
Entering Calculation Logic
Compiling
Using
10.3.7.1.1.1 Set Up
The first step in creating a custom indicator is to use the custom indicator wizard. The wizard
will generate the required NinjaScript code that will serve as the foundation for your custom
indicator.
1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button
Defining Plots
Below you will define how your indicator is plotted on a chart.
7. Enter the information as shown above. Note that we changed the "Color" to "Orange" and
the "Type" to "Bar"
8. Press the "Next >" button
9. Enter the information as shown above (make sure the "Name" fields are blank since we do
not need an oscillator line for a simple moving average indicator)
10. Press the "Next >" button
11. We are now finished entering in our indicator set up information. Press the "Finish"
button.
* At any time, you can press the "Generate" button in the wizard if you do not need to go
through each of the wizard steps.
You will now see the NinjaScript Editor preloaded with NinjaScript code generated by the
wizard. It should look something like the image below.
1. This section provides the indicator with the chart display name and description used in the
Indicator Dialog window.
2. The Initialize() section is processed only once when the indicator is initially loaded (added
to a chart for example) and can be used to set up any indicator configuration requirements.
You can see that this wizard generated code that added the plot color and style that we
defined.
3. This is the section that is called on each bar update (incoming tick) and is where you will
enter your indicator logic
10.3.7.1.1.2 Entering Calculation Logic
The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user
defined) when performing real-time calculations and is called on each bar of a data series
when re-calculating the indicator. For example, an indicator would be re-calculated when
adding it to an existing chart that has existing price data displayed. Therefore, this is the main
method called for indicator calculation and we will use this method to enter the script that will
check if the open price is equal to the close price.
The Comparison
Replace the wizard generated code with the following code into the OnBarUpdate() method in
the NinjaScript Editor:
Here we are doing a comparison of the current open price Open[0] and the current close
price Close[0] using a conditional operator "?" and setting a value to the "Plot0" property via
the Set() method. It might look a little intimidating but it is actually quite simple.
if the current open price is equal to the current close price ? use a value of 1 : other wise use
a value of 0
Our indicator then plots a value of 1 when we have a bar with the open price equal to the
close price or a value of 0 otherwise. The OnBarUpdate() method in your editor should look
identical to the image below.
10.3.7.1.1.3 Compiling
The indicator code is now complete and needs to be compiled. You can compile this indicator
from within the NinjaScript Editor right mouse button menu "Compile" menu or simply press
the F5 key. It is important to understand that this process makes the indicator ready for real-
time use and will run natively within NinjaTrader directly. It does not run interpreted as many
other applications do. This provides you with the highest performance possible. If there are
any errors reported during compiling, the error messages will be displayed at the bottom of
the NinjaScript Editor.
10.3.7.1.1.4 Using
Your indicator is now ready for use and will be listed in the Indicator Dialog window.
Once applied to a chart, it can look something like the image below.
In this beginner level tutorial we are going to build a custom indicator that calculates a moving
average of volume. This indicator will show you how to use the built in indicators of Moving
Average (SMA) and Volume.
Set Up
Entering Calculation Logic
Compiling
Using
10.3.7.1.2.1 Set Up
The first step in creating a custom indicator is to use the custom indicator wizard. The wizard
will generate the required NinjaScript code that will serve as the foundation for your custom
indicator.
1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button
Defining Plots
Below you will define how your indicator is plotted on a chart.
9. Enter the information as shown above (make sure the "Name" fields are blank since we do
not need an oscillator line for a simple moving average indicator)
10. Press the "Next >" button
11. We are now finished entering in our indicator set up information. Press "Finish" button.
* At any time, you can press the "Generate" button in the wizard if you do not need to go
through each of the wizard steps.
You will now see the NinjaScript Editor preloaded with NinjaScript code generated by the
wizard. It should look something like the image below.
1. This section provides the indicator with the chart display name and description used in the
Indicator Dialog window.
2. The Initialize() section is processed only once when the indicator is initially loaded (added
to a chart for example) and can be used to set up any indicator configuration requirements.
You can see that this wizard generated code that added the plot color and style and set the
default "Period" parameter that we define to 10.
3. This is the section that is called on each bar update (incoming tick) and is where you will
enter your indicator logic
10.3.7.1.2.2 Entering Calculation Logic
The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user
defined) when performing real-time calculations and is called on each bar of a data series
when re-calculating the indicator. For example, an indicator would be re-calculated when
adding it to an existing chart that has existing price data displayed. Therefore, this is the main
method called for indicator calculation and we will use this method to enter the script that will
calculate a simple moving average of volume.
Replace the wizard generated code with the following code into the OnBarUpdate() method in
Here we declared the variable "average" which is of type double. This serves as the
temporary storage for the current value of the simple moving average of volume. We then
use the simple moving average indicator and pass in the volume indicator as its input, pass in
our indicator "Period" property (a parameter we defined in the wizard) and access the current
value "[0]" that we will assign to our variable "average". If we wanted to assign the value one
bar ago, we could have used "[1]".
Final Assignment
Enter the following code into the OnBarUpdate() method and below the code snippet you
entered above:
Here we assign the "average" value to the property that represents the plot data using its "Set
()" method. We have just finished coding our simple moving average of volume. The
OnBarUpdate() method in your editor should look identical to the image below.
10.3.7.1.2.3 Compiling
The indicator code is now complete and needs to be compiled. You can compile this indicator
from within the NinjaScript Editor right mouse button menu "Compile" menu or simply press
the F5 key. It is important to understand that this process makes the indicator ready for real-
time use and will run natively within NinjaTrader directly. It does not run interpreted as many
other applications do. This provides you with the highest performance possible. If there are
any errors reported during compiling, the error messages will be displayed at the bottom of
the NinjaScript Editor.
10.3.7.1.2.4 Using
Your indicator is now ready for use and will be listed in the Indicator Dialog window.
Once applied to a chart, it can look something like the image below.
In this intermediate level tutorial we are going to build a simple moving average indicator. This
indicator will show you how to use the "for" loop and a single case "if" statement.
Set Up
Entering Calculation Logic
Compiling
Using
10.3.7.1.3.1 Set Up
The first step in creating a custom indicator is to use the custom indicator wizard. The wizard
will generate the required NinjaScript code that will serve as the foundation for your custom
indicator.
1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button
Defining Plots
Below you will define how your indicator is plotted on a chart.
10. Enter the information as shown above (make sure the "Name" fields are blank since we
do not need an oscillator line for a simple moving average indicator)
11. Press the "Next >" button
12. We are now finished entering in our indicator set up information. Press "Finish" button.
* At any time, you can press the "Generate" button in the wizard if you do not need to go
through each of the wizard steps.
You will now see the NinjaScript Editor preloaded with NinjaScript code generated by the
wizard. It should look something like the image below.
1. This section provides the indicator with the chart display name and description used in the
Indicator Dialog window.
2. The Initialize() section is processed only once when the indicator is initially loaded (added
to a chart for example) and can be used to set up any indicator configuration requirements.
You can see that this wizard generated code that added the plot color and style and set the
"Overlay" property which we configured in the wizard in step 4 above. The default value of the
"Period" parameter is set in the "Variables" region of the code above Initialize().
3. This is the section that is called on each bar update (incoming tick) and is where you will
enter your indicator logic
10.3.7.1.3.2 Entering Calculation Logic
The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user
defined) when performing real-time calculations and is called on each bar of a data series
when re-calculating the indicator. For example, an indicator would be re-calculated when
adding it to an existing chart that has existing price data displayed. Therefore, this is the main
method called for indicator calculation and we will use this method to enter the script that will
calculate a simple moving average.
To calculate a 20 period moving average you will need a minimum of 20 bars of data. The
first statement in our OnBarUpdate() method checks to see if there are enough bars of data
to perform the moving average calculation. "CurrentBar" returns the index number of the
current bar and this is checked against the user defined parameter "Period". If the current bar
number is less than the user defined period we "return" which skips calculating the moving
average.
First we must declare a variable that will store our sum total.
double sum = 0;
The variable "sum" whose value is of type "double" will serve as temporary storage.
Next we must calculate the sum. We use a standard "for" loop to skip through prices and add
them to the "sum" variable. Although the command that represents the loop may look
intimidating, its really quite simple. Let's look at it in English....
You can find more information on how loops work here. Once the loop has finished, it will
have calculated the total sum of closing prices for the period of our moving average.
* We use the value of Input[barsAgo] to get a price to use for our calculation. We could have
substituted Close[barsAgo] to use closing prices or High[barsAgo] to use high prices. The
reason we use Input[barsAgo] is since this allows flexibility for what the indicator is
calculated based off of. Remember users have the option to select a price type (High, Open,
Close etc...) from the Indicator Dialog window.
We can now calculate the final moving average value and assign it's value to the property that
represents the plot data. We have just finished coding our simple moving average. The
OnBarUpdate() method in your editor should look identical to the image below.
Alternate Implementation
In this tutorial we are using a "for" loop to iterate through a collection of prices and
accumulate a sum value. We chose this approach to demonstrate the use of a loop. A simple
moving average can actually be expressed in a more efficient manner using the built in SUM
indicator as show below.
The indicator code is now complete and needs to be compiled. You can compile this indicator
from within the NinjaScript Editor right mouse button menu "Compile" menu or simply press
the F5 key. It is important to understand that this process makes the indicator ready for real-
time use and will run natively within NinjaTrader directly. It does not run interpreted as many
other applications do. This provides you with the highest performance possible. If there are
any errors reported during compiling, the error messages will be displayed at the bottom of
the NinjaScript Editor.
10.3.7.1.3.4 Using
Your indicator is now ready for use and will be listed in the Indicator Dialog window.
Once applied to a chart, it can look something like the image below.
In this intermediate level tutorial we are going to build a custom indicator that stores
intermediary calculations without the use of plots. This indicator will show you how to use a
DataSeries object.
Set Up
Entering Calculation Logic
Compiling
Using
10.3.7.1.4.1 Set Up
The first step in creating a custom indicator is to use the custom indicator wizard. The wizard
will generate the required NinjaScript code that will serve as the foundation for your custom
indicator.
1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button
Defining Plots
Below you will define how your indicator is plotted on a chart.
9. Enter the information as shown above (make sure the "Name" fields are blank since we do
not need an oscillator line for a simple moving average indicator)
10. Press the "Next >" button
11. We are now finished entering in our indicator set up information. Press "Finish" button.
* At any time, you can press the "Generate" button in the wizard if you do not need to go
through each of the wizard steps.
You will now see the NinjaScript Editor preloaded with NinjaScript code generated by the
wizard. It should look something like the image below.
The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user
defined) when performing real-time calculations and is called on each bar of a data series
when re-calculating the indicator. For example, an indicator would be re-calculated when
adding it to an existing chart that has existing price data displayed. Therefore, this is the main
method called for indicator calculation and we will use this method to enter the script that will
do our calculations.
#region Variables
private DataSeries myDataSeries; // Declare a
DataSeries variable
#endregion
The value of a DataSeries object will be aligned with the current bar. This means that all
DataSeries objects will be synced with the CurrentBar index. It allows you to store a double
value that corresponds with every bar.
To plot our final calculation we will store the calculation in our Plot0.
1. Remove the wizard generated code in the OnBarUpdate() of “Plot0.Set(Close[0]);”
2. In the OnBarUpdate() method add the following code snippet
Here we assign the SMA + DataSeries value to the property that represents the plot data
using its "Set()" method. We have just finished coding our DataSeries example. The code in
your editor should look identical to the image below.
10.3.7.1.4.3 Compiling
The indicator code is now complete and needs to be compiled. You can compile this indicator
from within the NinjaScript Editor right mouse button menu "Compile" menu or simply press
the F5 key. It is important to understand that this process makes the indicator ready for real-
time use and will run natively within NinjaTrader directly. It does not run interpreted as many
other applications do. This provides you with the highest performance possible. If there are
any errors reported during compiling, the error messages will be displayed at the bottom of
the NinjaScript Editor.
10.3.7.1.4.4 Using
Your indicator is now ready for use and will be listed in the Indicator Dialog window.
Once applied to a chart, it can look something like the image below.
In this advanced level tutorial we are going to build a custom indicator which is a ROC
variation and paints one color above the zero band and another below. This indicator will
show you how to use the concept of plot thresholds.
Set Up
Entering Calculation Logic
Compiling
Using
10.3.7.1.5.1 Set Up
The first step in creating a custom indicator is to use the custom indicator wizard. The wizard
will generate the required NinjaScript code that will serve as the foundation for your custom
indicator.
1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button
5. This indicator requires two parameters "Period" and "Smooth", enter the information as
shown above
6. Press the "Next >" button
Defining Plots
Below you will define how your indicator is plotted on a chart.
7. Enter the information as shown above. Notice that we have added two plots. The
"AboveZero" plot will be plotted if the indicator value is above zero and the "BelowZero" plot
will be plotted if the indicator is below zero. We still have to add the NinjaScript code to make
this possible which is coming later in the tutorial.
8. Press the "Next >" button
9. Enter the information as shown above. We are adding one oscillator line that will be plotted
at a value of zero.
10. Press the "Next >" button
11. We are now finished entering in our indicator set up information. Press "Finish" button.
* At any time, you can press the "Generate" button in the wizard if you do not need to go
through each of the wizard steps.
You will now see the NinjaScript Editor pre loaded with NinjaScript code generated by the
wizard. It should look something like the image below.
The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user
defined) when performing real-time calculations and is called on each bar of a data series
when re-calculating the indicator. For example, an indicator would be re-calculated when
adding it to an existing chart that has existing price data displayed. Therefore, this is the main
method called for indicator calculation and we will use this method to enter the script that will
calculate the ROC value.
Initialize() method. It configures the indicator for two plots and one line and sets the
parameters.
Add(new Plot(Color.FromKnownColor(KnownColor.Green),
PlotStyle.Line, "AboveZero"));
Add(new Plot(Color.FromKnownColor(KnownColor.
OrangeRed), PlotStyle.Line, "BelowZero"));
Add(new Line(Color.FromKnownColor(KnownColor.Black),
0, "ZeroLine"));
Enter the following code in the Initialize() method and below the wizard generated code:
The concept of setting threshold values is to set when and when not to paint a plot on the
chart. In this indicator, we have an "AboveZero" plot with a default color of green which we
only want to see when the value of ROC is above zero and a "BelowZero" plot with a default
color of orangeRed which we only want to see when the value of ROC is below zero. In order
to make that happen we have to set the threshold values of each plot.
Plots[0].Min = 0;
This statement says, in the collection of Plot objects, take the first one (Plots[0]) and set its
minimum value to zero. This means any value below zero will not display.
Plots[1].Max = 0;
This statement says, in the collection of Plot objects, take the second one (Plots[1]) and set
its maximum value to zero. This means any value above zero will not display.
We now have a simple plot switching mechanism that displays the correct colored line
depending on if the value of ROC is above or below zero. In fact, you can take this concept a
little bit farther. You can even set different plots style (bar, dot etc..) depending on threshold
values.
A quick word about collections. Collections are objects that store a collection of objects, kind
of like a container. In this case we are working with a collection of plots. In the above wizard
generated code you will notice that we are adding new plots to the "Plots" collection.
"AboveZero" was added first and then "BelowZero". This means that we can reference the
"AboveZero" plot object through Plots[0]. The reason we don't pass in a value of 1 is because
collections are zero based indexes. This means the first item has an index of 0, the second
time an index of 1 and so forth.
The calculation first checks to ensure there are enough bars to complete the calculation and
then sets both plot lines to the ROC value.
The OnBarUpdate() method in your editor should look identical to the image below.
10.3.7.1.5.3 Compiling
The indicator code is now complete and needs to be compiled. You can compile this indicator
from within the NinjaScript Editor right mouse button menu "Compile" menu or simply press
the F5 key. It is important to understand that this process makes the indicator ready for real-
time use and will run natively within NinjaTrader directly. It does not run interpreted as many
other applications do. This provides you with the highest performance possible. If there are
any errors reported during compiling, the error messages will be displayed at the bottom of
the NinjaScript Editor.
10.3.7.1.5.4 Using
Your indicator is now ready for use and will be listed in the Indicator Dialog window.
Once applied to a chart, it can look something like the image below.
In this advanced level tutorial we are going to build a custom indicator which is a CCI variation
to show different drawing options for bar color, line color and background color.
Set Up
Entering Calculation Logic
Compiling
Using
10.3.7.1.6.1 Set Up
The first step in creating a custom indicator is to use the custom indicator wizard. The wizard
will generate the required NinjaScript code that will serve as the foundation for your custom
indicator.
1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button
5. This indicator requires one parameter, Period, enter the information as shown above
6. Press the "Next >" button
Defining Plots
Below you will define how your indicator is plotted on a chart.
7. Enter the information as shown above. Although the CCI indicator only has one plot, we
have defined three plots above. This is because we are going to turn on/off the display of
each plot depending on the actual CCI value. This will give the illusion that the CCI indicator
line has three different colors.
8. Press the "Next >" button
9. Enter the information as shown above. We are adding two refererence lines, one at +70
and the other at -70.
10. Press the "Next >" button
11. We are now finished entering in our indicator set up information. Press "Finish" button.
* At any time, you can press the "Generate" button in the wizard if you do not need to go
through each of the wizard steps
You will now see the NinjaScript Editor preloaded with NinjaScript code generated by the
wizard. It should look something like the image below.
The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user
defined) when performing real-time calculations and is called on each bar of a data series
when re-calculating the indicator. For example, an indicator would be re-calculated when
adding it to an existing chart that has existing price data displayed. Therefore, this is the main
method called for indicator calculation and we will use this method to enter the script that will
calculate the CCI value and set the conditions used to set custom drawing.
The Initialize() method is called once before any bar data is loaded and is used to configure
the indicator. The code below is automatically generated by the wizard and added to the
Initialize() method. It configures the indicator for three plots and two lines and sets the
parameters.
Add(new Plot(Color.FromKnownColor(KnownColor.
Magenta), PlotStyle.Line, "Above"));
Add(new Plot(Color.FromKnownColor(KnownColor.Black),
PlotStyle.Line, "Neutral"));
Add(new Plot(Color.FromKnownColor(KnownColor.
OrangeRed), PlotStyle.Line, "Below"));
Add(new Line(Color.FromKnownColor(KnownColor.Black),
70, "PosSeventy"));
Add(new Line(Color.FromKnownColor(KnownColor.Black),
-70, "NegSeventy"));
Enter the following code in the Initialize() method and below the wizard generated code:
The third plot named "Below" is of color OrangeRed and has a PlotStyle of line. The code
above changes the DashStyle property of this line from a solid line to a dashed line. This is
accomplished by accessing the plot via Plots[2] syntax. New plots are always added to the
collection Plots in sequence. Based on the wizard generated code above, we can see that
the plot named "Below" was the third added plot. Since collections are always zero based we
pass in the value of 2 (plot 1 = 0, plot 2 = 1, plot 3 = 2 etc...) to then access the Pen used to
draw the plot and change the DashStyle property. This is an advanced topic. Changing this
property can be done by the user of the indicator directly within the Indicator Dialog window.
You can read more about the Pen class here.
Enter the following code in the Initialize() method and below the code entered above:
The code above sets the plot threshold values. The concept of setting threshold values is to
set when and when not to paint a plot on the chart. This topic was covered in greater detail in
the "Custom Plot Colors via Thresholds" Tutorial.
Custom Drawing
Replace the wizard generated code with the following code into the OnBarUpdate() method in
the NinjaScript Editor:
The method first checks to ensure that there are enough bars to perform the calculation and
then assigns the CCI value to the variable value. A multi case if statement is used to
determine when to draw custom graphics.
The first branch checks if the value is greater than 200 and if true, sets the BackColor
property to PaleGreen, sets the BarColor property to yellow, and also sets the
CandleOutlineColor property to black.
BackColor sets the background color of the chart for the current bar.
BarColor sets the color of the current price bar.
CandleOutlineColor sets the color of the outline of the current price bar.
Each successive else if branch checks the value of value and sets custom drawing
properties.
To complete the indicator you must set the indicator value to each plot.
The Initialize() method in your editor should look identical to the image below:
The OnBarUpdate() method in your editor should look identical to the image below:
10.3.7.1.6.3 Compiling
The indicator code is now complete and needs to be compiled. You can compile this indicator
from within the NinjaScript Editor right mouse button menu "Compile" menu or simply press
the F5 key. It is important to understand that this process makes the indicator ready for real-
time use and will run natively within NinjaTrader directly. It does not run interpreted as many
other applications do. This provides you with the highest performance possible. If there are
any errors reported during compiling, the error messages will be displayed at the bottom of
the NinjaScript Editor.
10.3.7.1.6.4 Using
Your indicator is now ready for use and will be listed in the Indicator Dialog window.
Once applied to a chart, it can look something like the image below.
The following educational tutorials walk you through the strategy development process from
the beginner level through intermediate to advanced topics. More information as well as
development support can be found on the NinjaTrader Support Forum.
Developing Strategies
Level 1 - Simple MA Cross Over (Demonstrates strategy construction by wizard and
scripting)
Level 2 - RSI with Stop Loss & Profit Target (scripting only)
In this beginner level tutorial we are going to build a custom automated strategy that goes
long when the fast moving average crosses above the slow moving average and goes short
when the fast moving average crosses below the slow moving average.
Set Up
Creating the Strategy via the Wizard
Creating the Strategy via Self Programming
Compiling
10.3.7.2.1.1 Set Up
The first step in creating a custom strategy is to use the custom strategy wizard. The wizard
provides two options:
1. Within the NinjaTrader Control Center window select the Tools > New NinjaScript >
Strategy... menu
2. Press the "Next >" button
View Code... - Pressing this button loads the strategy code in the NinjaScript Editor for
viewing purposes only. This is a great approach if you are new to programming or you want
to see how the strategy wizard dynamically generates the correct script code on the fly.
Unlock Code - Pressing this button loads the strategy code in the NinjaScript editor for further
manual editing. Once this button is pressed, you can NOT go back to the Wizard for strategy
If you want to proceed with this tutorial through self programming continue here after pressing
the "Unlock Code" button.
10.3.7.2.1.2 Creating the Strategy via the Wizard
1. Press the "Add" button to display the "Condition Builder" window as per the image below
2. Expand the "Indicators" section by clicking on the "+" button and highlight the "SMA"
indicator
3. Select the "Period" property on the lower left window and press the "..." button to open the
"Value" window
4. From the "Value" window, expand the "User defined inputs" section and select the "Fast"
input
5. Press "OK" to assign the user define input "Fast" to the SMA "Period" property
6. Enable this indicator to be plotted on a chart
7. Select "CrossAbove" and set the look back period to a value of "1"
8. Select "SMA" indicator in the right window
9. Set the "Slow" period (just like you did for Fast in step 4)
10. Enable this indicator to be plotted on a chart
If you look at the image above, you just created an initial condition. The condition is "if the fast
simple moving average crosses above the slow simple moving average".
11. Press the "OK" button and you will see the following image
12. Press the "Add" button in the lower right section of the Wizard to bring up the "Strategy
Action" dialog window
13. Expand the "Order management" section by clicking on the "+" button and highlight the
"Enter Long position" action and then press the "OK" button
14. Select the condition as per the image below, right click and select "Copy" from the menu
15. Click on the "Set 2" tab and move your cursor into the conditions area, right click and
select "Paste" from the menu
16. Press the "..." button for the copied condition which will bring up the Condition Builder
17. In the Condition Builder, change the "CrossAbove" function to "CrossBelow"
18. We also want to set to "false" the "Plot on chart" parameters (Step #6) since we already
set them to true on "Set 1" tab
19. Press the "OK" button
20. Repeat steps #12 and #13 except substituting "Enter short position" for "Enter long
position"
21. Complete the remainder of the wizard by pressing the "Next >" button
10.3.7.2.1.3 Creating the Strategy via Self Programming
If you have not done so already, press the "Unlock Code" button within the wizard to launch
the NinjaScript Editor.
The OnBarUpdate() method is called for each incoming tick or on the close of a bar (user
defined) when performing real-time calculations. Therefore, this is the main method called for
strategy calculation and we will use this method to enter the script that check for entry and
exit conditions.
Translated into English, the code contained within the OnBarUpdate() method above reads:
if the fast simple moving average crosses above the slow simple moving average within the
last bar, go long
if the fast simple moving average crosses below the slow simple moving average within the
last bar, go short
CrossAbove() - Checks for a cross above condition and returns true or false
CrossBelow() - Checks for a cross below condition and returns true or false
SMA() - Returns the value of a simple moving average
EnterLong() - Enters a market order long
EnterShort() - Enters a market order short
10.3.7.2.1.4 Compiling
If you completed this tutorial via the Strategy Wizard, simply follow the wizard instructions
to the end at which time the strategy will compile.
If you self coded this tutorial you can compile this strategy from within the NinjaScript Editor
right mouse button menu "Compile" menu or simply press the F5 key.
It is important to understand that this process makes the strategy ready for real-time use and
will run natively within NinjaTrader directly. It does not run interpreted as many other
applications do. This provides you with the highest performance possible. If there are any
errors reported during compiling, the error messages will be displayed at the bottom of the
NinjaScript Editor.
In this intermediate level tutorial we are going to build a custom automated strategy that goes
long when RSI crosses above 20 and exits at a predefined stop loss or profit target,
whichever is hit first. This tutorial is demonstrates the use of the NinjaScript Editor.
Set Up
Entering Strategy Logic
Compiling
10.3.7.2.2.1 Set Up
The first step in creating a custom strategy is to use the custom strategy wizard. The wizard
provides two options:
This tutorial will cover the latter, conscructing a strategy via direct coding in the NinjaScript
editor.
1. Within the NinjaTrader Control Center window select the Tools > New NinjaScript >
Strategy... menu
2. Press the "Next >" button
Enter the code contained within the Initialize() method in the image below into the Initialize()
method in the NinjaScript Editor.
CalculateOnBarClose is set to true and sets the strategy to call the OnBarUpdate() method
below on the close of each bar instead of each incoming tick.
Add() method is called and the RSI() indicator method is passed in which will automatically
plot this indicator on a chart when the strategy runs.
Add(RSI(14, 3))
However, instead of hard coding the period value to 14 and the smooth value to 3, we
substituted the values for the user defined inputs we defined in the wizard. Calling the Add()
method in the following manner:
Add(RSI(RSIPeriod, RSISmooth))
Allows us to change the period and smooth parameters of the embedded RSI indicator in the
strategy at run time. This gives us a higher level of flexibility when working with our strategy.
SetStopLoss() and SetProfitTarget() are called with CalculationMode.Ticks. This means that
when a position is opened, the strategy will immediately submit a stop and target order with a
price that is calculated based on the StopLoss and ProfitTarget parameters passed in offset
from the positions average entry price.
Enter the code contained within the OnBarUpdate() method in the image below into the
Since our strategy exit logic has already been set up in the Initialize() method above, we only
need to focus on expressing our entry logic. The strategy entry logic is very straight forward
and can be translated to English:
if we have not seen the number of bars specified by the user defined input "RSIPeriod" then
do not go any further
CurrentBar - A value representing the current bar being processed (think of a chart where the
left most bar would be equal to one)
CrossAbove() - Checks for a cross above condition and returns true or false
RSI() - Returns the value of the RSI indicator
EnterLong() - Enters a market order long
10.3.7.2.2.3 Compiling
If you completed this tutorial via the Strategy Wizard, simply follow the wizard instructions
to the end at which time the strategy will compile.
If you self coded this tutorial you can compile this strategy from within the NinjaScript Editor
right mouse button menu "Compile" menu or simply press the F5 key.
It is important to understand that this process makes the strategy ready for real-time use and
will run natively within NinjaTrader directly. It does not run interpreted as many other
applications do. This provides you with the highest performance possible. If there are any
errors reported during compiling, the error messages will be displayed at the bottom of the
NinjaScript Editor.
A
AccountSize
Accumulation/Distribution (ADL)
Adaptive Price Zone (APZ)
Add() - Data
Add() - Indicator
Add() - Strategy
AddKagi()
AddLineBreak()
AddPointAndFigure()
AddRenko()
Alert()
AllowRemovalOfDrawObjects
AllTrades
Aroon
Aroon Oscillator
AtmStrategyCancelEntryOrder()
AtmStrategyChangeEntryOrder()
AtmStrategyChangeStopTarget()
AtmStrategyClose()
AtmStrategyCreate()
AutoScale
Average Directional Index (ADX)
Average Directional Movement Rating (ADXR)
Average True Range (ATR)
AvgBarsInTrade
AvgEtd
AvgMae
AvgMfe
AvgPrice
AvgProfit
AvgTradeDuration
B
BackColor
BackColorAll
BackColorAllSeries
BackColorSeries
Balance of Power (BOP)
BarColor
BarColorSeries
Bars
BarsArray
BarsInProgress
BarsPeriod
BarsPeriods
BarsRequired - Indicator
BarsRequired - Strategy
BarsSinceEntry()
BarsSinceExit()
BarsSinceSession
Bollinger Bands
BoolSeries Class
BuySell Pressure
BuySell Volume
C
CalculateOnBarClose
CancelOrder()
CandleStickPattern
CandleOutlineColor
CandleOutlineColorSeries
Chaikin Money Flow
Chaikin Oscillator
Chaikin Volatility
Chande Momentum Oscillator (CMO)
ChangeOrder()
ClearOutputWindow()
Close
Closes
Commission
Commodity Channel Index (CCI)
ConnectionLossHandling
Count - Data
Count - Strategy
CountIf()
CrossAbove()
CrossBelow()
CumProfit
Currency
Current Day OHL
CurrentBar
CurrentBars
D
Darvas
DataSeries Class
DataSeriesConfigurable
DateTimeSeries Class
DayOfWeek
DefaultQuantity
Directional Movement (DM)
Directional Movement Index (DMI)
DisconnetDelaySeconds
Displacement
DisplayInDataBox
Donchian Channel
Double Stochastics
DrawAndrewsPitchfork()
DrawArc()
DrawArrowDown()
DrawArrowLine()
DrawArrowUp()
DrawDiamond()
DrawDot()
DrawDown
DrawEllipse()
DrawExtendedLine()
DrawFibonacciCircle()
DrawFibonacciExtensions()
DrawFibonacciRetracements()
DrawFibonacciTimeExtensions()
DrawGannFan()
DrawHorizontalLine()
DrawLine()
DrawObjects
DrawOnPricePanel
DrawRay()
DrawRectangle()
DrawRegion()
DrawRegressionChannel()
DrawRuler()
DrawSquare()
DrawText()
DrawTextFixed()
DrawTriangle()
DrawTriangleDown()
DrawTriangleUp()
DrawVerticalLine()
Dynamic Momentum Index (DMIndex)
E
Ease of Movement
EnterLong()
EnterLongLimit()
EnterLongStop()
EnterLongStopLimit()
EnterShort()
EnterShortLimit()
EnterShortStop()
EnterShortStopLimit()
EntriesPerDirection
EntryHandling
ExcludeTradeHistoryInBacktest
ExitLong()
ExitLongLimit()
ExitLongStop()
ExitLongStopLimit()
ExitOnClose
ExitOnCloseSeconds
ExitShort()
ExitShortLimit()
ExitShortStop()
ExitShortStopLimit()
Expiry
F
Falling()
FirstBarOfSession
FirstTickOfBar
Fisher Transform
FloatSeries Class
ForceMaximumBarsLookBack256
Forecast Oscillator (FOSC)
FormatPriceMarker()
FullName
FundamentalDataEventArgs
G
GetAccountValue()
GetAtmStrategyEntryOrderStatus()
GetAtmStrategyMarketPosition()
GetAtmStrategyPositionAveragePrice()
GetAtmStrategyPositionQuantity()
GetAtmStrategyRealizedProfitLoss()
GetAtmStrategyStopTargetOrderStatus()
GetAtmStrategyUniqueId()
GetAtmStrategyUnrealizedPrfoitLoss()
GetBar()
GetCurrentAsk()
GetCurrentAskVolume()
GetCurrentBid()
GetCurrentBidVolume()
GetDayBar()
GetMedian()
GetNextBeginEnd
GetProfitLoss()
GetSharpeRatio()
GetTrades()
GrossLoss
GrossProfit
H
Heiken Ashi
High
HighestBar()
Highs
Historical
HorizontalGridLines
I
IAndrewsPitchfork
IArc
IArrowDown
IArrowLine
IArrowUp
IDataSeries
IDiamond
IDot
IDrawObject
IEllipse
IExecution
IExtendedLine
IFibonacciCircle
IFibonacciExtensions
IFibonacciRetracements
IFibonacciTimeExtensions
IGannFan
IgnoreOverFill
IHorizontalLine
ILine
IncludeCommission
InHitTest
Initialize()
Input
Instrument
IntSeries Class
IOrder
IPosition
IRay
IRectangle
IRegion
IRegressionChannel
IRuler
ISquare
IText
ITextFixed
ITriangle
ITriangleDown
ITriangleUp
IVerticalLine
K
Keltner Channel
KeyReversalDown
KeyReversalUp
L
LargestLoser
LargestWinner
Least Recent Occurence (LRO)
Line Class
Linear Regression
Linear Regression Intercept
Linear Regression Slope
Lines
LinesConfigurable
Log()
LongSeries Class
LongTrades
LosingTrades
Low
LowestBar()
Lows
M
MA Envelopes
MACD
MarketDataEventArgs
MarketDepthEventArgs
MarketPosition
MasterInstrument.Compare()
MasterInstrument.InstrumentType
MasterInstrument.Name
MasterInstrument.PointValue
MasterInstrument.Round2TickSize()
MaxConsecLoser
MaxConsecWinner
Maximum (MAX)
MaximumBarsLookBack
MaxRestartAttempts
MaxRestartMinutes
MaxTime2Recover
Median
Medians
Minimum (MIN)
Momentum
Money Flow Index (MFI)
N
n Bars Down
n Bars Up
O
On Balance Volume (OBV)
OnBarUpdate()
OnConnectionStatus()
OnExecution()
OnFundamentalData()
OnMarketData()
OnMarketDepth()
OnOrderUpdate()
OnPositionUpdate()
OnStartUp()
OnTermination()
Open
Opens
Overlay
P
PaintPriceMarkers
Parabolic SAR
Percent
Percentage Price Oscillator (PPO)
PercentComplete
Performance
Pivots
PlaySound()
Plot Class
PlotColors
Plots
PlotsConfigurable
Points
Polarized Fractal Efficiency (PFE)
Positions
Price Oscillator
PriceType
PriceTypeSupported
Print()
Prior Day OHLC
ProfitFactor
ProfitPerMonth
Q
Quantity
R
Range
Range Indicator (RIND)
Rate of Change (ROC)
RealtimeErrorHandling
RealtimeTrades
Regression Channel
Relative Spread Strength (RSS)
Relative Strength Index (RSI)
Relative Volatility Index (RVI)
RemoveDrawObject()
RemoveDrawObjects()
ResetAlert()
ResetAlerts()
RestartDelaySeconds
Rising()
R-squared
S
ScaleJustification
SendMail()
SessionBreakLines
SetProfitTarget()
SetStopLoss()
SetTrailStop()
SharpeRatio
ShortTrades
Slippage
Slope()
Standard Deviation (StdDev)
Standard Error (StdError)
StdDev
Stochastics
Stochastics Fast
Stochastics RSI (StochRSI)
StringSeries Class
SubmitOrder()
Summation (SUM)
Swing
T
TickCount
TickSize
Time
Time Series Forecast (TSF)
TimeInForce
Times
ToDay()
TotalTicks
ToTime()
TraceOrders
Trade Class
TradeCollection
TradesPerDay
TradesPerformance
TradesPerformanceValues
TriggerCustomEvent()
True Strength Index (TSI)
Typical
Typicals
U
Ultimate Oscillator
Unmanaged
Update()
V
Value
Values
VerticalGridLines
Volume
Volume (VOL)
Volume Moving Average (VOLMA)
Volume Oscillator
Volume Rate of Change (VROC)
Volume Up Down
Volumes
W
WaitForOcoClosingBracket
Weighted
Weighteds
Williams %R
WinningTrades
Woodies CCI
Woodies Pivots
Z
ZigZag
Definition
Generates a visual/audible alert for the Alerts window.
Syntax
Alert(string id, Priority priority, string message, string
soundLocation, int rearmSeconds, Color backColor, Color foreColor)
* Calls to this method are ignored on historical data, it will only work in real-time.
Parameters
id A unique id for this alert
priority Any one of the following values:
NinjaTrader.Cbi.Priority.High
NinjaTrader.Cbi.Priority.Low
NinjaTrader.Cbi.Priority.Medium
message Alert message
soundLocation File name of .wav file to play. Provide either the
absolute file path or just the name if the file is
located in C:\Program Files\NinjaTrader Installation
Folder\sounds folder
rearmSeconds Sets the number of seconds an alert will rearm. If
the same alert (identified by the id parameter) is
called within a time window of the time of last alert +
rearmSeconds, the alert will be ignored.
backColor The alert row back color (reference)
foreColor The alert row fore color (reference)
Examples
// Generates an alert
Alert("myAlert", NinjaTrader.Cbi.Priority.High,
"Reached threshold", "Alert1.wav", 10, Color.Black,
Color.Yellow);
10.4.2.2 ClearOutputWindow()
Definition
Clears all data from the NinjaTrader output window
Syntax
ClearOutputWindow()
10.4.2.3 Log()
Definition
Generates log output to the NinjaTrader Control Center window Log tab.
NOTE: Each call to this method creates a log entry which takes memory to keep loaded in
the Log tab of the Control Center. Excessive logging can result in huge portions of memory
being allocated to display the log messages. Please see the NinjaScript section of the
Performance Tips article for more information.
Syntax
Log(string message, LogLevel logLevel)
Parameters
message Alert message
logLevel Sets the message level for the log event. Different
levels are color coded in the NinjaTrader log.
Examples
// Generates a log message
Log("This is a log message", NinjaTrader.Cbi.
LogLevel.Information);
Definition
Plays a .wav file
Syntax
PlaySound(string fileName)
* Calls to this method are ignored on historical data, it will only work in real-time.
Parameters
fileName File name of .wav file to play
Examples
// Plays the wav file mySound.wav
PlaySound(@"C:\mySound.wav");
10.4.2.5 Print()
Definition
Prints data to the NinjaTrader output window.
NOTE: High frequency of Print() method calls can represent a performance hit on your PC.
Please see the NinjaScript section of the Performance Tips article for more information.
Syntax
Print(string message)
Print(bool value)
Print(double value)
Print(int value)
Print(DateTime value)
Parameters
message User defined message
Examples
// Generates a message
Print("This is a message");
Tips
1. You can align prices to be formatted for easier debugging such as Low[0].ToString("0.00").
So if you have
12.5
12.75
12.50
12.75
10.4.2.6 ResetAlert()
Definition
Resets the rearm time of an alert created via the Alert() method.
Syntax
ResetAlert(string id)
Parameters
id The unique id value identifying the alert
10.4.2.7 ResetAlerts()
Definition
Resets the rearm time of all triggered alerts across NinjaTrader regardless of where the
alerts were created.
Syntax
ResetAlert()
10.4.2.8 SendMail()
Definition
Sends an email message.
Syntax
SendMail(string from, string to, string subject, string text)
* Calls to this method are ignored on historical data, it will only work in real-time.
Parameters
from From email address
to To email address
subjecet Subject line of email
text Message body of email
Examples
// Generates an email message
SendMail("[email protected]",
"[email protected]", "Trade Alert", "Buy ES");
Tips
1. If mails are not sent, check the Control Center Log tab for any error information. You can
try changing the SMTP outgoing mail server to use your own ISP's mail server. You can
set this information via the Control Center window Tools > Options > Misc.
10.4.3 Data
The following section documents methods and properties available on both Indicators and
Strategies that access various forms of data including bar data, price data, and statistical
forms of data.
10.4.3.1 Working with Price Data
The core objective of developing custom Indicators and Strategies with NinjaScript is to
evaluate price data. NinjaScript allows you to reference current and historical price data.
There are several categories of price data which include Price Types, Indicator and Custom
Historical Series.
Definitions
Price Type - Standard bar based price types such as closing, opening, high, low prices and
volume
Indicator - Calculated values based on price type values such as a simple moving average
Custom Historical DataSeries - Custom calculated values that you wish to store and
associate to each historical bar
You will notice that to reference any price data you need to include a value for [int
barsAgo]. This is a very simple concept; barsAgo represents the number of bars ago to
reference and int indicates that barsAgo is an integer value. As an example, we could write a
statement to check if the the high price of 1 bar ago is less than the high price of the current
bar like this:
You could write a statement to calculate the average closing price of the last three bars like
this:
As you may have already figured out, referencing the current bar data is accomplished by
passing in a value of 0 (zero) to the barsAgo parameter. Basically, we are saying show me
the price data of zero bars ago, which means the current bar.
* Input is a special property that can be accessed and always points to the default price type.
If you have an indicator that supports using different price type as its source data, if you
reference the Input[in barsAgo] property it will automatically reference the correct price type
object. This is an advanced topic.
indicator(parameters)[int barsAgo]
where indicator is the name of the indicator you want to access, parameters is any
associated parameters the indicator requires and barsAgo is the number of bars we wish to
offset from the current bar.
As an example, we could write a statement to check if the current closing price is greater
than the 20 period simple moving average like this:
If you wanted to perform the same check but only check against a 20 period simple moving
average of high prices you would write it like this:
You could write a statement to see if a 14 period CCI indicator is rising like this:
Please review the Indicator Methods section for proper syntax for accessing different
indicator values.
10.4.3.2 Add()
Definition
Adds a Bars object to an indicator or strategy for developing a multi-series (multi-time frame
or multi-instrument) NinjaScript. When running NinjaScript, you will be able to choose the
primary instrument and bar interval to run on. This primary Bars object will carry a
BarsInProgress index of 0. In a multi-time frame and multi-instrument NinjaScript,
supplementary Bars objects are added via this method in the Initialize() method and given an
incremented BarsInProgress index value. See additional information on running multi-series
scripts.
Syntax
The following syntax will add another Bars object to the strategy for the primary instrument of
the script.
Add(PeriodType periodType, int period)
The following syntax allows you to add another Bars object for a different instrument to the
script.
Add(string instrumentName, PeriodType periodType, int period)
Add(string instrumentName, PeriodType periodType, int period,
MarketDataType marketDataType)
NOTE: You can optionally add the exchange name as a suffix to the symbol name. This is
only advised if the instrument has multiple possible exchanges that it can trade on and it is
configured within the Instrument Manager. For example: Add("MSFT Arca", PeriodType.
Minute, 5).
Parameters
instrumentName An instrument name such as "MSFT"
periodType The period type of the bar such as:
PeriodType.Day
PeriodType.Minute
PeriodType.Tick
PeriodType.Volume
period The period interval such as "3" for 3 minute bars
marketDataType Possible values are:
MarketDataType.Ask
MarketDataType.Bid
MarketDataType.Last
Examples
Definition
Similar to the Add() method for adding Bars objects to an indicator or strategy, this method
adds a Kagi Bars object for multi-series NinjaScript. When running NinjaScript, you will be
able to choose the primary instrument and bar interval to run on. This primary Bars object will
carry a BarsInProgress index of 0. In a multi-time frame and multi-instrument NinjaScript,
supplementary Bars objects are added via this method in the Initialize() method and given an
incremented BarsInProgress index value. See additional information on running multi-bars
scripts.
Syntax
AddKagi(string instrumentName, PeriodType basePeriodType, int
basePeriodTypeValue, int reversal, ReversalType reversalType,
MarketDataType marketDataType)
NOTE: You can optionally add the exchange name as a suffix to the symbol name. This is
only advised if the instrument has multiple possible exchanges that it can trade on and it is
configured within the Instrument Manager. For example: AddKagi("MSFT Arca",
PeriodType.Minute, 1, 2, ReversalType.Tick, MarketDataType.Last).
Parameters
instrumentName An instrument name such as "MSFT"
Examples
protected override void Initialize()
{
// Add a 1 minute Kagi Bars object for the ES
06-10 contract - BarsInProgress index = 1
AddKagi("ES 06-10", PeriodType.Minute, 1, 2,
ReversalType.Tick, MarketDataType.Last);
}
Definition
Similar to the Add() method for adding Bars objects to an indicator or strategy, this method
adds a Line Break Bars object for multi-series NinjaScript. When running NinjaScript, you will
be able to choose the primary instrument and bar interval to run on. This primary Bars object
will carry a BarsInProgress index of 0. In a multi-time frame and multi-instrument NinjaScript,
supplementary Bars objects are added via this method in the Initialize() method and given an
incremented BarsInProgress index value. See additional information on running multi-bars
scripts.
Syntax
AddLineBreak(string instrumentName, PeriodType basePeriodType, int
basePeriodTypeValue, int lineBreakCount, MarketDataType
marketDataType)
NOTE: You can optionally add the exchange name as a suffix to the symbol name. This is
only advised if the instrument has multiple possible exchanges that it can trade on and it is
configured within the Instrument Manager. For example: AddLineBreak("MSFT Arca",
PeriodType.Minute, 1, 3, MarketDataType.Last).
Parameters
instrumentName An instrument name such as "MSFT"
basePeriodType The underlying period type of the Point-and-Figure
such as:
PeriodType.Day
PeriodType.Minute
PeriodType.Tick
PeriodType.Volume
basePeriodTypeValue The underlying period interval such as "3" for 3
minute bars
lineBreakCount Number of bars back used to determine a line break
marketDataType Possible values are:
MarketDataType.Ask
MarketDataType.Bid
MarketDataType.Last
Examples
protected override void Initialize()
{
// Add a 1 minute LineBreak Bars object for the
ES 06-10 contract - BarsInProgress index = 1
AddLineBreak("ES 06-10", PeriodType.Minute, 1,
3, MarketDataType.Last);
}
}
}
10.4.3.5 AddPointAndFigure()
Definition
Similar to the Add() method for adding Bars objects to an indicator or strategy, this method
adds a Point-and-Figure Bars object for multi-series NinjaScript. When running NinjaScript,
you will be able to choose the primary instrument and bar interval to run on. This primary
Bars object will carry a BarsInProgress index of 0. In a multi-time frame and multi-instrument
NinjaScript, supplementary Bars objects are added via this method in the Initialize() method
and given an incremented BarsInProgress index value. See additional information on running
multi-bars scripts.
Syntax
AddPointAndFigure(string instrumentName, PeriodType basePeriodType,
int basePeriodTypeValue, int boxSize, int reversal,
PointAndFigurePriceType pointAndFigurePriceType, MarketDataType
marketDataType)
NOTE: You can optionally add the exchange name as a suffix to the symbol name. This is
only advised if the instrument has multiple possible exchanges that it can trade on and it is
configured within the Instrument Manager. For example: AddPointAndFigure("MSFT Arca",
PeriodType.Minute, 1, 2, 3, PointAndFigurePriceType.Close, MarketDataType.Last).
Parameters
instrumentName An instrument name such as "MSFT"
basePeriodType The underlying period type of the Point-and-Figure
such as:
PeriodType.Day
PeriodType.Minute
PeriodType.Tick
PeriodType.Volume
basePeriodTypeValue The underlying period interval such as "3" for 3
minute bars
boxSize Price movement signified by the X's and O's of a
Point-and-Figure chart
reversal Number of boxes the price needs to move in the
reversal direction before a new column will be built
pointAndFigurePriceT Determines where to base reversal calculations off
ype of.
Examples
protected override void Initialize()
{
// Add a 1 minute Point-and-Figure Bars object
for the ES 06-10 contract - BarsInProgress index = 1
AddPointAndFigure("ES 06-10", PeriodType.Minute,
1, 2, 3, PointAndFigurePriceType.Close,
MarketDataType.Last);
}
Definition
Similar to the Add() method for adding Bars objects to an indicator or strategy, this method
adds a Renko Bars object for multi-series NinjaScript. When running NinjaScript, you will be
able to choose the primary instrument and bar interval to run on. This primary Bars object will
carry a BarsInProgress index of 0. In a multi-time frame and multi-instrument NinjaScript,
supplementary Bars objects are added via this method in the Initialize() method and given an
incremented BarsInProgress index value. See additional information on running multi-bars
scripts.
Syntax
AddRenko(string instrumentName, int brickSize, MarketDataType
marketDataType)
NOTE: You can optionally add the exchange name as a suffix to the symbol name. This is
only advised if the instrument has multiple possible exchanges that it can trade on and it is
configured within the Instrument Manager. For example: AddRenko("MSFT Arca", 2,
MarketDataType.Last).
Parameters
instrumentName An instrument name such as "MSFT"
brickSize The size (in ticks) of each bar
Examples
protected override void Initialize()
{
// Add a 1 minute Renko Bars object for the ES
06-10 contract - BarsInProgress index = 1
AddRenko("ES 06-10", 2, MarketDataType.Last);
}
Definition
Bars objects represent the bars of data being processed by your indicator or strategy.
10.4.3.7.1 BarsSinceSession
Definition
The number of bars that have elapsed since the session started.
Property Value
An int value representing the number of bars elapsed.
Syntax
Bars.BarsSinceSession
Definition
Returns the bar index of the 1st bar from oldest to newest that matches the time stamp
based on the DateTime parameter passed in. If the time stamp passed in is older than the
1st bar, a bar index of 0 is returned. If the time stamp is newer than the last bar, the last bar
index is returned.
Syntax
Bars.GetBar(DateTime time)
Parameters
condition A true/false expression
lookBackPeriod Number of bars to look back to check for the test
condition
Examples
// Check that its past 9:45 AM
if (ToTime(Time[0]) >= ToTime(9, 45, 00))
{
// Calculate the bars ago value for the 9 AM bar
for the current day
int barsAgo = CurrentBar - Bars.GetBar(new
DateTime(2006, 12, 18, 9, 0, 0));
10.4.3.7.3 GetDayBar()
Definition
Returns a Bar object that represents a trading day whose properties for open, high, low,
close, time and volume can be accessed. This bar is a virtual bar built off of the underlying
data series. In some cases, the trading day bar can be used to represent a daily bar. Since
this bar is virtual, its property values are calculated based on session definitions contained in
the trading day only. This does not necessarily represent the actual day. You must check for
a null reference since null is returned if there is insufficient intraday data to build a trading day
bar.
!!! This method should ONLY be used for accessing prior trading day data. To access
current trading day data, use the CurrentDayOHL() method.
Syntax
The properties below return double values:
Bars.GetDayBar(int sessionsAgo).Open
Bars.GetDayBar(int sessionsAgo).High
Bars.GetDayBar(int sessionsAgo).Low
Bars.GetDayBar(int sessionsAgo).Close
Parameters
lookBackPeriod Number of bars back to include in the calculation
series Any DataSeries type object such as an indicator,
Close, High, Low, etc...
Examples
// Print the prior trading day's close
if (Bars.GetDayBar(1) != null)
Print("The prior trading day's close is: " +
Bars.GetDayBar(1).Close.ToString());
10.4.3.7.4 FirstBarOfSession
Definition
Gets a value indicating if the bar is the first bar of a session.
Property Value
This property returns true if the bar is the first bar of a session; otherwise, false.
Syntax
Bars.FirstBarOfSession
Definition
Gets a value indicating the completion percent of a bar.
Will always return a value of zero (0) when working with range bars
Will always return a value of one (1) which represents 100% during a strategy backtest
Property Value
A double value representing a percent. e.g. 50% complete would return 0.5.
Syntax
Bars.PercentComplete
Definition
Contains session template information.
Syntax
Bars.Session
Definition
Returns the date and time representing the next begin/end of a session.
Note: Returned values are paired for the same session. If the next DateTime is the session
end time, the begin time returned will be the paired begin time corresponding with that
session's end time. It is not the next begin time after the end time.
Property Value
A DateTime structure.
Syntax
Bars.Session.GetNextBeginEnd(DateTime time, out DateTime
sessionBegin, out DateTime sessionEnd)
Examples
private DateTime sessionBegin;
private DateTime sessionEnd;
Definition
Returns the name of the session template applied to the Bars object.
Property Value
A string representing the name of the session template.
Syntax
Bars.Session.TemplateName
10.4.3.7.6.3 TimeZoneInfo
Definition
The time zone of the session template.
Property Value
A TimeZoneInfo representing the time zone of the session.
Syntax
Bars.Session.TimeZoneInfo
Property Of
Custom Indicator, Custom Strategy
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// The session template's timezone
Print("The session time zone is: " + Bars.
Session.TimeZoneInfo.Id)
}
10.4.3.7.7 TickCount
Definition
The total number of ticks of the current bar.
Property Value
A int value that represents the total number of ticks of the current bar.
Syntax
Bars.TickCount
Examples
// Prints the tick count to the output window
Print("The tick count of the current bar is " + Bars.
TickCount.ToString());
Definition
Gets a value for the cumulative total of all ticks for all sessions.
Property Value
An int value representing total number of ticks.
Syntax
Bars.TotalTicks
10.4.3.8 BarsArray
Definition
BarsArray is an array holding Bars objects that are added via the Add() method. Bars objects
can be used as input for indicator methods. This property is of primary value when working
with multi-time frame or multi-instrument scripts.
NOTE: This property should NOT be accessed within the Initialize() method.
Property Value
An array of Bars objects.
Syntax
BarsArray[int index]
Examples
protected override void Initialize()
{
// Add a 5 minute Bars object which is added to
the BarArray
// which will take index 1 since the primary
Bars object of the strategy
// will be index 0
Add(PeriodType.Minute, 5);
}
Definition
An index value of the current Bars object that has called the OnBarUpdate() method. In a
multi-bars script, the OnBarUpdate() method is called for each Bars object of a script. This
flexibility allows you to separate trading logic from different bar events. In a single Bars
script this property will always return an index value of 0 representing the primary
Property Value
An int value represents the Bars object that is calling the OnBarUpdate() method.
Syntax
BarsInProgress
Examples
// Lets assume this sample script was added to a ES
12-06 1 minute chart
protected override void Initialize()
{
// Add a 5 minute Bars object: BarsInProgress
index = 1
Add(PeriodType.Minute, 5);
}
Definition
The primary Bars object period type and interval.
NOTE: This property should NOT be accessed within the Initialize() method.
Property Value
A Period object.
Syntax
BarsPeriod. Only relevant for Kagi, LineBreak,
BasePeriodType PointAndFigure, and Renko Bars objects.
Possible values:
PeriodType.Tick
PeriodType.Volume
PeriodType.Second
PeriodType.Range
PeriodType.Minute
PeriodType.Day
PeriodType.Week
PeriodType.Month
PeriodType.Year
PeriodType.Kagi
PeriodType.LineBreak
PeriodType.PointAndFigure
PeriodType.Renko
BarsPeriod. Only relevant for Kagi, LineBreak,
BasePeriodValue PointAndFigure, and Renko Bars objects.
Returns an integer value representing the
basePeriodTypeValue parameter
BarsPeriod.Id Same possible values as BarsPeriod.
BasePeriodType.
BarsPeriod. Possible values:
MarketDataType
MarketDataType.Ask
MarketDataType.Bid
MarketDataType.Last
BarsPeriod. Only relevant for PointAndFigure Bars objects.
PointAndFigurePric Possible values:
eType
PointAndFigurePriceType.Close
PointAndFigurePriceType.HighsAndLows
BarsPeriod. Only relevant for Kagi Bars objects. Possible
ReversalType values:
ReversalType.Percent
ReversalType.Tick
BarsPeriod.Value Returns an integer value representing the period
parameter.
- When using Kagi Bars objects this
represents the "reversal" parameter
- When using LineBreak Bars objects this
represents the "lineBreakCount" parameter
- When using PointAndFigure Bars
Examples
// Calculate only if there is a 100 tick chart or
greater
protected override void OnBarUpdate()
{
if (BarsPeriod.Id == PeriodType.Tick &&
BarsPeriod.Value >= 100)
{
// Indicator calculation logic here
}
}
10.4.3.11 BarsPeriods
Definition
Holds an array of Period objects synchronized to the number of unique Bars objects held
within the parent NinjaScript object. If an indicator holds two Bars series, then BarsPeriods
will hold two Period objects.
Property Value
An array of Periods objects.
Syntax
BarsPeriods[int barSeriesIndex]
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
Print(BarsPeriods[1].Value);
}
10.4.3.12 BoolSeries Class
Definition
A BoolSeries is a special type of data structure that holds a series of bool values and always
contains the same number of elements as bars in a chart. See the DataSeries Class for
related information.
1. Define a variable ("myBoolSeries" used in this example) of type BoolSeries that will hold a
BoolSeries object
2. In the Initialize() method, create a new BoolSeries object and assign it to the
"myBoolSeries" variable
#region Variables
private BoolSeries myBoolSeries; // Define a
BoolSeries variable
#endregion
Note: By default NinjaTrader limits the number of values stored for BoolSeries objects to 256.
This drastically improves memory performance by not holding onto old values that are
generally not needed. Should you need more values than the last 256 please be sure to
create the BoolSeries object so that it stores all values instead through the use of the
MaximumBarsLookBack property.
#region Variables
private BoolSeries myBoolSeries; // Define a
BoolSeries variable
#endregion
BoolSeries.Set(bool value)
Setting a value on a BoolSeries object is automatically aligned to the current bar being
evaluated. This ensures values across all BoolSeries objects are always in sync by the
CurrentBar index. The following code samples demonstrates analyzing the close vs. open
price and then storing the result in a BoolSeries object.
Calling the Reset() method is unique and can be very powerful for custom indicator
development. BoolSeries objects can hold null values which simply means that you do not
want to store a value for the current bar. Reset() will reset the current index value to null.
BoolSeries.ContainsValue(int barsAgo)
Returns a true or false value.
Getting Values
You can access BoolSeries object values using the syntax BoolSeries[int barsAgo]
where barsAgo represents the data value n number of bars ago.
10.4.3.13 CalculateOnBarClose
Definition
If true, OnBarUpdate() is called on the close of each bar otherwise it is called on each
incoming tick. This property should ONLY be set in an Initialize() method and be the last
statement within that method.
When indicators or strategies are running on historical data, OnBarUpdate() is only called
on the close of each historical bar even if this property is set to false. This is due to the fact
that with a historical data set, only the OHLCVT of the bar is known and not each tick that
made up the bar.
The CalculateOnBarClose property of indicators embedded within a strategy are overriden
by the CalculateOnBarClose property of the strategy
Property Value
This property returns true if the value is calculated on the close of each bar; otherwise, false.
Default set to true.
Syntax
CalculateOnBarClose
Examples
protected override void Initialize()
{
// Calculate on the close of each bar
CalculateOnBarClose = true;
}
Tips
1. Calculating indicators or systems for each incoming tick can be CPU intensive. Only
calculate indicators on each incoming tick if you have a requirement to calculate it intra bar.
10.4.3.14 Close
Definition
A collection of historical bar close prices.
Property Value
A DataSeries type object. Accessing this property via an index value [int barsAgo]
Syntax
Close
Close[int barsAgo]
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Checks if the current close is greater than
the prior bar close
if (Close[0] > Close[1])
Print("We had an up day");
}
10.4.3.15 Closes
Definition
Holds an array of DataSeries objects holding historical bar close prices. A DataSeries object
is added to this array when calling the Add() method in a Custom Strategy. Its purpose is to
provide access to the closing prices of all Bars objects in a multi-instrument or multi-time
frame strategy.
Property Value
An array of DataSeries objects.
Syntax
Closes[int barSeriesIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
greater");
}
10.4.3.16 Count
Definition
The total number of bars or data points.
Property Value
An int value representing the the total number of bars.
Syntax
Count
Tips
1. CurrentBar value is guaranteed to be <= Count - 1. This is because of the NinjaTrader
multi-threaded architecture, the Count value can have additional bars as inflight ticks come
in to the system.
10.4.3.17 CountIf()
Definition
Counts the number of occurrences of the test condition over the look back period expressed
in bars. This method will NOT work on multi-series strategies.
Syntax
CountIf(Condition condition, int lookBackPeriod)
Parameters
condition A true/false expression
lookBackPeriod Number of bars to look back to check for the test
condition
Examples
// If in the last 10 bars we have had 8 up bars then
go long
if (CountIf(delegate {return Close[0] > Open[0];},
10) > 8)
EnterLong();
10.4.3.18 CrossAbove()
Definition
Checks for a cross above condition over the specified bar look back period.
Syntax
CrossAbove(IDataSeries series1, double value, int lookBackPeriod)
CrossAbove(IDataSeries series1, IDataSeries series2, int
lookBackPeriod)
Parameters
lookBackPeriod Number of bars back to check the cross above
condition
series1 & series2 Any DataSeries type object such as an indicator,
Close, High, Low, etc...
value Any double value
Examples
// Go short if CCI crossed above 250 within the last
bar
if (CrossAbove(CCI(14), 250, 1))
EnterShort();
Definition
Checks for a cross below condition over the specified bar look back period.
Syntax
CrossBelow(IDataSeries series1, double value, int lookBackPeriod)
CrossBelow(IDataSeries series1, IDataSeries series2, int
lookBackPeriod)
Parameters
lookBackPeriod Number of bars back to check the cross above
condition
series1 & series2 Any DataSeries type object such as an indicator,
Close, High, Low, etc...
value Any double value
Examples
// Go long if CCI crossed above -250 within the last
bar
if (CrossBelow(CCI(14), -250, 1))
EnterLong();
Definition
A number representing the current bar in a Bars object that the OnBarUpdate() method in an
indicator or strategy is currently processing. For example, if a chart has 100 bars of data, the
very first bar of the chart (left most bar) will be number 0 (zero) and each subsequent bar
from left to right is incremented by 1.
Property Value
An int value that represents the current bar.
Syntax
CurrentBar
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Checks to make sure we have at least 20 or
more bars
if (CurrentBar < 20)
return;
Definition
Holds an array of int values representing the number of the current bar in a Bars object. An
int value is added to this array when calling the Add() method in a Custom Indicator/
Strategy. Its purpose is to provide access to the CurrentBar of all Bars objects in a multi-
instrument or multi-time frame indicator/strategy.
Property Value
An array of int values.
Syntax
CurrentBars[int barSeriesIndex]
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the script. It
will automatically be assigned
// a Bars object index of 1 since the primary
data the indicator is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
Definition
A DataSeries is a special type of data structure that holds a series of double values and
always contains the same number of elements as bars in a chart. If you have 200 bars
loaded in your chart with a moving average plotted, the moving average itself holds a
DataSeries object with 200 historical values of data, one for each bar. DataSeries objects
can be used as input data for all indicator methods. The DataSeries class implements the
IDataSeries interface.
1. Define a variable ("myDataSeries" used in this example) of type DataSeries that will hold a
DataSeries object
2. In the Initialize() method, create a new DataSeries object and assign it to the
"myDataSeries" variable
#region Variables
private DataSeries myDataSeries; // Define a
DataSeries variable
#endregion
Note: By default NinjaTrader limits the number of values stored for DataSeries objects to 256.
This drastically improves memory performance by not holding onto old values that are
generally not needed. Should you need more values than the last 256 please be sure to
create the DataSeries object so that it stores all values instead through the use of the
MaximumBarsLookBack property.
#region Variables
private DataSeries myDataSeries; // Define a
DataSeries variable
#endregion
DataSeries.Set(double value)
Setting a value on a DataSeries object is automatically aligned to the current bar being
evaluated. This ensures values across all DataSeries objects are always in sync by the
CurrentBar index. The following code samples demonstrates calculating the range of each
bar and storing the value in a DataSeries object.
Calling the Reset() method is unique and can be very powerful for custom indicator
development. DataSeries objects can hold null values which simply means that you do not
want to store a value for the current bar. Mathematically, you can correctly assign a value of
zero however if the DataSeries was the primary DataSeries of an indicator whose values
would be used for plotting, you may NOT want a zero value plotted. Meaning, you want a zero
value for proper calculations but not a zero value for chart visualization. The Reset() method
allows you to reset the current bar's DataSeries value to a zero for calculation purposes but
NinjaScript would ignore this value when it plotted it on a chart.
DataSeries.ContainsValue(int barsAgo)
Getting Values
You can access DataSeries object values using the syntax DataSeries[int barsAgo]
where barsAgo represents the data value n number of bars ago.
Definition
A DateTimeSeries is a special type of data structure that holds a series of DateTime values
and always contains the same number of elements as bars in a chart. See the DataSeries
Class for related information.
#region Variables
private DateTimeSeries myDateTimeSeries; // Define a
DateTimeSeries variable
#endregion
the variable
protected override void Initialize()
{
myDateTimeSeries = new DateTimeSeries(this); //
"this" refers to the indicator, or strategy
//
itself. This syncs the DateTimeSeries object
//
to historical data bars
}
Note: By default NinjaTrader limits the number of values stored for DateTimeSeries objects to
256. This drastically improves memory performance by not holding onto old values that are
generally not needed. Should you need more values than the last 256 please be sure to
create the DateTimeSeries object so that it stores all values instead through the use of the
MaximumBarsLookBack property.
#region Variables
private DateTimeSeries myDateTimeSeries; // Define a
DateTimeSeries variable
#endregion
DateTimeSeries.Set(DateTime value)
Setting a value on a DateTimeSeries object is automatically aligned to the current bar being
evaluated. This ensures values across all DateTimeSeries objects are always in sync by the
CurrentBar index. The following code samples demonstrates calculating the range of each
bar and storing the value in a DateTimeSeries object.
Calling the Reset() method is unique and can be very powerful for custom indicator
development. DateTimeSeries objects can hold null values which simply means that you do
not want to store a value for the current bar. Reset() will reset the current index value to null.
Getting Values
You can access DateTimeSeries object values using the syntax DateTimeSeries[int
barsAgo] where barsAgo represents the data value n number of bars ago.
10.4.3.24 DayOfWeek
Definition
The day of the week of the current bar accessed through the Time property.
Property Value
A DayOfWeek type such as:
DayOfWeek.Monday
DayOfWeek.Tuesday
DayOfWeek.Wednesday
DayOfWeek.Thursday
DayOfWeek.Friday
DayOfWeek.Saturday
DayOfWeek.Sunday
Syntax
Time[int barsAgo].DayOfWeek
Examples
Definition
Checks for a falling condition which is true when the current value is less than the value of 1
bar ago.
Syntax
Falling(IDataSeries series)
Parameters
series Any DataSeries type object such as an indicator,
Close, High, Low, etc...
Examples
// If the 20 period SMA is falling (in downtrend) go
short
if (Falling(SMA(20)))
EnterShort();
10.4.3.26 FirstTickOfBar
Definition
Indicates if the incoming tick is the first tick of a new bar. This property is only of value in
strategies that run tick by tick which is when the CalculateOnBarClose property is set to
false.
NOTE: This property should NOT be accessed outside of the OnBarUpdate() method.
Property Value
This property returns true if the incoming tick is the first tick of a new bar; otherwise, false.
Syntax
FirstTickOfBar
Examples
// On a tick by tick strategy the only way you know
when a bar is closed is when
// the FirsTickOfBar is true.
protected override void OnBarUpdate()
{
// Only process entry signals on a bar by bar
basis (not tick by tick)
if (FirstTickOfBar)
{
if (CCI(20)[1] < -250)
EnterLong();
return;
}
Definition
A FloatSeries is a special type of data structure that holds a series of float values and always
contains the same number of elements as bars in a chart. See the DataSeries Class for
related information.
#region Variables
private FloatSeries myFloatSeries; // Define a
FloatSeries variable
#endregion
Note: By default NinjaTrader limits the number of values stored for FloatSeries objects to 256.
This drastically improves memory performance by not holding onto old values that are
generally not needed. Should you need more values than the last 256 please be sure to
create the FloatSeries object so that it stores all values instead through the use of the
MaximumBarsLookBack property.
#region Variables
private FloatSeries myFloatSeries; // Define a
FloatSeries variable
#endregion
FloatSeries.Set(float value)
Setting a value on a FloatSeries object is automatically aligned to the current bar being
evaluated. This ensures values across all FloatSeries objects are always in sync by the
CurrentBar index. The following code samples demonstrates calculating the range of each
bar and storing the value in a FloatSeries object.
Calling the Reset() method is unique and can be very powerful for custom indicator
development. FloatSeries objects can hold null values which simply means that you do not
want to store a value for the current bar. Reset() will reset the current index value to null.
FloatSeries.ContainsValue(int barsAgo)
Returns a true or false value.
Getting Values
You can access FloatSeries object values using the syntax FloatSeries[int barsAgo]
where barsAgo represents the data value n number of bars ago.
10.4.3.28 FundamentalDataEventArgs
Definition
Represents a change in fundamental data and is passed as a parameter in the
OnFundamentalData() method.
PercentHeldByInstitutions
PriceEarningsRatio
SharesOutstanding
LongValue A long value representing fundamental data
ToString() A string representation of the
FundamentalDataEventArgs object
Examples
protected override void OnFundamentalData
(FundamentalDataEventArgs e)
{
// Print some data to the Output window
if (e.FundamentalDataType ==
FundamentalDataType.AverageDailyVolume)
Print("Average Daily Volume = " + e.
LongValue);
else if (e.FundamentalDataType ==
FundamentalDataType.PriceEarningsRatio)
Print("P/E Ratio = " + e.DoubleValue);
}
Tips
1. Not all connectivity providers support all FundamentalDataTypes.
10.4.3.29 GetCurrentAsk()
Definition
Returns the current ask price.
Syntax
GetCurrentAsk()
GetCurrentAsk(int barSeriesIndex)
10.4.3.30 GetCurrentAskVolume()
Definition
Returns the current ask volume.
Syntax
GetCurrentAskVolume()
GetCurrentAskVolume(int barSeriesIndex)
10.4.3.31 GetCurrentBid()
Definition
Returns the current bid price.
Syntax
GetCurrentBid()
GetCurrentBid(int barSeriesIndex)
10.4.3.32 GetCurrentBidVolume()
Definition
Returns the current bid volume.
Syntax
GetCurrentBidVolume()
GetCurrentBidVolume(int barSeriesIndex)
10.4.3.33 GetMedian()
Definition
Returns the median value of the specified series over the specified look back period. This
method will sort the values of the specified look back period in ascending order and return the
middle value. If an even number is passed in, the average of the two middle values in the
sorted values will be returned.
Syntax
GetMedian(IDataSeries series, int lookBackPeriod)
Parameters
lookBackPeriod Number of bars back to include in the calculation
series Any DataSeries type object such as an indicator,
Close, High, Low, etc...
Examples
// Print the median price of the last 10 open prices
if (GetMedian(Open, 10))
Print("The median of the last 10 open prices is:
Definition
A collection of historical bar high prices.
Property Value
A DataSeries type object. Accessing this property via an index value [int barsAgo]
returns a double value representing the price of the referenced bar.
Syntax
High
High[int barsAgo]
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Make sure we have at least 20 bars
if (CurrentBar < 20)
return;
10.4.3.35 HighestBar()
Definition
Returns the number of bars ago the highest price value occurred for the lookback period.
Syntax
HighestBar(IDataSeries series, int lookBackPeriod)
Parameters
lookBackPeriod Number of bars back to include in the calculation
series Any DataSeries type object such as an indicator,
Close, High, Low, etc...
Examples
// Prints out the number of bars ago for the highest
close of the current session
Print(HighestBar(Close, Bars.BarsSinceSession - 1).
ToString());
10.4.3.36 Highs
Definition
Holds an array of DataSeries objects holding historical bar high prices. A DataSeries object is
added to this array when calling the Add() method in a Custom Strategy. Its purpose is to
provide access to the high prices of all Bars objects in a multi-instrument or multi-time frame
strategy.
Property Value
An array of DataSeries objects.
Syntax
Highs[int barSeriesIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
10.4.3.37 Historical
Definition
Indicates if the NinjaScript object is running on historical data. With a strategy, when running
a backtest, this property will always return true. When running a live strategy, this property will
be true until the strategy starts processing real-time data. The property can be of value for
1. Filtering out historical data for real-time strategies that does not require any historical data
to initialize.
Property Value
This property returns true if the NinjaScript is running on historical data; otherwise, false.
Syntax
Historical
Examples
protected override void OnBarUpdate()
{
// Only run on real-time data
if (Historical)
return;
}
Tips
1. When using this property in a strategy that is running with "Wait until flat before executing
live", the property will return "true" until the strategy reaches a flat state and switches to live
executions.
10.4.3.38 IDataSeries
Definition
IDataSeries is an interface that is implemented by all NinjaScript classes that manage
historical data such as DataSeries, Indicators and other classes. The relevance of this boils
down to one practical use which is providing you with the means to write a method that has
flexibility in the types of price data arrays it can accept. By specifying a parameter of type
IDataSeries, you can then pass in an array of closing prices, an indicator or a user defined
data series.
The sample code below demonstrates a method named DoubleTheValue that accepts any
object that implements the IDataSeries interface as a parameter. This method is then used
twice, the first time passing in an array of closing prices and the second time passing in a 20
period simple moving average.
Tips
1. When working with IDataSeries objects in your code you may come across situations
where you are not sure if the value being accessed is a valid value or just a "placeholder"
value. To check if you are using valid values for your logic calculations that have been
explicitly set, please use .IsValidPlot(int barIdx) to check.
Definition
The Initialize() method is called once when starting a strategy. This method can be used to
configure indicator and strategy properties.
For example:
Strategies - Call the Add() method to add indicators to charts and to add additional Bars
objects to the strategy
Indicators - Set configuration properties such as Overlay and PaintPriceMarkers
Although this method is called once on the start of an indicator or strategy, there are times
that this method is also called (Opening an indicator dialog) when you may not expect it to.
FOR ADVANCED PROGRAMMERS, DO NOT USE THIS METHOD TO RUN CUSTOM
ROUTINES SUCH AS OPENING FORMS, MAKING EXTERNAL CALLS SUCH AS A
LICENSE CHECK. PLEASE USE OnStartUp() FOR THOSE PURPOSES.
Syntax
See example below. The NinjaScript indicator and strategy wizards automatically generate
the method syntax for you.
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
Definition
The main data input.
Property Value
A data series type object that implements the IDataSeries interface. Accessing this property
via an index value [int barsAgo] returns a double value representing the price of the
referenced bar.
Syntax
Input
Input[int barsAgo]
Examples
// Prints the the current value of input
Print(Input[0].ToString());
Tips
1. Input represents the input data source of the indicator. If you implement an indicator where
PriceTypeSupported is set to true, then when referencing the input data source value, you
will want to reference Input[0] instead of Close[0]. This is because Input[0] will return the
data value of the seleced PriceType.
2. When working with multi-series indicators, Input always references BarsInProgress 0.
Please be mindful as to when you access Input[0] as you will only be able to do so after
BarsInProgress 0 has bars. To check to ensure BarsInProgress 0 has some bars you can
use CurrentBars[0] to check.
10.4.3.41 Instrument
Definition
A tradeable instrument.
NOTE: The properties in this class should NOT be accessed within the Initialize() method.
MSFT)
MasterInstrument.PointValue Currency value of 1 full point of movement
MasterInstrument. Rounds the value to the nearest valid value
Round2TickSize()
10.4.3.41.1 Expiry
Definition
Returns the expiration date of a futures contract.
Property Value
A DateTime structure representing the expiration date of a futures contract.
Syntax
Instrument.Expiry
Definition
Returns the full NinjaTrader name of an instrument. For futures, this would include the
expiration date. The June S&P 500 Emini contract full name is "ES 09-09".
Property Value
A string representing the full name of the instrument.
Syntax
Instrument.FullName
Definition
Compares two price values with respect to the Instrument TickSize to ensure accuracy when
dealing with floating point math.
Syntax
Instrument.MasterInstrument.Compare(double price1, double price2)
Parameters
price1 A double value representing a price
price2 A double value representing a price
Examples
double newPrice = Close[0] + High[0] + Open[0];
if (Instrument.MasterInstrument.Compare(newPrice,
Close[1]) == 1)
// Do something since price1 is greater than
price2
10.4.3.41.4 MasterInstrument.InstrumentType
Definition
Returns the type of instrument.
Property Value
An InstrumentType representing the type of an instrument.
Syntax
Instrument.MasterInstrument.InstrumentType
Definition
Returns the NinjaTrader database name of an instrument. For example, "MSFT", "ES", "ER2"
etc...
Property Value
Syntax
Instrument.MasterInstrument.Name
Definition
Returns the currency value of 1 full point of movement. For example, 1 point in the S&P 500
Emini futures contract (ES) is $50 USD which is equal to $12.50 USD per tick.
Property Value
A double value representing the currency value of 1 point of movement.
Syntax
Instrument.MasterInstrument.PointValue
Definition
Returns a value that is rounded to the nearest valid value evenly divisible by the instrument's
tick size.
Syntax
Instrument.MasterInstrument.Round2TickSize(double price)
Parameters
price A double value representing a price
Definition
An IntSeries is a special type of data structure that holds a series of int values and always
contains the same number of elements as bars in a chart. See the DataSeries Class for
related information.
1. Define a variable ("myIntSeries" used in this example) of type IntSeries that will hold a
IntSeries object
2. In the Initialize() method, create a new IntSeries object and assign it to the "myIntSeries"
variable
#region Variables
private IntSeries myIntSeries; // Define a IntSeries
variable
#endregion
Note: By default NinjaTrader limits the number of values stored for IntSeries objects to 256.
This drastically improves memory performance by not holding onto old values that are
generally not needed. Should you need more values than the last 256 please be sure to
create the IntSeries object so that it stores all values instead through the use of the
MaximumBarsLookBack property.
#region Variables
private IntSeries myIntSeries; // Define a IntSeries
variable
#endregion
IntSeries.Set(int value)
Setting a value on a IntSeries object is automatically aligned to the current bar being
evaluated. This ensures values across all IntSeries objects are always in sync by the
CurrentBar index. The following code samples demonstrates calculating the range of each
bar and storing the value in an IntSeries object.
Calling the Reset() method is unique and can be very powerful for custom indicator
development. IntSeries objects can hold null values which simply means that you do not want
to store a value for the current bar. Reset() will reset the current index value to null.
IntSeries.ContainsValue(int barsAgo)
Returns a true or false value.
Getting Values
You can access IntSeries object values using the syntax IntSeries[int barsAgo]
where barsAgo represents the data value n number of bars ago.
Definition
Returns the number of bars ago that the test condition evaluated to true within the specified
look back period expressed in bars. It checks from the furthest bar away and works toward
the current bar. This method will NOT work on multi-instrument or multi-time frame
strategies.
Syntax
LRO(Condition condition, int instance, int lookBackPeriod)
Parameters
condition A true/false expression
instance The occurrence to check for (1 is the least recent, 2
is the 2nd least recent, etc...)
lookBackPeriod Number of bars to look back to check for the test
condition
Examples
// Prints the high price of the least recent up bar
over the last 10 bars
int barsAgo = LRO(delegate {return Close[0] > Open
[0];}, 1, 10);
if (barsAgo > -1)
Print("The bar high was " + High[barsAgo]);
See Also
Most Recent Occurence(MRO)
10.4.3.44 LongSeries Class
Definition
A LongSeries is a special type of data structure that holds a series of long values and
always contains the same number of elements as bars in a chart. See the DataSeries Class
1. Define a variable ("myLongSeries" used in this example) of type LongSeries that will hold a
LongSeries object
2. In the Initialize() method, create a new LongSeries object and assign it to the
"myLongSeries" variable
#region Variables
private LongSeries myLongSeries; // Define a
LongSeries variable
#endregion
Note: By default NinjaTrader limits the number of values stored for LongSeries objects to 256.
This drastically improves memory performance by not holding onto old values that are
generally not needed. Should you need more values than the last 256 please be sure to
create the LongSeries object so that it stores all values instead through the use of the
MaximumBarsLookBack property.
#region Variables
private LongSeries myLongSeries; // Define a
LongSeries variable
#endregion
MaximumBarsLookBack.Infinite);
}
LongSeries.Set(int value)
Setting a value on a LongSeries object is automatically aligned to the current bar being
evaluated. This ensures values across all LongSeries objects are always in sync by the
CurrentBar index. The following code samples demonstrates calculating the range of each
bar and storing the value in an LongSeries object.
Calling the Reset() method is unique and can be very powerful for custom indicator
development. LongSeries objects can hold null values which simply means that you do not
want to store a value for the current bar. Reset() will reset the current index value to null.
LongSeries.ContainsValue(int barsAgo)
Returns a true or false value.
Getting Values
You can access LongSeries object values using the syntax LongSeries[int barsAgo]
where barsAgo represents the data value n number of bars ago.
10.4.3.45 Low
Definition
A collection of historical bar low prices.
Property Value
A DataSeries type object. Accessing this property via an index value [int barsAgo]
returns a double value representing the price of the referenced bar.
Syntax
Low
Low[int barsAgo]
Examples
// Current bar low price
double barLowPrice = Low[0];
10.4.3.46 LowestBar()
Definition
Returns the number of bars ago the lowest price value occured for the lookback period.
Syntax
LowestBar(IDataSeries series, int lookBackPeriod)
Parameters
series Any DataSeries type object such as an indicator,
Close, High, Low, etc...
lookBackPeriod Number of bars to look back to check for the test
condition
Examples
// Prints out the number of bars ago for the lowest
SMA(20) value of the current session
Print(LowestBar(SMA(20), Bars.BarsSinceSession - 1).
ToString());
10.4.3.47 Lows
Definition
Holds an array of DataSeries objects holding historical bar low prices. A DataSeries object is
added to this array when calling the Add() method in a Custom Strategy. Its purpose is to
provide access to the low prices of all Bars objects in a multi-instrument or multi-time frame
strategy.
Property Value
An array of DataSeries objects.
Syntax
Lows[int barSeriesIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
Definition
Represents a change in level one market data and is passed as a parameter in the
OnMarketData() method.
MarketDataType.Opening
Price A double value representing the price
Time A DateTime structure representing the time
ToString() A string representation of the
MarketDataEventArgs object
Volume A long value representing volume
Examples
protected override void OnMarketData
(MarketDataEventArgs e)
{
// Print some data to the Output window
if (e.MarketDataType == MarketDataType.Last)
Print("Last = " + e.Price + " " + e.
Volume);
else if (e.MarketDataType == MarketDataType.Ask)
Print("Ask = " + e.Price + " " + e.Volume);
else if (e.MarketDataType == MarketDataType.Bid)
Print("Bid = " + e.Price + " " + e.Volume);
}
Tips
1. Not all connectivity providers support all MarketDataTypes.
10.4.3.49 MarketDepthEventArgs
Definition
Represents a change in level two market data also known as market depth and is passed as
a parameter in the OnMarketDepth() method.
Examples
protected override void OnMarketDepth
(MarketDepthEventArgs e)
{
// Print some data to the Output window
if (e.MarketDataType == MarketDataType.Ask && e.
Operation == Operation.Update)
Print("The most recent ask change is " + e.
Price + " " + e.Volume);
}
10.4.3.50 MaximumBarsLookBack
Definition
Improves memory performance of objects that implement the IDataSeries interface (such as
DataSeries, LongSeries, etc.). When using MaximumBarsLookBack.TwoHundredFiftySix,
only the last 256 values of the series object will be stored in memory and be accessible for
reference. This results in significant memory savings when using multiple series objects. In
the rare case should you need older values you can use MaximumBarsLookBack.Infinite to
allow full access of the series, but you will then not be able to utilize the benefits in memory
optimization here. DataSeries objects that hold indicator plot values are always set to
MaximumBarsLookBack.Infinite which ensures that charts will always display the entire
indicator's calculated values.
Property Value
MaximumBarsLookBack.Infinite
MaximumBarsLookBack.TwoHundredFiftySix
Syntax
MaximumBarsLookBack
Examples
protected override void Initialize()
{
// Store all series values instead of only the
last 256 values
MaximumBarsLookBack = MaximumBarsLookBack.
Infinite;
}
10.4.3.51 Median
Definition
A collection of historical bar median prices. Median price = (High + Low) / 2.
Property Value
A DataSeries type object. Accessing this property via an index value [int barsAgo]
returns a double value representing the price of the referenced bar.
Syntax
Median
Median[int barsAgo]
Examples
// Current bar median price
double barMedianPrice = Median[0];
10.4.3.52 Medians
Definition
Holds an array of DataSeries objects holding historical bar median prices. A DataSeries
object is added to this array when calling the Add() method in a Custom Strategy. Its purpose
is to provide access to the median prices of all Bars objects in a multi-instrument or multi-
time frame strategy.
Property Value
An array of DataSeries objects.
Syntax
Medians[int barSeriesIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
Definition
Returns the number of bars ago that the test condition evaluated to true within the specified
look back period expressed in bars. It checks from the current bar works away (back) from it.
This method will NOT work on multi-instrument or multi-time frame strategies.
Syntax
MRO(Condition condition, int instance, int lookBackPeriod)
Parameters
condition A true/false expression
instance The occurrence to check for (1 is the least recent, 2
is the 2nd least recent, etc...)
lookBackPeriod Number of bars to look back to check for the test
condition
Examples
// Prints the high price of the most recent up bar
over the last 10 bars
int barsAgo = MRO(delegate {return Close[0] > Open
[0];}, 1, 10);
if (barsAgo > -1)
Print("The bar high was " + High[barsAgo]);
See Also
Least Recent Occurence(LRO)
10.4.3.54 OnBarUpdate()
Definition
The OnBarUpdate() method is called whenever a bar is updated. If the "CalculateOnBarClose
" property is set to true, it is only called on the close of each bar, otherwise it is called on each
incoming tick. This is the method where all of your strategy or indicator core calculation logic
should be contained.
For multi-timeframe and instrument strategies, this method is called for each Bars object of
a strategy and you MUST filter for the exact bar update events using the "BarsInProgress"
property you want your system logic to execute against.
Syntax
See example below. The NinjaScript indicator and strategy wizards automatically generate
the method syntax for you.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 1)
return;
Definition
The OnFundamentalData() method is called for every change in fundamental data for the
underlying instrument.
Method Parameters
FundamentalDataEventArgs e
Syntax
You must override the method in your strategy or indicator with the following syntax.
Examples
protected override void OnFundamentalData
(FundamentalDataEventArgs e)
{
// Print some data to the Output window
if (e.FundamentalDataType ==
FundamentalDataType.CurrentYearsEarningsPerShare)
Print("The current year's EPS is " + e.
DoubleValue);
}
Tips
1. With multi-time frame and instrument strategies, OnFundamentalData() will be called for
all unique instruments in your strategy. Use the BarsInProgress to filter the
OnFundamentalData() method for a specific instrument.
2. Do not leave an unused OnFundamentalData() method declared in your NinjaScript object.
This will unnecessarily attach a data stream to your strategy which uses unnecessary
CPU cycles.
10.4.3.56 OnMarketData()
Definition
The OnMarketData() method is called and guaranteed to be in the correct sequence for every
change in level one market data for the underlying instrument. This can include but is not
limited to the bid, ask, last price and volume.
Method Parameters
MarketDataEventArgs e
Syntax
You must override the method in your strategy or indicator with the following syntax.
Examples
protected override void OnMarketData
(MarketDataEventArgs e)
{
// Print some data to the Output window
if (e.MarketDataType == MarketDataType.Last)
Print("Last = " + e.Price + " " + e.
Volume);
Tips
1. With multi-time frame and instrument strategies, OnMarketData() will be called for all
unique instruments in your strategy. Use the BarsInProgress to filter the OnMarketData()
method for a specific instrument.
2. Do not leave an unused OnMarketData() method declared in your NinjaScript object. This
will unnecessarily attach a data stream to your strategy which uses unnecessary CPU
cycles.
3. Should you wish to run comparisons against prior values you will need to store and update
local variables to track the relevant values.
4. With NinjaTrader being multi-threaded, you should not rely on any particular sequence of
events like OnMarketData() always being called before OnBarUpdate() or vice versa.
10.4.3.57 OnMarketDepth()
Definition
The OnMarketDepth() method is called and guaranteed to be in the correct sequence for
every change in level two market data (market depth) for the underlying instrument. This
method can be used to build your own level two book.
Method Parameters
MarketDepthEventArgs e
Syntax
You must override the method in your strategy or indicator with the following syntax.
Examples
protected override void OnMarketDepth
(MarketDepthEventArgs e)
{
// Print some data to the Output window
if (e.MarketDataType == MarketDataType.Ask && e.
Operation == Operation.Update)
Print("The most recent ask change is " + e.
Price + " " + e.Volume);
}
Tips
1. With multi-time frame and instrument strategies, OnMarketDepth will be called for all
unique instruments in your strategy. Use the BarsInProgress to filter the OnMarketDepth()
method for a specific instrument.
2. Do not leave an unused OnMarketDepth() method declared in your NinjaScript object. This
will unnecessarily attach a data stream to your strategy which uses unnecessary CPU
cycles.
3. Should you wish to run comparisons against prior values you will need to store and update
local variables to track the relevant values.
4. With NinjaTrader being multi-threaded, you should not rely on any particular sequence of
events like OnMarketDepth() always being called before OnMarketData() or vice versa.
10.4.3.58 OnStartUp()
Definition
You can override the OnStartUp() method to initialize any variables or resources you wish to
use in the custom indicator or strategy. This method is called only once immediately prior to
the start of your script, but after the Initialize() method.
Syntax
You must override the method in your strategy or indicator with the following syntax.
Examples
protected override void OnStartUp()
{
// Set any variables or logic you wish to do
only once at start of your indicator/strategy
}
10.4.3.59 OnTermination()
Definition
For advanced programmers: You can override the OnTermination() method to clean up all
resources owned by the custom indicator or strategy.
Note: Please do NOT overload the Dispose() method. Dispose() method could be triggered
much later than expected resulting in resources not being released early enough.
Syntax
You must override the method in your strategy or indicator with the following syntax.
Examples
protected override void OnTermination()
{
// Clean up your resources here
}
10.4.3.60 Open
Definition
A collection of historical bar opening prices.
Property Value
A DataSeries type object. Accessing this property via an index value [int barsAgo]
returns a double value representing the price of the referenced bar.
Syntax
Open
Open[int barsAgo]
Examples
// Current bar opening price
double barOpenPrice = Open[0];
10.4.3.61 Opens
Definition
Holds an array of DataSeries objects holding historical bar open prices. A DataSeries object
is added to this array when calling the Add() method in a Custom Strategy. Its purpose is to
provide access to the open prices of all Bars objects in a multi-instrument or multi-time frame
strategy.
Property Value
An array of DataSeries objects.
Syntax
Opens[int barSeriesIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
{
// Compares the primary bar's open price to the
5-minute bar's open price
if (Opens[0][0] > Opens[1][0])
Print("The current bar's open price is
greater");
}
10.4.3.62 Rising()
Definition
Checks for a rising condition which is true when the current value is greater than the value of
1 bar ago.
Syntax
Rising(IDataSeries series)
Parameters
series Any DataSeries type object such as an indicator,
Close, High, Low, etc...
Examples
// If the 20 period SMA is rising (in uptrend) go
long
if (Rising(SMA(20)))
EnterLong();
10.4.3.63 Slope()
Definition
The slope is a measure of the steepness of a line.
Syntax
Slope(IDataSeries series, int startBarsAgo, int endBarsAgo)
Parameters
series Any DataSeries type object such as an indicator,
Close, High, Low, etc...
startBarsAgo Specifies the starting point of a line
endBarsAgo Specifies the ending point of a line
Examples
// Prints the slope of the 20 period simple moving
average of the last 10 bars
Print(Slope(SMA(20), 10, 0));
Definition
A StringSeries is a special type of data structure that holds a series of string values and
always contains the same number of elements as bars in a chart. See the DataSeries Class
for related information.
1. Define a variable ("myStringSeries" used in this example) of type StringSeries that will hold
a StringSeries object
2. In the Initialize() method, create a new StringSeries object and assign it to the
"myStringSeries" variable
#region Variables
private StringSeries myStringSeries; // Define a
StringSeries variable
#endregion
Note: By default NinjaTrader limits the number of values stored for StringSeries objects to
256. This drastically improves memory performance by not holding onto old values that are
generally not needed. Should you need more values than the last 256 please be sure to
create the StringSeries object so that it stores all values instead through the use of the
MaximumBarsLookBack property.
#region Variables
private StringSeries myStringSeries; // Define a
StringSeries variable
#endregion
StringSeries.Set(string value)
Setting a value on a StringSeries object is automatically aligned to the current bar being
evaluated. This ensures values across all StringSeries objects are always in sync by the
CurrentBar index. The following code samples demonstrates calculating the range of each
bar and storing the value in a StringSeries object.
Calling the Reset() method is unique and can be very powerful for custom indicator
development. StringSeries objects can hold null values which simply means that you do not
want to store a value for the current bar. Reset() will reset the current index value to null.
StringSeries.ContainsValue(int barsAgo)
Returns a true or false value.
Getting Values
You can access StringSeries object values using the syntax StringSeries[int
barsAgo] where barsAgo represents the data value n number of bars ago.
10.4.3.65 TickSize
Definition
The minimum fluctuation value; the value of 1 tick for the corresponding instrument.
NOTE: This property should NOT be accessed within the Initialize() method.
Property Value
A double value that represents the minimum fluctuation of an instrument.
Syntax
TickSize
Examples
// Prints the ticksize to the output window
Print("The ticksize of this instrument is " +
TickSize.ToString());
10.4.3.66 Time
Definition
A collection of historical bar time stamp values.
Property Value
A TimeSeries type object.
Syntax
Time
Time[int barsAgo] (returns a DateTime structure)
Examples
// Prints the current bar time stamp
Print(Time[0].ToString());
10.4.3.67 Times
Definition
Holds an array of TimeSeries objects holding historical bar times. A TimeSeries object is
added to this array when calling the Add() method in a Custom Strategy. Its purpose is to
provide access to the times of all Bars objects in a multi-instrument or multi-time frame
strategy.
Property Value
An array of TimeSeries objects.
Syntax
Times[int barSeriesIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
Definition
Calculates an integer value representing day. NinjaScript uses the .NET DateTime structures
which can be complicated for novice programmers. If you are familiar with C# you can
directly use DateTime structure properties and methods for date and time comparisons
Integer representation of day is in the following format yyyyMMdd where January 8, 2007
would be 20070108.
Syntax
ToDay(DateTime time)
Parameters
time A DateTime structure such as Time[0] - See Time
property
Examples
// Compare the date of the current bar to September
15, 2008
if (ToDay(Time[0]) > 20080915)
// Do something
10.4.3.69 ToTime()
Definition
Calculates an integer value representing time. NinjaScript uses the .NET DateTime structure
which can be complicated for novice programmers. If you are familiar with C# you can
directly use DateTime structure properties and methods for date and time comparisons
otherwise use this method and the ToDay() method.
Integer representation of time is in the following format Hmmss where 7:30 AM would be
73000 and 2:15:12 PM would be 141512.
Syntax
ToTime(DateTime time)
Parameters
time A DateTime structure such as Time[0] - See Time
property
Examples
// Only trade between 7:45 AM and 1:45 PM
if (ToTime(Time[0]) >= 74500 && ToTime(Time[0]) <=
134500)
{
// Strategy logic goes here
}
10.4.3.70 TriggerCustomEvent()
Definition
This method provides a way to use your own custom events (such as a Timer object) so that
internal NinjaScript indexes and pointers are correctly set prior to processing user code
triggered by your custom event. When calling this event, NinjaTrader will synchronize all
internal pointers and then call your custom event handler where your user code is located.
Syntax
TriggerCustomEvent(CustomEvent customEvent, int barsIndex, object
state)
Parameters
barsIndex Index of the bar series you want to synchronize to
CustomEvent Delegate of your custom event method
state Any object you want passed into your custom event
method
Examples
// Your timer object tick event handler
private void OnTimerTick()
{
// Do not process your code here but instead
call the TriggerCustomEvent()
// method and process your code in the
MyCustomHandler method
TriggerCustomEvent(new CustomEvent
(MyCustomHandler, 0, "myText");
}
Definition
A collection of historical bar typical prices. Typical price = (High + Low + Close) / 3.
Property Value
A DataSeries type object. Accessing this property via an index value [int barsAgo]
returns a double value representing the price of the referenced bar.
Syntax
Typical
Typical[int barsAgo]
Examples
// Current bar typical price
double barTypicalPrice = Typical[0];
10.4.3.72 Typicals
Definition
Holds an array of DataSeries objects holding historical bar typical prices. A DataSeries object
is added to this array when calling the Add() method in a Custom Strategy. Its purpose is to
provide access to the typical prices of all Bars objects in a multi-instrument or multi-time
frame strategy.
Property Value
An array of DataSeries objects.
Syntax
Typicals[int barSeriesIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Adds a 5 minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
10.4.3.73 Volume
Definition
A collection of historical bar volume values.
Property Value
A DataSeries type object. Accessing this property via an index value [int barsAgo]
returns a double value representing the volume of the referenced bar.
Syntax
Volume
Volume[int barsAgo]
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Is current volume greater than twice the
prior bar's volume
if (Volume[0] > Volume[1] * 2)
Print("We have increased volume");
10.4.3.74 Volumes
Definition
Holds an array of DataSeries objects holding historical bar volumes. A DataSeries object is
added to this array when calling the Add() method in a Custom Strategy. Its purpose is to
provide access to the volumes of all Bars objects in a multi-instrument or multi-time frame
strategy.
Property Value
An array of DataSeries objects.
Syntax
Examples
protected override void Initialize()
{
// Adds a 5-minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
10.4.3.75 Weighted
Definition
A collection of historical bar weighted prices. Weighted price = (High + Low + Close +
Close) / 4.
Property Value
A DataSeries type object. Accessing this property via an index value [int barsAgo]
returns a double value representing the price of the referenced bar.
Syntax
Weighted
Weighted[int barsAgo]
Examples
// Current bar weighted price
double barWeigthedPrice = Weighted[0];
10.4.3.76 Weighteds
Definition
Holds an array of DataSeries objects holding historical bar weighted prices. A DataSeries
object is added to this array when calling the Add() method in a Custom Strategy. Its purpose
is to provide access to the weighted prices of all Bars objects in a multi-instrument or multi-
time frame strategy.
Property Value
An array of DataSeries objects.
Syntax
Weighteds[int barSeriesIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Adds a 5 minute Bars object to the strategy
and is automatically assigned
// a Bars object index of 1 since the primary
data the strategy is run against
// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
Tips
1. Custom graphics for custom indicators can be painted on either the price panel or indicator
panel. You could for example have a custom indicator displayed in an indicator panel yet
have associated custom graphics painted on the price panel. The "DrawOnPricePanel"
property is set to true as default which means that custom graphics will always be painted
on the price panel even if the indicator is plotted in a separate panel. If you want your
custom graphics to be plotted on the indicator panel, set this property to false in the
Initialize() method of your custom indicator.
2. Set unique tag values for each draw object. A common trick is to incorporate the bar
number as part of the unique tag identifier. For example, if you wanted to draw a dot that
indicated a buying condition above a bar, you could express it:
DrawDot(CurrentBar.ToString() + "Buy", 0, High[0] + TickSize, Color.
ForestGreen)
3. Draw methods will not work if they are called from the Initialize() method.
10.4.4.1 AllowRemovalOfDrawObjects
Definition
If true, draw objects from the indicator or strategy can be removed from the chart manually. If
false, draw objects from the indicator or strategy can only be removed from the chart if the
script is removed as well.
Property Value
This property returns true if the draw objects can be removed from the chart independent of
the indicator or strategy; otherwise, false. Default set to false.
Syntax
AllowRemovalOfDrawObjects
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
AllowRemovalOfDrawObjects = true; // Draw
objects can be removed separately from the script
}
10.4.4.2 BackColor
Definition
Sets the chart panel back color for the current bar.
Property Value
A color structure that represents the color of this price bar.
Syntax
BarColor
Examples
// Sets the chart panel back color to pale green
BackColor = Color.PaleGreen;
10.4.4.3 BackColorAll
Definition
Sets the back color for all chart panels for the current bar.
Property Value
A color structure that represents the color of this price bar.
Syntax
BackColorAll
Examples
// Sets the back color to pale green
BackColorAll = Color.PaleGreen;
10.4.4.4 BackColorAllSeries
Definition
A collection of historical background colors for all chart panels.
Property Value
A color series type object. Accessing this property via an index value [int barsAgo]
returns a color structure representing the color of the background color on the referenced bar
for all chart panels.
Syntax
BackColorAllSeries
BackColorAllSeries[int barsAgo]
Examples
// Sets the color of the background on the current
bar as blue on all chart panels.
BackColorAllSeries[0] = Color.Blue;
Definition
A collection of historical background colors for the chart panel.
Property Value
A color series type object. Accessing this property via an index value [int barsAgo]
returns a color structure representing the color of the background color on the referenced
bar.
Syntax
BackColorSeries
BackColorSeries[int barsAgo]
Examples
// Sets the color of the background on the current
bar as blue
BackColorSeries[0] = Color.Blue;
Definition
Sets the color of a price bar.
Property Value
A color structure that represents the color of this price bar.
Syntax
BarColor
Examples
// Sets the bar color to yellow
BarColor = Color.Yellow;
10.4.4.7 BarColorSeries
Definition
A collection of historical bar colors.
Property Value
A color series type object. Accessing this property via an index value [int barsAgo]
returns a color structure representing the referenced bar's color.
Note: This will only return the color of a bar in which an explicit color overwrite was used.
Otherwise it will return Color [Empty].
Syntax
BarColorSeries
BarColorSeries[int barsAgo]
Examples
// Sets the color of the current bar to blue.
BarColorSeries[0] = Color.Blue;
Definition
Sets the outline color of a candle stick.
* If you set the BarColor property and the CandleOutlineColor property is not set, the outline
color will take the color set by the BarColor property.
Property Value
A color structure that represents the color of this price bar.
Syntax
CandleOutlineColor
Examples
// Sets the candle outline color to black
CandleOutlineColor = Color.Black;
10.4.4.9 CandleOutlineColorSeries
Definition
A collection of historical outline colors for candle sticks.
* If you set the BarColor property and the CandleOutlineColor property is not set, the outline
color will take the color set by the BarColor property.
Property Value
A color series type object. Accessing this property via an index value [int barsAgo]
returns a color structure representing the referenced bar's outline color.
Note: This will only return the color of a bar in which an explicit color overwrite was used.
Otherwise it will return Color [Empty].
Syntax
CandleOutlineColorSeries
CandleOutlineColorSeries[int barsAgo]
Examples
// Sets the outline color of the current bar to
black.
CandleOutlineColorSeries[0] = Color.Black;
There are virtually no limits for custom drawing on a chart panel. Since NinjaScript is based
on Microsoft C#, the entire System.Drawing namespace is available for use. Custom drawing
is an advanced programming topic and should only be considered by programmers familiar
with Microsoft C# and the .NET Framework.
Please see the following indicators for reference samples of custom drawing by overriding
the Plot() method of the Indicator base class:
CustomPlotSample
TickCounter
VolumeZones
10.4.4.11 DrawAndrewsPitchfork()
Definition
Draws an Andrew's Pitchfork.
Syntax
DrawAndrewsPitchfork(string tag, bool autoScale, int anchor1BarsAgo
, double anchor1Y, int anchor2BarsAgo, double anchor2Y, int
anchor3BarsAgo,double anchor3Y)
DrawAndrewsPitchfork(string tag, bool autoScale, DateTime
anchor1Time, double anchor1Y, DateTime anchor2Time, double anchor2Y
, DateTime anchor3Time, double anchor3Y)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
anchor1BarsAgo The number of bars ago (x value) of the 1st anchor
point
anchor1Time The time of the 1st anchor point
anchor1Y The y value of the 1st anchor point
anchor2BarsAgo The number of bars ago (x value) of the 2nd anchor
point
anchor2Time The time of the 2nd anchor point
anchor2Y The y value of the 2nd anchor point
anchor3BarsAgo The number of bars ago (x value) of the 3rd anchor
point
anchor3Time The time of the 3rd anchor point
anchor3Y The y value of the 3rd anchor point
Examples
DrawAndrewsPitchfork("tag1", true, 4, Low[4], 3, High
[3], 1, Low[1]);
10.4.4.12 DrawArc()
Definition
Draws an arc.
Syntax
DrawArc(string tag, int startBarsAgo, double startY, int endBarsAgo
, double endY, Color color)
DrawArc(string tag, bool autoScale, int startBarsAgo, double startY
, int endBarsAgo, double endY, Color color, DashStyle dashStyle,
int width)
DrawArc(string tag, bool autoScale, DateTime startTime, double
startY, DateTime endTime, double endY, Color color, DashStyle
dashStyle, int width)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back.
startTime The starting time where the draw object will be
drawn.
startY The starting y value co-ordinate where the draw
object will be drawn
endBarsAgo The end bar (x axis co-ordinate) where the draw
object will terminate
endTime The end time where the draw object will terminate
endY The end y value co-ordinate where the draw object
will terminate
color The draw object color (reference)
dashStyle DashStyle.Dash
DashStyle.DashDot
DashStyle.DashDotDot
DashStyle.Dot
DashStyle.Solid
(reference)
Examples
// Draws a dotted lime green arc
DrawArc("tag1", false, 10, 1000, 0, 1001, Color.
LimeGreen, DashStyle.Dot, 2);
10.4.4.13 DrawArrowDown()
Definition
Draws an arrow pointing down.
Syntax
DrawArrowDown(string tag, bool autoScale, int barsAgo, double y,
Color color)
DrawArrowDown(string tag, bool autoScale, DateTime time, double y,
Color color)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
barsAgo The bar the object will be drawn at. A value of 10
would be 10 bars ago.
time The time the object will be drawn at.
y The y value
color The draw object color (reference)
Examples
// Paints a red down arrow on the current bar 1 tick
above the high
DrawArrowDown("tag1", true, 0, High[0] + TickSize,
Color.Red);
10.4.4.14 DrawArrowLine()
Definition
Draws an arrow line.
Syntax
DrawArrowLine(string tag, int startBarsAgo, double startY, int
endBarsAgo, double endY, Color color)
DrawArrowLine(string tag, bool autoScale, int startBarsAgo, double
startY, int endBarsAgo, double endY, Color color, DashStyle
dashStyle, int width)
DrawArrowLine(string tag, bool autoScale, DateTime startTime,
double startY, DateTime endTime, double endY, Color color,
DashStyle dashStyle, int width)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back.
startTime The starting time where the draw object will be
drawn.
startY The starting y value co-ordinate where the draw
object will be drawn
endBarsAgo The end bar (x axis co-ordinate) where the draw
object will terminate
endTime The end time where the draw object will terminate
endY The end y value co-ordinate where the draw object
will terminate
color The draw object color (reference)
dashStyle DashStyle.Dash
DashStyle.DashDot
DashStyle.DashDotDot
DashStyle.Dot
DashStyle.Solid
(reference)
Examples
// Draws a dotted lime green arrow line
DrawArrowLine("tag1", false, 10, 1000, 0, 1001,
Color.LimeGreen, DashStyle.Dot, 2);
10.4.4.15 DrawArrowUp()
Definition
Draws an arrow pointing up.
Syntax
DrawArrowUp(string tag, bool autoScale, int barsAgo, double y,
Color color)
DrawArrowUp(string tag, bool autoScale, DateTime time, double y,
Color color)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
barsAgo The bar the object will be drawn at. A value of 10
would be 10 bars ago.
time The time the object will be drawn at.
y The y value
color The draw object color (reference)
Examples
// Paints a red down arrow on the current bar 1 tick
below the low
DrawArrowUp("tag1", true, 0, Low[0] - TickSize,
Color.Red);
10.4.4.16 DrawDiamond()
Definition
Draws a diamond.
Syntax
DrawDiamond(string tag, bool autoScale, int barsAgo, double y,
Color color)
DrawDiamond(string tag, bool autoScale, DateTime time, double y,
Color color)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
barsAgo The bar the object will be drawn at. A value of 10
would be 10 bars ago.
time The time the object will be drawn at.
y The y value
color The draw object color (reference)
Examples
// Paints a red diamond on the current bar 1 tick
below the low
DrawDiamond("tag1", true, 0, Low[0] - TickSize,
Color.Red);
10.4.4.17 DrawDot()
Definition
Draws a dot.
Syntax
DrawDot(string tag, bool autoScale, int barsAgo, double y, Color
color)
DrawDot(string tag, bool autoScale, DateTime time, double y, Color
color)
Parameters
tag A user defined unique id used to reference the draw
object. For example, if you pass in a value of
Examples
// Paints a red dot on the current bar 1 tick below
the low
DrawDot("tag1", true, 0, Low[0] - TickSize, Color.
Red);
10.4.4.18 DrawEllipse()
Definition
Draws an ellipse.
Syntax
DrawEllipse(string tag, int startBarsAgo, double startY, int
endBarsAgo, double endY, Color color)
DrawEllipse(string tag, bool autoScale, int startBarsAgo, double
startY, int endBarsAgo, double endY, Color color, Color areaColor,
int areaOpacity)
DrawEllipse(string tag, bool autoScale, DateTime startTime, double
startY, DateTime endTime, double endY, Color color, Color areaColor
, int areaOpacity)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back
startTime The starting time where the draw object will be
drawn
Examples
// Paints a red ellipse on the current bar
DrawEllipse("tag1", true, 5, Close[5], 0, Close[0],
Color.Red, Color.Red, 5);
10.4.4.19 DrawExtendedLine()
Definition
Draws a line with infinite end points.
Syntax
DrawExtendedLine(string tag, int startBarsAgo, double startY, int
endBarsAgo, double endY, Color color)
DrawExtendedLine(string tag, bool autoScale, int startBarsAgo,
double startY, int endBarsAgo, double endY, Color color, DashStyle
dashStyle, int width)
DrawExtendedLine(string tag, bool autoScale, DateTime startTime,
double startY, DateTime endTime, double endY, Color color,
DashStyle dashStyle, int width)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back
startTime The starting time where the draw object will be
drawn
Examples
// Draws a dotted lime green
DrawExtendedLine("tag1", false, 10, Close[10], 0,
Close[0], Color.LimeGreen, DashStyle.Dot, 2);
10.4.4.20 DrawFibonacciCircle()
Definition
Draws a fibonacci circle.
Syntax
DrawFibonacciCircle(string tag, bool autoScale, int startBarsAgo,
double startY, int endBarsAgo, double endY)
DrawFibonacciCircle(string tag, bool autoScale, DateTime startTime,
double startY, DateTime endTime, double endY)
Parameters
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.
Examples
// Draws a fibonnaci circle
DrawFibonacciCircle("tag1", true, 10, Low[10], 0,
High[0]);
10.4.4.21 DrawFibonacciExtensions()
Definition
Draws a fibonacci extension.
Syntax
DrawFibonacciExtensions(string tag, bool autoScale, int
anchor1BarsAgo, double anchor1Y, int anchor2BarsAgo, double
anchor2Y, int anchor3BarsAgo, double anchor3Y)
DrawFibonacciExtensions(string tag, bool autoScale, DateTime
anchor1Time, double anchor1Y, DateTime anchor2Time, double anchor2Y
, DateTime anchor3Time, double anchor3Y)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
anchor1BarsAgo The number of bars ago (x value) of the 1st anchor
point
anchor1Time The time of the 1st anchor point
anchor1Y The y value of the 1st anchor point
Examples
DrawFibonacciExtensions("tag1", true, 4, Low[4], 3,
High[3], 1, Low[1]);
10.4.4.22 DrawFibonacciRetracements()
Definition
Draws a fibonacci retracement.
Syntax
DrawFibonacciRetracements(string tag, bool autoScale, int
startBarsAgo, double startY, int endBarsAgo, double endY)
DrawFibonacciRetracements(string tag, bool autoScale, DateTime
startTime, double startY, DateTime endTime, double endY)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back.
startTime The starting time where the draw object will be
drawn.
startY The starting y value co-ordinate where the draw
object will be drawn
endBarsAgo The end bar (x axis co-ordinate) where the draw
object will terminate
endTime The end time where the draw object will terminate
endY The end y value co-ordinate where the draw object
will terminate
Examples
// Draws a fibonnaci retracement
DrawFibonacciRetracements("tag1", true, 10, Low[10],
0, High[0]);
10.4.4.23 DrawFibonacciTimeExtensions()
Definition
Draws a fibonacci time extension.
Syntax
DrawFibonacciTimeExtensions(string tag, int startBarsAgo, double
startY, int endBarsAgo, double endY)
DrawFibonacciTimeExtensions(string tag, DateTime startTime, double
startY, DateTime endTime, double endY)
Parameters
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.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back.
startTime The starting time where the draw object will be
drawn.
startY The starting y value co-ordinate where the draw
object will be drawn
endBarsAgo The end bar (x axis co-ordinate) where the draw
object will terminate
endTime The end time where the draw object will terminate
endY The end y value co-ordinate where the draw object
will terminate
Examples
// Draws a fibonacci time extension object
DrawFibonacciTimeExtensions("tag1", 10, Low[10], 0,
High[0]);
10.4.4.24 DrawGannFan()
Definition
Draws a Gann Fan.
Syntax
DrawGannFan(string tag, bool autoScale, int barsAgo, double y)
DrawGannFan(string tag, bool autoScale, DateTime time, double y)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
barsAgo The bar the object will be drawn at. A value of 10
would be 10 bars ago.
time The time the object will be drawn at.
y The y value
Examples
// Draws a Gann Fan at the current bar low
DrawGannFan("tag1", true, 0, Low[0]);
10.4.4.25 DrawHorizontalLine()
Definition
Draws a horizontal line.
Syntax
DrawHorizontalLine(string tag, double y, Color color)
DrawHorizontalLine(string tag, bool autoScale, double y, Color
color, DashStyle dashStyle, int width)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
y The y value
color The draw object color (reference)
dashStyle DashStyle.Dash
DashStyle.DashDot
DashStyle.DashDotDot
DashStyle.Dot
DashStyle.Solid
(reference)
Examples
// Draws a horizontal line
DrawHorizontalLine("tag1", 1000, Color.Black);
10.4.4.26 DrawLine()
Definition
Draws a line between two points.
Syntax
DrawLine(string tag, int startBarsAgo, double startY, int
endBarsAgo, double endY, Color color)
DrawLine(string tag, bool autoScale, int startBarsAgo, double
startY, int endBarsAgo, double endY, Color color, DashStyle
dashStyle, int width)
DrawLine(string tag, bool autoScale, DateTime startTime, double
startY, DateTime endTime, double endY, Color color, DashStyle
dashStyle, int width)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back.
startTime The starting time where the draw object will be
drawn
startY The starting y value co-ordinate where the draw
Examples
// Draws a dotted lime green line from 10 bars back
to the current bar
// with a width of 2 pixels
DrawLine("tag1", false, 10, 1000, 0, 1001, Color.
LimeGreen, DashStyle.Dot, 2);
10.4.4.27 DrawObjects
Definition
A collection holding all of the draw objects on the chart for the primary bar series. The draw
objects can be manually drawn or script generated objects.
Property Value
A collection of IDrawObject objects.
Syntax
DrawObjects
DrawObjects[string tag]
DrawObjects.Count
Examples
// Example #1: Finding the draw object of a specific
tag
protected override void OnBarUpdate()
{
10.4.4.28 DrawRay()
Definition
Draws a line which has an infinite end point in one direction.
Syntax
DrawRay(string tag, int anchor1BarsAgo, double anchor1Y, int
anchor2BarsAgo, double anchor2Y, Color color)
DrawRay(string tag, bool autoScale, int anchor1BarsAgo, double
anchor1Y, int anchor2BarsAgo, double anchor2Y, Color color,
DashStyle dashStyle, int width)
DrawRay(string tag, bool autoScale, DateTime anchor1Time, double
anchor1Y, DateTime anchor2Time, double anchor2Y, Color color,
DashStyle dashStyle, int width)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
anchor1BarsAgo The number of bars ago (x value) of the 1st anchor
point
anchor1Time The time of the 1st anchor point
anchor1Y The y value of the 1st anchor point
anchor2BarsAgo The number of bars ago (x value) of the 2nd anchor
point
anchor2Time The time of the 2nd anchor point
anchor2Y The y value of the 2nd anchor point
color The draw object color (reference)
dashStyle DashStyle.Dash
DashStyle.DashDot
DashStyle.DashDotDot
DashStyle.Dot
DashStyle.Solid
(reference)
Examples
// Draws a lime green ray from 10 bars back through
the current bar
DrawRay("tag1", 10, 1000, 0, 1001, Color.LimeGreen);
10.4.4.29 DrawRectangle()
Definition
Draws a rectangle.
Syntax
DrawRectangle(string tag, int startBarsAgo, double startY, int
endBarsAgo, double endY, Color color)
DrawRectangle(string tag, bool autoScale, int startBarsAgo, double
startY, int endBarsAgo, double endY, Color color, Color areaColor,
int areaOpacity)
DrawRectangle(string tag, bool autoScale, DateTime startTime,
double startY, DateTime endTime, double endY, Color color, Color
areaColor, int areaOpacity)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back.
startTime The starting time where the draw object will be
drawn
startY The starting y value co-ordinate where the draw
object will be drawn
endBarsAgo The end bar (x axis co-ordinate) where the draw
object will terminate
endTime The end time where the draw object will terminate
endY The end y value co-ordinate where the draw object
will terminate
color The draw object color (reference)
areaColor The fill color for the object (reference)
areaOpacity Sets the level of transparency for the fill color. Valid
values between 1 - 10.
Examples
// Draws a blue rectangle from the low 10 bars back
to the high of 5 bars back
DrawRectangle("tag1", 10, Low[10] - TickSize, 5, High
[5] + Ticksize, Color.Blue);
Definition
Draws a region on a chart.
Syntax
DrawRegion(string tag, int startBarsAgo, int endBarsAgo,
IDataSeries series, double y, Color outlineColor, Color areaColor,
int areaOpacity)
DrawRegion(string tag, int startBarsAgo, int endBarsAgo,
IDataSeries series1, IDataSeries series2, Color outlineColor, Color
areaColor, int areaOpacity)
DrawRegion(string tag, DateTime startTime, DateTime endTime,
IDataSeries series, double y, Color outlineColor, Color areaColor,
int areaOpacity)
DrawRegion(string tag, DateTime startTime, DateTime endTime,
IDataSeries series1, IDataSeries series2, Color outlineColor, Color
areaColor, int areaOpacity)
Parameters
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.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back.
startTime The starting time where the draw object will be
drawn.
Examples
// Fills in the region between the upper and lower
bollinger bands
DrawRegion("tag1", CurrentBar, 0, Bollinger(2, 14).
Upper, Bollinger(2, 14).Lower, Color.Empty, Color.
Lime, 2);
Tips
1. Pass in Color.Empty to the "outlineColor" parameter if you do not want to have an outline
color.
2. If you wanted to fill a region between a value (20 period simple moving average) and the
upper edge of the chart, pass in an extreme value to the "y" parameter such as 1000000.
3. Should you be drawing regions based on DataSeries objects instead of indicator plots, be
sure to create the DataSeries with the MaximumBarsLookBack.Infinite parameter if the region
you are drawing would be maintained on the chart for more than 256 bars back.
10.4.4.31 DrawRegressionChannel()
Definition
Draws a rectangle.
Syntax
DrawRegressionChannel(string tag, int startBarsAgo, int endBarsAgo,
Color color)
DrawRegressionChannel(string tag, bool autoScale, int startBarsAgo,
int endBarsAgo, Color upperColor, DashStyle upperDashStyle, int
upperWidth, Color middleColor, DashStyle middleDashStyle, int
middleWidth, Color lowerColor, DashStyle lowerDashStyle, int
lowerWidth)
DrawRegressionChannel(string tag, bool autoScale, DateTime
startTime, DateTime endTime, Color upperColor, DashStyle
upperDashStyle, int upperWidth, Color middleColor, DashStyle
middleDashStyle, int middleWidth, Color lowerColor, DashStyle
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale. Default value is false.
startBarsAgo The starting bar (x axis co-ordinate) where the draw
object will be drawn. For example, a value of 10
would paint the draw object 10 bars back.
startTime The starting time where the draw object will be
drawn.
endBarsAgo The end bar (x axis co-ordinate) where the draw
object will terminate
endTime The end time where the draw object will terminate
color The draw object color (reference)
upperDashStyle, DashStyle.Dash
middleDashStyle, DashStyle.DashDot
lowerDashStyle DashStyle.DashDotDot
DashStyle.Dot
DashStyle.Solid
(reference)
Examples
// Draws a regression channel from the low 10 bars
back to the high of 5 bars back
DrawRegressionChannel("tag1", 10, 0, Color.Blue);
10.4.4.32 DrawRuler()
Definition
Draws a ruler.
Syntax
DrawRuler(string tag, bool autoScale, IDataSeries series, int
anchor1BarsAgo, double anchor1Y, int anchor2BarsAgo, double
anchor2Y, int anchor3BarsAgo, double anchor3Y)
DrawRuler(string tag, bool autoScale, IDataSeries series, DateTime
anchor1Time, double anchor1Y, DateTime anchor2Time, double anchor2Y
, DateTime anchor3Time, double anchor3Y)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
series The series the ruler will measure
anchor1BarsAgo The number of bars ago (x value) of the 1st anchor
point
anchor1Time The time of the 1st anchor point
anchor1Y The y value of the 1st anchor point
anchor2BarsAgo The number of bars ago (x value) of the 2nd anchor
point
anchor2Time The time of the 2nd anchor point
anchor2Y The y value of the 2nd anchor point
anchor3BarsAgo The number of bars ago (x value) of the 3rd anchor
point
anchor3Time The time of the 3rd anchor point
anchor3Y The y value of the 3rd anchor point
Examples
// Draws a ruler measuring the primary bar series
DrawRuler("tag1", true, BarsArray[0], 4, Low[4], 3,
High[3], 1, Low[1]);
10.4.4.33 DrawSquare()
Definition
Draws a square.
Syntax
DrawSquare(string tag, bool autoScale, int barsAgo, double y, Color
color)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
barsAgo The bar the object will be drawn at. A value of 10
would be 10 bars ago.
time The time the object will be drawn at.
y The y value
color The draw object color (reference)
Examples
// Paints a red square on the current bar 1 tick
below the low
DrawSquare("tag1", true, 0, Low[0] - TickSize, Color.
Red);
10.4.4.34 DrawText()
Definition
Draws text.
Syntax
DrawText(string tag, string text, int barsAgo, double y, Color
color)
DrawText(string tag, bool autoScale, string text, int barsAgo,
double y, int yPixelOffset, Color textColor, Font font,
StringAlignment alignment, Color outlineColor, Color areaColor, int
areaOpacity)
DrawText(string tag, bool autoScale, string text, DateTime time,
double y, int yPixelOffset, Color textColor, Font font,
StringAlignment alignment, Color outlineColor, Color areaColor, int
areaOpacity)
Parameters
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
Examples
// Draws text
DrawText("tag1", "Text to draw", 10, 1000, Color.
Black);
10.4.4.35 DrawTextFixed()
Definition
Draws text in one of 5 available pre-defined fixed locations on panel 1 (price panel) of a chart.
Syntax
DrawTextFixed(string tag, string text, TextPosition textPosition)
DrawTextFixed(string tag, string text, TextPosition textPosition,
Color textColor, Font font, Color outlineColor, Color areaColor,
int areaOpacity)
Parameters
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
Examples
// Draws text in the upper right corner of panel 1
DrawTextFixed("tag1", "Text to draw", TextPosition.
TopRight);
10.4.4.36 DrawTriangle()
Definition
Draws a triangle.
Syntax
DrawTriangle(string tag, int anchor1BarsAgo, double anchor1Y, int
anchor2BarsAgo, double anchor2Y, int anchor3BarsAgo, double
anchor3Y, Color color)
DrawTriangle(string tag, bool autoScale, int anchor1BarsAgo, double
anchor1Y, int anchor2BarsAgo, double anchor2Y, int anchor3BarsAgo,
double anchor3Y, Color color, Color areaColor, int areaOpacity)
DrawTriangle(string tag, bool autoScale, DateTime anchor1Time,
double anchor1Y, DateTime anchor2Time, double anchor2Y, DateTime
anchor3Time, double anchor3Y, Color color, Color areaColor, int
areaOpacity)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
Examples
// Paints a blue triangle on the chart
DrawTriangle("tag1", 4, Low[4], 3, High[3], 1, Low
[1], Color.Blue);
10.4.4.37 DrawTriangleDown()
Definition
Draws a triangle pointing down.
Syntax
DrawTriangleDown(string tag, bool autoScale, int barsAgo, double y,
Color color)
DrawTriangleDown(string tag, bool autoScale, DateTime time, double
y, Color color)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
barsAgo The bar the object will be drawn at. A value of 10
would be 10 bars ago.
time The time the object will be drawn at.
y The y value
Examples
// Paints a red triangle pointing down on the current
bar 1 tick below the low
DrawTriangleDown("tag1", true, 0, Low[0] - TickSize,
Color.Red);
10.4.4.38 DrawTriangleUp()
Definition
Draws a triangle pointing up.
Syntax
DrawTriangleUp(string tag, bool autoScale, int barsAgo, double y,
Color color)
DrawTriangleUp(string tag, bool autoScale, DateTime time, double y,
Color color)
Parameters
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.
autoScale Determines if the draw object will be included in the
y-axis scale
barsAgo The bar the object will be drawn at. A value of 10
would be 10 bars ago.
time The time the object will be drawn at.
y The y value
color The draw object color (reference)
Examples
// Paints a red triangle pointing up on the current
bar 1 tick below the low
DrawTriangleUp("tag1", true, 0, Low[0] - TickSize,
Color.Red);
10.4.4.39 DrawVerticalLine()
Definition
Draws a vertical line.
Syntax
DrawVerticalLine(string tag, int barsAgo, Color color)
DrawVerticalLine(string tag, DateTime time, Color color, DashStyle
dashStyle, int width)
Parameters
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.
barsAgo The bar the object will be drawn at. A value of 10
would be 10 bars ago.
time The time the object will be drawn at.
color The draw object color (reference)
dashStyle DashStyle.Dash
DashStyle.DashDot
DashStyle.DashDotDot
DashStyle.Dot
DashStyle.Solid
(reference)
Examples
// Draws a vertical line
DrawVerticalLine("tag1", 10, Color.Black);
10.4.4.40 IAndrewsPitchfork
Definition
Represents an interface that exposes information regarding an Andrews Pitchfork
IDrawObject.
CalculationMethod.ModifiedSchiff
CalculationMethod.Schiff
CalculationMethod.StandardPitchfork
Pen The Pen object used to draw the object
ShowText A bool value representing if text will be drawn
along with the draw object
Examples
protected override void OnBarUpdate()
{
// Draws an Andrews Pitchfork
IAndrewsPitchfork pitchfork =
DrawAndrewsPitchfork("tag1", true, 4, Low[4], 3, High
[3], 1, Low[1]);
Definition
Represents an interface that exposes information regarding an Arc IDrawObject.
ending point
EndY A double value representing the y value of the
ending point
Pen The Pen object used to draw the object
Examples
protected override void OnBarUpdate()
{
// Draws an arc
IArc arc = DrawArc("tag1", false, 10, 1000, 0,
1001, Color.LimeGreen, DashStyle.Dot, 2);
Definition
Represents an interface that exposes information regarding an Arrow Down IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws an Arrow Down
IArrowDown arrow = DrawArrowDown("tag1", true,
0, High[0] + TickSize, Color.Red);
10.4.4.43 IArrowLine
Definition
Represents an interface that exposes information regarding an Arrow Line IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws an Arrow Line
IArrowLine arrow = DrawArrowLine("tag1", false,
10, 1000, 0, 1001, Color.LimeGreen, DashStyle.Dot,
2);
Definition
Represents an interface that exposes information regarding an Arrow Up IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws an Arrow Up
IArrowUp arrow = DrawArrowUp("tag1", true, 0,
Low[0] - TickSize, Color.Red);
Definition
Represents an interface that exposes information regarding a Diamond IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a diamond
IDiamond diamond = DrawDiamond("tag1", true, 0,
Low[0] - TickSize, Color.Red);
Definition
Represents an interface that exposes information regarding a Dot IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a dot
IDot dot = DrawDot("tag1", true, 0, Low[0] -
TickSize, Color.Red);
Definition
Represents an interface that exposes information regarding a draw object.
DrawType.AndrewsPitchfork
DrawType.Arc
DrawType.ArrowDown
DrawType.Line
DrawType.Up
DrawType.Diamond
DrawType.Dot
DrawType.Ellipse
DrawType.ExtendedLine
DrawType.FibonacciCircle
DrawType.FibonacciExtensions
DrawType.FibonacciRetracements
DrawType.FibonacciTimeExtensions
DrawType.GannFan
DrawType.HorizontalLine
DrawType.Line
DrawType.Ray
DrawType.Rectangle
DrawType.Region
DrawType.RegressionChannel
DrawType.Ruler
DrawType.Square
DrawType.Text
DrawType.TextFixed
DrawType.TriangleDown
DrawType.TriangleUp
DrawType.VerticalLine
Locked A bool value representing if the draw object can be
manually moved on the chart
SeparateZOrder A bool value representing if the draw object is on
the same Z-order as the NinjaScript
Tag A string value representing the unique ID of the
draw object. Global draw objects will have an "@"
added as a prefix to the string.
ToString() A string value representing the draw object
UserDrawn A bool value representing if the draw object was
manually drawn as opposed to programmatically
drawn
Examples
protected override void OnBarUpdate()
{
// Loops through the DrawObjects collection
foreach (IDrawObject draw in DrawObjects)
{
// Unlocks all draw objects for manual
manipulation on the chart
draw.Locked = false;
}
}
10.4.4.48 IEllipse
Definition
Represents an interface that exposes information regarding an Ellipse IDrawObject.
ending point
AreaOpacity An int value representing the opacity of the area
color
AreaColor A Color structure representing the fill color of the
draw object
Pen The Pen object used to draw the object
Examples
protected override void OnBarUpdate()
{
// Draws an ellipse
IEllipse ellipse = DrawEllipse("tag1", true, 5,
Close[5], 0, Close[0], Color.Red, Color.Red, 5);
Definition
Represents an interface that exposes information regarding an Extended Line IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws an Extended Line
IExtendedLine extLine = DrawExtendedLine
("tag1", false, 10, Close[10], 0, Close[0], Color.
LimeGreen, DashStyle.Dot, 2);
Definition
Represents an interface that exposes information regarding a Fibonacci Circle IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Fibonacci Circle
IFibonacciCircle fibCircle = DrawFibonacciCircle
("tag1", true, 10, Low[10], 0, High[0]);
Definition
Represents an interface that exposes information regarding a Fibonacci Extensions
IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Fibonacci Extension
IFibonacciExtensions fibExt =
DrawFibonacciExtensions("tag1", true, 4, Low[4], 3,
High[3], 1, Low[1]);
Definition
Represents an interface that exposes information regarding a Fibonacci Retracements
IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Fibonacci Retracement
IFibonacciRetracements fibRetracements =
DrawFibonacciRetracements("tag1", true, 10, Low[10],
0, High[0]);
Definition
Represents an interface that exposes information regarding a Fibonacci Time Extensions
IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Fibonacci Time Extension
IFibonacciTimeExtensions fibTimeExt =
DrawFibonacciTimeExtensions("tag1", 10, Low[10], 0,
High[0]);
Definition
Represents an interface that exposes information regarding a Gann Fan IDrawObject.
GannFanDirection.DownLeft
GannFanDirection.DownRight
GannFanDirection.UpLeft
GannFanDirection.UpRight
PointsPerBar A double value representing the number of points
per bar
ShowText A bool value representing if text will be drawn
along with the draw object
Examples
protected override void OnBarUpdate()
{
// Draws an Gann Fan
IGannFan gann = DrawGannFan("tag1", true, 0, Low
[0]);
10.4.4.55 IHorizontalLine
Definition
Represents an interface that exposes information regarding a Horizontal Line IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Horizontal Line
IHorizontalLine hLine = DrawHorizontalLine
("tag1", 1000, Color.Black);
Definition
Represents an interface that exposes information regarding a Line IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Line
ILine line = DrawLine("tag1", false, 10, 1000,
0, 1001, Color.LimeGreen, DashStyle.Dot, 2);
Definition
Represents an interface that exposes information regarding a Ray IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a ray
IRay ray = DrawRay("tag1", 10, 1000, 0, 1001,
Color.LimeGreen);
Definition
Represents an interface that exposes information regarding a Rectangle IDrawObject.
starting point
EndBarsAgo An int value representing the number of bars ago
of the ending point
EndTime A DateTime structure representing the time of the
ending point
EndY A double value representing the y value of the
ending point
AreaColor A Color structure representing the fill color of the
draw object
AreaOpacity An int value representing the opacity of the area
color
Pen The Pen object used to draw the object
Examples
protected override void OnBarUpdate()
{
// Draws a rectangle
IRectangle rectangle = DrawRectangle("tag1",
false, 10, Low[10] - TickSize, 5, High[5] + TickSize,
Color.PaleGreen, Color.PaleGreen, 2);
Definition
Represents an interface that exposes information regarding a Region IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a region
IRegion region = DrawRegion("tag1", CurrentBar,
0, Bollinger(2, 14).Upper, Bollinger(2, 14).Lower,
Color.Empty, Color.Lime, 2);
Definition
Represents an interface that exposes information regarding a Regression Channel
IDrawObject.
PriceType.Close
PriceType.High
PriceType.Low
PriceType.Median
PriceType.Open
PriceType.Typical
IsStdDevType A bool value representing if the object will use
standard deviations calculations for the upper/lower
lines
Examples
protected override void OnBarUpdate()
{
// Draws a rectangle
IRegressionChannel regression =
DrawRegressionChannel("tag1", 10, 0, Color.Blue);
Definition
Represents an interface that exposes information regarding a Ruler IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a ruler measuring the primary bar
series
IRuler ruler = DrawRuler("tag1", true, BarsArray
[0], 4, Low[4], 3, High[3], 1, Low[1]);
Definition
Represents an interface that exposes information regarding a Square IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a square
ISquare square = DrawSquare("tag1", true, 0, Low
[0] - TickSize, Color.Red);
Definition
Represents an interface that exposes information regarding a Text IDrawObject.
StringAlignment.Center
StringAlignment.Far
StringAlignment.Near
(reference)
AreaOpacity An int value representing the opacity of the area
color
AreaColor A Color structure representing the fill color of the
text box
Text A string value representing the text to be drawn
TextColor A Color structure representing the color of the text
Font A Font object representing the font for the text
Pen The Pen object used to outline the text box
Examples
protected override void OnBarUpdate()
{
// Draws a text object
IText text = DrawText("tag1", "Text to draw",
10, 1000, Color.Black);
Definition
Represents an interface that exposes information regarding a Text Fixed IDrawObject.
TextPosition.BottomLeft
TextPosition.BottomRight
TextPosition.Center
TextPosition.TopLeft
TextPosition.TopRight
Font A Font object representing the font for the text
Pen The Pen object used to outline the text box
Examples
protected override void OnBarUpdate()
{
// Draws a text object
ITextFixed textFixed = DrawTextFixed("tag1",
"Text to draw", TextPosition.TopRight);
Definition
Represents an interface that exposes information regarding a Triangle IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Triangle
ITriangle tri = DrawTriangle("tag1", 4, Low[4],
3, High[3], 1, Low[1], Color.Blue);
Definition
Represents an interface that exposes information regarding a Triangle Down IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Triangle Down
ITriangleDown triangle = DrawTriangleDown
("tag1", true, 0, Low[0] - TickSize, Color.Red);
Definition
Represents an interface that exposes information regarding a Triangle Up IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Triangle Up
ITriangleUp triangle = DrawTriangleUp("tag1",
true, 0, Low[0] - TickSize, Color.Red);
Definition
Represents an interface that exposes information regarding a Vertical Line IDrawObject.
Examples
protected override void OnBarUpdate()
{
// Draws a Vertical Line
IVerticalLine vLine = DrawVerticalLine("tag1",
10, Color.Black);
Definition
Qualifies if object drawn in custom Plot method should be selectable in the indicator's hit test
procedure. The hit test procedure determines whether where your mouse is clicking will
Syntax
InHitTest
Examples
public override void Plot(Graphics graphics,
Rectangle bounds, double min, double max)
{
// Only draws a rectangle that covers the panel
canvas when the indicator is not going through the
hit test procedure.
// This effectively prevents clicking on the
area with the custom rectangle from actually
selecting the indicator.
if (!InHitTest)
graphics.FillRectangle(someBrush, new
Rectangle (0, 0, 2000, 2000));
}
10.4.4.70 RemoveDrawObject()
Definition
Removes a draw object from the chart based on its tag value.
Syntax
RemoveDrawObject(string tag)
Parameters
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.
Examples
// Removes a draw object with the tag "tag1"
RemoveDrawObject("tag1");
10.4.4.71 RemoveDrawObjects()
Definition
Removes all draw objects originating from the indicator or strategy from the chart. Manually
drawn objects will not be removed.
Syntax
RemoveDrawObjects()
Examples
// Removes all draw objects
RemoveDrawObjects();
10.4.5 Indicator
The methods and properties covered in this section are unique to custom indicator
development.
Indicator configuration properties globally define various behaviors of indicators. All properties
have default values and can be overridden by setting them in the Initialize() method of the
indicator.
10.4.5.1 Add()
Definition
Adds plot and line objects that define how an indicator data series is visualized on a chart.
When this method is called to add a plot, an associated DataSeries object is created that is
held in the Values collection.
Syntax
Add(Plot plot)
Add(Line line)
Parameters
plot A Plot object
line A Line object
Examples
// Adds a blue line style plot
Add(new Plot(Color.Blue, "myPlot"));
Tips
1. There are many variations of defined plot and line objects that are not documented. We
suggest using the NinjaScript indicator wizard to generate your indicator plot and oscillator
lines.
2. Plot objects DO NOT hold the actual indicator values. They simply define how the
indicator's values are plotted on a chart.
3. An indicator may calculate multiple values and therefore hold multiple plots to determine
the display of each calculated value. Indicator values are held in the indicator's Values
collection.
4. If your indicator calculates and stores three values then plots are assigned as per the
example below.
Definition
If true, the indicator plot(s) are included to determine the y scaling of the chart.
Property Value
This property returns true if the indicator plot(s) are included in the y-scale; otherwise, false.
Default set to true.
Syntax
AutoScale
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
AutoScale = false;
}
10.4.5.3 BarsRequired
Definition
The number of bars on a chart required before the indicator plots. This is NOT the same as a
minimum number of bars required to calculate the indicator values.
Property Value
An int value that represents the minimum number of bars required.
Syntax
BarsRequired
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
BarsRequired = 10; // Do not plot until the 11th
bar on the chart
}
Tips
1. When working with a multi-series indicator, real-time bar update events for a particular
Bars object are only received when that Bars object has satisfied the BarsRequired
requirement. To ensure this requirement is met, please use the CurrentBars array.
10.4.5.4 Displacement
Definition
An offset value that shifts the plotted value of an indicator.
Property Value
An int value that represents the number of bars ago to offset with.
Syntax
Displacement
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
Displacement = 2; // Plots the indicator value
from 2 bars ago on the current bar
}
10.4.5.5 DisplayInDataBox
Definition
If true, the indicator plot(s) values are displayed in the chart data box.
Property Value
This property returns true if the indicator plot(s) values are displayed in the chart data box;
otherwise, false. Default set to true.
Syntax
DisplayInDataBox
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
DisplayInDataBox = false;
}
10.4.5.6 DrawOnPricePanel
Definition
If true, all draw objects are painted on the price panel which is the panel that displays the
price bar data. If false, draw objects are painted on the actual indicator panel itself.
Property Value
This property returns true if the indicator paints draw objects on the price panel; otherwise,
false. Default set to true.
Syntax
DrawOnPricePanel
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
DrawOnPricePanel = false; // Draw objects now
paint on the indicator panel itself
}
10.4.5.7 FormatPriceMarker()
Definition
The FormatPriceMarker() method can be used to format the plot values
Property Value
This method returns a string representing the formatted price value.
Syntax
You must override the method in your indicator with the following syntax
Examples
// FormatPriceMarker method of a custom indicator
public override string FormatPriceMarker(double price
)
{
// Formats price values to 4 decimal places
return price.ToString("N4");
}
10.4.5.8 HorizontalGridLines
Definition
Plots horizontal grid lines on the indicator panel.
Property Value
This property returns true if horizontal grid lines are plotted on the indicator panel; otherwise,
false. Default set to true.
Syntax
HorizontalGridLines
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
HorizontalGridLines = false; // Horizontal grid
lines will not plot on the indicator panel
}
Tips
1. The indicator panel's parent chart has a similar property 'HorizontalGridLines' which if set
to false, will override the indicator's local setting if true.
10.4.5.9 Line Class
Definition
Objects derived from the Line class are used to characterize how an oscillator line is visually
displayed (plotted) on a chart.
Syntax
Line(Color color, double value, string name)
Line(Pen pen, double value, string name)
Parameters
color The line color (reference)
name The line name
pen The pen used to draw the plot (reference)
value The value used to define where the line is plotted
Examples
See the Add() method for examples.
10.4.5.10 Lines
Definition
A collection holding all of the Line objects that define the visualization characteristics
oscillator lines of the indicator.
Property Value
A collection of Line objects.
Syntax
Lines[int index]
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
// Lines are added to the Lines collection in
order
Add(new Line(Color.Gray, 30, "Lower")); //
Stored in Lines[0]
Add(new Line(Color.Gray, 70, "Upper")); //
Stored in Lines[1]
}
Definition
If true, any indicator line(s) are configurable within the indicator dialog window.
Property Value
This property returns true if any indicator line(s) are configurable; otherwise, false. Default
set to true.
Syntax
LinesConfigurable
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
LinesConfigurable = false; // Indicator lines
are not configurable
}
10.4.5.12 Overlay
Definition
If true, any indicator plot(s) are drawn on the chart panel over top of price.
Property Value
This property returns true if any indicator plot(s) are drawn on the chart panel; otherwise,
false. Default set to true.
Syntax
Overlay
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
Overlay = true; // Indicator plots are drawn on
the chart panel on top of price
}
10.4.5.13 PaintPriceMarkers
Definition
If true, any indicator plot values are displayed by price markers in the y-axis.
Property Value
This property returns true if the indicator plot values are displayed in the y-axis; otherwise,
false. Default set to true.
Syntax
PaintPriceMarkers
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
PaintPriceMarkers = true; // Indicator plots
values are displayed in the y-axis
}
10.4.5.14 Plot Class
Definition
Objects derived from the Plot class are used to characterize how a plot is visually displayed
(plotted) on a chart.
Syntax
Plot(Color color, string name)
Plot(Pen pen, string name)
Plot(Color color, PlotStyle plotStyle, string name)
Plot(Pen pen, PlotStyle plotStyle, string name)
Properties
Plot.Min - Sets the minimum value required for the plot to display
Plot.Max - Sets the maximum value the plot will display
Please note that these properties are subject to a pixel rounding logic meaning that if your plot
falls exactly on the .Min or .Max value, it is possible you would not see it painted depending on
your panel height. To avoid this please set the .Min and .Max threshold a little bit wider than
the minimum and maximum you desire.
* See tutorial "Custom Plot Color via Thresholds" for example of Plot.Min and Plot.Max
properties.
Parameters
color The line color (reference)
name The plot name
pen The pen used to draw the plot (reference)
plotStyle The plot's PlotStyle:
PlotStyle.Bar
PlotStyle.Block
PlotStyle.Cross
PlotStyle.Dot
PlotStyle.Hash
PlotStyle.HLine
PlotStyle.Line
PlotStyle.Square
PlotStyle.TriangleDown
PlotStyle.TriangleUp
Examples
See the Add() method for examples.
10.4.5.15 PlotColors
Definition
Holds an array of color series objects holding historical bar colors. A color series object is
added to this array when calling the Add() method in a Custom Indicator for plots. Its purpose
is to provide access to the color property of all bars.
Property Value
An array of color series objects.
Syntax
PlotColors[int PlotIndex][int barsAgo]
Examples
protected override void Initialize()
{
// Add two plots
Add(new Plot(Color.Blue, PlotStyle.Line, "Upper"));
Add(new Plot(Color.Orange, PlotStyle.Line, "Lower"));
}
PlotColors[1][0] = Color.Red;
else
PlotColors[1][0] = Color.Yellow;
}
10.4.5.16 Plots
Definition
A collection holding all of the Plot objects that define the visualization characteristics of the
indicator.
Property Value
A collection of Plot objects.
Syntax
Plots[int index]
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
// Lines are added to the Lines collection in
order
Add(new Plot(Color.Orange, "Plot1")); // Stored
in Plots[0]
Add(new Plot(Color.Blue, "Plot2")); // Stored
in Plots[1]
}
Definition
If true, any indicator plot(s) are configurable within the indicator dialog window.
Property Value
This property returns true if any indicator plot(s) are configurable; otherwise, false. Default
set to true.
Syntax
PlotsConfigurable
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
PlotsConfigurable = false; // Plots are not
configurable in the indicator dialog
}
10.4.5.18 PriceType
Definition
Type of price data such as open, high, low, etc...
Property Value
This property returns a PriceType value of either:
PriceType.Close
PriceType.High
PriceType.Low
PriceType.Median
PriceType.Open
PriceType.Typical
Syntax
PriceType
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
PriceType = PriceType.High; // Indicator will
use high prices for calculations
}
10.4.5.19 PriceTypeSupported
Definition
If true, the user can configure the indicator within the indicator dialog window to use different
price types for input.
Property Value
This property returns true if the indicator can be configured by price type; otherwise, false.
Default set to true.
Syntax
PriceTypeSupported
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
PriceTypeSupported = true; // Different price
types can be selected when applying an
// indicator to a
chart
}
Tips
1. When applying an indicator to a chart, the default input data used in the indicator is the data
series representing the price bars of a chart. Since price bars have open, high, low, close,
and volume data points, the indicator defaults to using the 'close' data point for indicator
calculation. If you set the 'PriceTypeSupported' value to true, the user of the indicator can
then configure it to use any of the supported price types for calculation.
10.4.5.20 SessionBreakLines
Definition
Plots session break lines on the indicator panel.
Property Value
This property returns true if session break lines are plotted on the indicator panel; otherwise,
false. Default set to true.
Syntax
SessionBreakLines
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
SessionBreakLines = false; // Session break
lines will not plot on the indicator panel
}
Tips
1. The indicator panel's parent chart has a similar property 'Plot session break line' which if
set to false, will override the indicator's local setting if true.
10.4.5.21 ScaleJustification
Definition
Determines which scale the indicator will be plotted on
Property Value
This property returns a ScaleJustification value of either:
ScaleJustification.Right
ScaleJustification.Left
ScaleJustification.Overlay
Syntax
ScaleJustification
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Add(new Plot(Color.Orange, "SMA"));
ScaleJustification = ScaleJustification.Left; //
Indicator will be plotted on the left scale
}
10.4.5.22 Update()
Definition
This method will force the OnBarUpdate() method to be called so that indicator values are
updated. This method is only relevant in specific use cases and likely only used by advanced
programmers.
When indicators are embedded (called) within a NinjaScript strategy, they are optimized to
calculate only when they are called upon in a historical backtest. Since the NinjaTrader
indicator model is very flexible, it is possible to create public properties on a custom indicator
that return values of internal user defined variables. If these properties require that the
OnBarUpdate() method is called before returning a value, include a call to this Update()
method in the property getter.
Syntax
Update()
Examples
private double tripleValue = 0;
return;
tripleValue = SMA(20)[0] * 3;
Value.Set(SMA(20)[0]);
}
Definition
Value references the first DataSeries object Values[0] in the indicator. This is the primary
indicator value.
Property Value
A DataSeries object.
Syntax
Value
Examples
// OnBarUpdate method of a custom indicator
protected override void OnBarUpdate()
{
// Ensures we have enough bars loaded for our
indicator
if (CurrentBar < 1)
return;
Tips
1. The DataSeries object referenced by this property is created by calling the Add() method.
10.4.5.24 Values
Definition
Values is a collection holding DataSeries objects that hold the indicator's underlying
calculated values.
DataSeries objects held by this collection are added by calling the Add() method.
Property Value
A collection of DataSeries objects.
Syntax
Values[int index]
Examples
// OnBarUpdate method of a custom indicator
protected override void OnBarUpdate()
{
// Ensures we have enough bars loaded for our
indicator
if (CurrentBar < 1)
return;
Definition
Plots vertical grid lines on the indicator panel.
Property Value
This property returns true if vertical grid lines are plotted on the indicator panel; otherwise,
false. Default set to true.
Syntax
VerticalGridLines
Examples
// Initialize method of a custom indicator
protected override void Initialize()
{
Tips
1. The indicator panel's parent object has a similar property 'VerticalGridLines' which if set to
false, will override the indicator's local setting if true.
10.4.6 Indicator Methods
The "Indicators" reference provides definitions, syntax, parameter definitions and examples
for NinjaTrader system indicator methods of both the Indicator and Strategy Class.
10.4.6.1 Valid Input Data for Indicator Methods
Indicator method can accept the following valid forms of input data.
Default Input
Default input of the custom indicator, Market Analyzer column or strategy is used as default
input if input is not specified.
Price Series
Open, High, Low, Close and Volume can all be used as input for an indicator method.
Indicator
Indicators can be used as input for indicators.
DataSeries
DataSeries can be used as input for indicators.
Bars Object
A Bars object (holds a series of bar object that contain OHLC data) can be used as input for
indicators.
Tips
1. The input series of an indicator cannot be the hosting indicator as it will cause recursive
loops.
Description
There are many indicators available to measure volume and the flow of money for a particular
stock, index or security. One of the most popular volume indicators over the years has been
the Accumulation/Distribution Line. The basic premise behind volume indicators, including the
Accumulation/Distribution Line, is that volume precedes price. Volume reflects the amount of
shares traded in a particular stock, and is a direct reflection of the money flowing into and out
of a stock. Many times before a stock advances, there will be period of increased volume just
prior to the move. Most volume or money flow indicators are designed to identify early
increases in positive or negative volume flow to gain an edge before the price moves. (Note:
the terms "money flow" and "volume flow" are essentially interchangeable.)
Syntax
ADL()
ADL(IDataSeries input)
ADL()[int barsAgo]
ADL(IDataSeries input)[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
Examples
// Checks if ADL is rising
bool isRising = Rising(ADL());
Print("Is ADL rising? " + isRising);
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.3 Adaptive Price Zone (APZ)
Description
The Adaptive Price Zone indicator from the S&C, September 2006 article "Trading With An
Adpative Price Zone" by Lee Leibfarth is a set of bands based on a short term double smooth
exponential moving average. The bands form a channel that surrounds the average price and
tracks price fluctuations quickly, especially in volatile markets. As price crosses above the
zone it can signal an opportunity to sell in anticipation of a reversal. As price crosses below
the zone it can signal an opportunity to buy in anticipation of a reversal.
Syntax
APZ(double barPct, int period)
APZ(IDataSeries input, double barPct, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
barPct The number of standard deviations
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current upper band value of a 20 period
APZ
double upperValue = APZ(2, 20).Upper[0];
Print("The current APZ upper value is " + upperValue.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.4 Aroon
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(IDataSeries input, int period)
Returns up value
Aroon(int period).Up[int barsAgo]
Aroon(IDataSeries input, int period).Up[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Example
// 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);
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.5 Aroon Oscillator
Description
A trend-following indicator that uses aspects of the Aroon indicator ("Aroon up" and "Aroon
down") to gauge the strength of a current trend and the likelihood that it will continue. The
Aroon oscillator is calculated by subtracting Aroon down from Aroon up. Readings above zero
indicate that an uptrend is present, while readings below zero indicate that a downtrend is
present.
Syntax
AroonOscillator(int period)
AroonOscillator(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current values of a 20 period
AroonOscillator using default price type
double upValue = AroonOscillator(20)[0];
Print("The current AroonOscillator value is " +
upValue.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.6 Average Directional Index (ADX)
Description
An indicator used in technical analysis as an objective value for the strength of trend. ADX is
non-directional so it will quantify a trend's strength regardless of whether it is up or down.
ADX is usually plotted in a chart window along with two lines known as the DMI (Directional
Movement Indicators). ADX is derived from the relationship of the DMI lines.
Syntax
ADX(int period)
ADX(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period ADX using
default price type
double value = ADX(20)[0];
Print("The current ADX value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.7 Average Directional Movement Rating (ADXR)
Description
The ADXR is equal to the current ADX plus the ADX from n bars ago divided by two.
Syntax
ADXR(int interval, int period)
ADXR(IDataSeries input, int interval, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
interval The interval between the first ADX value and the
current ADX value
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period ADXR using
default price type
double value = ADXR(10, 20)[0];
Print("The current ADXR value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.8 Average True Range (ATR)
Description
A measure of volatility introduced by Welles Wilder in his book: New Concepts in Technical
Trading Systems.
The Average True Range is a moving average (generally 14-days) of the True Ranges.
Syntax
ATR(int period)
ATR(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
Examples
// Prints the current value of a 20 period ATR using
default price type
double value = ATR(20)[0];
Print("The current ATR value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.9 Balance of Power (BOP)
Description
The balance of power (BOP) indicator measures the strength of the bulls vs. bears by
assessing the ability of each to push price to an extreme level.
Syntax
BOP(int smooth)
BOP(IDataSeries input, int smooth)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
smooth The smoothing period
Examples
// Prints the current value of BOP using default
price type and 3 period smoothing
double value = BOP(3)[0];
Print("The current BOP value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.10 Bollinger Bands
Description
Developed by John Bollinger, Bollinger Bands are an indicator that allows users to compare
volatility and relative price levels over a period time. The indicator consists of three bands
designed to encompass the majority of a security's price action.
Standard deviation is a statistical unit of measure that provides a good assessment of a price
plot's volatility. Using the standard deviation ensures that the bands will react quickly to price
movements and reflect periods of high and low volatility. Sharp price increases (or
decreases), and hence volatility, will lead to a widening of the bands.
Syntax
Bollinger(double numStdDev, int period)
Bollinger(IDataSeries input, double numStdDev, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current upper band value of a 20 period
Bollinger using default price type
double upperValue = Bollinger(2, 20).Upper[0];
Print("The current Bollinger upper value is " +
upperValue.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.11 BuySell Pressure
Description
The BuySellPressure indicator displays both the current bar's buying and selling pressure as
percentage values based on the categorization of trades as buy or sell trades. Trades are
categorized in real-time as a buy (at the ask or above) or as a sell (at the bid or below)....
Trades in between the market are ignored. This is a real-time indicator only. It functions only
on real-time data and therefore does not plot any values on historical data. If you change any
property, interval or instrument on a chart, this indicator will restart and any accumulated real-
time data plots will be lost.
Syntax
BuySellPressure()
BuySellPressure(IDataSeries input)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
Examples
// Initialize method
protected override void Initialize()
{
// You have to set this specific indicator's
CalculateOnBarClose property
// to false if the strategy, indicator or Quote
Board Column's CalculateOnBarClose
// property is set to true, otherwise the
indicator will not calculate it's values
BuySellPressure().CalculateOnBarClose = false;
}
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Looking for a long breakout signal
if (Close[0] > DonchianChannel(20).Upper[5])
{
// !! See notes below !!
if (Historical || BuySellPressure().
BuyPressure[0] > 70)
EnterLong();
}
}
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
The BuySellVolume indicator displays a real-time horizontal histogram of volume categorized
as buy or sell trades. Trades are categorized in real-time as a buy (at the ask or above) or as
a sell (at the bid or below) and then color coded .... Trades in between the market are
ignored. This is a real-time indicator only. It functions only on real-time data and therefore
does not plot any values on historical data. If you change any property, interval or instrument
on a chart, this indicator will restart and any accumulated real-time data plots will be lost.
Syntax
Syntax goes here.
Comments use style "Code Example Comments"
Types use style "Code Example Types"
Parameters use style "Code Example Parameters"
Example:
SMA(IDataSeries input, int period)[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
Example code
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.13 CandleStickPattern
Description
Detects the specified candle stick pattern.
Syntax
CandleStickPattern(ChartPattern pattern, int trendStrength)
CandleStickPattern(IDataSeries input, ChartPattern pattern, int
trendStrength)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
pattern Possible values are:
ChartPattern.BearishBeltHold
ChartPattern.BearishEngulfing
ChartPattern.BearishHarami
ChartPattern.BearishHaramiCross
ChartPattern.BullishBeltHold
ChartPattern.BullishEngulfing
ChartPattern.BullishHarami
ChartPattern.BullishHaramiCross
ChartPattern.DarkCloudCover
ChartPattern.Doji
ChartPattern.DownsideTasukiGap
ChartPattern.EveningStar
ChartPattern.FallingThreeMethods
ChartPattern.Hammer
ChartPattern.HangingMan
ChartPattern.InvertedHammer
ChartPattern.MorningStart
ChartPattern.PiercingLine
ChartPattern.RisingThreeMethods
ChartPattern.ShootingStar
ChartPattern.StickSandwich
ChartPattern.ThreeBlackCrows
ChartPattern.ThreeWhiteSoldiers
ChartPattern.UpsideGapTwoCrows
ChartPattern.UpsideTasukiGap
trendStrength The number of required bars to the left and right of
the swing point used to determine trend. A value of
zero will exclude the requirement of a trend and only
detect based on the candles themselves.
Examples
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.14 Chaikin Money Flow
Description
The formula for Chaikin Money Flow is the cumulative total of the Accumulation/Distribution
Values for 21 periods divided by the cumulative total of volume for 21 periods.
Syntax
ChaikinMoneyFlow(int period)
ChaikinMoneyFlow(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period
ChaikinMoneyFlow using default price type
double value = ChaikinMoneyFlow(20)[0];
Print("The current ChaikinMoneyFlow value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.15 Chaikin Oscillator
Description
The Chaikin Oscillator is simply the Moving Average Convergence Divergence indicator
(MACD) applied to the Accumulation/Distribution Line. The formula is the difference between
the 3-day exponential moving average and the 10-day exponential moving average of the
Accumulation/Distribution Line. Just as the MACD-Histogram is an indicator to predict moving
average crossovers in MACD, the Chaikin Oscillator is an indicator to predict changes in the
Accumulation/Distribution Line.
Syntax
ChaikinOscillator(int fast, int slow)
ChaikinOscillator(IDataSeries input, int fast, int slow)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
fast The number of bars to calculate the fast EMA
input Indicator source data (?)
slow The number of bars to calculate the slow EMA
Examples
// Prints the current value of a ChaikinOscillator
using default price type
double value = ChaikinOscillator(3, 10)[0];
Print("The current ChaikinOscillator value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
The Chaikin Volatility Indicator is the difference between two moving averages of a volume
weighted accumulation-distribution line. By comparing the spread between a security's high
and low prices, it quantifies volatility as a widening of the range between the high and the low
price.
Syntax
ChaikinVolatility(int period)
ChaikinVolatility(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of the 20 period Chaikin
Volatility
double value = ChaikinVolatility(20)[0];
Print("The current Chaikin Volatility value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.17 Chande Momentum Oscillator (CMO)
Description
The Chande Momentum Oscillator was developed by Tushar S. Chande and is described in
the 1994 book The New Technical Trader by Tushar S. Chande and Stanley Kroll. This
indicator is a modified RSI. Where the RSI divides the upward movement by the net
movement (up / (up + down)), the CMO divides the total movement by the net movement ((up
- down) / (up + down)). Values under -50 indicate oversold conditions while values over 50
indicate overbought conditions.
Syntax
CMO(int period)
CMO(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period The number of bars to include in the calculation
Examples
// Prints the current value of a 20 period CMO using
default price type
double value = CMO(20)[0];
Print("The current CMO value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.18 Commodity Channel Index (CCI)
Description
Developed by Donald Lambert, the Commodity Channel Index (CCI) was designed to identify
cyclical turns in commodities. The assumption behind the indicator is that commodities (or
stocks or bonds) move in cycles, with highs and lows coming at periodic intervals.
Syntax
CCI(int period)
CCI(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period CCI using
default price type
double value = CCI(20)[0];
Print("The current CCI value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.19 Current Day OHL
Description
The current day (session) open, high and low values.
Syntax
CurrentDayOHL()
CurrentDayOHL(IDataSeries input)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of the session low
double value = CurrentDayOHL().CurrentLow[0];
Print("The current session low value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.20 Darvas
Description
A trading strategy that was developed in 1956 by former ballroom dancer Nicolas Darvas.
Darvas' trading technique involved buying into stocks that were trading at new 52-week highs
with correspondingly high volumes.
Syntax
Darvas()
Darvas(IDataSeries input)
Darvas().Upper[int barsAgo]
Darvas(IDataSeries input).Upper[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
Examples
// Prints the current upper Darvas value
double value = Darvas().Upper[0];
Print("The current upper Darvas value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.21 Directional Movement (DM)
Description
Same as the ADX indicator with the addition of the +DI and -DI values.
Syntax
DM(int period)
DM(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period +DI using
default price type
double value = DM(20).DiPlus[0];
Print("The current +DI value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.22 Directional Movement Index (DMI)
Description
An indicator developed by J. Welles Wilder for identifying when a definable trend is present in
an instrument. That is, the DMI tells whether an instrument is trending or not.
Syntax
DMI(int period)
DMI(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
Examples
// Prints the current value of a 20 period DMI using
default price type
double value = DMI(20)[0];
Print("The current DMI value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.23 Donchian Channel
Description
A moving average indicator developed by Richard Donchian. It plots the highest high and
lowest low over the last period time intervals.
Syntax
DonchianChannel(int period)
DonchianChannel(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current upper value of a 20 period
DonchianChannel using default price type
double value = DonchianChannel(20).Upper[0];
Print("The current DonchianChannel upper value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.24 Double Stochastics
Description
Double Stochastics is a variation of the Stochastics indicator developed by William Blau.
Syntax
DoubleStochastics(int period)
DoubleStochastics(IDataSeries input, int period)
Returns %K value
DoubleStochastics(int period).K[int barsAgo]
DoubleStochastics(IDataSeries input, int period).K[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.25 Dynamic Momentum Index (DMIndex)
Description
An indicator used in technical analysis that determines overbought and oversold conditions of
a particular asset. This indicator is very similar to the relative strength index (RSI). The main
difference between the two is that the RSI uses a fixed number of time periods (usually 14),
while the dynamic momentum index uses different time periods as volatility changes.
Syntax
DMIndex(int smooth)
DMIndex(IDataSeries input, int smooth)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
smooth The number of bars to include in the calculation
Examples
// Prints the current value of DMIndex using default
price type
double value = DMIndex(3)[0];
Print("The current DMIndex value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.26 Ease of Movement
Description
The Ease of Movement indicator was designed to illustrate the relationship between volume
and price change. It shows how much volume is required to move prices.
High Ease of Movement values occur when prices are moving upward with light volume. Low
values occur when prices are moving downward on light volume. If prices are not moving or if
heavy volume is required to move prices then the indicator will read near zero. A buy signal is
produced when it crosses above zero. A sell signal is produced when the indicator crosses
below zero (prices are moving downward more easily).
Syntax
EaseOfMovement(int smoothing, int volumeDivisor)
EaseOfMovement(IDataSeries input, int smoothing, int volumeDivisor)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
smoothing The number of bars used to smooth the signal
volumeDivisor The value used to calculate the box ratio
Examples
// Prints the current value of Ease of Movement using
default price type
double value = EaseOfMovement(14, 10000)[0];
Print("The current Ease of Movement value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.27 Fisher Transform
Description
With distinct turning points and a rapid response time, the Fisher Transform uses the
assumption that while prices do not have a normal or Gaussian probability density function
(that familiar bell-shaped curve), you can create a nearly Gaussian probability density function
by normalizing price (or an indicator such as RSI) and applying the Fisher Transform. Use
the resulting peak swings to clearly identify price reversals.
Syntax
FisherTransform(int period)
FisherTransform(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 10 period using
default (median) price type
double value = FisherTransform(10)[0];
Print("The current Fisher Transform value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
The Forecast Oscillator calculates the percentage difference between the actual price and
the Time Series Forecast (the endpoint of a linear regression line). When the price and the
forecast are equal, the Oscillator is zero. When the price is greater than the forecast, the
Oscillator is greater than zero. When the price is less than the forecast, the Oscillator is less
than zero.
Syntax
FOSC(int period)
FOSC(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Checks if the current bar FOCS is above zero
if (FOSC(14)[0] > 0)
Print("FOSC is above zero indicating prices
may rise");
}
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
Heiken-Ashi is an averaging technique used in conjunction with candlestick bars primarily for
identifying when markets are trending.
Syntax
HeikenAshi()
HeikenAshi(IDataSeries input)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
Examples
// Prints the current HA open value
double value = HeikenAshi().HAOpen[0];
Print("The current Heiken-Ashi open value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.30 Keltner Channel
Description
Keltner Channel indicator is based on volatility using a pair of values placed as an "envelope"
around the data field.
Syntax
KeltnerChannel(double offsetMutiplier, int period)
KeltnerChannel(IDataSeries input, double offsetMutiplier, int
period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current upper value of a 20 period
KeltnerChannel using default price type
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.31 KeyReversalDown
Description
Returns a value of 1 when the current close is less than the prior close and the current high
has penetrated the highest high of the last n bars.
Syntax
KeyReversalDown(int period)
KeyReversalDown(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
protected override void OnBarUpdate()
{
// If we get a reversal over the past 10 bars go
short
if (KeyReversalDown(10)[0] == 1)
EnterShort();
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.32 KeyReversalUp
Description
Returns a value of 1 when the current close is greater than the prior close and the current low
has penetrated the lowest low of the last n bars.
Syntax
KeyReversalUp(int period)
KeyReversalUp(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
protected override void OnBarUpdate()
{
// If we get a reversal over the past 10 bars go
long
if (KeyReversalUp(10)[0] == 1)
EnterLong();
}
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
The Linear Regression Indicator plots the trend of a security's price over time. That trend is
determined by calculating a Linear Regression Trendline using the least squares method.
This ensures the minimum distance between the data points and a Linear Regression
Trendline.
Syntax
LinReg(int period)
LinReg(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period LinReg
using default price type
double value = LinReg(20)[0];
Print("The current LinReg value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
The Linear Regression Intercept provides the intercept value of the Linear Regression
trendline.
Syntax
LinRegIntercept(int period)
LinRegIntercept(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current intercept value of a 20 period
LinReg using default price type
double value = LinRegIntercept(20)[0];
Print("The current intercept value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.35 Linear Regression Slope
Description
The Linear Regression Slope provides the slope value of the Linear Regression trendline.
Syntax
LinRegSlope(int period)
LinRegSlope(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current slope value of a 20 period
LinReg using default price type
double value = LinRegSlope(20)[0];
Print("The current slope value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.36 MA Envelopes
Description
The Moving Average Envelope consists of moving averages calculated from the underling
price, shifted up and down by a fixed percentage.
Syntax
MAEnvelopes(double envelopePercentage, int mAType, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
envelopePercentage Percentage around MA that envelopes will be drawn
input Indicator source data (?)
mAType Moving average type:
1 = EMA
2 = HMA
3 = SMA
4 = TMA
5 = TEMA
6 = WMA
period Number of bars used in the calculation
Examples
// Prints the current upper band value of a 20 period
SMA envelope using default price type
double upperValue = MAEnvelopes(0.2, 3, 20).Upper[0];
Print("The current SMA envelope upper value is " +
upperValue.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.37 Maximum (MAX)
Description
Returns the highest value over the specified period.
Syntax
MAX(int period)
MAX(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the highest high value over the last 20
periods
double value = MAX(High, 20)[0];
Print("The current MAX value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
Returns the lowest value over the specified period.
Syntax
MIN(int period)
MIN(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the lowest low value over the last 20
periods
double value = MIN(Low, 20)[0];
Print("The current MIN value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.39 Momentum
Description
By measuring the amount that a security's price has changed over a given time span, the
Momentum indicator provides an indication of a market's velocity and to some degree, a
measure of the extent to which a trend still holds true. It can also be helpful in spotting likely
reversal points.
Syntax
Momentum(int period)
Momentum(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period Momentum
using default price type
double value = Momentum(20)[0];
Print("The current Momentum value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.40 Money Flow Index (MFI)
Description
The Money Flow Index (MFI) is a momentum indicator that is similar to the Relative Strength
Index (RSI) in both interpretation and calculation. However, MFI is a more rigid indicator in that
it is volume-weighted, and is therefore a good measure of the strength of money flowing in
and out of a security.
Syntax
MFI(int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period MFI using
default price type
double value = MFI(20)[0];
Print("The current MFI value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.41 Moving Average - Double Exponential (DEMA)
Description
The Double Exponential Moving Average (DEMA) is a combination of a single exponential
moving average and a double exponential moving average. The advantage is that gives a
reduced amount of lag time than either of the two separate moving averages alone.
Syntax
DEMA(int period)
DEMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period DEMA using
default price type
double value = DEMA(20)[0];
Print("The current DEMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.42 Moving Average - Exponential (EMA)
Description
The exponential moving average is but one type of a moving average. In a simple moving
average, all price data has an equal weight in the computation of the average with the oldest
value removed as each new value is added. In the exponential moving average equation the
most recent market action is assigned greater importance as the average is calculated. The
oldest pricing data in the exponential moving average is however never removed.
Syntax
EMA(int period)
EMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period EMA using
default price type
double value = EMA(20)[0];
Print("The current EMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.43 Moving Average - Hull (HMA)
Description
The HMA manages to keep up with rapid changes in price activity whilst having superior
smoothing over an SMA of the same period. The HMA employs weighted moving averages
and dampens the smoothing effect (and resulting lag) by using the square root of the period
instead of the actual period itself. Developed by Alan Hull.
Syntax
HMA(int period)
HMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period HMA using
default price type
double value = HMA(20)[0];
Print("The current HMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.44 Moving Average - Kaufman's Adaptive (KAMA)
Description
Developed by Perry Kaufman, this indicator is an EMA using an Efficiency Ratio to modify the
smoothing constant, which ranges from a minimum of Fast Length to a maximum of Slow
Length.
Syntax
KAMA(int fast, int period, int slow)
KAMA(IDataSeries input, int fast, int period, int slow)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
fast Fast length
Examples
// Prints the current value of a 20 period KAMA using
default price type
double value = KAMA(2, 20, 30)[0];
Print("The current KAMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.45 Moving Average - Mesa Adaptive (MAMA)
Description
The MESA Adaptive Moving Average (MAMA) adapts to price movement in an entirely new
and unique way. The adaptation is based on the rate change of phase as measured by the
Hilbert Transform Discriminator. The advantage of this method of adaptation is that it features
a fast attack average and a slow decay average so that composite average rapidly ratchets
behind price changes and holds the average value until the next ratchet occurs.
Syntax
MAMA(double fastLimit, double slowLimit)
MAMA(IDataSeries input, double fastLimit, double slowLimit)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
fastLimit Upper limit of the alpha value
input Indicator source data (?)
slowLimit Lower limit of the alpha value
Examples
// Prints the current value of a 20 period MAMA using
default price type
double value = MAMA(0.5,0.05).Default[0];
Print("The current MAMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.46 Moving Average - Simple (SMA)
Description
The Simple Moving Average is calculated by summing the closing prices of the security for a
period of time and then dividing this total by the number of time periods. Sometimes called an
arithmetic moving average, the SMA is basically the average stock price over time.
Syntax
SMA(int period)
SMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period SMA using
default price type
double value = SMA(20)[0];
Print("The current SMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.47 Moving Average - T3 (T3)
Description
The T3 is a type of moving average, or smoothing function. It is based on the DEMA. The T3
takes the DEMA calculation and adds a vfactor which is between zero and 1. The resultant
function is called the GD, or Generalized DEMA. A GD with vfactorof 1 is the same as the
DEMA. A GD with a vfactor of zero is the same as an Exponential Moving Average. The T3
typically uses a vfactor of 0.7.
Syntax
T3(int period, int tCount, double vFactor)
T3(IDataSeries input, int period, int tCount, double vFactor)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
tCount Number of smooth iterations
vFactor A multiplier fudge factor
Examples
// Prints the current value of a 20 period T3 using
default price type
double value = T3(20, 3, 0.7)[0];
Print("The current T3 value is " + value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.48 Moving Average - Triangular (TMA)
Description
The Triangular Moving Average is a form of Weighted Moving Average wherein the weights
are assigned in a triangular pattern. For example, the weights for a 7 period Triangular Moving
Average would be 1, 2, 3, 4, 3, 2, 1. This gives more weight to the middle of the time series
and less weight to the oldest and newest data.
Syntax
TMA(int period)
TMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period TMA using
default price type
double value = TMA(20)[0];
Print("The current TMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.49 Moving Average - Triple Exponential (TEMA)
Description
The TEMA is a smoothing indicator. It was developed by Patrick Mulloy and is described in his
article in the January, 1994 issue of Technical Analysis of Stocks and Commodities
magazine.
Syntax
TEMA(int period)
TEMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period TEMA using
default price type
double value = TEMA(20)[0];
Print("The current TEMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.50 Moving Average - Triple Exponential (TRIX)
Description
The triple exponential average (TRIX) indicator is an oscillator used to identify oversold and
overbought markets, and it can also be used as a momentum indicator.
Syntax
TRIX(int period, int signalPeriod)
TRIX(IDataSeries input, int period, int signalPeriod)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
Examples
// Prints the current value of a 20 period TRIX using
default price type
double value = TRIX(20, 3).Default[0];
Print("The current TRIX value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.51 Moving Average - Variable (VMA)
Description
A Variable Moving Average is an exponential moving average that automatically adjusts its
smoothing percentage based on market volatility. Giving more weight to the current data
increases sensitivity thus making it a better signal indicator for short and long term markets.
Syntax
VMA(int period, int volatilityPeriod)
VMA(IDataSeries input, int period, int volatilityPeriod)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// OnBarUpdate method of a strategy
protected override void OnBarUpdate()
{
// Print out the VMA value of lows 3 bars ago for
fun
double value = VMA(Low, 9, 9)[3];
Print("The value is " + value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.52 Moving Average - Volume Weighted (VWMA)
Description
The Volume Weighted Moving Average is a weighted moving average that uses the volume
as the weighting factor, so that higher volume days have more weight. It is a non-cumulative
moving average, in that only data within the time period is used in the calculation.
Syntax
VWMA(int period)
VWMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Checks for a VWMA cross over to the long side
if (CrossAbove(VWMA(14), VWMA(40), 1))
Print("We have a moving average cross over
long");
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.53 Moving Average - Weighted (WMA)
Description
The Weighted Moving Average gives the latest price more weight than prior prices. Each prior
price in the period gets progressively less weight as they become older.
Syntax
WMA(int period)
WMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period WMA using
default price type
double value = WMA(20)[0];
Print("The current WMA value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.54 Moving Average - Zero Lag Exponential (ZLEMA)
Description
The Zero-Lag Exponential Moving Average is a variation on the Exponential Moving Average.
The Zero-Lag keeps the benefit of the heavier weighting of recent values, but attempts to
remove lag by subtracting older data to minimize the cumulative effect.
Syntax
ZLEMA(int period)
ZLEMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period ZLEMA
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.55 Moving Average Convergence-Divergence (MACD)
Description
MACD uses moving averages, which are lagging indicators, to include some trend-following
characteristics. These lagging indicators are turned into a momentum oscillator by
subtracting the longer moving average from the shorter moving average.
Syntax
MACD(int fast, int slow, int smooth)
MACD(IDataSeries input, int fast, int slow, int smooth)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
fast The number of bars to calculate the fast EMA
input Indicator source data (?)
slow The numbers of bars to calculate the slow EMA
smooth The number of bars to calculate the EMA signal line
Examples
// Prints the current MACD value
double value = MACD(12, 26, 9)[0];
Print("The current MACD value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.56 n Bars Down
Description
Checks for n number of consecutive lower closes. Returns a value of 1 when the condition is
true or 0 when false.
Syntax
NBarsDown(int barCount, bool BarDown, bool lowerHigh, bool lowerLow
)
NBarsDown(IDataSeries input, int barCount, bool BarDown, bool
lowerHigh, bool lowerLow)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
barCount The number of required consecutive lower closes
BarDown Each bar's open must be less than the close; true
or false
input Indicator source data (?)
lowestHigh Consecutive lower highs required; true or false
lowestLow Consecutive lower lows required; true or false
Examples
// Checks if we have 3 consecutive lower closes
double value = NBarsDown(3, true, true, true)[0];
if (value == 1)
Print("We have three consecutive lower closes);
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.57 n Bars Up
Description
Checks for n number of consecutive higher closes. Returns a value of 1 when the condition
is true or 0 when false.
Syntax
NBarsUp(int barCount, bool BarUp, bool higherHigh, bool higherLow)
NBarsUp(IDataSeries input, int barCount, bool BarUp, bool
higherHigh, bool higherLow)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
Parameters
barCount The number of required consecutive higher closes
BarUp Each bar's open must be higher than the close;
true or false
higherHigh Consecutive higher highs required; true or false
higherLow Consecutive higher lows required; true or false
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Checks if we have 3 consecutive higher closes
double value = NBarsUp(3, true, true, true)[0];
if (value == 1)
Print("We have three consecutive higher closes);
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.58 On Balance Volume (OBV)
Description
OBV is a simple indicator that adds a period's volume when the close is up and subtracts the
period's volume when the close is down. A cumulative total of the volume additions and
subtractions forms the OBV line. This line can then be compared with the price chart of the
underlying security to look for divergences or confirmation.
Syntax
OBV()
OBV(IDataSeries input)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of OBV
double value = OBV()[0];
Print("The current OBV value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.59 Parabolic SAR
Description
The parabolic SAR is a technical indicator that is used by many traders to determine the
direction of an asset's momentum and the point in time when this momentum has a higher-
than-normal probability of switching directions.
Syntax
ParabolicSAR(double acceleration, double accelerationStep, double
accelerationMax)
ParabolicSAR(IDataSeries input, double acceleration, double
accelerationStep, double accelerationMax)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
acceleration Acceleration value
accelerationStep Step value used to increment acceleration value
accelerationMax Max acceleration value
Examples
// Prints the current value of ParabolicSAR using
default price type
double value = ParabolicSAR(0.02, 0.2, 0.02)[0];
Print("The current ParabolicSAR value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.60 Percentage Price Oscillator (PPO)
Description
The Percentage Price Oscillator shows the percentage difference between two exponential
moving averages.
Syntax
PPO(int fast, int slow, int smooth)
PPO(IDataSeries input, int fast, int slow, int smooth)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
fast The number of bars to calculate the fast EMA
input Indicator source data (?)
slow The number of bars to calculate the slow EMA
smooth The number of bars to calculate the EMA signal line
Examples
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.61 Pivots
Description
The pivot point is used as a predictive indicator. If the following day's market price falls below
the pivot point, it may be used as a new resistance level. Conversely, if the market price rises
above the pivot point, it may act as the new support level.
Syntax
Pivots(PivotRange pivotRangeType, HLCCalculationMode priorDayHLC,
double userDefinedClose, double userDefinedHigh, double
userDefinedLow, int width)
Pivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, double userDefinedClose, double
userDefinedHigh, double userDefinedLow, int width)
Returns R1 value
Pivots(PivotRange pivotRangeType, HLCCalculationMode priorDayHLC,
double userDefinedClose, double userDefinedHigh, double
userDefinedLow, int width).R1[int barsAgo]
Pivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, double userDefinedClose, double
userDefinedHigh, double userDefinedLow, int width).R1[int barsAgo]
Returns R2 value
Pivots(PivotRange pivotRangeType, HLCCalculationMode priorDayHLC,
double userDefinedClose, double userDefinedHigh, double
userDefinedLow, int width).R2[int barsAgo]
Returns R3 value
Pivots(PivotRange pivotRangeType, HLCCalculationMode priorDayHLC,
double userDefinedClose, double userDefinedHigh, double
userDefinedLow, int width).R3[int barsAgo]
Pivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, double userDefinedClose, double
userDefinedHigh, double userDefinedLow, int width).R3[int barsAgo]
Returns S1 value
Pivots(PivotRange pivotRangeType, HLCCalculationMode priorDayHLC,
double userDefinedClose, double userDefinedHigh, double
userDefinedLow, int width).S1[int barsAgo]
Pivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, double userDefinedClose, double
userDefinedHigh, double userDefinedLow, int width).S1[int barsAgo]
Returns S2 value
Pivots(PivotRange pivotRangeType, HLCCalculationMode priorDayHLC,
double userDefinedClose, double userDefinedHigh, double
userDefinedLow, int width).S2[int barsAgo]
Pivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, double userDefinedClose, double
userDefinedHigh, double userDefinedLow, int width).S2[int barsAgo]
Returns S3 value
Pivots(PivotRange pivotRangeType, HLCCalculationMode priorDayHLC,
double userDefinedClose, double userDefinedHigh, double
userDefinedLow, int width).S3[int barsAgo]
Pivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, double userDefinedClose, double
userDefinedHigh, double userDefinedLow, int width).S3[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
pivotRangeType Sets the range for the type of pivot calculated.
Possible values are:
PivotRange.Daily
PivotRange.Weekly
PivotRange.Monthly
priorDayHLC Sets how the prior range High, Low, Close values
are calculated. Possible values are:
HLCCalculationMode.CalcFromIntradayData
HLCCalculationMode.DailyBars
HLCCalculationMode.UserDefinedValues
userDefinedClose Sets the close for Pivots calculations when using
HLCCalculationMode.UserDefinedValues.
userDefinedHigh Sets the high for Pivots calculations when using
HLCCalculationMode.UserDefinedValues.
userDefinedLow Sets the low for Pivots calculations when using
HLCCalculationMode.UserDefinedValues.
width Sets how long the Pivots lines will be drawn
Examples
// Prints the current pivot point value
double value = Pivots(PivotRange.Daily,
HLCCalculationMode.CalcFromIntradayData, 0, 0, 0,
20).PP[0];
Print("The current Pivots' pivot value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Tips
1. When using HLCCalculationMode.DailyBars it can be expected that a value of 0 is returned
when the daily bars have not been loaded yet. Due to the asynchronous nature of this
indicator calling daily bars you should only access the pivot values when the indicator has
loaded all required Bars objects. To ensure you are accessing accurate values you can
use .ContainsValue() as a check:
Description
The Polarized Fractal Efficiency indicator uses fractal geometry to determine how efficiently
the price is moving. When the PFE is zigzagging around zero, then the price is congested
and not trending. When the PFE is smooth and above/below zero, then the price is in an up/
down trend. The higher/lower the PFE value, the stronger the trend is.
Syntax
PFE(int period)
PFE(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period PFE using
default price type
double value = PFE(20)[0];
Print("The current PFE value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.63 Price Oscillator
Description
The Price Oscillator is an indicator based on the difference between two moving averages,
and is expressed as either a percentage or in absolute terms.
Syntax
PriceOscillator(int fast, int slow, int smooth)
PriceOscillator(IDataSeries input, int fast, int slow, int smooth)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
fast The number of bars to calculate the fast EMA
input Indicator source data (?)
slow The number of bars to calculate the slow EMA
smooth The number of bars to calculate the EMA signal line
Examples
// Prints the current value of a 20 period
PriceOscillator using default price type
double value = PriceOscillator(12, 26, 9)[0];
Print("The current PriceOscillator value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
The prior day (session) open, high, low and close values.
Syntax
PriorDayOHLC()
PriorDayOHLC(IDataSeries input)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the value of the prior session low
double value = PriorDayOHLC().PriorLow[0];
Print("The prior session low value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.65 Range
Description
Returns the range of a bar.
Syntax
Range()
Range(IDataSeries input)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period ROC using
default price type
double value = Range()[0];
Print("The current bar's range is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.66 Range Indicator (RIND)
Description
The Range indicator compares the intraday range (high - low) to the inter-day (close -
previous close) range. When the inter-day range is less than the intraday range, the Range
Indicator will be a high value. This signals an end to the current trend. When the Range
The Range Indicator was developed by Jack Weinberg and was introduced in his article in the
June, 1995 issue of Technical Analysis of Stocks & Commodities magazine.
Syntax
RIND(int periodQ, int smooth)
RIND(IDataSeries input, int periodQ, int smooth)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
periodQ The number of bars to include in the calculation for
the short term stochastic range lookback
smooth The number of bars to include for the EMA
smoothing of the indicator
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Prints out a historical RIND value
double value = RIND(3, 10)[5];
Print("RIND value of 5 bars ago is " + value.
ToString());
}
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.67 Rate of Change (ROC)
Description
The Rate of Change (ROC) indicator is a very simple yet effective momentum oscillator that
measures the percent change in price from one period to the next. The ROC calculation
compares the current price with the price n periods ago.
Syntax
ROC(int period)
ROC(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period ROC using
default price type
double value = ROC(20)[0];
Print("The current ROC value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.68 Regression Channel
Description
A Regression Channel is created by drawing parallel lines above and below the Linear
Regression line.
Parallel and equidistant lines are drawn n standard deviations (width parameter) above and
below a Linear Regression trendline. The distance between the channel lines and the
regression line is the greatest distance that any one closing price is from the regression line.
Regression Channels contain price movement, the top channel line provides resistance and
the bottom channel line provides support. A reversal in trend may be indicated when prices
remain outside the channel for a longer period of time.
A Linear Regression trendline shows where equilibrium exists but Linear Regression
Channels show the range prices can be expected to deviate from a trendline.
Syntax
RegressionChannel(int period, int width)
RegressionChannel(IDataSeries input, int period, int width)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
width Number of std deviations to calculate the channel
lines
Tips
You should not access historical values of this indicator since the values can change from
bar to bar. The values from n bars ago does not reflect what the values of the current bar
really are. It is suggested that you only access the current bar value for this indicator.
Examples
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.69 Relative Spread Strength (RSS)
Description
Developed by Ian Copsey, Relative Spread Strength is a variation to the Relative Strength
Index.
Syntax
RSS(int eMA1, int eMA2, int length)
RSS(IDataSeries input, int eMA1, int eMA2, int length)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
eMA1 First EMA's period
eMA2 Second EMA's period
input Indicator source data (?)
length Number of bars used in the calculation
Examples
// Prints the current value of the RSS using default
price type
double value = RSS(10, 40, 5)[0];
Print("The current RSS value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.70 Relative Strength Index (RSI)
Description
Developed by J. Welles Wilder and introduced in his 1978 book, New Concepts in Technical
Trading Systems, the Relative Strength Index (RSI) is an extremely useful and popular
momentum oscillator. The RSI compares the magnitude of a stock's recent gains to the
magnitude of its recent losses and turns that information into a number that ranges from 0 to
100.
Syntax
RSI(int period, int smooth)
RSI(IDataSeries input, int period, int smooth)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
smooth Smoothing period
Examples
// Prints the current value of a 20 period RSI using
default price type
double value = RSI(20, 3)[0];
Print("The current RSI value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.71 Relative Volatility Index (RVI)
Description
Developed by Donald Dorsey, the Relative Volatility Index is the RSI using the standard
deviation over the indicator period in place of the daily price change. The RVI measures the
direction of volatility on a scale from 0 to 100. Readings below 50 indicate that the direction of
volatility is to the downside and that you should be looking to sell, readings above 50 indicate
that the direction of volatilty is to the upside and that you should be looking to buy.
Syntax
RVI(int period)
RVI(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// OnBarUpdate method of a stratgegy
protected override void OnBarUpdate()
{
// Check for buy condition
if (RVI(14)[0] > 50 && CrossAbove(SMA(9), SMA
(14), 1))
{
// System logic here...
}
}
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.72 R-squared
Description
The r-squared indicator calculates how well the price approximates a linear regression line.
The indicator gets its name from the calculation, which is, the square of the correlation
coefficient (referred to in mathematics by the Greek letter rho, or r). The range of the r-
squared is from zero to one.
Syntax
RSquared(int period)
RSquared(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period R-squared
using default price type
double value = RSquared(20)[0];
Print("The current R-squared value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.73 Standard Deviation (StdDev)
Description
In probability theory and statistics, standard deviation is a measure of the variability or
dispersion of a population, a data set, or a probability distribution. A low standard deviation
indicates that the data points tend to be very close to the same value (the mean), while high
standard deviation indicates that the data are “spread out” over a large range of values.
Syntax
StdDev(int period)
StdDev(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period StdDev
using default price type
double value = StdDev(20)[0];
Print("The current StdDev value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.74 Standard Error (StdError)
Description
The standard error of a method of measurement or estimation is the standard deviation of the
sampling distribution associated with the estimation method. The term may also be used to
refer to an estimate of that standard deviation, derived from a particular sample used to
compute the estimate.
Syntax
StdError(int period)
StdError(IDataSeries input, int period)
Returns default value which is the mid line (also known as linear
regression)
StdError(int period)[int barsAgo]
StdError(IDataSeries input, int period)[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current upper value of a 20 period
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.75 Stochastics
Description
Developed by George C. Lane in the late 1950s, the Stochastic Oscillator is a momentum
indicator that shows the location of the current close relative to the high/low range over a set
number of periods. Closing levels that are consistently near the top of the range indicate
accumulation (buying pressure) and those near the bottom of the range indicate distribution
(selling pressure).
Syntax
Stochastics(int periodD, int periodK, int smooth)
Stochastics(IDataSeries input, int periodD, int periodK, int smooth
)
Returns %D value
Stochastics(int periodD, int periodK, int smooth).D[int barsAgo]
Stochastics(IDataSeries input, int periodD, int periodK, int smooth
).D[int barsAgo]
Returns %K value
Stochastics(int periodD, int periodK, int smooth).K[int barsAgo]
Stochastics(IDataSeries input, int periodD, int periodK, int smooth
).K[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
periodD The period moving average of periodK
periodK The number of bars used to include in
thecalculation
smooth The period moving average of periodD
Examples
// Prints the current %D value
double value = Stochastics(3, 14, 7).D[0];
Print("The current Stochastics %D value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.76 Stochastics Fast
Description
Developed by George C. Lane in the late 1950s, the Stochastic Oscillator is a momentum
indicator that shows the location of the current close relative to the high/low range over a set
number of periods. Closing levels that are consistently near the top of the range indicate
accumulation (buying pressure) and those near the bottom of the range indicate distribution
(selling pressure).
Syntax
StochasticsFast(int periodD, int periodK)
StochasticsFast(IDataSeries input, int periodD, int periodK)
Returns %D value
StochasticsFast(int periodD, int periodK).D[int barsAgo]
StochasticsFast(IDataSeries input, int periodD, int periodK).D[int
barsAgo]
Returns %K value
StochasticsFast(int periodD, int periodK).K[int barsAgo]
StochasticsFast(IDataSeries input, int periodD, int periodK).K[int
barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
periodD The period moving average of periodK
periodK The number of bars to include in the calculation
Examples
// Prints the current %D value
double value = StochasticsFast(3, 14).D[0];
Print("The current StochasticsFast %D value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.77 Stochastics RSI (StochRSI)
Description
This is an indicator on indicator implementation. It is simply a Stochastics indicator applied
on RSI.
Syntax
StochRSI(int period)
StochRSI(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Checks if the current bar StochRSI value is
greater than the value one bar ago
if (StochRSI(14)[0] > StochRSI(14)[1])
Print("Stochastics RSI is rising");
}
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.78 Summation (SUM)
Description
Returns the sum over the specified period.
Syntax
SUM(int period)
SUM(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period SUM using
default price type
double value = SUM(20)[0];
Print("The current SUM value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.79 Swing
Description
The Swing indicator will plot lines that represent the swing points based on the strength
(number of bars to the left and right of the swing point) parameter provided. You can access
methods within this indicator to determine the number of bars ago a swing point occured or
the current swing value.
Low Bar
Swing(int strength).SwingLowBar(int barsAgo, int instance, int
lookBackPeriod)
Swing(IDataSeries input, int strength).SwingLowBar(int barsAgo, int
instance, int lookBackPeriod)
Return Value
An int value representing the number of bars ago. Returns a value of -1 if a swing point is
not found within the look back period.
Syntax - Value
High Value
Swing(int strength).SwingHigh[int barsAgo]
Swing(IDataSeries input, int strength).SwingHigh[int barsAgo]
Low Value
Swing(int strength).SwingLow[int barsAgo]
Swing(IDataSeries input, int strength).SwingLow[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
* A return value of 0 (zero) will be returned if the CurrentBar is less than the
Parameters
barsAgo The number of bars ago that serves as the starting
bar and works backwards
input Indicator source data (?)
instance The occurrence to check for (1 is the most recent,
2 is the 2nd most recent, etc...)
lookBackPeriod Number of bars to look back to check for the test
condition
strength The number of required bars to the left and right of
the swing point
Examples
// Prints the high price of the most recent swing
high
Print("The high of the swing bar is " + High[Math.Max
(0, Swing(5).SwingHighBar(0, 1, 10))]);
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.80 Time Series Forecast (TSF)
Description
The Time Series Forecast function displays the statistical trend of a security's price over a
specified time period based on linear regression analysis. Instead of a straight linear
regression trendline, the Time Series Forecast plots the last point of multiple linear
regression trendlines. This is why this indicator may sometimes referred to as the "moving
linear regression" indicator or the "regression oscillator."
Syntax
TSF(int forecast, int period)
TSF(IDataSeries input, int forecast, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
Parameters
forecast Forecast period
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period TSF using
default price type
double value = TSF(3, 20)[0];
Print("The current TSF value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.81 True Strength Index (TSI)
Description
The True Strength Index (TSI) is a momentum-based indicator, developed by William Blau.
Designed to determine both trend and overbought/oversold conditions, the TSI is applicable to
intraday time frames as well as long term trading.
Syntax
TSI(int fast, int slow)
TSI(IDataSeries input, int fast, int slow)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
fast The number of bars to include in the calculation
input Indicator source data (?)
slow The number of bars to include in the calculation
Examples
// Prints the current value of a 20 period TSI using
default price type
double value = TSI(20)[0];
Print("The current TSI value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.82 Ultimate Oscillator
Description
Developed by Larry Williams and introduced in his article in the April, 1985 issue of Technical
Analysis of Stocks and Commodities magazine, this indicator is the weighted sum of three
oscillators of different time periods. The there time periods represent short, intermediate and
long term market cycles. Typical periods are 7, 14 and 28. The values of the Ultimate
Oscillator range from zero to 100. Values over 70 indicate overbought conditions, and values
under 30 indicate oversold conditions.
Syntax
UltimateOscillator(int fast, int intermediate, int slow)
UltimateOscillator(IDataSeries input, int fast, int intermediate,
int slow)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
Examples
// Prints the current value of a typical Ultimate
Oscillator using default price type
double value = UltimateOscillator(7, 14, 28)[0];
Print("The current Ultimate Oscillator value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.83 Volume (VOL)
Description
Volume is simply the number of shares (or contracts) traded during a specified time frame (e.
g., hour, day, week, month, etc). The analysis of volume is a basic yet very important element
of technical analysis. Volume provides clues as to the intensity of a given price move.
Syntax
VOL()
VOL(IDataSeries input)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
Examples
// Prints the current value VOL
int value = VOL()[0];
Print("The current VOL value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.84 Volume Moving Average (VOLMA)
Description
The Volume Moving Average indicator is an indicator on indicator implementation. It
calculates and returns the value of an exponential moving average of volume.
Syntax
VOLMA(int period)
VOLMA(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// OnBarUpdate method
protected override void OnBarUpdate()
{
// Checks if the current volume is greater than
the 20 period EMA of volume
if (Volume[0] > VOLMA(20)[0])
Print("Volume has risen above its 20 period
average");
}
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.85 Volume Oscillator
Description
The Volume Oscillator uses the difference between two moving averages of volume to
determine if the trend is increasing or decreasing. A value above zero indicates that the
shorter term volume moving average has risen above the longer term volume moving
average. This indicates that the shorter term trend is higher than the longer term trend. Rising
prices with with increased short term volume is bullish as is falling prices with decreased
volume. Falling prices with increased volume or rising prices with decreased volume indicate
market weakness.
Syntax
VolumeOscillator(int fast, int slow)
VolumeOscillator(IDataSeries input, int fast, int slow)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
fast The number of bars to include in the short term
moving average
input Indicator source data (?)
slow The number of bars to include in the long term
moving average
Examples
// Prints the current value of a Volume Oscillator
double value = VolumeOscillator(12, 26)[0];
Print("The current Volume Oscillator value is " +
value.ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
Description
Volume Rate of Change is identical to Price Rate Of Change (ROC) indicator except that it
uses volume instead of price.
Syntax
VROC(int period, int smooth)
VROC(IDataSeries input, int period, int smooth)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
smooth The number of bars for smoothing the signal
Examples
// Prints the current value of VROC
double value = VROC(13, 3)[0];
Print("The current VROC value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.87 Volume Up Down
Description
Variation of the VOL (Volume) indicator that colors the volume histogram different color
depending if the current bar is up or down bar.
Syntax
VolumeUpDown()
VolumeUpDown(IDataSeries input)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
Examples
// Prints the current value VolumeUpDown
int value = VolumeUpDown()[0];
Print("The current Volume value is " + value.ToString
());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.88 Williams %R
Description
Developed by Larry Williams, Williams %R is a momentum indicator that works much like
the Stochastic Oscillator. It is especially popular for measuring overbought and oversold
levels. The scale ranges from 0 to -100 with readings from 0 to -20 considered overbought,
and readings from -80 to -100 considered oversold.
Syntax
WilliamsR(int period)
WilliamsR(IDataSeries input, int period)
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
period Number of bars used in the calculation
Examples
// Prints the current value of a 20 period WilliamsR
using default price type
double value = WilliamsR(20)[0];
Print("The current WilliamsR value is " + value.
ToString());
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.6.89 Woodies CCI
Description
NinjaTrader provides the Woodies CCI indicator. It's implemented as specified by Woodie.
Syntax
WoodiesCCI()
WoodiesCCI(IDataSeries input)
-4 = DarkRed
-3 = LightRed
-2 = DarkOrange
-1 = LightOrange
0 = Yellow
1 = Lime
2 = LightGreen
3 = DarkGreen
4 = Cyan
-1 = Warning
0 = Neutral
1 = Trending
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
Examples
// Prints the current value of a 20 period WoodiesCCI
using default price type
double value = WoodiesCCI(20)[0];
Print("The current WoodiesCCI value is " + value.
ToString());
Description
Woodies CCI Club pivots indicator.
Syntax
WoodiesPivots(PivotRange pivotRangeType, HLCCalculationMode
priorDayHLC, int width)
WoodiesPivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, int width)
Returns R1 value
WoodiesPivots(PivotRange pivotRangeType, HLCCalculationMode
priorDayHLC, int width).R1[int barsAgo]
WoodiesPivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, int width).R1[int barsAgo]
Returns R2 value
WoodiesPivots(PivotRange pivotRangeType, HLCCalculationMode
priorDayHLC, int width).R2[int barsAgo]
WoodiesPivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, int width).R2[int barsAgo]
Returns S1 value
WoodiesPivots(PivotRange pivotRangeType, HLCCalculationMode
priorDayHLC, int width).S1[int barsAgo]
WoodiesPivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, int width).S1[int barsAgo]
Returns S2 value
WoodiesPivots(PivotRange pivotRangeType, HLCCalculationMode
priorDayHLC, int width).S2[int barsAgo]
WoodiesPivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, int width).S2[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
Parameters
input Indicator source data (?)
pivotRangeType Sets the range for the type of pivot calculated.
Possible values are:
PivotRange.Daily
PivotRange.Weekly
PivotRange.Monthly
priorDayHLC Sets how the prior range High, Low, Close values
are calculated. Possible values are:
HLCCalculationMode.CalcFromIntradayData
HLCCalculationMode.DailyBars
HLCCalculationMode.UserDefinedValues
Examples
// Prints the current pivot point value
double value = WoodiesPivots(PivotRange.Daily,
HLCCalculationMode.CalcFromIntradayData, 20).PP[0];
Print("The current Woodies Pivots' pivot value is " +
value.ToString());
Tips
1. When using HLCCalculationMode.DailyBars it can be expected that a value of 0 is returned
when the daily bars have not been loaded yet. Due to the asynchronous nature of this
indicator calling daily bars you should only access the pivot values when the indicator has
loaded all required Bars objects. To ensure you are accessing accurate values you can
use .ContainsValue() as a check:
}
10.4.6.91 ZigZag
Description
The ZigZag indicator highlights trends based on user defined threshold values. You can
access methods within this indicator to determine the number of bars ago a zigzag high or
low point occured or the current zigzag value.
Low Bar
ZigZag(DeviationType deviationType, double deviationValue, bool
useHighLow).LowBar(int barsAgo, int instance, int lookBackPeriod)
ZigZag(IDataSeries input, DeviationType deviationType, double
deviationValue, bool useHighLow).LowBar(int barsAgo, int instance,
int lookBackPeriod)
Return Value
An int value representing the number of bars ago. Returns a value of -1 if a swing point is
not found within the look back period.
Syntax - Value
High Value
ZigZag(DeviationType deviationType, double deviationValue, bool
useHighLow).ZigZagHigh[int barsAgo]
ZigZag(IDataSeries input, DeviationType deviationType, double
deviationValue, bool useHighLow).ZigZagHigh[int barsAgo]
Low Value
ZigZag(DeviationType deviationType, double deviationValue, bool
useHighLow).ZigZagLow[int barsAgo]
ZigZag(IDataSeries input, DeviationType deviationType, double
deviationValue, bool useHighLow).ZigZagLow[int barsAgo]
Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.
* A return value of 0 (zero) indicates that a zigzag high or low has not yet formed.
Parameters
barsAgo The number of bars ago that serves as the starting
bar and works backwards
deviationType Possible values are:
DeviationType.Points
DeviationType.Percent
deviationValue The deviation value
input Indicator source data (?)
instance The occurrence to check for (1 is the most recent,
2 is the 2nd most recent etc...)
lookBackPeriod Number of bars to look back to check for the test
condition
Examples
// Prints the high price of the most recent zig zag
high
Print("The high of the zigzag bar is " + High[Math.
Max(0, ZigZag(DeviationType.Points, 0.5, false).
HighBar(0, 1, 100)]));
Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.
10.4.7 Strategy
The methods and properties covered in this section are unique to custom strategy
development.
10.4.7.1 Advanced Event Driven Programming Concepts
In addition to the OnBarUpdate() and Initialize() methods, NinjaScript exposes the following
advanced event-driven methods:
10.4.7.2 AccountSize
Definition
A cash value used to calculate order size of strategy entry orders. Order size is dynamically
calculated based on this property only when setting the "New Strategy" dialog window during
backtest or on a real-time chart "Set order quantity" property to "by account size".
Equities - Order share size is calculated based on AccountSize / Current Close Price
Futures and Forex - Order contract/lot size is calculated based on AccountSize / Margin
Requirement (margin set per instrument in the Instrument Manager)
Note: This property does not update dynamically for access to updated account size values.
It is dynamic for order sizing only. Should you want a dynamically updating account size you
will need to track this with your own variables.
Property Value
An int value representing the account size.
Syntax
AccountSize
Examples
protected override void Initialize()
{
AccountSize = 10000;
}
10.4.7.3 Add()
Definition
Adds an indicator to the strategy only for the purpose of displaying it on a chart.
Syntax
Add(Indicator indicator)
Parameters
indicator An indicator object
Examples
protected override void Initialize()
{
// Charts a 20 period simple moving average to
the chart
Add(SMA(20));
}
From a NinjaScript strategy it is possible to use ATM strategies to manage your positions.
Benefit of such an approach is that you can use the NinjaScript strategy to generate
automated entry signals and once entered, you can delegate exit management to an ATM
strategy which allows you degrees of manual control over how to close out of a trade.
For more information please see the Using ATM Strategies section.
10.4.7.4.1 AtmStrategyCancelEntryOrder()
Definition
Cancels the specified entry order.
Syntax
AtmStrategyCancelEntryOrder(string orderId)
Parameters
orderId The unique identifier for the entry order
Examples
protected override void OnBarUpdate()
{
AtmStrategyCancelEntryOrder("orderIdValue");
}
10.4.7.4.2 AtmStrategyChangeEntryOrder()
Definition
Changes the price of the specified entry order.
Syntax
AtmStrategyChangeEntryOrder(double limitPrice, double stopPrice,
string orderId)
Parameters
limitPrice Order limit price
stopPrice Order stop price
orderId The unique identifier for the entry order
Examples
protected override void OnBarUpdate()
{
AtmStrategyChangeEntryOrder(GetCurrentBid(), 0,
"orderIdValue");
}
10.4.7.4.3 AtmStrategyChangeStopTarget()
Definition
Changes the price of the specified order of the specified ATM strategy.
Syntax
AtmStrategyChangeStopTarget(double limitPrice, double stopPrice,
string orderName, string AtmStrategyId)
Parameters
limitPrice Order limit price
stopPrice Order stop price
orderName The order name such as "STOP1" or "TARGET2"
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
AtmStrategyChangeStopTarget(0, SMA(10)[0],
"STOP1", "AtmIdValue");
}
10.4.7.4.4 AtmStrategyClose()
Definition
Cancels any working orders and closes any open position of a strategy by first modifying any
existing target orders so they are filled or submitting a market order if no target orders exist.
Syntax
AtmStrategyClose(string AtmStrategyId)
Parameters
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
if (Historical)
return;
Definition
Submits an entry order that will execute the specified ATM Strategy that can then be
managed manually by any order entry window such as the SuperDOM or within your
NinjaScript strategy.
Returns true if the specified ATM strategy was found; otherwise false. True in NO WAY
indicates that the strategy in fact has been closed. It indicates that the the specified
ATMstrategy was found and the internal close routine was triggered.
Syntax
AtmStrategyCreate(OrderAction action, OrderType orderType, double
limitPrice, double stopPrice, TimeInForce timeInForce, string
orderId, string strategyTemplateName, string AtmStrategyId)
Parameters
action Sets if the entry order is a buy or sell order.
Possible values are:
OrderAction.Buy
OrderAction.Sell
orderType Sets the order type of the entry order. Possible
values are:
OrderType.Limit
OrderType.Market
OrderType.Stop
OrderType.StopLimit
limitPrice The limit price of the order
stopPrice The stop price of the order
timeInForce Sets the time in force of the entry order. Possible
values are:
TimeInForce.Day
TimeInForce.Gtc
orderId The unique identifier for the entry order
strategyTemplateNa Specifies which strategy template will be used
me
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
if (Historical)
return;
Definition
Gets the current state of the specified entry order. If the method can't find the specified order,
an empty array is returned.
Syntax
GetAtmStrategyEntryOrderStatus(string orderId)
Parameters
orderId The unique identifier for the entry order
Examples
protected override void OnBarUpdate()
{
string[] entryOrder =
GetAtmStrategyEntryOrderStatus("orderId");
Definition
Gets the current market position of the specified ATM Strategy.
Syntax
GetAtmStrategyMarketPosition(string AtmStrategyId)
Parameters
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
// Check if flat
if (GetAtmStrategyMarketPosition("id") ==
MarketPosition.Flat)
Print("ATM Strategy position is currently
flat");
}
10.4.7.4.8 GetAtmStrategyPositionAveragePrice()
Definition
Gets the current position's average price of the specified ATM Strategy.
Syntax
GetAtmStrategyPositionAveragePrice(string AtmStrategyId)
Parameters
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
// Check if flat
if (GetAtmStrategyMarketPosition("id") !=
MarketPosition.Flat)
Print("Average price is " +
GetAtmStrategyPositionAveragePrice("id").ToString
());
}
10.4.7.4.9 GetAtmStrategyPositionQuantity()
Definition
Gets the current position quantity of the specified ATM Strategy.
Syntax
GetAtmStrategyPositionQuantity(string AtmStrategyId)
Parameters
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
// Check if flat
if (GetAtmStrategyMarketPosition("idValue") !=
MarketPosition.Flat)
Print("Position size is " +
GetAtmStrategyPositionQuantity("id").ToString());
}
10.4.7.4.10 GetAtmStrategyRealizedProfitLoss()
Definition
Gets the realized profit and loss value of the specified ATM Strategy.
Syntax
GetAtmStrategyRealizedProfitLoss(string AtmStrategyId)
Parameters
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
Print("PnL is " +
GetAtmStrategyRealizedProfitLoss("id").ToString());
}
10.4.7.4.11 GetAtmStrategyStopTargetOrderStatus()
Definition
Gets the current state(s) of the specified stop or target order. If the method can't find the
specified order(s), an empty array is returned.
!!! A specified stop or target within an ATM strategy can actually hold multiple orders. For
example, if your ATM strategy submits a stop and target and you receive multiple partial fills
on entry with a delay of a few seconds or more between entry fills, the ATM strategy will
submit stop and target orders for each partial fill all with the same price and order type.
Syntax
GetAtmStrategyStopTargetOrderStatus(string orderName, string
AtmStrategyId)
Parameters
orderName The order name such as "STOP1" or "TARGET2"
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
string[,] orders =
GetAtmStrategyStopTargetOrderStatus("TARGET1",
"idValue");
Definition
Generates a unique id value.
Syntax
GetAtmStrategyUniqueId()
Examples
protected override void OnBarUpdate()
{
string orderId = GetAtmStrategyUniqueId();
}
10.4.7.4.13 GetAtmStrategyUnrealizedProfitLoss()
Definition
Gets the unrealized profit and loss value of the specified ATM Strategy.
Syntax
GetAtmStrategyUnrealizedProfitLoss(string AtmStrategyId)
Parameters
AtmStrategyId The unique identifier for the ATM strategy
Examples
protected override void OnBarUpdate()
{
Print("Unrealized PnL is " +
GetAtmStrategyUnrealizedProfitLoss("id").ToString());
}
10.4.7.5 BarsRequired
Definition
The number of historical bars required before the strategy starts processing calls to the
OnBarUpdate() method. This property is generally set via the UI when starting a strategy.
The OnBarUpdate() method is not triggered until CurrentBar >= BarsRequired. In a multi-
series strategy this restriction applies only for the primary Bars object. Should your strategy
logic intertwine calculations across different Bars objects please ensure all Bars objects have
met the BarsRequired requirement before proceeding. This can be done via checks on the
CurrentBars array.
Property Value
An int value representing the number of historical bars.
Syntax
BarsRequired
Examples
protected override void Initialize()
{
BarsRequired = 20;
}
Tips
1. When working with a multi-series strategy, real-time bar update events for a particular
Bars object are only received when that Bars object has satisfied the BarsRequired
requirement. To ensure this requirement is met, please use the CurrentBars array.
10.4.7.6 BarsSinceEntry()
Definition
Returns the number of bars that have elapsed since the last specified entry.
Syntax
BarsSinceEntry()
BarsSinceEntry(string signalName)
The following method signature should be used when working with multi-time frame and
instrument strategies:
Note: When working with a multi-series strategy the BarsSinceEntry() will return you the
elapsed bars as determined by the first Bars object for the instrument specified by the
barsInProgressIndex.
Parameters
signalName The signal name of an entry order specified in an
order entry method. Pass in empty string "" for
default signal.
barsInProgressIndex The index of the Bars object the entry order was
submitted against. See the BarsInProgress
property.
entriesAgo Number of entries ago. Pass in 0 for the number of
bars since the last entry.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
Definition
Returns the number of bars that have elapsed since the last specified exit.
Syntax
BarsSinceExit()
BarsSinceExit(string signalName)
The following method signature should be used when working with multi-time frame and
instrument strategies:
Note: When working with a multi-series strategy the BarsSinceExit() will return you the
elapsed bars as determined by the first Bars object for the instrument specified in the
barsInProgressIndex.
Parameters
signalName The signal name of an entry order specified in an
order entry method. Pass in empty string "" for
default signal.
barsInProgressIndex The index of the Bars object the entry order was
submitted against. See the BarsInProgress
property.
exitsAgo Number of exits ago. Pass in 0 for the number of
bars since the last exit.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
Definition
Sets the manner in which your strategy will behave when a connection loss is detected.
KeepRunning: Keeps the strategy running and sends a disconnect email alert. When
the connection is reestablished the strategy will resume as if no disconnect occurred.
StopStrategy: Automatically stops the strategy when disconnected for more than
DisconnectDelaySeconds and sends a disconnect email alert. No action will be taken
when a connection is reestablished.
Property Value
ConnectionLossHandling.KeepRunning
ConnectionLossHandling.Recalculate
ConnectionLossHandling.StopStrategy
Syntax
ConnectionLossHandling
Examples
protected override void Initialize()
{
// Keeps the strategy running as if no
disconnect occurred
ConnectionLossHandling = ConnectionLossHandling.
KeepRunning;
}
10.4.7.9 DataSeriesConfigurable
Definition
Indicates if the strategy will allow the configuration of the main data series that will drive the
strategy via the Strategy dialog window when starting a strategy from either a chart or the
Strategies tab of the Control Center window. This property is only of value if a strategy should
only be run on a specific data series.
Property Value
This property returns true if the data series is configureable; otherwise, false.
Syntax
DataSeriesConfigurable
Examples
protected override void Initialize()
{
DataSeriesConfigurable = true;
}
10.4.7.10 DefaultQuantity
Definition
An order size variable that can be set either programmatically or overriden via the Strategy
that determines the quantity of an entry order.
Property Value
An int value represents the number of contracts or shares to enter a position with.
Syntax
DefaultQuantity
Examples
protected override void Initialize()
{
DefaultQuantity = 1;
}
10.4.7.11 Disable()
Definition
Disables the running strategy.
Syntax
Disable()
Examples
Definition
Indicates the amount of time a disconnect would have to last before certain connection loss
handling actions will be taken
Property Value
An int value represents the time required for a disconnect to last before connection loss
handling actions will occur.
Syntax
DisconnectDelaySeconds
Examples
protected override void Initialize()
{
// Disconnect has to be at least 10 seconds
DisconnectDelaySeconds = 10;
}
10.4.7.13 EntriesPerDirection
Definition
Indicates the maximum number of entries allowed per direction while a position is active
based on the EntryHandling property.
Property Value
An int value represents the maximum number of entries allowed.
Syntax
EntriesPerDirection
Examples
// Example #1
// If an open position already exists, subsequent
EnterLong() calls are ignored.
protected override void Initialize()
{
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
}
// Example #2
// EnterLong() will be processed once for each
uniquely named entry.
protected override void Initialize()
{
EntriesPerDirection = 1;
EntryHandling = EntryHandling.UniqueEntries;
}
Definition
Sets the manner in how entry orders are handled. If set to "EntryHandling.AllEntries",
NinjaScript will process all order entry methods until the maximum allowable entries set by
the EntriesPerDirection property has been reached while in an open position. If set to
"EntryHandling.UniqueEntries", NinjaScript will process order entry methods until the
maximum allowable entries set by the EntriesPerDirection property per each uniquely named
entry.
Property Value
EntryHandling.AllEntries
EntryHandling.UniqueEntries
Syntax
EntryHandling
Examples
// Example #1
// Will allow a maximum of two entries while a
position is open
// Example #2
// EnterLong() will be processed once for each
uniquely named entry.
protected override void Initialize()
{
EntriesPerDirection = 1;
EntryHandling = EntryHandling.UniqueEntries;
}
10.4.7.15 ExcludeTradeHistoryInBacktest
Definition
Indicates if the strategy will exclude orders, trades, and execution history. When this property
is set to true you will see significant memory savings at the expense of having access to the
detailed trading information.
Note: Since trade information is not stored you will only see executions plotted on the chart
with no connecting PnL trade lines.
Property Value
This property returns true if the strategy will exclude trade history; otherwise, false. Default is
set to false.
Syntax
ExcludeTradeHistoryInBacktest
Examples
Definition
Indicates if the strategy will cancel all strategy generated orders and close all open strategy
positions at the close of the session. This property can be set programatically in the Initialize
() method or be driven by the UI at run time. See also "ExitOnCloseSeconds".
Property Value
This property returns true if the strategy will exit on close; otherwise, false.
Syntax
ExitOnClose
Examples
protected override void Initialize()
{
// Triggers the exit on close function 30
seconds prior to session end
ExitOnClose = true;
ExitOnCloseSeconds = 30;
}
10.4.7.17 ExitOnCloseSeconds
Definition
The number of seconds before the actual session end time that the "ExitOnClose" function
will trigger. This property can be set programatically in the Initialize() method or be driven by
the UI at run time.
Property Value
An int value representing the number of seconds.
Syntax
ExitOnCloseSeconds
Examples
protected override void Initialize()
{
Definition
Indicates if the strategy will force all DataSeries objects including plot series objects to hold
only values for 256 bars. This property supercedes the UI property of "Maximum bars look
back".
Property Value
This property returns true if the strategy will force a maximum of 256 bars lookback;
otherwise, false. Default is set to false.
Syntax
ForceMaximumBarsLookBack256
Examples
protected override void Initialize()
{
// DataSeries objects will have a maximum of 256
bars for lookback.
ForceMaximumBarsLookBack256 = true;
}
10.4.7.19 GetAccountValue()
Definition
Returns information about the account the strategy is running on.
Syntax
GetAccountValue(AccountItem accountItem)
Parameters
accountItem Possible values:
AccountItem.BuyingPower
AccountItem.CashValue
AccountItem.RealizedProfitLoss
Examples
protected override void OnBarUpdate()
{
// Checks to see if the account has more than
$25000
if (GetAccountValue(AccountItem.CashValue) >
25000)
// Do something;
}
10.4.7.20 IExecution
Definition
Represents a read only interface that exposes information regarding an execution (fill)
resulting from an order and is passed as a parameter in the OnExecution() method.
* The "Price" property may return a value that is not aligned to the underlying instruments tick
size. This can happen if the original order price was submitted not aligned to tick size or if the
period in time being backtested contains split/dividend back adjusted data that is also not
aligned to tick size. However, most if not all execution grid displays will display a rounded to
tick size value. You can also use the method Round2TickSize().
Examples
private IOrder entryOrder = null;
Definition
Indicates if the strategy performance results will include commission on a historical backtest.
Property Value
This property returns true if the strategy includes commission on a historical backtest;
otherwise, false.
Syntax
IncludeCommission
Examples
protected override void Initialize()
{
IncludeCommission = true;
}
10.4.7.22 IOrder
Definition
Represents a read only interface that exposes information regarding an order.
An IOrder object returned from calling an order method is dynamic in that its properties will
always reflect the current state of an order
The property <IOrder>.OrderId is NOT a unique value since it can change throughout an
order's lifetime
The property <IOrder>.Token is NOT a unique value since it will change as the strategy
transitions from historical to real-time
The property <IOrder>.Oco WILL be appended with a suffix when the strategy transitions
from historical to real-time to ensure the OCO id is unique across multiple strategies for
live orders
To check for equality you can compare IOrder objects directly
OrderAction.Buy
OrderAction.BuyToCover
OrderAction.Sell
OrderAction.SellShort
AvgFillPrice A double value representing the average fill price
of an order
Filled An int value representing the filled amount of an
order
FromEntrySignal A string representing the user defined
fromEntrySignal parameter on an order
Instrument An Instrument value representing the instrument of
an order
LimitPrice A double value representing the limit price of an
order
LiveUntilCancelled *A bool value representing if the order is live until
cancelled by the user
Name A string representing the name of an order which
can be provided by the entry or exit signal name
NativeError Possible values are:
ErrorCode.BrokerOrderError
ErrorCode.InvalidInstrument
ErrorCode.LoginFailed
ErrorCode.NoError
ErrorCode.NotConnected
ErrorCode.NotSupported
ErrorCode.OrderRejected
ErrorCode.Panic
ErrorCode.ServerConnectionIsBroken
ErrorCode.UnableToCancelOrder
ErrorCode.UnableToChangeOrder
ErrorCode.UnableToSubmitOrder
ErrorCode.UserAbort
Oco A string representing the OCO (one cancels
other) id of an order
OrderId A string representing the broker issued order id
value (this value can change)
OrderState See table below
OrderType Possible values are:
OrderType.Limit
OrderType.Market
OrderType.Stop
OrderType.StopLimit
OverFill **A bool value representing if the order is an
overfill. For use when using Unmanaged orders
and IgnoreOverFill
TimeInForce.Day
TimeInForce.Gtc
Token A string representing the unique id of an order
ToString() A string representation of an order
OrderState Values
OrderState.Accepted Order has been acknowledged by the broker
OrderState.Cancelled Order has been cancelled
OrderState.Filled Order has been filled
OrderState.PartFilled Order has been part filled
OrderState. An order cancellation request has been submitted
PendingCancel
OrderState. An order change request has been submitted
PendingChange
OrderState. An order has been submitted
PendingSubmit
OrderState.Rejected An order has been rejected
OrderState.Working An order is working at the exchange
OrderState.Unknown An unknown order state
* In a historical backtest, orders will always reach a "Working" state. In real-time, some stop
orders may only reach "Accepted" state if they are simulated/held on a brokers server
** An overfill is categorized as when an order returns a "Filled" or "PartFilled" state after the
order was already marked for cancellation. The cancel request could have been induced by
an explicit CancelOrder() call, from more implicit cancellations like those that occur when
another order sharing the same OCO ID is filled, or from things like order expirations.
Examples
private IOrder entryOrder = null;
protected override void OnBarUpdate()
{
if (entryOrder == null && Close[0] > Open[0])
entryOrder = EnterLong();
}
entryOrder = null;
}
}
10.4.7.23 IPosition
Definition
Represents a read only interface that exposes information regarding a position and is passed
as a parameter in the OnPositionUpdate() method.
MarketPosition.Flat
MarketPosition.Long
MarketPosition.Short
Quantity An int value representing quantity of an execution
ToString() A string representation of an execution
Examples
protected override void OnPositionUpdate(IPosition
position)
{
if (position.MarketPosition == MarketPosition.
Flat)
{
// Do something like reset some variables
here
}
}
10.4.7.24 MaxRestartAttempts
Definition
Indicates the maximum number of restart attempts allowed within the last x minutes defined
in MaxRestartMinutes when the strategy experiences a connection loss. If restart attempts
exceeds this property within a time span shorter than or equal to MaxRestartMinutes, then the
strategy will be stopped and no further attempts will occur. The purpose of these settings is
to stop the strategy should your connection be unstable and incapable of maintaining a
consistent connected state.
Property Value
An int value represents the maximum number of restart attempts.
Syntax
MaxRestartAttempts
Examples
protected override void Initialize()
{
// Only allow the strategy to restart 4 times
within the MaxRestartMinutes time span
// If disconnected more than 4 times within that
time span, stop the strategy and do not attempt any
further restarts.
MaxRestartAttempts = 4;
}
10.4.7.25 MaxRestartMinutes
Definition
The strategy will only restart off a reestablished connection when there have been fewer
restart attempts than MaxRestartAttempts in the last MaxRestartMinutes time span. The
purpose of these settings is to stop the strategy should your connection be unstable and
incapable of maintaining a consistent connected state.
Property Value
An int value representing the maximum number of minutes in the time span in which restart
attempts have to be less than MaxRestartAttempts for a strategy to be restarted when a
connection is reestablished.
Syntax
MaxRestartMinutes
Examples
protected override void Initialize()
{
// Allow for restarting the strategy only if
there were less restart attempts than
MaxRestartAttempts
// within the last 5 minutes
MaxRestartMinutes = 5;
}
10.4.7.26 OnConnectionStatus()
Definition
The OnConnectionStatus() method is called on a change in connection status.
Method Parameters
ConnectionStatus orderStatus and priceStatus
ConnectionStatus.Connected
ConnectionStatus.Connecting
ConnectionStatus.ConnectionLost
ConnectionStatus.Disconnected
A NinjaTrader connection may have two internally may have two separate connections, one
for the price server and the other for the order server.
Syntax
You must override the method in your strategy with the following syntax.
Examples
private ConnectionStatus dataFeed = ConnectionStatus.
Connected;
protected override void OnOrderUpdate(IOrder order)
{
if (dataFeed != ConnectionStatus.Connected)
{
// Do something
}
}
Additional reference code samples are available the NinjaScript Educational Resources
section of our support forum.
10.4.7.27 OnExecution()
Definition
The OnExecution() method is called on an incoming execution. An execution is another name
for a fill of an order.
If you are relying on the OnExecution() method to trigger actions such as the submission of a
stop loss order when your entry order is filled ALWAYS reference the properties on the IOrder
object property attached to the IExecution object passed into the OnExecution() method.
Method Parameters
IExecution execution
Syntax
You must override the method in your strategy with the following syntax.
Examples
private IOrder entryOrder = null;
See OnFundamentalData()
10.4.7.29 OnMarketData()
See OnMarketData()
10.4.7.30 OnMarketDepth()
See OnMarketDepth()
10.4.7.31 OnOrderUpdate()
Definition
The OnOrderUpdate() method is called everytime an order managed by a strategy changes
state. An order will change state when a change in order quantity, price or state (working to
filled) occurs.
This method guarantees that you will see each order state change in sequence
This method does not provide an update for the most current state of an order but instead
provides you an event notifying you of each state change in sequence and the relevant
information on the order at the time the state changed
CRITICAL: If you want to drive your strategy logic based on order fills you must use
OnExecution() instead of OnOrderUpdate(). OnExecution() is always triggered after
OnOrderUpdate(). There is internal strategy logic that is triggered after OnOrderUpdate() is
called but before OnExecution() that can adversely affect your strategy if you are relying on
tracking fills within OnOrderUpdate().
As an example, the NinjaTrader core may have received "Working" and then "PartFilled"
order state change events back from the broker API on thread "B" and at some point in time
(milliseconds later) the NinjaTrader core will take these events and trigger the
OnOrderUpdate() method in the strategy on thread "A". Thus, when the strategy receives
the first "Working" state for an order, the IOrder object passed in will reflect the "Working"
state although the actual order is really in a state of "Part Filled" which is truly reflected in
the original IOrder object returned in any of the order methods such as EnterLong(). Of
course, the OnOrderUpdate() method will subsequently receive the event for "PartFilled"
state.
When connected to the Market Replay Connection, calling market order based methods
such as EnterLong() and EnterShort() will result in order state events being fired prior to the
order method return an IOrder object. This is done to ensure that all events are in sync at
If you are relying on the OnOrderUpdate() method to trigger actions such as the submission
of a stop loss order when your entry order is filled ALWAYS reference the properties on the
IOrder object passed into the OnOrderUpdate() method.
Method Parameters
IOrder order
Syntax
You must override the method in your strategy with the following syntax.
Examples
private IOrder entryOrder = null;
10.4.7.32 OnPositionUpdate()
Definition
The OnPositionUpdate() method is called everytime a position managed by a strategy
changes state.
Method Parameters
IPosition position
Syntax
You must override the method in your strategy with the following syntax.
Examples
protected override void OnPositionUpdate(IPosition
position)
{
if (position.MarketPosition == MarketPosition.
Flat)
{
// Do something like reset some variables
here
}
}
See OnStartUp()
10.4.7.34 OnTermination()
See OnTermination()
NinjaScript provides several approaches you can use for order placement within your
NinjaScript strategy. The main approaches can be categorized as a Managed approach and
an Unmanaged approach.
The Managed approach offers you order methods that are wrapped with an invisible
convenience layer that allows you to focus on your system's trading rules leaving the
underlying mechanics of order management and the relationships between entry and exit
orders and positions to NinjaTrader. The cost for having the convenience layer is that there
are order handling rules that must be followed to prevent order errors.
The Unmanaged approach offers you more flexible order methods without the convenience
layer. This means you are not restricted to any order handling rules besides those imposed
by the brokerage/exchange. With such flexibility though, you will have to ensure to program
your strategy to handle any and all issues that may arise with placing orders.
Please note that you will not be able to mix and match the two approaches. If you decide to
go with the Managed approach you will only be able to use the Managed order methods. If you
decide to go with the Unmanaged approach you will only be able to use the Unmanaged order
methods.
Managed Unmanaged
Understanding the Managed approach Understanding the Unmanaged
Advanced Order Handling approach
CancelOrder() CancelOrder()
EnterLong() ChangeOrder()
EnterLongLimit() IgnoreOverFill
EnterLongStop() SubmitOrder()
EnterLongStopLimit() Unmanaged
EnterShort()
EnterShortLimit()
EnterShortStop()
EnterShortStopLimit()
ExitLong()
ExitLongLimit()
ExitLongStop()
ExitLongStopLimit()
ExitShort()
ExitShortLimit()
ExitShortStop()
ExitShortStopLimit()
SetProfitTarget()
SetStopLoss()
SetTrailStop()
The Managed approach in NinjaScript is the most commonly used approach because of the
ease-of-use it has to offer. The order methods are wrapped with an invisible convenience
layer that allows you to focus on your system's trading rules leaving the underlying
mechanics of order management and the relationships between entry and exit orders and
positions to NinjaTrader. This will become more evident as you review this section.
What makes this approach so universal for all levels of programmers is the flexibility in being
able to scale its use for ease or for control. As such, this approach is best suited for simple to
moderate order complexity strategies and can be further broken down into a Basic/Common
approach and a more Advanced one. The following section will discuss the use of the Basic/
Common approach.
Orders are submitted as live working orders when a strategy is running in real-time
*Profit targets, stop loss and trail stop orders are submitted immediately as entry orders
are filled and are also OCO tied
Order changes and cancellations are queued in the event that the order is in a state where
it can't be cancelled or modified
By default, orders submitted via Entry() and Exit() methods automatically cancel at the end
of a bar if not re-submitted
In the example below, a buy limit order to enter a long position is working at the bid price
provided that the close price of the current bar is greater than the current value of the 20
period simple moving average. If the entry condition is no longer true and the order is still
active it will be immediately cancelled.
This technique allows you the quickest and easiest order submission method suitable
for programmers of all levels. Should you want to submit an order and not have to keep
re-submitting it to keep it alive you can use an advanced approach reserved for
experienced programmers called "live until cancelled".
Entry Methods
Entry Methods
Entry methods are used to submit orders that create a market position if none exists or
to reverse an existing position. An example of an entry method that submitted a buy
market order would look like the following:
EnterLong();
An example of an entry method that submitted a sell short market order with a tagged
signal name would look like the following:
To illustrate how the above properties control the processing of entry methods let's look
at the example code below. The code contains two entry conditions and two EnterLong
methods each tagged with unique signal names.
EnterLong("Condition 1 Entry");
// Entry condition 2
if (CrossAbove(RSI(14, 3), 30, 1))
EnterLong("Condition 2 Entry");
}
If you wanted your strategy to enter only once per direction on either condition 1 or
condition 2, whichever condition evaluated to true first, you would set the
EntriesPerDirection to a value of "1" and the EntryHandling to a value "AllEntries".
If you wanted your strategy to enter only once per direction for both conditions, you
would set EntriesPerDirection to a value of "1" and the EntryHandling to the value
"UniqueEntries". This is possible since the entry methods have been tagged with unique
signal names.
Closing a Position using a Stop Loss, Trailing Stop and/or Profit Target
You can predefine a stop loss, trailing stop and/or profit target in a strategy by calling the
SetStopLoss(), SetTrailStop() or SetProfitTarget() methods from inside the Initialize()
method. When these methods are called, they submit live working orders in real-time
operation as executions are reported as a result of calling an entry method. Stop and
target orders are submitted to the market as soon as fills come in from an entry order.
Trailing stop orders are modified in real-time and NOT on the close of a bar. A stop and
target order are also tied via OCO (one cancels the other) so if one is filled, the other is
automatically cancelled.
Stops and targets are generated either per fill or per position. This is determined by the
"Stop & target submission" property which is set running a strategy live via the UI.
Property values are:
ByStrategyPosition - When this is selected, only one stop loss, trail stop and/or profit
target order is submitted. As entry executions come in, the order size is amended. The
downside of this approach is that if you have partial fills, the orders are re-inserted into
the exchange order queue. The upside is that if you broker charges you a per order
commission (not per lot), you will not incur additional commission expenses.
PerEntryExecution - When this is selected, a stop loss, trail stop and/or profit target
order is submitted for each partial fill received. The downside is if your broker charges
commission per order, you can incur very expensive commission costs if you receive
partial fills. The upside is that orders are submitted as soon as possible giving you the
advantage of getting into the order queue immediately.
ExitLong();
ExitLong(1);
}
Identifying entries with a signal name allows you to have multiple unique entries within a
single strategy and call exit methods with specified signal names so that only a position
created with the tagged signal name is closed. In the example below, there are two entry
conditions which create positions. There are two exit conditions that specify which
position to close based on the signal name.
// Entry condition 2
if (CrossAbove(RSI(14, 3), 30, 1))
EnterLong("Condition 2 Entry");
For the most part, you do not need to be intimately familiar with these rules as you
develop your strategies, its all taken care of for you internal within a strategy. If a rule is
violated, you will be notified through an error log in the Control Center log tab when
running a strategy in real-time or in a backtest.
Set() methods that generate orders to exit a position will be ignored if:
A position is open and an order submitted by an enter method (EnterLongLimit() for
example) is active and the order is used to open a position in the opposite direction
A position is open and an order submitted by an exit method (ExitLongLimit() for
example) is active
10.4.7.35.1.1 Advanced Order Handling
An IOrder object returned from calling an order method is dynamic in that its properties
will always reflect the current state of an order
The property <IOrder>.OrderId is NOT a unique value since it can change throughout
an order's lifetime
The property <IOrder>.Token is NOT a unique value since it will change as the
strategy transitions from historical to real-time
To check for equality you can compare IOrder objects directly
The following example code demonstrates the submission of an order and assigning the
IOrder return object to the variable "entryOrder" and then checking the object in
OnOrderUpdate() method for equality and then checking if the order was filled.
Let's take as an example the EnterLongLimit() method and one of its method variations
(below) designed for advanced order handling:
Let's also continue with the example above where a "MSFT" 1 minute chart is the
primary bar series the strategy is running on. We add a secondary bar series, an "AAPL"
1 min series to our strategy by calling the Add() method in the Initialize() method as
follows:
In NinjaScript, "MSFT" has a bars index value of "0" and "AAPL" would have bars index
value of "1". More information on this concept can be found in the multi-time frame and
instrument strategies section as well as the property BarsInProgress. In a multi-
instrument strategy, using the EnterLongLimit() method above will generate an order for
the instrument that is associated to the value of the "barsInProgressIndex" parameter
you pass in.
The following example code demonstrates how you can monitor for bar update events
on "MSFT" but submit an order to "AAPL". The key is in passing in a value of "1" (bold
red below) into for the "BarsInProgressIndex". A value of 1 represents the "AAPL" bar
series and thus the order is submitted for "AAPL".
Definition
Cancels the specified order.
This method is made available for experienced programmers that fully understanding the
concepts of advanced order handling
This method sends a cancel request to the broker and does not guarantee that an order is
completely cancelled. Most of the time you can expect your order to come back 100%
cancelled. An order can be completely filled or part filled in the time that you send the
cancel request and the time the exchange receives the request. Check the OnOrderUpdate
() method for the state of an order you attempted to cancelled.
Syntax
CancelOrder(IOrder order)
Parameters
order An IOrder object representing the order you wish to
cancel.
Examples
Definition
Generates a buy market order to enter a long position.
Syntax
EnterLong()
EnterLong(string signalName)
EnterLong(int quantity)
EnterLong(int quantity, string signalName)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
quantity Entry order quantity.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
Definition
Generates a buy limit order to enter a long position.
Syntax
EnterLongLimit(double limitPrice)
EnterLongLimit(double limitPrice, string signalName)
EnterLongLimit(int quantity, double limitPrice)
EnterLongLimit(int quantity, double limitPrice, string signalName)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
limitPrice The limit price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar, but
instead remain live until the CancelOrder() method
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
Definition
Generates a buy stop order to enter a long position.
Syntax
EnterLongStop(double stopPrice)
EnterLongStop(double stopPrice, string signalName)
EnterLongStop(int quantity, double stopPrice)
EnterLongStop(int quantity, double stopPrice, string signalName)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
limitPrice The limit price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar, but
instead remain live until the CancelOrder() method
is called or its time in force has been reached.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
Definition
Generates a buy stop limit order to enter a long position.
Syntax
EnterLongStopLimit(double limitPrice, double stopPrice)
EnterLongStopLimit(double limitPrice, double stopPrice, string
signalName)
EnterLongStopLimit(int quantity, double limitPrice, double
stopPrice)
EnterLongStopLimit(int quantity, double limitPrice, double
stopPrice, string signalName)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
limitPrice The limit price of the order.
stopPrice The stop price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar, but
instead remain live until the CancelOrder() method
is called or its time in force has been reached.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
10.4.7.35.1.7 EnterShort()
Definition
Generates a sell short market order to enter a short position.
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 concepts.
Parameters
signalName User defined signal name identifying the order
generated.
quantity Entry order quantity.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
backtesting a strategy
10.4.7.35.1.8 EnterShortLimit()
Definition
Generates a sell short limit order to enter a short position.
Syntax
EnterShortLimit(double limitPrice)
EnterShortLimit(double limitPrice, string signalName)
EnterShortLimit(int quantity, double limitPrice)
EnterShortLimit(int quantity, double limitPrice, string signalName)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
limitPrice The limit price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar, but
instead remain live until the CancelOrder() method
is called or its time in force has been reached.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
Entry");
}
Definition
Generates a sell short stop order to enter a short position.
Syntax
EnterShortStop(double stopPrice)
EnterShortStop(double stopPrice, string signalName)
EnterShortStop(int quantity, double stopPrice)
EnterShortStop(int quantity, double stopPrice, string signalName)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
stopPrice The stop price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar, but
instead remain live until the CancelOrder() method
is called or its time in force has been reached.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
Definition
Generates a sell short stop limit order to enter a short position.
Syntax
EnterShortStopLimit(double limitPrice, double stopPrice)
EnterShortStopLimit(double limitPrice, double stopPrice, string
signalName)
EnterShortStopLimit(int quantity, double limitPrice, double
stopPrice)
EnterShortStopLimit(int quantity, double limitPrice, double
stopPrice, string signalName)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
limitPrice The limit price of the order.
stopPrice The stop price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar, but
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
Definition
Generates a sell market order to exit a long position.
Syntax
ExitLong()
ExitLong(int quantity)
ExitLong(string fromEntrySignal)
ExitLong(string signalName, string fromEntrySignal)
ExitLong(int quantity, string signalName, string fromEntrySignal)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
string fromEntrySignal)
Parameters
signalName User defined signal name identifying the order
generated.
fromEntrySignal The entry signal name. This ties the exit to the entry
and exits the position quantity represented by the
actual entry.
quantity Entry order quantity.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
// Exits position
if (CrossBelow(SMA(10), SMA(20), 1))
ExitLong();
}
Definition
Generates a sell limit order to exit a long position.
An IOrder read-only object that represents the order. Reserved for experienced
programmers, additional information can be found within the Advanced Order Handling
section.
Syntax
ExitLongLimit(double limitPrice)
ExitLongLimit(int quantity, double limitPrice)
ExitLongLimit(double limitPrice, string fromEntrySignal)
ExitLongLimit(double limitPrice, string signalName, string
fromEntrySignal)
ExitLongLimit(int quantity, double limitPrice, string signalName,
string fromEntrySignal)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
fromEntrySignal The entry signal name. This ties the exit to the entry
and exits the position quantity represented by the
actual entry.
limitPrice The limit price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar but
instead remain live until the CancelOrder() method
is called or its time in force has been reached.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
// Exits position
if (CrossBelow(SMA(10), SMA(20), 1))
ExitLongLimit(GetCurrentBid());
}
Definition
Generates a sell stop order to exit a long position.
Syntax
ExitLongStop(double stopPrice)
ExitLongStop(int quantity, double stopPrice)
ExitLongStop(double stopPrice, string fromEntrySignal)
ExitLongStop(double stopPrice, string signalName, string
fromEntrySignal)
ExitLongStop(int quantity, double stopPrice, string signalName,
string fromEntrySignal)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
fromEntrySignal The entry signal name. This ties the exit to the entry
and exits the position quantity represented by the
actual entry.
Examples
private double stopPrice = 0;
// Exits position
ExitLongStop(stopPrice);
}
Definition
Generates a sell stop limit order to exit a long position.
An IOrder read-only object that represents the order. Reserved for experienced
programmers, additional information can be found within the Advanced Order Handling
section.
Syntax
ExitLongStopLimit(double limitPrice, double stopPrice)
ExitLongStopLimit(int quantity, double limitPrice, double stopPrice
)
ExitLongStopLimit(double limitPrice, double stopPrice, string
fromEntrySignal)
ExitLongStopLimit(double limitPrice, double stopPrice, string
signalName, string fromEntrySignal)
ExitLongStopLimit(int quantity, double limitPrice, double stopPrice
, string signalName, string fromEntrySignal)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
fromEntrySignal The entry signal name. This ties the exit to the entry
and exits the position quantity represented by the
actual entry.
limitPrice The limit price of the order
stopPrice The stop price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar but
instead remain live until the CancelOrder() method
is called or its time in force has been reached.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
private double stopPrice = 0;
// Exits position
ExitLongStopLimit(stopPrice - (10 * TickSize),
stopPrice);
}
Definition
Generates a buy to cover market order to exit a short position.
Syntax
ExitShort()
ExitShort(int quantity)
ExitShort(string fromEntrySignal)
ExitShort(string signalName, string fromEntrySignal)
ExitShort(int quantity, string signalName, string fromEntrySignal)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
// Exits position
if (CrossBelow(SMA(10), SMA(20), 1))
ExitShort();
}
Definition
Generates a buy to cover limit order to exit a short position.
Syntax
ExitShortLimit(double limitPrice)
ExitShortLimit(int quantity, double limitPrice)
ExitShortLimit(double limitPrice, string fromEntrySignal)
ExitShortLimit(double limitPrice, string signalName, string
fromEntrySignal)
ExitShortLimit(int quantity, double limitPrice, string signalName,
string fromEntrySignal)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
fromEntrySignal The entry signal name. This ties the exit to the entry
and exits the position quantity represented by the
actual entry.
limitPrice The limit price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar but
instead remain live until the CancelOrder() method
is called or its time in force has been reached.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;
// Exits position
if (CrossAbove(SMA(10), SMA(20), 1))
ExitShortLimit(GetCurrentAsk());
}
Definition
Generates a buy to cover stop order to exit a short position.
Syntax
ExitShortStop(double stopPrice)
ExitShortStop(int quantity, double stopPrice)
ExitShortStop(double stopPrice, string fromEntrySignal)
ExitShortStop(double stopPrice, string signalName, string
fromEntrySignal)
ExitShortStop(int quantity, double stopPrice, string signalName,
string fromEntrySignal)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
fromEntrySignal The entry signal name. This ties the exit to the entry
and exits the position quantity represented by the
actual entry.
stopPrice The stop price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar but
Examples
private double stopPrice = 0;
// Exits position
ExitShortStop(stopPrice);
}
Definition
Generates a buy to cover stop limit order to exit a short position.
Syntax
ExitShortStopLimit(double limitPrice, double stopPrice)
ExitShortStopLimit(int quantity, double limitPrice, double
stopPrice)
ExitShortStopLimit(double limitPrice, double stopPrice, string
fromEntrySignal)
ExitShortStopLimit(double limitPrice, double stopPrice, string
signalName, string fromEntrySignal)
ExitShortStopLimit(int quantity, double limitPrice, double
stopPrice, string signalName, string fromEntrySignal)
The following method variation is for experienced programmers who fully understand
Advanced Order Handling concepts.
Parameters
signalName User defined signal name identifying the order
generated.
fromEntrySignal The entry signal name. This ties the exit to the entry
and exits the position quantity represented by the
actual entry.
limitPrice The limit price of the order
stopPrice The stop price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar but
instead remain live until the CancelOrder() method
is called or its time in force has been reached.
barsInProgressIndex The index of the Bars object the order is to be
submitted against. See the BarsInProgress
property. This determines what instrument the order
is submitted for.
Examples
private double stopPrice = 0;
SMA(20), 1))
{
EnterShort("SMA Cross Entry");
stopPrice = Low[0];
}
// Exits position
ExitShortStopLimit(stopPrice + (10 * TickSize),
stopPrice);
}
Definition
Generates a limit profit target order to exit a position. Profit target orders are real working
orders submitted immediately to the market upon receiving an execution from an entry order.
It is suggested to call this method from within the strategy Initialize() method if your profit
target price/offset is static
You may call this method from within the strategy OnBarUpdate() method should you wish
to dynamically change the target price while in an open position
Should you call this method to dynamically change the target price in the strategy
OnBarUpdate() method, you should always reset the target price/offset value when your
strategy is flat otherwise, the last price/offset value set will be used to generate your profit
target order on your next open position
Syntax
SetProfitTarget(double currency)
SetProfitTarget(CalculationMode mode, double value)
SetProfitTarget(string fromEntrySignal, CalculationMode mode,
double value)
Parameters
currency Sets the profit target amount in currency ($500
profit for example)
mode CalculationMode.Percent
CalculationMode.Price
CalculationMode.Ticks
value The value the profit target order is offset from the
position entry price (exception is using .Price mode
where 'value' will represent the actual price)
fromEntrySignal The entry signal name. This ties the profit target exit
to the entry and exits the position quantity
represented by the actual entry.
Examples
protected override void Initialize()
{
// Submits a profit target order 10 ticks away
from the avg entry price
SetProfitTarget(CalculationMode.Ticks, 10);
}
Definition
Generates a stop loss order to exit a position. Stop loss orders are real working orders
(unless simulated is specified in which case the stop order is locally simulated and submitted
as market once triggered) submitted immediately to the market upon receiving an execution
from an entry order.
It is suggested to call this method from within the strategy Initialize() method if your stop
loss price/offset is static
You may call this method from within the strategy OnBarUpdate() method should you wish
to dynamically change the stop loss price while in an open position
Should you call this method to dynamically change the stop loss price in the strategy
OnBarUpdate() method, you should always reset the stop loss price/offset value when your
strategy is flat otherwise, the last price/offset value set will be used to generate your stop
loss order on your next open position
Syntax
SetStopLoss(double currency)
SetStopLoss(double currency, bool simulated)
SetStopLoss(CalculationMode mode, double value)
SetStopLoss(string fromEntrySignal, CalculationMode mode, double
Parameters
currency Sets the stop loss amount in currency ($500 loss
for example)
mode CalculationMode.Percent
CalculationMode.Price
CalculationMode.Ticks
simulated If true, will simulate the stop order and submit as
market once triggered
value The value the stop loss order is offset from the
position entry price (exception is using .Price mode
where 'value' will represent the actual price)
fromEntrySignal The entry signal name. This ties the stop loss exit to
the entry and exits the position quantity represented
by the actual entry.
Examples
protected override void Initialize()
{
// Submits a stop loss of $500
SetStopLoss(500);
}
Definition
Generates a trail stop order to exit a position. Trail stops are amended on a tick by tick basis.
Trail stop orders are real working orders (unless simulated is specified in which case the
stop order is locally simulated and submitted as market once triggered) submitted
immediately to the market upon receiving an execution from an entry order.
It is suggested to call this method from within the strategy Initialize() method if your trail
stop price/offset is static
You may call this method from within the strategy OnBarUpdate() method should you wish
to dynamically change the trail stop price while in an open position
Should you call this method to dynamically change the trail stop price in the strategy
OnBarUpdate() method, you should always reset the trail stop price/offset value when your
strategy is flat otherwise, the last price/offset value set will be used to generate your trail
stop order on your next open position
Syntax
SetTrailStop(double currency)
SetTrailStop(double currency, bool simulated)
SetTrailStop(CalculationMode mode, double value)
SetTrailStop(string fromEntrySignal, CalculationMode mode, double
value, bool simulated)
Parameters
currency Sets the stop loss amount in currency ($500 loss
for example)
mode Possible values:
CalculationMode.Percent
CalculationMode.Ticks
Examples
protected override void Initialize()
{
// Sets a trail stop of 12 ticks
SetTrailStop(CalculationMode.Ticks, 12);
}
Please note that you will not be able to mix order methods from the two approaches.
When setting Unmanaged to true, you can only use Unmanaged order methods in the
strategy.
Order Submission
Order submission with the Unmanaged approach is done solely from a single order
method. Parameterizing the SubmitOrder() method differently will determine what kind of
order you will be submitting. Please note that these orders are live until cancelled.
Should you want to cancel these orders you will need to use the CancelOrder() method
or wait till the orders expire due to the strategy's time in force setting.
In the example below, a buy limit order to enter a long position is working at the bid price
provided that the close price of the current bar is greater than the current value of the 20
period simple moving average.
It is critical to assign an IOrder object to keep track of your order or else you will not be
able to identify it in your code later since there is no signal tracking when using
Unmanaged order methods. Please be aware of the following information about IOrder
objects:
An IOrder object returned from calling an order method is dynamic in that its properties
will always reflect the current state of an order
The property <IOrder>.OrderId is NOT a unique value since it can change throughout
an order's lifetime
The property <IOrder>.Token is NOT a unique value since it will change as the
strategy transitions from historical to real-time
To check for equality you can compare IOrder objects directly
Order Modification
Unlike the Managed approach where you could modify a working order by calling the
entry order method again with your new parameters, the Unmanaged approach requires
the utilization of the ChangeOrder() method. The ChangeOrder() method requires you to
have access to the IOrder object you wish to modify so it is important to hold onto those
for any active order you have in your strategy.
Order Cancellation
Similar to the live until cancelled technique from the Managed approach, cancelling
Signal Tracking
Since the Unmanaged approach does not utilize NinjaScript's signal tracking the
features associated with it will no longer be relevant. The following properties and their
associated concept cannot be used with Unmanaged order methods:
EntriesPerDirection
EntryHandling
Methods utilizing signal names like BarsSinceEntry() and BarsSinceExit() can still be
used though.
Over-Fills
Over-Fills is a serious issue that can occur when using complex entry conditions that
bracket the market in both directions end up with both entries being filled instead of one
being cancelled. Over-Fills can also occur when you place a trade quickly hoping to
close a position while a prior order to close the same position already had an in-flight
execution. The exact scenarios in which an over-fill can occur is highly dependent on the
specific strategy programming. By default, NinjaTrader will protect against over-fills even
though you are using the Unmanaged approach by halting the strategy, but should you
decide to custom program your own over-fill handling it is up to you to either prevent
over-fills from being a possibility in your code or by introducing logic to address over-fills
should one occur.
Order rejections
Order rejections are not local to using Unmanaged order methods, but the impact of
improper rejection management is just as detrimental. Please be sure the strategy has
significant contingency programming to handle order rejections so as to prevent your
strategy from being left in some sort of limbo state. This is especially important if you
decide to turn off RealtimeErrorHandling protection.
Connection Loss
Even though NinjaTrader provides connection loss handling features it is still important
to ensure your recovered strategy's internal state is not in limbo. Should you have
internal variables tracking various information it may be necessary for you to program
your own additional connection loss handling into OnConnectionStatus() to properly
recover all aspects of your strategy in the manner you desired.
10.4.7.35.2.1 CancelOrder()
Definition
Amends an Unmanaged order.
Syntax
ChangeOrder(IOrder iOrder, int quantity, double limitPrice, double
stopPrice)
Parameters
iOrder IOrder object of the order you wish to amend
quantity Order quantity
limitPrice Order limit price. Use "0" should this parameter be
irrelevant for the OrderType being submitted.
stopPrice Order stop price. Use "0" should this parameter be
irrelevant for the OrderType being submitted.
Examples
private IOrder stopOrder = null;
10.4.7.35.2.3 IgnoreOverFill
Definition
Defines the behaviour of a strategy when an overfill is detected. This property is only relevant
when using Unmanaged order methods.
Setting this property value to "true" can have *serious* adverse affects on a running
strategy unless you have programmed your own overfill handling
User defined overfill handling is advanced and should *only* be addressed by
experienced programmers. Additional information can be found on over-fills in the
Unmanaged approach section
NOTE: An overfill is categorized as when an order returns a "Filled" or "PartFilled" state after
the order was already marked for cancellation. The cancel request could have been induced
by an explicit CancelOrder() call, from more implicit cancellations like those that occur when
another order sharing the same OCO ID is filled, or from things like order expirations.
Property Value
This property returns true if the strategy will ignore overfills; otherwise, false. Default is set
to false.
Syntax
IgnoreOverFill
Examples
protected override void Initialize()
{
// Allows for custom overfill handling
IgnoreOverFill = true;
}
10.4.7.35.2.4 SubmitOrder()
Definition
Generates an Unmanaged order.
Syntax
SubmitOrder(int barsInProgressIndex, OrderAction orderAction,
OrderType orderType, int quantity, double limitPrice, double
stopPrice, string ocoId, string signalName)
Parameters
OrderAction.Buy
OrderAction.BuyToCover
OrderAction.Sell
OrderAction.SellShort
orderType Possible values:
OrderType.Limit
OrderType.Market
OrderType.Stop
OrderType.StopLimit
quantity Order quantity
limitPrice Order limit price. Use "0" should this parameter be
irrelevant for the OrderType being submitted.
stopPrice Order stop price. Use "0" should this parameter be
irrelevant for the OrderType being submitted.
ocoId A string representing the OCO ID used to link OCO
orders together
signalName A string representing the name of the order
Examples
private IOrder entryOrder = null;
Definition
Indicates if the strategy will be using Unmanaged order methods. Please note that you will not
be able to mix Unmanaged order methods with Managed order methods.
Property Value
This property returns true if the strategy will use Unmanaged order methods; otherwise,
false. Default is set to false.
Syntax
Unmanaged
Examples
protected override void Initialize()
{
// Use Unmanaged order methods
Unmanaged = true;
}
10.4.7.36 Performance
Definition
The Performance object holds all trades and trade performance data generated by a strategy.
A NinjaScript strategy can generate both synthetic trades (historical backtest trades) and
real-time trades executed on a real-time data stream. If you wish to access only real-time
trades, access the "RealtimeTrades" collection
The first trade of the "RealtimeTrades" collection will contain a synthetic entry execution if
the strategy was NOT flat at the time you start the strategy.
Examples
protected override void OnBarUpdate()
{
// Print out the number of long trades
Print("The strategy has taken " + Performance.
LongTrades.Count + " long trades.");
}
10.4.7.36.1 AllTrades
Definition
AllTrades is a TradeCollection object of all trades generated by a strategy.
Syntax
Performance.AllTrades
Examples
protected override void OnBarUpdate()
{
// Print out the number of long trades
Print("The strategy has taken " + Performance.
AllTrades.Count + " trades.");
}
10.4.7.36.2 LongTrades
Definition
LongTrades is a TradeCollection object of long trades generated by a strategy.
Syntax
Performance.LongTrades
Examples
protected override void OnBarUpdate()
{
// Print out the number of long trades
Print("The strategy has taken " + Performance.
LongTrades.Count + " long trades.");
}
10.4.7.36.3 RealtimeTrades
Definition
RealtimeTrades is a TradeCollection object of real-time trades generated by a strategy.
Syntax
Performance.RealtimeTrades
Examples
protected override void OnBarUpdate()
{
// Print out the number of real-time trades
Print("The strategy has taken " + Performance.
RealtimeTrades.Count + " real-time trades.");
}
10.4.7.36.4 ShortTrades
Definition
ShortTrades is a TradeCollection object of short trades generated by a strategy.
Syntax
Performance.ShortTrades
Examples
protected override void OnBarUpdate()
{
// Print out the number of short trades
Print("The strategy has taken " + Performance.
ShortTrades.Count + " short trades.");
}
10.4.7.37 Position
Definition
The Position object holds data related to a currently held position by a strategy.
Examples
protected override void OnBarUpdate()
{
// Print out the average entry price
Print("The average entry price is " + Position.
AvgPrice);
}
10.4.7.37.1 AvgPrice
Definition
Gets the average price of a strategy position.
Property Value
A double value representing the position's average price per unit.
Syntax
Position.AvgPrice
Examples
protected override void OnBarUpdate()
{
// Raise stop loss to breakeven when there is at
least 10 ticks in profit
if (Close[0] >= Position.AvgPrice + 10 *
TickSize)
ExitLongStop(Position.Quantity, Position.
AvgPrice);
}
10.4.7.37.2 GetProfitLoss()
Definition
Calculates the unrealized PnL for the position.
Syntax
Position.GetProfitLoss(double marketPrice, PerformanceUnit
performanceUnit)
Parameters
marketPrice Price used to calculate the PnL such as Close[0].
This value is used as the current price and
compared against your entry price for the PnL.
performanceUnit Possible values:
PerformanceUnit.Currency
PerformanceUnit.Percent
PerformanceUnit.Points
Examples
protected override void OnBarUpdate()
{
// If not flat print our unrealized PnL
if (Position.MarketPosition != MarketPosition.
Flat)
Print("Open PnL: " + Position.GetProfitLoss
(Close[0], PerformanceUnit.Points));
}
10.4.7.37.3 MarketPosition
Definition
Gets the current market position.
Property Value
MarketPosition.Flat
MarketPosition.Long
MarketPosition.Short
Syntax
Position.MarketPosition
Examples
protected override void OnBarUpdate()
{
// If not flat print our open PnL
if (Position.MarketPosition != MarketPosition.
Flat)
Print("Open PnL: " + Position.GetProfitLoss
(Close[0], PerformanceUnit.Points));
}
10.4.7.37.4 Quantity
Definition
Gets the current position size.
Property Value
An int value representing the position size.
Syntax
Position.Quantity
Examples
protected override void OnBarUpdate()
{
// Prints out the current market position
Print(Position.MarketPosition.ToString() + " " +
Position.Quantity.ToString());
}
10.4.7.38 Positions
Definition
Holds an array of Position objects that represent positions managed by the strategy. This
property should only be used when your strategy is executing orders against multiple
instruments.
Index value is based on the the array of Bars objects added via the Add() method. For
example:
Positions[0] == ES position
Positions[1] == Always a flat position, ES position will always be Positions[0]
Positions[2] == ER2 position
Property Value
An array of Position objects.
Syntax
Positions[int index]
Property Of
Custom Strategy
Examples
protected override void Initialize()
{
Add(Instrument, PeriodType.Minute, 5);
Add("ER2 06-07, PeriodType.Minute, 5);
}
Definition
Defines the behaviour of a strategy when a strategy generated order is returned from the
broker's server in a "Rejected" state. Default behaviour is to stop the strategy, cancel any
remaining working orders, and then close any open positions managed by the strategy by
submitting one "Close" order for each unique position.
Setting this property value to "TakeNoAction" can have *serious* adverse affects on a
running strategy unless you have programmed your own order rejection handling in the
OnOrderUpdate() method
User defined rejection handling is advanced and should *only* be addressed by
experienced programmers
Property Value
RealtimeErrorHandling.TakeNoAction
RealtimeErrorHandling.StopStrategyCancelOrdersClosePosition (Default value of a strategy)
Syntax
RealtimeErrorHandling
Examples
protected override void Initialize()
{
RealtimeErrorHandling = RealtimeErrorHandling.
TakeNoAction;
}
if (stopLossOrder == null)
stopLossOrder = ExitLongStop(Position.
AvgPrice - 10 * TickSize);
}
10.4.7.40 RestartDelaySeconds
Definition
Indicates the amount of time a reestablished connection needs to be held before certain
connection loss handling actions will be taken
Property Value
An int value representing the time required for a reconnection to last before certain
connection loss handling actions will occur.
Syntax
RestartDelaySeconds
Examples
protected override void Initialize()
{
// Recalculate strategy only after connection is
reestablished for at least 10 seconds
RestartDelaySeconds = 10;
}
10.4.7.41 Slippage
Definition
Sets the amount of slippage in ticks used in performance calculations during backtests.
Property Value
An int value representing the number ticks.
Syntax
Slippage
Examples
protected override void Initialize()
{
Slippage = 2;
}
10.4.7.42 TimeInForce
Definition
Sets the time in force property for all orders generated by a strategy. This property is
dependant on what time in force your broker may or may not support.
Property Value
Cbi.TimeInForce.Day
Cbi.TimeInForce.Gtc
Syntax
TimeInForce
Examples
protected override void Initialize()
{
TimeInForce = Cbi.TimeInForce.Day;
}
10.4.7.43 TraceOrders
Definition
When enabled, traces are generated and displayed in the NinjaScript Output window for each
call of an order method providing confirmation that the method is entered and providing
information if order methods are ignored and why. This is valuable for debugging if you are
not seeing expected behaviour when calling an order method. This property can be set
programatically in the Initialize() method.
The output will reference a method "PlaceOrder()" which is an internal method that all Enter()
and Exit() methods use.
Property Value
This property returns true if the strategy will output trace information; otherwise, false.
Syntax
TraceOrders
Examples
protected override void Initialize()
{
TraceOrders = true;
}
10.4.7.44 Trade
Definition
A Trade is a completed buy/sell or sell/buy transaction. It consists of an entry and exit
execution.
Example 1:
Buy 1 contract at a price of 1000 and sell 1 contract at a price of 1001 is one complete trade.
Example 2:
Buy 2 contracts at a price of 1000 and sell the 1st contract at a price of 1001, then sell the
2nd contract at a price of 1002 are two completed trades.
In the second example above, two trade objects are created to represent each individual
trade. Each trade object will hold the same entry execution for two contracts since this single
execution was the opening execution for both individual trades.
Examples
protected override void OnBarUpdate()
{
// Check to make sure there is at least one
trade in the collection
if (Performance.RealtimeTrades.Count > 0)
{
// Get the last completed real-time trade
(at index 0)
Trade lastTrade = Performance.
RealtimeTrades[Performance.RealtimeTrades.Count - 1];
Definition
A collection of Trade objects. You can access a trade object by providing an index value.
Trades are indexed sequentially meaning the oldest trade taken in a strategy will be at an
index value of zero. The most recent trade taken will be at an index value of the total trades in
the collection minus 1.
Examples
EXAMPLE 1
protected override void OnBarUpdate()
{
// Accesses the first/last trade in the strategy
(oldest trade is at index 0)
// and prints out the profit as a percentage to
the output window
if (Performance.AllTrades.Count > 1)
{
Trade lastTrade = Performance.AllTrades
[Performance.AllTrades.Count - 1];
Trade firstTrade = Performance.AllTrades
[0];
EXAMPLE 2
protected override void OnBarUpdate()
{
// Once the strategy has executed 20 trades loop
through the losing trades
// collection and print out the PnL on only long
trades
if (Performance.AllTrades.Count == 20)
{
Print("There are " + Performance.AllTrades.
LosingTrades.Count + " losing trades.");
foreach (Trade myTrade in Performance.
AllTrades.LosingTrades)
{
if (myTrade.Entry.MarketPosition ==
MarketPosition.Long)
Print(myTrade.ProfitCurrency *
myTrade.Quantity);
}
}
}
10.4.7.45.1 Count
Definition
Returns the number of trades in the collection.
Property Value
An int value that represents the number of trades in the collection.
Syntax
<TradeCollection>.Count
Examples
protected override void OnBarUpdate()
{
// Print out the number of long trades
Print("The strategy has taken " + Performance.
LongTrades.Count + " long trades.");
}
10.4.7.45.2 GetTrades()
Definition
Returns a TradeCollection object representing all trades that make up the specified position.
Syntax
<TradeCollection>.GetTrades(string instrument, string
entrySignalName, int instance)
Parameters
instrument An instrument name such as "MSFT"
entrySignalName The name of your entry signal
instance The occurrence to check for (1 is the most recent,
2 is the 2nd most recent position, etc...)
Examples
TradeCollection myTrades = Performance.AllTrades.
GetTrades("MSFT", "myEntrySignal", 1);
Print("The last position was comprised of " +
myTrades.Count + " trades.");
10.4.7.45.3 LosingTrades
Definition
A subcollection of Trade objects consisting of only the losing trades in a TradeCollection. You
can access a trade object by providing an index value. Trades are indexed sequentially
meaning the oldest trade taken in a strategy will be at an index value of zero. The most recent
trade taken will be at an index value of the total trades in the collection minus 1.
Syntax
<TradeCollection>.LosingTrades
Examples
protected override void OnBarUpdate()
{
// Accesses the first/last losing trade in the
strategy (oldest trade is at index 0)
// and prints out the profit as a percentage to
the output window
if (Performance.AllTrades.LosingTrades.Count >
1)
{
Trade lastTrade = Performance.AllTrades.
LosingTrades[Performance.AllTrades.Count - 1];
Trade firstTrade = Performance.AllTrades.
LosingTrades[0];
Definition
Performance profile of a collection of Trade objects.
Examples
protected override void OnBarUpdate()
{
// Only trade if you have less than 5
consecutive losers in a row
if (Performance.RealtimeTrades.
TradesPerformance.MaxConsecLoser < 5)
{
// Trade logic here
}
}
10.4.7.45.4.1 AvgBarsInTrade
Definition
Returns the average number of bars per trade.
Property Value
A double value that represents the average number of bars per trade.
Syntax
<TradeCollection>.TradesPerformance.AvgBarsInTrade
Examples
protected override void OnBarUpdate()
{
// Print out the average number of bars per
trade of all trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.
AvgBarsInTrade);
}
10.4.7.45.4.2 AvgTradeDuration
Definition
Returns the average duration of a trade weighted by quantity.
Property Value
A TimeSpan value that represents the quantity-weighted average duration of a trade.
Syntax
<TradeCollection>.TradesPerformance.AvgTradeDuration
Examples
protected override void OnBarUpdate()
{
// Print out the quantity-weighted average
duration of all trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.
AvgTradeDuration);
}
10.4.7.45.4.3 Commission
Definition
Returns the total commission.
Property Value
A double value that represents the total commission.
Syntax
<TradeCollection>.TradesPerformance.Commission
Examples
protected override void OnBarUpdate()
{
// Print out the total commission of all trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.Commission);
}
10.4.7.45.4.4 Currency
Definition
Returns a TradesPerformanceValues object in currency.
Property Value
A TradesPerformanceValues object that is represented in currency.
Syntax
<TradeCollection>.TradesPerformance.Percent
Examples
protected override void OnBarUpdate()
{
// Print out the avg. profit of all trades in
currency
Print("Average profit: " + Performance.
AllTrades.TradesPerformance.Currency.AvgProfit);
}
10.4.7.45.4.5 GetSharpeRatio()
Definition
Returns the Sharpe ratio for the TradeCollection object calculated from a defined risk-free
rate.
Syntax
<TradeCollection>.TradesPerformance.GetSharpeRatio(double
riskFreeRate)
Parameters
riskFreeRate The risk-free rate to calculate the Sharpe ratio from
Examples
double sharpeRatio = Performance.AllTrades.
TradesPerformance.GetSharpeRatio(0.035);
Print("The Sharpe ratio based on a 3.5 percent risk-
free rate is " + sharpeRatio);
10.4.7.45.4.6 GrossLoss
Definition
Returns the gross loss.
Property Value
A double value that represents the gross loss.
Syntax
<TradeCollection>.TradesPerformance.GrossLoss
Examples
protected override void OnBarUpdate()
{
// Print out the gross loss of all trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.GrossLoss);
}
10.4.7.45.4.7 GrossProfit
Definition
Returns the gross profit.
Property Value
A double value that represents the gross profit.
Syntax
<TradeCollection>.TradesPerformance.GrossProfit
Examples
protected override void OnBarUpdate()
{
// Print out the gross profit of all trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.GrossProfit);
}
10.4.7.45.4.8 MaxConsecLoser
Definition
Returns the maximum number of consecutive losers seen.
Property Value
An int value that represents the maximum number of consecutive losers seen.
Syntax
<TradeCollection>.TradesPerformance.MaxConsecLoser
Examples
protected override void OnBarUpdate()
{
// Print out the max consecutive losers of all
trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.
MaxConsecLoser);
}
10.4.7.45.4.9 MaxConsecWinner
Definition
Returns the maximum number of consecutive winners seen.
Property Value
An int value that represents the maximum number of consecutive winners seen.
Syntax
<TradeCollection>.TradesPerformance.MaxConsecWinner
Examples
protected override void OnBarUpdate()
{
// Print out the max consecutive winners of all
trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.
MaxConsecWinner);
}
10.4.7.45.4.10 MaxTime2Recover
Definition
Returns the maximum time to recover from a draw down.
Property Value
A TimeSpan value that represents the maximum time to recover from a draw down.
Syntax
<TradeCollection>.TradesPerformance.MaxTime2Recover
Examples
protected override void OnBarUpdate()
{
// Print out the maximum time to recover from a
draw down
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.
MaxTime2Recover);
}
10.4.7.45.4.11 Percent
Definition
Returns a TradesPerformanceValues object in percent.
Property Value
Syntax
<TradeCollection>.TradesPerformance.Percent
Examples
protected override void OnBarUpdate()
{
// Print out the avg. profit of all trades in
percent
Print("Average profit: " + Performance.
AllTrades.TradesPerformance.Percent.AvgProfit);
}
10.4.7.45.4.12 Points
Definition
Returns a TradesPerformanceValues object in points.
Property Value
A TradesPerformanceValues object that is represented in points.
Syntax
<TradeCollection>.TradesPerformance.Points
Examples
protected override void OnBarUpdate()
{
// Print out the avg. profit of all trades in
points
Print("Average profit: " + Performance.
AllTrades.TradesPerformance.Points.AvgProfit);
}
10.4.7.45.4.13 ProfitFactor
Definition
Returns the profit factor.
Property Value
A double value that represents the profit factor.
Syntax
<TradeCollection>.TradesPerformance.ProfitFactor
Examples
protected override void OnBarUpdate()
{
// Print out the profit factor of all trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.
ProfitFactor);
}
10.4.7.45.4.14 SharpeRatio
Definition
Returns the Sharpe ratio using a zero risk free return.
Property Value
A double value that represents the Sharpe ratio using a zero risk free return.
Syntax
<TradeCollection>.TradesPerformance.SharpeRatio
Examples
protected override void OnBarUpdate()
{
// Print out the Sharpe ratio of all trades
based on a zero risk free return
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.SharpeRatio);
}
10.4.7.45.4.15 TradesPerDay
Definition
Returns the average number of trades per day.
Property Value
An int value that represents the average number of trades per day.
Syntax
<TradeCollection>.TradesPerformance.TradesPerDay
Examples
protected override void OnBarUpdate()
{
// Print out the average number of trades per
day of all trades
Print("Average # bars per trade is: " +
Performance.AllTrades.TradesPerformance.
TradesPerDay);
}
10.4.7.45.5 WinningTrades
Definition
A subcollection of Trade objects consisting of only the winning trades in a TradeCollection.
You can access a trade object by providing an index value. Trades are indexed sequentially
meaning the oldest trade taken in a strategy will be at an index value of zero. The most recent
trade taken will be at an index value of the total trades in the collection minus 1.
Syntax
<TradeCollection>.WinningTrades
Examples
protected override void OnBarUpdate()
{
// Accesses the first/last winning trade in the
strategy (oldest trade is at index 0)
// and prints out the profit as a percentage to
the output window
if (Performance.AllTrades.WinningTrades.Count >
1)
{
Trade lastTrade = Performance.AllTrades.
WinningTrades[Performance.AllTrades.Count - 1];
Trade firstTrade = Performance.AllTrades.
WinningTrades[0];
Definition
Performance values of a collection of Trade objects.
Examples
protected override void OnBarUpdate()
{
// If the profit on real-time trades is > $1000
stop trading
if (Performance.RealtimeTrades.
TradesPerformance.Currency.CumProfit > 1000)
return;
}
10.4.7.46.1 AvgEtd
Definition
Returns the average ETD (end trade draw down) of the collection.
Property Value
A double value that represents the average ETD of the collection.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
AvgEtd
Examples
protected override void OnBarUpdate()
{
// Print out the average ETD of all trades in
currency
Print("Average ETD of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
AvgEtd);
}
10.4.7.46.2 AvgMae
Definition
Returns the average MAE (max adverse excursion) of the collection.
Property Value
A double value that represents the average MAE of the collection.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
AvgMae
Examples
protected override void OnBarUpdate()
{
// Print out the average MAE of all trades in
currency
Print("Average MAE of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
AvgMae);
}
10.4.7.46.3 AvgMfe
Definition
Returns the average MFE (max favorable excursion) of the collection.
Property Value
A double value that represents the average MFE of the collection.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
AvgMfe
Examples
protected override void OnBarUpdate()
{
// Print out the average MFE of all trades in
currency
Print("Average MFE of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
AvgMfe);
}
10.4.7.46.4 AvgProfit
Definition
Returns the average profit of the collection.
Property Value
A double value that represents the average profit of the collection.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
AvgProfit
Examples
protected override void OnBarUpdate()
{
// Print out the average profit of all trades in
currency
Print("Average profit of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
AvgProfit);
}
10.4.7.46.5 CumProfit
Definition
Returns the cumulative profit of the collection.
Property Value
A double value that represents the cumulative profit of the collection.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
CumProfit
Examples
protected override void OnBarUpdate()
{
// Print out the cumulative profit of all trades
in currency
Print("Average cumulative profit of all trades
is: " + Performance.AllTrades.TradesPerformance.
Currency.CumProfit);
}
10.4.7.46.6 Draw Dow n
Definition
Returns the draw down of the collection.
Property Value
A double value that represents the average ETD of the collection.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
DrawDown
Examples
protected override void OnBarUpdate()
{
// Print out the draw down of all trades in
currency
Print("Draw down of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
DrawDown);
}
10.4.7.46.7 LargestLoser
Definition
Returns the largest loss amount of the collection.
Property Value
A double value that represents the largest loss amount of the collection.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
LargestLoser
Examples
protected override void OnBarUpdate()
{
// Print out the largest loss of all trades in
currency
Print("Largest loss of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
LargestLoser);
}
10.4.7.46.8 LargestWinner
Definition
Returns the largest win amount of the collection.
Property Value
A double value that represents the largest win amount of the collection.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
LargestWinner
Examples
protected override void OnBarUpdate()
{
// Print out the largest win of all trades in
currency
Print("Largest win of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
LargestWinner);
}
10.4.7.46.9 ProfitPerMonth
Definition
Returns the profit per month of the collection. This value is always returned as a percentage.
Property Value
A double value that represents the profit per month of the collection as a percentage.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
ProfitPerMonth
Examples
protected override void OnBarUpdate()
{
// Print out the profit per month of all trades
Print("Profit per month of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
ProfitPerMonth);
}
10.4.7.46.10 StdDev
Definition
Returns the standard deviation of the collection on a per unit basis.
Property Value
A double value that represents the standard deviation of the collection on a per unit basis.
Syntax
<TradeCollection>.TradesPerformance.<TradesPerformanceValues>.
StdDev
Examples
protected override void OnBarUpdate()
{
// Print out the standard deviation of all
trades
Print("Standard deviation of all trades is: " +
Performance.AllTrades.TradesPerformance.Currency.
StdDev);
}
10.4.7.47 WaitForOcoClosingBracket
Definition
There may be brokers who require that OCO orders are submitted simultaneously in a single
API call vs sending them in sequence with an include user defined OCO identifier. For
brokers that require OCO orders to be submitted in a single function call, a NinjaScript
strategy must wait until it has both legs of the OCO pair generated by SetStopLoss(),
SetTrailStop() and SetProfitTarget().
If you only wish to send a stop loss or profit target (but not both) via any of the Set...()
methods mentioned above, when WaitForOcoClosingBracket is enabled, your exit
orders will never be sent since NinjaTrader needs to wait until it has both orders of the OCO
bracket. If you disable WaitForOcoClosingBracket, NinjaTrader will immediately submit
a stop or profit target order, whichever is submitted first.
TD AMERITRADE
Property Value
This property returns true if the strategy will wait for both legs of an OCO bracket to be called
in a strategy before submitting the order pair to the broker; otherwise, false.
Syntax
WaitForOcoClosingBracket
Examples
protected override void Initialize()
{
WaitForOcoClosingBracket = false;
}