Ninja Trader Version 7 Help Guide

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1009

NinjaTrader Version 7 Help Guide

© 2011 NinjaTrader, LLC


2 NinjaTrader Version 7

Table of Contents
Part I Welcome to NinjaTrader Version 7 18

Part II What's New in Version 7 20

Part III Release Notes 27

Part IV Video Library 86

Part V Risks of Electronic Trading with NinjaTrader 93

Part VI Copyrights 96

Part VII Introduction 100


1 Getting
...................................................................................................................................
Help & Support 100
2 Purchase
...................................................................................................................................
NinjaTrader 101
3 Learning
...................................................................................................................................
to Use NinjaTrader 101

Part VIII Configuration 104


1 Connecting
................................................................................................................................... 104
Connecting to..........................................................................................................................................................
your Account 104
Multiple Connections
.......................................................................................................................................................... 108
External Data..........................................................................................................................................................
Feed Connection 109
Market Replay..........................................................................................................................................................
Connection 109
Sim ulated Data
..........................................................................................................................................................
Feed Connection 109
Connecting to..........................................................................................................................................................
Kinetick 111
Connecting to..........................................................................................................................................................
TradeStation 112
Connecting to..........................................................................................................................................................
Collective2 113
2 Installation
................................................................................................................................... 116
Minim um System
..........................................................................................................................................................
Requirem ents 117
Clear Brow ser
..........................................................................................................................................................
Cache 117
3 Options
................................................................................................................................... 117
General Tab .......................................................................................................................................................... 118
Strategies Tab
.......................................................................................................................................................... 119
Sim ulator Tab
.......................................................................................................................................................... 121
Log Tab .......................................................................................................................................................... 124
Com m ission..........................................................................................................................................................
Tab 125
ATI Tab .......................................................................................................................................................... 128
Data Tab .......................................................................................................................................................... 130
RSS Tab .......................................................................................................................................................... 131
Misc Tab .......................................................................................................................................................... 132
4 Performance
...................................................................................................................................
Tips 134

Part IX Operations 137

© 2011 NinjaTrader, LLC


Contents 3

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

© 2011 NinjaTrader, LLC

3
4 NinjaTrader Version 7

Tips ................................................................................................................................... 211


Running NinjaScript
..........................................................................................................................................................
Strategies 212
Setting Real-Time
.........................................................................................................................................................
Strategy Options 212
Running a.........................................................................................................................................................
NinjaScriptStrategy from a Chart 212
Running a.........................................................................................................................................................
NinjaScriptStrategy from the Strategies Tab 216
Running FX.........................................................................................................................................................
Strategies 219
5 Backup
...................................................................................................................................
& Restore 220
Creating a Backup
..........................................................................................................................................................
Archive 220
Restoring a Backup
..........................................................................................................................................................
Archive 222
6 Charts
................................................................................................................................... 223
Creating a Chart
.......................................................................................................................................................... 224
Navigating a ..........................................................................................................................................................
Chart 226
Working w ith..........................................................................................................................................................
Price Data 236
Bar Types .......................................................................................................................................................... 245
Working w ith..........................................................................................................................................................
Indicators 253
Working w ith..........................................................................................................................................................
Draw ing Tools & Objects 258
Working w ith..........................................................................................................................................................
Autom ated Strategies 268
Chart Tem plates
.......................................................................................................................................................... 270
Saving Chart..........................................................................................................................................................
Defaults 271
Data Box .......................................................................................................................................................... 276
Global Cross..........................................................................................................................................................
Hair 280
Trading from..........................................................................................................................................................
a Chart 282
Chart Properties
.......................................................................................................................................................... 282
Pow er Volum ..........................................................................................................................................................
e Indicators 284
Reload Historical
..........................................................................................................................................................
Data 285
Window Linking
.......................................................................................................................................................... 286
How Bars are..........................................................................................................................................................
Built 286
How Trade Executions
..........................................................................................................................................................
are Plotted 288
7 Control
...................................................................................................................................
Center 290
File Menu .......................................................................................................................................................... 291
Tools Menu .......................................................................................................................................................... 292
Help Menu .......................................................................................................................................................... 292
Orders Tab .......................................................................................................................................................... 293
Strategies Tab .......................................................................................................................................................... 295
Executions Tab .......................................................................................................................................................... 297
Positions Tab .......................................................................................................................................................... 299
Accounts Tab .......................................................................................................................................................... 300
Account Perform..........................................................................................................................................................
ance Tab 300
Performance.........................................................................................................................................................
Data Tabs 302
Efficiency.........................................................................................................................................................
Graphs 306
Statistics .........................................................................................................................................................
Definitions 307
Log Tab .......................................................................................................................................................... 312
Status Bar .......................................................................................................................................................... 313
8 Data...................................................................................................................................
Grids 313
Working w ith
..........................................................................................................................................................
Data Grids 313
9 Historical
...................................................................................................................................
& Real-Time Data 315
10 Historical
...................................................................................................................................
Data Manager 320
Im porting .......................................................................................................................................................... 321
Exporting .......................................................................................................................................................... 325
Editing .......................................................................................................................................................... 326
Dow nload .......................................................................................................................................................... 329
11 Hot Key
...................................................................................................................................
Manager 330

© 2011 NinjaTrader, LLC


Contents 5

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

© 2011 NinjaTrader, LLC

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

© 2011 NinjaTrader, LLC


Contents 7

Linking Window
..........................................................................................................................................................
s 513
24 Workspaces
................................................................................................................................... 514
Managing Workspaces
.......................................................................................................................................................... 514

Part X NinjaScript 518


1 Distribution
................................................................................................................................... 518
Im port .......................................................................................................................................................... 518
Export .......................................................................................................................................................... 518
Export Problem ..........................................................................................................................................................
s 521
Protection/DLL ..........................................................................................................................................................
Security 524
Com m ercial..........................................................................................................................................................
Distribution 526
Licensing/User
.........................................................................................................................................................
Authentication 527
Best Practices
......................................................................................................................................................... 527
Distribution
.........................................................................................................................................................
Procedure 527
2 Editor
................................................................................................................................... 529
NS Editor Com..........................................................................................................................................................
ponents 529
Intellisense .......................................................................................................................................................... 530
Autom atically
..........................................................................................................................................................
Inserting Actions and Conditions 533
Code Snippets.......................................................................................................................................................... 534
Com pile Errors
.......................................................................................................................................................... 537
Visual Studio..........................................................................................................................................................
Debugging 538
Com pile Error
..........................................................................................................................................................
Codes 541
CS0019 ......................................................................................................................................................... 542
CS0021 ......................................................................................................................................................... 543
CS0029 ......................................................................................................................................................... 544
CS0103 ......................................................................................................................................................... 544
CS0117 ......................................................................................................................................................... 545
CS0118 ......................................................................................................................................................... 546
CS0200 ......................................................................................................................................................... 546
CS0201 ......................................................................................................................................................... 547
CS0234 ......................................................................................................................................................... 547
CS0246 ......................................................................................................................................................... 548
CS0428 ......................................................................................................................................................... 548
CS0443 ......................................................................................................................................................... 549
CS0665 ......................................................................................................................................................... 549
CS1002 ......................................................................................................................................................... 550
CS1501 ......................................................................................................................................................... 550
CS1502 ......................................................................................................................................................... 551
CS1503 ......................................................................................................................................................... 551
CS1513 ......................................................................................................................................................... 552
NT0019 ......................................................................................................................................................... 553
NT0029 ......................................................................................................................................................... 554
NT1503 ......................................................................................................................................................... 554
NoDoc ......................................................................................................................................................... 555
3 Educational
...................................................................................................................................
Resources 555
Basic Program
..........................................................................................................................................................
m ing Concepts 555
Basic Syntax
......................................................................................................................................................... 556
Branching.........................................................................................................................................................
Commands 560
Looping Commands
......................................................................................................................................................... 561
Functions.........................................................................................................................................................
and Methods Explained 564
Developing Indicators
.......................................................................................................................................................... 566
Developing
.........................................................................................................................................................
Outside of the NinjaScript Editor 567

© 2011 NinjaTrader, LLC

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

© 2011 NinjaTrader, LLC


Contents 9

Set Up ................................................................................................................................... 649


Creating the Strategy
...................................................................................................................................
via the Wizard 651
Creating the Strategy
...................................................................................................................................
via Self Programming 655
Compiling ................................................................................................................................... 656
Intermediate - RSI
.........................................................................................................................................
w ith Stop Loss & Profit Target 657
Set Up ................................................................................................................................... 657
Entering Strategy...................................................................................................................................
Logic 659
Compiling ................................................................................................................................... 661
4 Language
...................................................................................................................................
Reference 662
Alphabetical..........................................................................................................................................................
Reference 662
Alert & Debug .......................................................................................................................................................... 671
Alert() ......................................................................................................................................................... 671
ClearOutputWindow
.........................................................................................................................................................
() 672
Log() ......................................................................................................................................................... 672
PlaySound()
......................................................................................................................................................... 672
Print() ......................................................................................................................................................... 673
ResetAlert()
......................................................................................................................................................... 674
ResetAlerts()
......................................................................................................................................................... 674
SendMail()......................................................................................................................................................... 674
Data .......................................................................................................................................................... 675
Working w .........................................................................................................................................................
ith Price Data 675
Add() ......................................................................................................................................................... 676
AddKagi()......................................................................................................................................................... 678
AddLineBreak()
......................................................................................................................................................... 679
AddPointAndFigure()
......................................................................................................................................................... 681
AddRenko()......................................................................................................................................................... 682
Bars ......................................................................................................................................................... 683
BarsSinceSession ......................................................................................................................................... 683
GetBar() ......................................................................................................................................... 684
GetDayBar() ......................................................................................................................................... 685
FirstBarOfSession ......................................................................................................................................... 685
PercentComplete ......................................................................................................................................... 686
Session ......................................................................................................................................... 686
GetNextBeginEnd ................................................................................................................................... 686
TemplateName ................................................................................................................................... 687
TimeZoneInfo ................................................................................................................................... 687
TickCount ......................................................................................................................................... 688
TotalTicks ......................................................................................................................................... 688
BarsArray ......................................................................................................................................................... 689
BarsInProgress
......................................................................................................................................................... 689
BarsPeriod......................................................................................................................................................... 690
BarsPeriods
......................................................................................................................................................... 692
BoolSeries.........................................................................................................................................................
Class 693
CalculateOnBarClose
......................................................................................................................................................... 695
Close ......................................................................................................................................................... 695
Closes ......................................................................................................................................................... 696
Count ......................................................................................................................................................... 697
CountIf() ......................................................................................................................................................... 697
CrossAbove()
......................................................................................................................................................... 698
CrossBelow.........................................................................................................................................................
() 698
CurrentBar......................................................................................................................................................... 699
CurrentBars
......................................................................................................................................................... 700
DataSeries.........................................................................................................................................................
Class 700
DateTimeSeries
.........................................................................................................................................................
Class 703

© 2011 NinjaTrader, LLC

9
10 NinjaTrader Version 7

DayOfWeek ......................................................................................................................................................... 705


Falling() ......................................................................................................................................................... 706
FirstTickOfBar
......................................................................................................................................................... 706
FloatSeries .........................................................................................................................................................
Class 707
FundamentalDataEventArgs
......................................................................................................................................................... 709
GetCurrentAsk()
......................................................................................................................................................... 710
GetCurrentAskVolume()
......................................................................................................................................................... 710
GetCurrentBid()
......................................................................................................................................................... 711
GetCurrentBidVolume()
......................................................................................................................................................... 711
GetMedian() ......................................................................................................................................................... 711
High ......................................................................................................................................................... 712
HighestBar()......................................................................................................................................................... 712
Highs ......................................................................................................................................................... 713
Historical......................................................................................................................................................... 713
IDataSeries ......................................................................................................................................................... 714
Initialize()......................................................................................................................................................... 715
Input ......................................................................................................................................................... 716
Instrument ......................................................................................................................................................... 716
Expiry ......................................................................................................................................... 717
FullName ......................................................................................................................................... 717
MasterInstrument.Compare()
......................................................................................................................................... 717
MasterInstrument.InstrumentType
......................................................................................................................................... 718
MasterInstrument.Name ......................................................................................................................................... 718
MasterInstrument.PointValue
......................................................................................................................................... 719
MasterInstrument.Round2TickSize()
......................................................................................................................................... 719
IntSeries .........................................................................................................................................................
Class 720
Least Recent.........................................................................................................................................................
Occurence (LRO) 722
LongSeries .........................................................................................................................................................
Class 722
Low ......................................................................................................................................................... 725
Low estBar()......................................................................................................................................................... 725
Low s ......................................................................................................................................................... 726
MarketDataEventArgs
......................................................................................................................................................... 726
MarketDepthEventArgs
......................................................................................................................................................... 727
MaximumBarsLookBack
......................................................................................................................................................... 728
Median ......................................................................................................................................................... 728
Medians ......................................................................................................................................................... 729
Most Recent .........................................................................................................................................................
Occurence (MRO) 730
OnBarUpdate()
......................................................................................................................................................... 730
OnFundamentalData()
......................................................................................................................................................... 731
OnMarketData()
......................................................................................................................................................... 732
OnMarketDepth()
......................................................................................................................................................... 733
OnStartUp() ......................................................................................................................................................... 734
OnTermination()
......................................................................................................................................................... 735
Open ......................................................................................................................................................... 735
Opens ......................................................................................................................................................... 736
Rising() ......................................................................................................................................................... 737
Slope() ......................................................................................................................................................... 737
StringSeries.........................................................................................................................................................
Class 738
TickSize ......................................................................................................................................................... 740
Time ......................................................................................................................................................... 740
Times ......................................................................................................................................................... 741
ToDay() ......................................................................................................................................................... 741
ToTime() ......................................................................................................................................................... 742
TriggerCustomEvent()
......................................................................................................................................................... 743

© 2011 NinjaTrader, LLC


Contents 11

Typical ......................................................................................................................................................... 743


Typicals ......................................................................................................................................................... 744
Volume ......................................................................................................................................................... 745
Volumes ......................................................................................................................................................... 745
Weighted......................................................................................................................................................... 746
Weighteds ......................................................................................................................................................... 747
Draw ing .......................................................................................................................................................... 747
Allow RemovalOfDraw
.........................................................................................................................................................
Objects 748
BackColor......................................................................................................................................................... 748
BackColorAll
......................................................................................................................................................... 749
BackColorAllSeries
......................................................................................................................................................... 750
BackColorSeries
......................................................................................................................................................... 751
BarColor ......................................................................................................................................................... 751
BarColorSeries
......................................................................................................................................................... 752
CandleOutlineColor
......................................................................................................................................................... 752
CandleOutlineColorSeries
......................................................................................................................................................... 753
Custom Draw.........................................................................................................................................................
ing 753
Draw Andrew.........................................................................................................................................................
sPitchfork() 754
Draw Arc() ......................................................................................................................................................... 754
Draw Arrow .........................................................................................................................................................
Dow n() 756
Draw Arrow .........................................................................................................................................................
Line() 757
Draw Arrow .........................................................................................................................................................
Up() 758
Draw Diamond()
......................................................................................................................................................... 758
Draw Dot() ......................................................................................................................................................... 759
Draw Ellipse()
......................................................................................................................................................... 760
Draw ExtendedLine()
......................................................................................................................................................... 761
Draw FibonacciCircle()
......................................................................................................................................................... 762
Draw FibonacciExtensions()
......................................................................................................................................................... 763
Draw FibonacciRetracements()
......................................................................................................................................................... 764
Draw FibonacciTimeExtensions()
......................................................................................................................................................... 765
Draw GannFan()
......................................................................................................................................................... 765
Draw HorizontalLine()
......................................................................................................................................................... 766
Draw Line()......................................................................................................................................................... 767
Draw Objects
......................................................................................................................................................... 768
Draw Ray() ......................................................................................................................................................... 770
Draw Rectangle()
......................................................................................................................................................... 771
Draw Region()
......................................................................................................................................................... 772
Draw RegressionChannel()
......................................................................................................................................................... 773
Draw Ruler()
......................................................................................................................................................... 774
Draw Square()
......................................................................................................................................................... 775
Draw Text()......................................................................................................................................................... 776
Draw TextFixed()
......................................................................................................................................................... 777
Draw Triangle()
......................................................................................................................................................... 778
Draw TriangleDow
.........................................................................................................................................................
n() 779
Draw TriangleUp()
......................................................................................................................................................... 780
Draw VerticalLine()
......................................................................................................................................................... 780
IAndrew sPitchfork
......................................................................................................................................................... 781
IArc ......................................................................................................................................................... 782
IArrow Dow .........................................................................................................................................................
n 783
IArrow Line......................................................................................................................................................... 784
IArrow Up......................................................................................................................................................... 784
IDiamond ......................................................................................................................................................... 785
IDot ......................................................................................................................................................... 785
IDraw Object
......................................................................................................................................................... 786

© 2011 NinjaTrader, LLC

11
12 NinjaTrader Version 7

IEllipse ......................................................................................................................................................... 787


IExtendedLine
......................................................................................................................................................... 788
IFibonacciCircle
......................................................................................................................................................... 789
IFibonacciExtensions
......................................................................................................................................................... 789
IFibonacciRetracements
......................................................................................................................................................... 790
IFibonacciTimeExtensions
......................................................................................................................................................... 791
IGannFan......................................................................................................................................................... 792
IHorizontalLine
......................................................................................................................................................... 793
ILine ......................................................................................................................................................... 793
IRay ......................................................................................................................................................... 794
IRectangle ......................................................................................................................................................... 794
IRegion ......................................................................................................................................................... 795
IRegressionChannel
......................................................................................................................................................... 796
IRuler ......................................................................................................................................................... 797
ISquare ......................................................................................................................................................... 798
IText ......................................................................................................................................................... 798
ITextFixed......................................................................................................................................................... 799
ITriangle ......................................................................................................................................................... 800
ITriangleDow
.........................................................................................................................................................
n 801
ITriangleUp......................................................................................................................................................... 801
IVerticalLine
......................................................................................................................................................... 802
InHitTest ......................................................................................................................................................... 802
RemoveDraw .........................................................................................................................................................
Object() 803
RemoveDraw .........................................................................................................................................................
Objects() 803
Indicator .......................................................................................................................................................... 804
Add() ......................................................................................................................................................... 804
AutoScale ......................................................................................................................................................... 805
BarsRequired
......................................................................................................................................................... 805
Displacement
......................................................................................................................................................... 806
DisplayInDataBox
......................................................................................................................................................... 806
Draw OnPricePanel
......................................................................................................................................................... 807
FormatPriceMarker()
......................................................................................................................................................... 807
HorizontalGridLines
......................................................................................................................................................... 808
Line Class......................................................................................................................................................... 808
Lines ......................................................................................................................................................... 809
LinesConfigurable
......................................................................................................................................................... 809
Overlay ......................................................................................................................................................... 810
PaintPriceMarkers
......................................................................................................................................................... 810
Plot Class......................................................................................................................................................... 811
PlotColors......................................................................................................................................................... 812
Plots ......................................................................................................................................................... 813
PlotsConfigurable
......................................................................................................................................................... 813
PriceType......................................................................................................................................................... 814
PriceTypeSupported
......................................................................................................................................................... 814
SessionBreakLines
......................................................................................................................................................... 815
ScaleJustification
......................................................................................................................................................... 816
Update() ......................................................................................................................................................... 816
Value ......................................................................................................................................................... 817
Values ......................................................................................................................................................... 818
VerticalGridLines
......................................................................................................................................................... 818
Indicator Methods
.......................................................................................................................................................... 819
Valid Input.........................................................................................................................................................
Data for Indicator Methods 819
Accumulation/Distribution
.........................................................................................................................................................
(ADL) 820
Adaptive .........................................................................................................................................................
Price Zone (APZ) 821

© 2011 NinjaTrader, LLC


Contents 13

Aroon ......................................................................................................................................................... 822


Aroon Oscillator
......................................................................................................................................................... 823
Average .........................................................................................................................................................
Directional Index (ADX) 824
Average .........................................................................................................................................................
Directional Movement Rating (ADXR) 825
Average .........................................................................................................................................................
True Range (ATR) 826
Balance of.........................................................................................................................................................
Pow er (BOP) 827
Bollinger Bands
......................................................................................................................................................... 828
BuySell Pressure
......................................................................................................................................................... 829
BuySell Volume
......................................................................................................................................................... 831
CandleStickPattern
......................................................................................................................................................... 831
Chaikin Money
.........................................................................................................................................................
Flow 833
Chaikin Oscillator
......................................................................................................................................................... 834
Chaikin Volatility
......................................................................................................................................................... 835
Chande Momentum
.........................................................................................................................................................
Oscillator (CMO) 835
Commodity .........................................................................................................................................................
Channel Index (CCI) 836
Current Day
.........................................................................................................................................................
OHL 837
Darvas ......................................................................................................................................................... 838
Directional
.........................................................................................................................................................
Movement (DM) 839
Directional
.........................................................................................................................................................
Movement Index (DMI) 840
Donchian.........................................................................................................................................................
Channel 841
Double Stochastics
......................................................................................................................................................... 842
Dynamic Momentum
.........................................................................................................................................................
Index (DMIndex) 843
Ease of Movement
......................................................................................................................................................... 844
Fisher Transform
......................................................................................................................................................... 845
Forecast .........................................................................................................................................................
Oscillator (FOSC) 846
Heiken Ashi
......................................................................................................................................................... 847
Keltner Channel
......................................................................................................................................................... 848
KeyReversalDow
.........................................................................................................................................................
n 849
KeyReversalUp
......................................................................................................................................................... 850
Linear Regression
......................................................................................................................................................... 851
Linear Regression
.........................................................................................................................................................
Intercept 852
Linear Regression
.........................................................................................................................................................
Slope 852
MA Envelopes
......................................................................................................................................................... 853
Maximum.........................................................................................................................................................
(MAX) 855
Minimum (MIN)
......................................................................................................................................................... 856
Momentum ......................................................................................................................................................... 856
Money Flow.........................................................................................................................................................
Index (MFI) 857
Moving Average
.........................................................................................................................................................
- Double Exponential (DEMA) 858
Moving Average
.........................................................................................................................................................
- Exponential (EMA) 859
Moving Average
.........................................................................................................................................................
- Hull (HMA) 860
Moving Average
.........................................................................................................................................................
- Kaufman's Adaptive (KAMA) 861
Moving Average
.........................................................................................................................................................
- Mesa Adaptive (MAMA) 862
Moving Average
.........................................................................................................................................................
- Simple (SMA) 863
Moving Average
.........................................................................................................................................................
- T3 (T3) 864
Moving Average
.........................................................................................................................................................
- Triangular (TMA) 865
Moving Average
.........................................................................................................................................................
- Triple Exponential (TEMA) 866
Moving Average
.........................................................................................................................................................
- Triple Exponential (TRIX) 867
Moving Average
.........................................................................................................................................................
- Variable (VMA) 868
Moving Average
.........................................................................................................................................................
- Volume Weighted (VWMA) 869
Moving Average
.........................................................................................................................................................
- Weighted (WMA) 870
Moving Average
.........................................................................................................................................................
- Zero Lag Exponential (ZLEMA) 871
Moving Average
.........................................................................................................................................................
Convergence-Divergence (MACD) 872
n Bars Dow.........................................................................................................................................................
n 873
n Bars Up......................................................................................................................................................... 874

© 2011 NinjaTrader, LLC

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

© 2011 NinjaTrader, LLC


Contents 15

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

© 2011 NinjaTrader, LLC

15
16 NinjaTrader Version 7

IgnoreOverFill ................................................................................................................................... 981


SubmitOrder() ................................................................................................................................... 981
Unmanaged ................................................................................................................................... 982
Performance
......................................................................................................................................................... 983
AllTrades ......................................................................................................................................... 983
LongTrades ......................................................................................................................................... 984
RealtimeTrades......................................................................................................................................... 984
ShortTrades ......................................................................................................................................... 984
Position ......................................................................................................................................................... 985
AvgPrice ......................................................................................................................................... 985
GetProfitLoss()......................................................................................................................................... 986
MarketPosition ......................................................................................................................................... 986
Quantity ......................................................................................................................................... 987
Positions ......................................................................................................................................................... 987
RealtimeErrorHandling
......................................................................................................................................................... 988
RestartDelaySeconds
......................................................................................................................................................... 989
Slippage ......................................................................................................................................................... 990
TimeInForce
......................................................................................................................................................... 990
TraceOrders
......................................................................................................................................................... 991
Trade ......................................................................................................................................................... 991
TradeCollection
......................................................................................................................................................... 992
Count ......................................................................................................................................... 994
GetTrades() ......................................................................................................................................... 994
LosingTrades ......................................................................................................................................... 994
TradesPerformance ......................................................................................................................................... 995
AvgBarsInTrade ................................................................................................................................... 996
AvgTradeDuration ................................................................................................................................... 997
Commission ................................................................................................................................... 997
Currency ................................................................................................................................... 997
GetSharpeRatio() ................................................................................................................................... 998
GrossLoss ................................................................................................................................... 998
GrossProfit ................................................................................................................................... 999
MaxConsecLoser ................................................................................................................................... 999
MaxConsecWinner ................................................................................................................................... 1000
MaxTime2Recover ................................................................................................................................... 1000
Percent ................................................................................................................................... 1000
Points ................................................................................................................................... 1001
ProfitFactor ................................................................................................................................... 1001
SharpeRatio ................................................................................................................................... 1002
TradesPerDay................................................................................................................................... 1002
WinningTrades......................................................................................................................................... 1003
TradesPerformanceValues
......................................................................................................................................................... 1003
AvgEtd ......................................................................................................................................... 1004
AvgMae ......................................................................................................................................... 1005
AvgMfe ......................................................................................................................................... 1005
AvgProfit ......................................................................................................................................... 1006
CumProfit ......................................................................................................................................... 1006
Draw Dow n ......................................................................................................................................... 1006
LargestLoser ......................................................................................................................................... 1007
LargestWinner......................................................................................................................................... 1007
ProfitPerMonth......................................................................................................................................... 1008
StdDev ......................................................................................................................................... 1008
WaitForOcoClosingBracket
......................................................................................................................................................... 1009

© 2011 NinjaTrader, LLC


Part

I
18 NinjaTrader Version 7

1 Welcome to 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.

Additional information and a schedule of upcoming training events.

Thank you for choosing NinjaTrader.

Good trading,
NinjaTrader Customer Service

© 2011 NinjaTrader, LLC


Part

II
20 NinjaTrader Version 7

2 What's New in Version 7


General Enhancements

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

Strategy Analyzer Enhancements

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

© 2011 NinjaTrader, LLC


What's New in Version 7 21

now optimize on bar interval


New multi-instrument optimization that aggregates all optimization results of an
instrument list into a virtual data set which then generates a "total" performance report
Add performance graph - Trades by Entry Time as histogram
Added performance graph - Trades by Exit Time as histogram
Bars required parameter is now only relevant on the first test period during walk forward
optimization

Strategy Wizard Enhancements

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

Data Management Enhancements

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

Market Replay Enhancements

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

© 2011 NinjaTrader, LLC


22 NinjaTrader Version 7

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

Market Analyzer Enhancements

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

© 2011 NinjaTrader, LLC


What's New in Version 7 23

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

New Multi-Series Charting


Accurately mix multiple data series on the same chart
Data series can be any mix of instruments or interval types
New "Format Data Series" dialog window to support multiple series
Each data series can be parameterized independently allowing for full visual
customization

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

Enhanced Y Axis Scaling


Logarithmic or linear
User defined fixed range y axis
Three independent scales per panel (Left, right and overlay)
User defined horizontal grid lines now expressed in points
Reduced white space in left and right margins creating a bigger chart canvas

New Flexible Chart Panel Management


Move panels up or down
Panel properties dialog window
Panels can be maximized to full screen and restored
Auto-arrange panels to default ratios
Panels can be removed which removes all objects within a panel
When adding a new indicator or data series to a chart you can select "New Panel",
"Same as input series" or by panel number

© 2011 NinjaTrader, LLC


24 NinjaTrader Version 7

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

Enhanced Data Box


Enhanced to support multi-series charts
Can control the display of data series labels, indicator labels and panel numbers
Added "Auto Size" function that automatically resizes the Data Box based on the number
of data rows required for display
Added "Always On Top" toggle
Added user defined fonts
Plots that are set to a transparent color are no longer displayed
Sizeable column widths

Enhanced Mini Data Box


Condensed format to preserve space
Only displays data from within the panel
Added display for indicator values

New Chart Object Manipulation


Any object on chart can now be selected
Drag and drop indicators or data series to a different panel or create a new one by
dropping it in between panels or at the upper/lower boundaries of a chart
Change the paint order (z-order) of any chart object per panel
Double click on any chart object to bring up it's properties dialog window
Right mouse clicking on any chart object will show relevant context menu commands
Press the delete button on any selected chart object will remove it

Connectivity Adapter Enhancements

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

© 2011 NinjaTrader, LLC


What's New in Version 7 25

Fixed issue where timestamps could be inaccurate during pre and post market hours

Interactive Brokers Adapter


Fixed issue where price events with zero volume were filtered

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

© 2011 NinjaTrader, LLC


Part

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.

© 2011 NinjaTrader, LLC


28 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Release Notes 29

NinjaTrader Version 7.0.1000.1 Production Release - December 1, 2010


Status Issue # Category Comments
Improved 4203 Charts Improved intraday x-axis labeling to reduce tightly grouped
vertical gridlines near the day break
Improved 4205 ZenFire Updated 64-bit API to address an issue where the L2
adapter subscription could be lost
Improved 4210 General Streamlined the popup prompts on importing NinjaScript
archives with the same filenames
Fixed 4191 PFG adapterOrders which had been modified, but already had partial fills
could have been inadvertently cancelled on reconnect
Fixed 4193 PFG adapterThere could have been messages on reconnect of partial
fills for modified orders
Fixed 4198 Charts Price marker for overlay indicators weren't painted when the
panel did not have a y-axis, but the chart did.
Fixed 4199 Charts Moving slider in Market Replay and pressing the middle
mouse button on the chart could crash NT
Fixed 4200 Charts Reloading historical data did not necessarily bring up the
"Loading data..." message
Fixed 4201 Charts Panning or zooming y-axis could make line objects flicker
when the anchor points were very close to the x-axis
Fixed 4202 Charts Physically resizing a non-equidistant chart didn't necessarily
work as expected
Fixed 4207 ZenFire 64-bit adapter could show connection loss on the Control
adapter Center even though the connection was already restored
Fixed 4208 General Importing existing protected archive exported from 64-bit
didn't overwrite both DLLs (.x86 and .x64) if 'Yes' was
selected on overwrite prompt
Fixed 4212 Charts Non-intraday and multiple day bars could be timestamped
wrong under certain scenarios
Fixed 4213 PFG adapterOn processing fills, the LimitPrice, StopPrice, and Qty of an
order could have been restored inadvertently to the price
before the last order change
Fixed 4214 BarChart Requests for historical tick data could throw errors
adapter
Fixed 4215 Charts If a non-equidistant chart had many session breaks visible it
could have erroneously stopped plotting session breaks on
the right side.
Fixed 4216 General Executions could be placed on wrong bar on non-intraday
bar series charts with periods > 1
Fixed 4218 General Indicators using double.Compare extension method could
not be exported
Fixed 4219 Charts On non-equidistant charts, drawing objects with anchor
points much earlier than the visible charted time range could
seem like it changes slope when scrolling through the chart
Fixed 4220 Basic Entry Changes in the Basic Entry grid cells were not applied when
pressing "Enter"
Fixed 4221 TT adapter Submitting orders on TF did not necessarily work properly
Fixed 4222 General GAIN provider could have been lost after NT was running for
an hour
Fixed 4223 Market Session template setting of "Use instrument setting" did not

© 2011 NinjaTrader, LLC


30 NinjaTrader Version 7

Analyzer use the session template of each individual instrument


Fixed 4224 Charts LineBreak volume was incorrectly calculated. The charted
High and Low did not match the DataSeries High and Low.
Fixed 4225 Charts @VolumeUpDown indicator colors were inconsistent for doji
bars when compared against OHLC chart style
Fixed 4226 Charts Certain scenarios could cause the strategy caption to stay
in the panel header despite the strategy already being
removed
Fixed 4229 NinjaScript Multi-series indicators could cause a crash if there was no
indicators data available on any of the series
Fixed 4233 Charts When using data providers that do not offer daily bars for the
current day, the synthetically generated daily bar could have
had wrong date stamps depending on the local time zone
versus session template time zone
Fixed 4234 General Removing a NinjaScript assemblies could have failed if the
remaining NinjaScript assemblies were referencing each
other
Fixed 4237 Strategy In the Chart tab, the "Reload historical data" item was
Analyzer erroneously available

NinjaTrader Version 7.0.0.23 Release Candidate 1 - October 28, 2010


Status Issue # Category Comments
Changed 4181 ZenFire Changed default connection points to servers that provide
adapter unfiltered bid/ask data (Existing users must re-create their
account connection)
Changed 4133 MBT adapterReject order submission if account is not available.
Changed 4184 Market Account groups can no longer be selected from an account
Replay list
Fixed 4114 Charts Historical minute data on the current day could get corrupted
if there had been a lot of bars per day with high volume
Fixed 4116 Charts @Stochastics, @StochasticsFast, @DoubleStochastics
sometimes go out of range when applied on other indicator.
Fixed 4117 Charts CandleStick Doji Pattern was incorrectly defined
Fixed 4118 Vision Pulling historical data did not work as 64-bit option was
adapter enabled.
Fixed 4119 NinjaScript Syncing of backtest order to live orders did not work properly
strategies for exit orders with "Cancel exit orders" checked.
Fixed 4120 NinjaScript Unique OCO ID's were not necessarily generated when
strategies using several instances of the same strategy.
Fixed 4121 Charts 1 second bar series were built erroneously
Fixed 4122 General Closing NinjaTrader quickly after pressing OK in indicator
dialog while the Data Box with auto scale is open could
throw exception
Fixed 4123 Charts Regression channel on multi-series chart could be moved
after last bar of base series, causing the chart to be only
partially drawn
Fixed 4124 WorkspacesRare scenarios with closing a workspace could cause an
object disposed exception
Fixed 4125 Data box Chart data box didn't update properly when instrument was
switched on chart

© 2011 NinjaTrader, LLC


Release Notes 31

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

© 2011 NinjaTrader, LLC


32 NinjaTrader Version 7

prevented by "Loading data..." messages


Fixed 4156 Strategy Using "Chart" feature in the Executions/Trades tab could
Analyzer result in a chart with no bar series
Fixed 4157 Charts Live charts did not necessarily roll to the next date if opened
during a session gap and left overnight
Fixed 4158 NinjaScript Orders rolling from historical to live did not auto expire/
strategies cancel on the next bar when not using
liveUntilCancelled=true.
Fixed 4159 Charts Using Chart Trader with a logarithmic scaled chart could
have resulted in a slowly expanding y-axis
Fixed 4160 Charts Using a non-equidistant chart erroneously did not have bars
drawn when at the beginning of the chart
Fixed 4161 Instrument Rollover date could be calculated wrong (to 0) when rollover
Manager date was on a Monday and rollover offset was calculated on
daily data
Fixed 4163 Charts Chart->Indicator: properties had been visible although they
could not be edited.
Fixed 4164 Instrument Merge offset could be applied wrong when requesting bar
Manager with session definition with several session segments on a
rollover day
Fixed 4165 Charts Modified ruler draw object to make outline color, width and
style configurable
Fixed 4166 Charts Cross hair label in y axis could produce ghost effects
Fixed 4167 Instrument Merging future contracts could get wrong results when
Manager before charts were opened with merge settings
'DoNotMerge'
Fixed 4168 NinjaScript Colors were incorrectly resetting with the @VolumeProfile
indicators indicator
Fixed 4169 SuperDOM Market depth remove events were not processed in certain
scenarios
Fixed 4170 Chart TraderOrders or open positions on Chart Trader forced a small
rescale even when not necessary
Fixed 4173 Strategy BarColor or CandleOutlineColor set from a strategy hosted
Analyzer indicator didn't set bar/candle outline color on SA chart.
Fixed 4175 Charts Opening multi-series charts with bar series on different time
ranges while not connected could leave the chart with a
maximum zoom factor that was too low
Fixed 4176 Performanc "Largest Losing/Winning Trade" in "Points" mode was not
e reports reported on a per trade basis.
Fixed 4177 Chart TraderRight click->place buy/sell stop-limit's offset selector did not
increment correctly
Fixed 4182 Market Templates with "Total row" did not handle adding
Analyzer instruments properly
Fixed 4183 NinjaScript Sim stop orders placed live had not been handled properly
strategies on strategy restart

NinjaTrader Version 7.0.0.22 Beta Release 22 - September 29, 2010


Status Issue # Category Comments
Improved 4110 Indicators Added Smooth parameter to @PFE indicator
Improved 4091 Charts Hit detection of drawing objects near bars and indicators

© 2011 NinjaTrader, LLC


Release Notes 33

works better now


Improved 4104 ZenFire Add .Reconnect logic as adapter reports a heartbeat alert
adapter
Changed 4065 Charts Introduced new Kagi implementation
Changed 4086 Charts Changed toolbar button and context menu caption from
'Remove Drawing Objects' to 'Remove Drawing Objects...'.
Fixed 4073 Charts Kagi chart style could cause a crash when there were no
bars/lines displayed on chart
Fixed 4074 Output Added some logic to prevent text being added while the
window window itself wasn't disposed yet.
Fixed 4075 NinjaScript Drawing objects from hosted indicators had been drawn on
indicators chart which is not expected.
Fixed 4076 Yahoo Yahoo! changed page layout which broke NinjaTrader's logic
adapter to pull splits and dividends.
Fixed 4077 Vision Historical data requests are not routed to NinjaTrader's data
adapter server when using the 64-bit option.
Fixed 4078 NinjaScript Backtest orders and executions had been marked with
strategies timestamps of incorrect series on multi-series strategies
with multiple series on the same instrument.
Fixed 4079 PFG adapterPrices for instruments traded in quarters of 1/32 (like the ZF)
had not been formatted properly.
Fixed 4080 General Commissions no longer are pulled from the first connection
but from the connection where the (live) account belongs to.
Fixed 4081 BarChart There could be data missing for the current session on time
adapter zones ahead of CST.
Fixed 4082 NinjaScript Rolling simulated stop order from backtest to live
strategies erroneously placed the simulated stop order as live
Fixed 4083 NinjaScript Stop price checks for multi-series strategies could have
strategies been done on the wrong BIP
Fixed 4084 GAIN CRITICAL: Major change to GAIN connection - GAIN users
adapter please read - http://www.ninjatrader-support2.com/
announcements/GAIN_Announcement.php
Fixed 4087 Charts Having equidistant setting to false in chart properties default
didn't display indicator labels initially
Fixed 4089 IB adapter IB adapter could throw redundant Connection Lost events
since TWS continues to report Connection Lost despite no
new connection loss occurring
Fixed 4090 Charts Historical session segments after rollover date and before
live session could be missing on chart
Fixed 4092 Charts Scrolling/panning non-equidistant charts into white space
after last visible bar had erroneous behavior
Fixed 4093 Strategy Drawing Fibonacci retracements from strategies on SA
Analyzer showed unexpected behaviour
Fixed 4094 NinjaScript Right click -> 'Save As' in NinjaScript Editor didn't restrict
naming filenames to numbers and digits.
Fixed 4095 Charts Connecting to Market Replay could change panel height
ratios.
Fixed 4096 Strategy Sorting by Period in Periods tab of SA and Account
Analyzer Performance was incorrect.
Fixed 4097 NinjaScript Calling DrawTextFixed from a hosted indicator could yield
indicators exception when saving workspace containing chart with

© 2011 NinjaTrader, LLC


34 NinjaTrader Version 7

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

NinjaTrader Version 7.0.0.21 Beta Release 21 - September 9, 2010


Status Issue # Category Comments
Added 4039 ZenFire Zen-Fire adapter supports 64bit
adapter
Added 4039 Vision Vision Financial adapter supports 64bit
Financial
adapter
Changed 4052 TT adapter TT Transaction Credit trade data is now submitted securely
via HTTPS
Improved 4054 NinjaScript @PriorDayOHLC/@CurrentDayOHL uses new NinjaScript
indicators method 'GetTradingDayFromLocal()' instead of
'GetSessionDate()' which is not public anymore.
Improved 4055 NinjaScript GetSessionBar() was not working as expected on some
session templates and is now deprecated. Please use new
GetDayBar() method instead.
Fixed 4026 Account Account performance reports could have been off when
Performanc filtering by ATM templates
e
Fixed 4027 Instrument Fixed "object not being tracked" bug when adding an
Manager instrument to a list.

© 2011 NinjaTrader, LLC


Release Notes 35

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

© 2011 NinjaTrader, LLC


36 NinjaTrader Version 7

Replay the Market Replay connection now


Fixed 4059 NinjaScript Multi-series indicators hosted by indicators on chart did not
indicators take the session settings from their host.
Fixed 4060 Market Connecting to Market Replay could yield an exception when
Replay an indicator is on the chart on a panel before the bar series
panel
Fixed 4061 General Real-time tick from a data provider that provides
timestamps could hang a chart with a multi-series indicator
on it under certain circumstances
Fixed 4062 NinjaScript Indicators hosting multi-series indicators could get incorrect
indicators values from the hosted multi-series indicator under certain
circumstances
Fixed 4066 Strategy On the Chart tab of the Strategy Analyzer, after running a
Analyzer backtest, switching from an instrument with no data to an
instrument with data could cause a crash
Fixed 4067 Charts Opening a chart with very old years requests could cause a
crash (e.g. 400 year chart)
Fixed 4068 Charts Immediately closing a chart after switching the chart's
interval period could cause a crash
Fixed 4069 PFG adapterNinjaScript strategies rolling form historical to live could
have had orders stuck in "PendingSubmit" state
Fixed 4070 General Typing in "0M" into any quantity selector could cause a
crash
Fixed 4071 Alerts Pressing F1 with the Alerts window open did not bring up the
window Help Guide

NinjaTrader Version 7.0.0.20 Beta Release 20 - August 12, 2010


Status Issue # Category Comments
Added 4005 Instrument Data for instruments wasn't deleted from repository when
Manager master instrument was deleted
Improved 4013 PFG adapterNow supports placement of orders in sub accounts
(customer accounts) of a broker account.
Improved 4020 IQFeed/ Instruments running on delayed data will now throw a log
Kinetick message
adapter
Fixed 3946 Charts Moving auto-scale objects on logarithmic scale could make
the scale change very fast.
Fixed 3954 Market Changing From: date in Market Replay while an indicator is
Replay on the chart could yield exception.
Fixed 3962 Strategy Executions disappeared from SA's chart tab and SA's "Send
Analyzer to Chart" charts when disconnected from provider
Fixed 3964 BarChart Requests for historical tick data had been flawed and could
adapter throw errors.
Fixed 3965 Position grid Position grid could cause exception when NT was closed
Fixed 3966 NinjaScript Overhauled locking concept on strategy persistence to avoid
strategies deadlock e.g. on market replay.
Fixed 3967 TDA adapter Updated to latest API to fix an issue where NT would hang in
case of incorrect user/pwd.
Fixed 3968 Strategy SA now displays chart executions independent of what was
Analyzer set in the default settings for the "Plot executions" property

© 2011 NinjaTrader, LLC


Release Notes 37

of the selected period type


Fixed 3969 Charts Trade lines weren't displayed on chart when anchor
executions were left and right off from visible chart.
Fixed 3970 Market Strategies enabled on strategies tab would erroneously
Replay place their historical orders "live" to the replay account when
using Market Replay.
Fixed 3971 PFG adapterPFG adapter now supports DailyVolume. Please update to
latest PFG API 1.0.440.
Fixed 3972 Charts Displayed time range of multi-series chart could be off when
<= 1 bar was contained in series
Fixed 3973 Charts When 'To' date was changed to today in bars data dialog of
open chart, time portion could be displayed.
Fixed 3974 Charts Strategies BarColor, BackColor and CandleOutlineColor
wasn't displayed on chart created from SA -> Trades tab
Fixed 3975 Strategy Executions on SA -> Trades tab were lost when connected
Analyzer to provider
Fixed 3976 Charts Scrolling in leftmost region of a large non-equidistant chart
was more sluggish then on the rightmost region
Fixed 3977 Charts Opening indicator or strategy dialog and adding indicators/
strategies while reloading bars data could yield exception
Fixed 3978 Charts Executions weren't displayed properly on non-equidistant
daily charts
Fixed 3979 NinjaScript 'AttachedTo' property of chart objects can't be accessed
from NS anymore.
Fixed 3980 Charts When a workspace contains a chart with a deleted
instrument, the chart will be restored as an empty chart
along with an alert now.
Fixed 3981 Charts Using the mini data box on a chart with 1 bar series and at
least 2 indicators not on the right scale caused an
exception.
Fixed 3982 Charts Some scenarios on chart with no bars could yield
exceptions/error messages
Fixed 3983 Strategy Connect to provider could remove executions on charts
Analyzer created from SA -> Executions or SA -> Trades tab
Fixed 3984 Charts When switching instruments on a equidistant chart using
the bars back setting, the x-axis did not refresh to reflect
proper dates in some situations
Fixed 3985 Charts Trying to drag and drop bar series while mini data box was
displayed could leave mouse cursor with drag symbol
Fixed 3986 Charts Data box labels for bar series on multi-series charts weren't
displayed when data box was opened with the mouse before
first/after last bar of a series
Fixed 3987 General Applied fix to resolve the "Entity Object not being Tracked -
NinjaTrader.Strategy.StrategyData" errors.
Fixed 3989 Market Moving slider back on Market Replay could throw strategies
Replay off from chart
Fixed 3990 Charts Indicators with displacement != 0 were displayed wrong on
non equidistant charts.
Fixed 3991 Charts Non-overlay indicators put on chart from a backtest strategy
could be initally placed on wrong panel
Fixed 3992 Strategy Consecutive backtests with Distribution graph open could

© 2011 NinjaTrader, LLC


38 NinjaTrader Version 7

Analyzer cause a crash


Fixed 3993 Genetic Optimizing on bools and enums resulted in duplicate
Optimizer iterations
Fixed 3994 Instrument Adding an instrument with the same name as one that
Manager already exists could cause an exception
Fixed 3995 Strategy Heiken Ashi indicator on SA did not hide the bar series
Analyzer properly.
Fixed 3996 Instrument Symbol mapping for master instrument AUDJPY for
Manager BarChart was not correct.
Fixed 3997 Strategy Closing SA while backtest/optimize was in progress could
Analyzer yield exception
Fixed 3998 Charts 'Remove all drawing objects' on @PriceAlert indicator could
cause a crash
Fixed 3999 Charts Empty xml file for global chart objects could yield an
exception
Fixed 4000 Strategy Pressing 'Esc' in SA optimizer grid and right click ->
Analyzer 'Performance Viewer' brought up an exception
Fixed 4001 Kinetick Changed internal logic to pull historical minute and daily data
adapter
Fixed 4002 Kinetick DailyVolume for currencies did not work as expected which
adapter e.g. prevented building the daily bar to the current day on
chart.
Fixed 4003 Charts Chart markers on charts could cause a crash when clicked
while no bar series were on the chart
Fixed 4004 NinjaScript Added flag to prevent re-entrance of "close on error"
strategies handling.
Fixed 4005 Instrument Data for instruments wasn't deleted from repository when
Manager master instrument was deleted
Fixed 4006 Charts Multi anchor chart objects on non-equidistant charts could
not be moved left, past the first visible bar. Moving the right
anchor on wide chart objects did not work properly either.
Fixed 4007 Charts Chart objects could be missing when resized from a very
small to a very large chart canvas size
Fixed 4008 General NinjaTrader could crash when operating the "File" menu
system while shutting down.
Fixed 4009 Sound files Missing sound files or sound files which were recorded in an
incorrect format caused issues on order management.
Fixed 4010 Charts Applied some fixes for scale justification of indicators and
trade lines on chart
Fixed 4011 ZenFire Instrument with custom exchange "NLX" (like YI,YG,ZI,ZG)
adapter could not close their positions via the "close position" logic
Fixed 4012 Strategy Foreground color of SA grid cells were not always accurate.
Analyzer
Fixed 4014 Instrument Tools->Instrument Manager->Select instrument->Edit->Ok
Manager could cause an 'Object not tracked' exception
Fixed 4015 Kinetick The CME waiver option was not persisted.
adapter
Fixed 4016 Kinetick The bar with midnight timestamp on historical minute
adapter requests could be missing or be assigned to the incorrect
date.
Fixed 4017 NinjaScript A crash could occur if an instrument was removed from the

© 2011 NinjaTrader, LLC


Release Notes 39

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

NinjaTrader Version 7.0.0.19 Beta Release 19 - July 22, 2010


Status Issue # Category Comments
Added 3853 Kinetick/ Now supports an option for back adjusted continuous
DTN adapter contracts.
Improved 3910 Charts Adding new bar series objects to a chart will have the
primary bar's width assigned to the new series automatically
Improved 3918 IB adapter Updated to latest TWS 906
Improved 3925 eSignal eSignal adapter now supports $TVOL/$TVOLA/$TVOLQ
adapter
Fixed 3900 FX Pro Link button did not work when toggling instruments.
Fixed 3901 FXPro/ Would have non FX instruments erroneously selected if
FXEntry those instruments had been selected by a different UI linked
by the link button.
Fixed 3902 Vendor Vendor license management form could throw exceptions if
licensing the authorization failed.
Fixed 3903 Charts Pressing middle button down on chart while reloading
historical data could crash NT
Fixed 3904 Market Instrument on MA linked with link button could get out of
Analyzer sync when it was below an empty row.
Fixed 3905 Charts Right click --> Data Series properties was erroneously
allowed on charts in SA and Account Performance
windows.
Fixed 3906 Strategy On SA strategy properties panel, 'floating' could be selected
Analyzer and now is disabled.
Fixed 3907 Charts Cross hair label could erroneously go into the y-axis on
indicator panels under certain circumstances
Fixed 3908 Charts Deleting a bar series while still loading a bar series on the
same chart could cause a crash
Fixed 3909 NinjaScript OnTermination() for hosted indicators could have been
strategies called unexpectedly which e.g. caused premature freeing of
resources.

© 2011 NinjaTrader, LLC


40 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


Release Notes 41

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.

© 2011 NinjaTrader, LLC


42 NinjaTrader Version 7

Fixed 3957 NinjaScript Setting HorizontalGridLines, VerticalGridLines, or


indicators SessionBreakLines in an indicator's Initialize() method can
cause an error
Fixed 3958 Charts Chart templates applied onto a multi-series chart could have
been applied with incorrect bar spacing
Fixed 3959 Historical Downloading data of an instrument type not supported by
Data current connection could delete pre-existing data
Manager
Fixed 3960 Historical Deleting tick data in the Edit tab could crash NT when using
Data non-US PC locales
Manager
Fixed 3961 Simulator When connecting, sim account restore could prevent a
successful connection
Fixed 3962 Strategy Executions disappeared from the Chart tab when user
Analyzer disconnected from the data provider
Fixed 3963 Chart Indicators could be on wrong panel when applied from a
multi-series chart template

NinjaTrader Version 7.0.0.18 Beta Release 18 - June 30, 2010


Status Issue # Category Comments
Added 3898 Kinetick Implemented CME waiver program
adapter
Improved 3864 Strategy Overhauled genetic optimizer
Analyzer
Improved 3897 Charts Optimized several system indicators
Improved 3841 Market Account related events (OnAccountUpdate, OnExecution,
Analyzer OnOrderUpdate, OnPositionUpdate) now receive all events
from all active accounts.
Improved 3849 Charts On switching expiries on futures instruments, drawing
objects are kept when switched from same master
instrument from one expiry to other.
Improved 3862 Charts Global chart object setting is now saved as part of a draw
object's default settings
Improved 3897 NinjaScript Optimized @Aroon, @Bollinger, and @StdDev system
indicators indicators
Improved 3899 Backup/ Backup archives will now only include NinjaScript files when
Restore there are no compiler errors
Fixed 3815 SuperDOM Changing instruments quickly on SuperDOM with
workspace containing SuperDOM and several charts linked
with link button resulted in endless requests.
Fixed 3820 Charts Disconnecting from PATS while chart data was loading
could cause a crash
Fixed 3840 Grids Grids->Right click->send email had a redundant
"NinjaTrader" text in the subject.
Fixed 3842 Charts Having a multi-series indicator on a chart, then removing a
series in the code and reloading the chart could throw an
error.
Fixed 3843 Backup Error message when restoring backup with no NinjaTrader
6.5 folder in Documents folder.
Fixed 3844 Charts Reload historical data on daily data could produce gaps

© 2011 NinjaTrader, LLC


Release Notes 43

from beginning of first year which was reloaded


Fixed 3845 Charts Minimized charts on non-active workspaces could show up
with normal window state but with empty content when the
workspace is activated.
Fixed 3846 Charts When active strategies had indicators on higher panel # and
workspace was restored, there could be empty panels.
Fixed 3847 NinjaScript Several methods on custom data series with
MaximumBarsLookBack.Infinite could throw exceptions.
Fixed 3848 Charts Changes in a session used as <Use instrument settings>
didn't refresh when changed until next NT startup.
Fixed 3850 Kinetick/ Historical minute requests could have had gaps at the start
DTN of the series if the local time zone was before EST.
adapters
Fixed 3851 Charts Chart Panel properties -> Reset could cause improper
panel height on multi-panel charts
Fixed 3852 Connecting Quickly disconnecting from data provider (e.g. NT's data
server) could throw off NT's logic and leave "Loading data"
on chart and messages in the status bar
Fixed 3854 Strategy SA->Trades tab->Right click->Chart was not meant to have
Analyzer indicators on it. Disabled the respective options.
Fixed 3855 Charts Pasting draw objects could crash chart when the series that
the object was attached to was not found on destination
chart panel.
Fixed 3856 DTN adapterVolume for historical tick data was incorrect.
Fixed 3857 Charts @HeikenAshi indicator could leave the bar series color
invisible when removed after restore or indicator contained
in template was removed
Fixed 3858 Kinetick Timestamps of realtime data could be off and e.g. causing
adapter charts built from it being off.
Fixed 3859 NinjaScript SyncAccountPosition=true now always flattens the account
strategies on strategy start if using WaitUntilFlat
Fixed 3860 Charts Min/Max indicators did not work as expected when
CalculateOnBarClose was set to false
Fixed 3861 NinjaScript Restarting NS strategies could throw log errors
strategies
Fixed 3865 NinjaScript WaitUntilFlat=true, if a strategy historically would end flat but
strategies still had a live order in place, then this order would not be
migrated to a live order.
Fixed 3866 Charts Changes in settings of Fibonacci properties were
erroneously applied to the chart object when the 'Manage
templates' dialog was opened
Fixed 3867 Charts Charts using session templates with several session
definitions starting on same day but ending on different days
could result in the last historical session of today (the
session before the live session) being missing
Fixed 3868 Hot Key Applied fix for the 'Key "x" already added' error.
Manager
Fixed 3869 Kinetick/ Historical data requests for expiries earlier than 2009 could
DTN yield "unknown instrument" error.
adapters
Fixed 3871 Charts On 24/7 session realtime minute charts, Bars.

© 2011 NinjaTrader, LLC


44 NinjaTrader Version 7

FirstBarOfSession was erroneously true also on last bar of


last historical session
Fixed 3872 Charts "Overflow in 'RoundPrice'" exception could have caused a
red 'X' on charts
Fixed 3873 Kinetick/ NT could lock up on instrument lookup.
DTN
adapters
Fixed 3874 Charts Reversing logic on PointAndFigure charts was flawed.
Fixed 3875 Charts Trying to move horizontal or vertical line objects into the
chart's "white space" before the first bar with Snap Mode set
to "Bar & price" could have caused a crash
Fixed 3876 Connecting Connection to NT data server was not properly terminated
as the connection was closed while the internet was down.
Fixed 3877 Charts "End date" rolling logic on live charts when disconnected but
left running over midnight wasn't working
Fixed 3878 Charts Indicator plot style 'Line' had an erroneous offset from other
plot styles, e.g. 'Bar'.
Fixed 3879 WorkspacesNT could crash as a workspace was saved under a different
name and there had been strategies on that workspace.
Fixed 3880 Market "Indicators" columns removed from the MA had not been
Analyzer properly disposed which could have caused any hosted
indicators to not be disposed. OnTermination() was not
called either.
Fixed 3881 Kinetick Improved connection loss handling as network is down.
adapter
Fixed 3882 Charts Requesting a continuous future contract (e.g. FDAX ##-##
or NG ##-##) from before first rollover date in rollover
collection could have caused a crash
Fixed 3883 Charts Copy/paste of chart objects from equidistant chart to
different equidistant charts wasn't working as expected
Fixed 3884 Charts Y-axis labels and left/right horizontal grid line could be off on
instruments with fractional price on some occasions.
Fixed 3885 General NT could crash as color=Transparent was set on various
UI's
Fixed 3886 Charts Confined (e.g. fib retracement) global chart objects with
anchors older than 20 days were not displayed on restore of
charts
Fixed 3887 Instrument Added new tick size values as factors of 10 to better support
Manager very large or small index values.
Fixed 3888 NinjaScript "Virtual Entry Executions" are no longer created when
strategies running strategies with WaitUntilFlat
Fixed 3889 Position grid "Unrealized PnL" was not updating on the correct row, if the
row sorting was changed.
Fixed 3890 Charts Erroneous bar spacing could occur when zooming out on a
multi-series chart with bar series at different starting time.
Fixed 3891 Charts 'Loading data...' message was stuck on chart when
workspace with chart on instrument was opened and
instrument didn't exist in database
Fixed 3894 Charts 'Loading data...' wasn't displayed on chart when bars data
was loading and a second bar series was added via typing
instrument name on the chart

© 2011 NinjaTrader, LLC


Release Notes 45

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.

NinjaTrader Version 7.0.0.17 Beta Release 17 - June 10, 2010


Status Issue # Category Comments
Fixed 3750 General Handling which should prevent requesting data from
provider when data was already in repository did not work
properly for purely historical non intra-day requests.
Fixed 3761 YAHOO Dividends and splits had not been pulled correctly for some
adapter instruments
Fixed 3762 Importing Status bar was not updated.
stock lists
Fixed 3763 Historical Export historical data in HDM did not work.
Data
Manager
Fixed 3764 Charts Lines drawn nearly vertical were hard to select.
Fixed 3766 Charts Handling which should avoid redundant bar requests from
provider was not working properly for daily bar series
Fixed 3767 Charts Indicator plot lines were not aligned correctly when they had
thick plot lines
Fixed 3768 Charts Changing period value/switching instruments quickly while
data was still being loaded from provider could crash NT
Fixed 3769 Charts HA indicator could yield error in log when on chart while
period type/value is switched.
Fixed 3770 Charts Adding new Bar series when HeikenAshi indicator was on
primary series could produced Bar series with transparent
bar up/down colors.
Fixed 3771 Charts Moving and removing global chart objects on charts with
very different periods could crash NT.
Improved 3772 Historical Import data from MetaStock does not work with 64-bit
Data version of NinjaTrader. Added error message to reflect this
Manager behaviour.
Fixed 3774 Strategy Fixed bug in Genetic Algorithm.
Analyzer
Fixed 3775 Charts Copy/pasting draw objects on non-equidistant charts did not
working on some language settings.
Fixed 3776 Importing File->Utilities->Import stock list could crash NT if an
stock lists instrument list was selected.
Fixed 3777 PnL display PnL display could have been incorrect if connected to
multiple connections where the first did not support
currencies.
Fixed 3778 Charts Changed date/time labels for bars types Kagi and Point and
Figure from date only to logic depending on base bars.
Fixed 3779 Charts Strategies which had indicators on non-overlay panels could
produce new empty panels on consecutive backtests
Fixed 3780 Strategy Executions and PnL lines were missing on SA -> trades tab

© 2011 NinjaTrader, LLC


46 NinjaTrader Version 7

Analyzer -> Chart


Fixed 3781 Charts Indicators were not drawing with the dash style which was
applied in indicator plot properties.
Fixed 3782 Charts Changed 'session parts' to 'session date' mapping for
@Pivots and WoodiesPivots
Fixed 3783 Order entry Connecting to ZenFire then IB, and then placing a currency
order on a ZenFire account could crash NT.
Fixed 3784 Kinetick Real-time volume for indexes could be off.
adapter
Fixed 3785 WorkspacesDeleting a workspace or renaming a workspace which had
characters like brackets, quotes, etc. could crash NT.
Improved 3786 Charts Amended exception text for indicator error when user sets
an invalid plot value
Fixed 3787 Charts Kagi charts' horizontal connection lines did not work
properly in some cases
Fixed 3788 Kinetick Kinetick adapter produced a sequence of
adapter ConnectionLoss+Connected if the account had no L2 data
enabled.
Fixed 3789 Strategy Entry executions of a EntriesPerDirection > 1 strategy could
Analyzer have placed on wrong location on chart and the exit had
"phantom" duplicates
Improved 3790 Charts Changed indicator price label formatting to the following: If
not on the overlay scale justification or any (recursive) input
indicator is not on the overlay scale justification, then go with
indicator price label formatting logic, else go with bars series
price label formatting logic.
Improved 3792 Barchart Incorporated latest API version from Barchart.com
adapter
Fixed 3793 MBT adapterAccount value BuyingPower no longer supported by MBT.
Fixed 3794 NinjaScript IExecution.Order could have been null.
strategies
Fixed 3795 General When period type is not supported, write log message
instead of exception, and use minute period type.
Fixed 3796 General Throw error message when user tries to open a NT6.5 (or
earlier) workspace, applies a chart template saved from
NT6.5 (or earlier), or applies a Market Analyzer template
saved from NT6.5 (or earlier).
Fixed 3797 NinjaScript Managing paired OCO orders has not been running through
strategies the regular NS strategies order handling.
Fixed 3798 NinjaScript Option "Immediately submit live..." was not properly
strategies executed for "Close positions" which could result in
unprotected positions as the strategy trades live.
Fixed 3799 Charts Reload historical data did not work properly for futures when
timestamp of first bar on chart was before first defined
rollover date.
Fixed 3800 Charts Modified chart restore logic to be more tolerant if corrupt
workspace is loaded (e.g. when saved after crash).
Changed 3802 Kinetick Can no longer use DTN account to login to Kinetick
adapter
Fixed 3803 Charts Opening a historical daily chart when real-time daily chart
already open could result in request to provider not being

© 2011 NinjaTrader, LLC


Release Notes 47

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

© 2011 NinjaTrader, LLC


48 NinjaTrader Version 7

keyboard could crash NT.


Fixed 3828 TradeStation Fixed bug on NTDataDownload caused by EasyLanguage
ATI incompatibilities
Fixed 3829 Executions Executions attached to strategies in memory no longer can
tab be removed.
Fixed 3830 Charts X axis labels for labels after last bar of series could be off for
non-intraday bars types: weekly, monthly and yearly
Fixed 3831 Charts Calculating rollover offsets on sessions chart where session
ending on different day than starting could calculate offset
for wrong day when daily bars on server exists
Fixed 3832 Charts Pressing OK on Data Series dialog could yield exception in
certain scenarios
Fixed 3833 Charts Opening charts with very high days back (e.g. 146,000 days
= 400 years) could crash NT
Fixed 3834 Charts Opening futures chart on day after rollover date before
session begin could result in data requests from 01/01/1800
Fixed 3835 TDA adapter TDA API sending blank position information could throw off
NT and prevent successful login.
Fixed 3836 ZenFire L2 ladder now is rebuilt after a connection recovery.
adapter
Fixed 3837 Simulated Deleting sim account did not work properly when account
accounts contained ATM strategies.
Fixed 3838 Charts Close price of today's bar on daily charts could be wrong
when last day's daily bar was not yielded from provider.
Improved 3839 PFG adapterPreviously the PFG API would report error as one requested
historical data which would exceed the max lookback period.
This was improved by PFG. In turn NT no longer would
check "From" and "To" parameters on a historical data
request

NinjaTrader Version 7.0.0.16 Beta Release 16 - May 20, 2010


Status Issue # Category Comments
Added 3710 Kinetic Added support for Kinetic adapter
adapter
Changed 3754 Charts Replaced HeikenAshi bars type with HeikenAshi indicator
Fixed 3693 Hot Key Hot keys for modifying or cancelling last submitted order did
Manager not work properly
Fixed 3694 MBT adapterNT could run into login issues on weekends if MBT accounts
were "unavailable for trading" at the time of login attempt
Fixed 3695 General Filename generation for saving files like a chart could have
erroneously used illegal character of "." and has now been
replaced with "_" instead
Fixed 3696 General Aborting the "Loading data.." process e.g. by disconnecting
or killing NT could result in an inconsistent cache.
Fixed 3697 Connecting Failed connects could cause NT to hang on startup if the
connection was set up "Connect on startup".
Fixed 3698 Charts Fibonacci drawing objects price format was different than y-
axis price labels when trailing price had zeros at the end
Fixed 3700 Charts Indicator plot type bar could cause overflow error in log
when indicator's scale value range was very small or far off

© 2011 NinjaTrader, LLC


Release Notes 49

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

© 2011 NinjaTrader, LLC


50 NinjaTrader Version 7

based on excessive .DLL filename length


Fixed 3731 TDA adapter Requests for daily historical data could throw the error "Hdr:
400 Data acquisition failed for 1 of 1 requests.Error
retrieving data" when there is no data available.
Fixed 3734 Historical Importing data could throw exceptions if the imported
Data timestamps are invalid.
Manager
Fixed 3735 Charts Input of very large values into indicator series values or fixed
y-axis max could crash chart
Fixed 3736 Charts Bars.FirstBarOfSession didn't work properly on Tick,
Volume and some tick based period types
Fixed 3737 Charts @Pivots and WoodiesPivots could have caused
performance issues when a lot of instances were on a
chart.
Fixed 3738 WorkspacesWorkspace restore with lots of chart objects could bring up
'Collection was modified' exception.
Fixed 3739 Charts Session break line on tick-based equidistant charts were
drawn on wrong bar
Fixed 3740 Charts Only first bar series of multi-series chart was updated to live
when connected to live after been connected to Market
Replay
Fixed 3741 NinjaScript Indicators with on OnMarketData() logic did not get market
indicators events when indicator was on a minimized chart after an
auto data feed connect at NT startup
Improved 3742 Charts Y-axis price formatting changed to follow indicator logic if
indicator is on the same panel as the Bar series, but on a
different scale justification
Fixed 3743 Level II, T&S Right click->Instrument did not always correctly toggle the
windows selected instrument
Fixed 3744 Charts Chart bars 'To' could set to intra day timestamp on
connecting to normal data feed after being connected to
Market Replay.
Fixed 3745 Charts Text specific properties of global chart objects were not
shared into global text objects on other Bar series
Fixed 3746 Strategies Position related columns had not been working as expected.
grid
Fixed 3747 NinjaScript introduced NS methods GetBarOverrideColor() and
GetCandleOutlineOverrideColor()
Fixed 3748 Internal Replaced occurrences of the deprecated Bars.
SessionBreak in our code with Bars.FirstBarOfSession.
Fixed 3749 Charts Volume of incoming tick which built a new bar was
erroneously added to previous and next bar's volume
Fixed 3750 Internal Handling which should prevent requesting data from
provider when data is already in repository didn't work
properly for pure historical non-intraday requests.
Fixed 3751 Account Trade execution pairing could be off if instruments had been
Performanc traded on different exchanges.
e
Fixed 3752 Charts Switching period value of non-intra day charts via toolbar
after error occurred on first request could leave chart blank.
Fixed 3755 Executions Removed executions could have been restored on next NT

© 2011 NinjaTrader, LLC


Release Notes 51

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".

NinjaTrader Version 7.0.0.15 Beta Release 15 - April 29, 2010


Status Issue # Category Comments
Fixed 3633 Charts Reloading historical data on PnF chart could have caused
some data to not display
Fixed 3637 General Adding account groups could crash NT if in Global Sim
Mode
Improved 3638 General Snfe RTH session template now uses "AUS Eastern
Standard Time" timezone
Fixed 3639 Market Market Replay could lock up NT if many ATM strategies
Replay were rapidly placed
Fixed 3640 General Reloading historical data on futures did not reload data from
previous expiry's
Fixed 3641 Charts PnF charts could have built downward bars beginning below
the low of previous bar instead of being below the high
resulting in gaps
Fixed 3642 Market Custom color conditions could have conflicted with hard
Analyzer coded color settings on certain columns (PositionSize,
ProfitLoss, RealizedProfitLoss, UnrealizedProfitLoss)
Fixed 3643 General Installer file used the wrong icon
Fixed 3644 Charts Prices on bars with 12:00 AM timestamp on rollover date
could be off when used in conjunction with a session
template with begin time of 12:00 AM in local PC timezone
Fixed 3645 Charts LineBreak bars could have built bars with data from future
bars
Fixed 3646 Charts Kagi, LineBreak, Renko could have had erroneous values
when viewing the bars between historical and live bars on
session breaks
Fixed 3648 Internal Session templates with special characters in the name
could throw off cache directory
Fixed 3649 Charts Ruler property dialog controls had 2nd and 3rd anchor
points reversed
Fixed 3650 Charts Crosshairs could have caused a ghosting effect on the x-
axis when a Bar series was removed from the chart
Fixed 3651 Session Session templates with single quotes could have cause
Manager errors
Fixed 3653 Charts Indicators with displacements > 0 could not be selected
when chart was scrolled behind the most recent bar
Fixed 3654 Charts Fibonacci templates did not save "Text location" property
settings when set to "Do not show"

© 2011 NinjaTrader, LLC


52 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Release Notes 53

historical data requests when there simply is no data


available
Fixed 3681 NinjaScript Exit on close orders could cause exceptions on strategies
Strategies with multiple series on the same instrument
Fixed 3682 General Reloading historical data for continuous future contracts did
not work properly
Fixed 3683 NinjaScript Getting and setting ChartStyle.Pen could cause crashes
Fixed 3684 NinjaScript Indicators using other indicators as their input series did not
Indicators work as expected when accessed in NinjaScript
Fixed 3685 Strategy Nested indicators in a strategy could cause issues on the
Analyzer Chart tab of the Strategy Analyzer
Fixed 3686 IQFeed Disconnecting from IQFeed would have resulted in
adapter IQConnect being closed. If IQConnect was started from a
different application this could have caused issues.
Fixed 3687 Backup/ Restoring backup files with database files greater than
Restore 256MB could have caused errors
Improved 3688 NinjaScript Setting ChartStyle.Pen is no longer possible. !!! Please do
not set the Pen object itself, instead use the explicit
properties of the Pen for this purpose.
Fixed 3689 Market PnL calculations for currency instrument were incorrect
Replay
Fixed 3690 Charts Trades not associated to a running strategy could have
been plotted on the chart in certain situations

NinjaTrader Version 7.0.0.14 Beta Release 14 - April 12, 2010


Status Issue # Category Comments
Fixed 3584 NinjaScript Did not properly recover their live orders on restoring after
Strategies NT restart which causes several issues in syncing when re-
enabling.
Fixed 3589 Charts Price type settings had not been maintained for indicator on
indicator as the data series was switched e.g. to a different
time frame
Fixed 3590 General Integrated RemoteSoft Protector V3.1
Fixed 3591 Historical Deleting exclusions for minute and ticks could destroy data
Data for that data unit in HDM, building a spike on chart.
Manager exclusions in grid were sorted wrong.
Fixed 3592 Market Didn't display data correctly on moving slider/switching
Replay period value when data begin time was before replay from
data
Fixed 3593 Charts Using Fibonacci templates could bring up log errors
Fixed 3594 Charts Entire date range scaling settings didn't work for indicator
series. chart objects on actual screen were included into
entire date range scaling.
Fixed 3595 Charts Performance graphs compressed could crash NT
Fixed 3596 Market There could be multiple requests to provider from
Analyzer instrument column on MA, even if instrument wasn't
supported by provider.
Fixed 3597 General NT could throw an exception on startup.
Fixed 3598 Strategy Periods tab: file names used for grid export etc. had not
Analyzer been reflective of the actually selected period type.

© 2011 NinjaTrader, LLC


54 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Release Notes 55

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

NinjaTrader Version 7.0.0.13 Beta Release 13 - March 31, 2010


Status Issue # Category Comments
Fixed 3566 MBT adapterRequests for tick data could yield error 26.
Fixed 3567 C2 adapter C2 adapter did not work properly.
Fixed 3569 Market Resolved inconsistency on handling accounts for NS
Replay strategies
Fixed 3570 General Resolved "AssemblyResolveEvent handlers cannot return
Assemblies loaded for reflection only" issue.
Fixed 3571 Time And T&S window did not persist the columns settings
Sales
Fixed 3572 Chart TraderThere could be rare conditions after minimizing/maximizing
Chart Trader where PnL had not been shown although
"Show PnL when flat" was set.
Fixed 3573 Executions Right click->Add execution would throw assert as the
tab license was a sim license.
Fixed 3574 ZenFire Filter "invalid" trades (like they happened on EUREX recently)
adapter
Fixed 3575 Charts On charts there could be a gap in data on session before
last day's session.
Fixed 3576 Historical User could not save modification after removing last
Data exclusion from HDM.
Manager
Fixed 3577 Strategy Bar series dialog in toolbar was not disabled in SA
Analyzer
Fixed 3578 Strategy Strategy performance window was left disabled after
Performanc pressing 'no' on question, if window should be closed on
e window removing strategy from chart.
Fixed 3579 Strategy SA could crash when chart open after backtest, and user
Analyzer changes instruments (clicks instruments in tree view) in

© 2011 NinjaTrader, LLC


56 NinjaTrader Version 7

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"

NinjaTrader Version 7.0.0.12 Beta Release 12 - March 24, 2010


Status Issue # Category Comments
Changed 3564 RemoteSoft Reverted back to RemoteSoft Protector V3 !! Please see
Protector notes in email announcement regarding implications
Fixed 3541 Charts Pivots and WoodiesPivots indicators could calculate pivots
wrong on defined combination of session definition and time
zones.
Fixed 3544 General NT now can handle negative realtime data.
Fixed 3545 Charts Reloading bars data could set auto scale of indicator to true
on multi-series charts when other than default session
template was applied.
Fixed 3546 Charts Bar series and indicators could be selected on different than
containing panel
Fixed 3547 Charts Price labels of indicators with "Calculate on bar close" set to
true could be off 1 bar on non equidistant charts. Price
labels showed up in wrong color on penultimate bar
Fixed 3548 Charts Indicator error messages in log could appear when realtime
chart containing indicators and strategies chart was closed.
Fixed 3549 Charts Timestamp of daily bars on chart didn't always reflect the
session end of the last to that daily bar associated intra-day
session.
Fixed 3550 Strategy Trades in Strategy Analyzer on a daily chart were placed on
Analyzer wrong bar index
Fixed 3551 Market Crash when reversing an ATM with a shadow strategy
Replay
Fixed 3552 WorkspacesRestoring workspaces containing multi series chart with
indicators on several series could throw exception in
indicators.
Fixed 3553 Charts Bars series for actual date could have wrong merge offset
when session beginning on pre-day(s) and today is rollover
date of the requested instrument

© 2011 NinjaTrader, LLC


Release Notes 57

Fixed 3554 Strategy Right click on Instrument/Optimizer/WalkForward grid-


Analyzer >Save had set some fixed timestamps and not the actual
timestamp.
Fixed 3555 Hot Key Hot Key Manager could crash when trying to remove a hot
Manager key on a collapsed group.
Fixed 3557 Session Calculation of time when contracts roll could be wrong,
Manager leading to gaps or missing sessions in data.
Fixed 3558 Basic Entry +/- buttons would no longer work after pressing them
multiple times rapidly.
Fixed 3559 Strategies Right click->Edit strategy->Cancel did change strategy
grid settings regardless.
Fixed 3560 Charts Disabling/enabling strategies did not properly live orders
attached to the prior instance of the strategy which resulted
in syncing issues on the new strategy instance.
Fixed 3561 Historical If all data rows for one node were 'excluded', changes
Data weren't saved, so data was still there.
Manager
Fixed 3562 MBT adapterRequests for daily historical data could yield error 26.
Fixed 3563 Market Panel height ratio were reset on moving slider
Replay

NinjaTrader Version 7.0.0.11 Beta Release 11 - March 18th, 2010


Status Issue # Category Comments
Fixed 3493 eSignal Added $TVOLQ to the list of non-supported instruments.
adapter
Fixed 3494 Session Pressing the Save button could cause exceptions.
Manager
Fixed 3495 Charts @RVI indicator wasn't working properly for
CalculateOnBarClose and realtime.
Fixed 3496 Strategy Data series parameter had not been saved if the results of
Analyzer an optimization on data series had been saved.
Fixed 3497 Session "CME US Index Futures ETH" session template was
Manager incorrect
Fixed 3498 Market Connecting to MR or rewinding could cause exception if
Replay there were charts opened with indicators on
Fixed 3499 IQFeed Now supports 2 digit year codes. !!! DTN/IQFeed users
adapter must use this version or later before March 31, 2010
Fixed 3501 NinjaScript Updated to latest version of the 3rd party editor component
Editor from ActiPro.
Fixed 3502 Strategy Summary tab did not always show correct values.
Analyzer
Fixed 3503 Strategy Hid detail tabs as "Instruments" tab is selected in Walk
Analyzer Forward mode.
Fixed 3504 Strategy "COMBINED RESULTS" could have had details tabs
Analyzer exposed.
Fixed 3505 Strategy "Combined results", "# of trades per day" was incorrect.
Analyzer
Fixed 3506 NinjaScript Multi plot indicators would cause exceptions as not all plots
indicators would be populated in each OnBarUpdate() call.
Fixed 3507 NinjaScript NS strategies having ToString() overwritten to return blank

© 2011 NinjaTrader, LLC


58 NinjaTrader Version 7

strategies would not be listed on chart->right click->Strategy


performance
Fixed 3508 BarChart. Realtime timestamps for currencies had been 10min behind
com adapter and could e.g. cause charts being off.
Fixed 3509 NinjaScript Multi series indicators could cause exceptions when added
indicators to a chart.
Fixed 3510 NinjaScript Restoring multi series NinjaScript strategies on restart could
strategies yield log errors, if the secondary series was one of those
which required special Add... methods
Fixed 3511 NinjaScript Persisting NS strategies could result in StrategyUpdateJob
strategies errors - object not being tracked.
Fixed 3513 Charts Changed candle chart style and open/close style to be
painted thinner, allowing to have thinner bars, and set default
to 3 instead of 2.
Fixed 3514 Strategy Chart trader enabled property was visible in chart properties
Analyzer in SA
Fixed 3515 Charts Mini instrument selected could be used when switching of
adding bar series or period type/value or instrument
shouldn't be possible
Fixed 3516 Charts VOL indicator could cause overflow exceptions.
Fixed 3517 T&S window Reset on properties dialog did not reset to factory settings.
Fixed 3518 Basic Entry "Set Default" on properties dialog did not work.
Fixed 3519 MBT adapterFixed bug on requesting historical data which would prevent
NT working with new MBT Nav 11.5.0.5
Fixed 3520 Charts Trade markers and executions could disappear from
receiving chart on scrolling on sending chart with global
cross hair
Fixed 3521 Chart TraderChart Trader orders were selectable even when out of panel
(price higher max or lower min of panel)
Fixed 3522 Charts Indicator labels were not displayed on non equidistant charts
when last bar of base series was right from last visible bar
Fixed 3523 Charts Anchor time of chart objects were displayed wrong in object
properties dialogs if anchor were outside of handled range
Fixed 3524 General Disconnecting while loading bars and reconnecting could
crash NT.
Fixed 3525 PFGBEST. Fixed a couple of issues related to block accounts. !!! An
com adapter updated PFGBEST.com client is required from our
website
Fixed 3526 PFGBEST. Tools->Options->Ok would reset values on Accounts tab.
com adapter
Fixed 3527 NinjaScript Multi-series NS strategies had not been properly synced up
strategies on their first few bars.
Fixed 3528 Chart NT could crash when chart was opened with session
definition with begin time or end time in daylight saving time
Fixed 3529 Market Executions in market replay could disappear when period
Replay value was switched
Fixed 3530 Strategy Walk Forward tab will now display trades for multi series
Analyzer strategies.
Fixed 3533 Charts Daily bars on realtime were built incorrectly, breaking up on
midnight instead of the session borders.
Fixed 3534 SuperDOM SuperDOM did not update Instrument in Entry Parameters

© 2011 NinjaTrader, LLC


Release Notes 59

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

NinjaTrader Version 7.0.0.10 Beta Release 10 - February 23rd, 2010


Status Issue # Category Comments
Fixed 3447 NinjaScript Multi series indicators could cause GetMinMaxValues
indicators exceptions when applied to a chart.
Fixed 3448 Charts Reset on chart properties now does not reset panel
properties. reset on chart panel properties now does not
reset chart properties.
Fixed 3449 Strategy In the Strategy Analyzer Data Series dialog it was not
Analyzer possible to modify the base period type of a strategy
backtest when there was a default set for the according
period type.
Fixed 3450 NinjaScript BarsAgo properties (e.g. StartBarsAgo, EndBarsAgo) on
IDrawObjects (e.g. ILine) didn't work properly on manual
drawn objects.
Fixed 3451 Charts Pasted chart objects could change slope when pasted on
logarithmic scale.
Fixed 3452 Charts The historical part of strategies on chart was not executed.
Fixed 3453 Charts Scaling margins didn't work properly on panels with very
small min/max difference.
Fixed 3454 Chart Pivots and WoodiesPivots didn't show correct values when
indicators calculated from daily bars and session was over midnight
for local session settings
Fixed 3455 Chart ZigZag indicator was calculated to the last visible bar only
indicators (not to the last existing), making it's lines change when
applied on historical part of chart and scrolled to right
Fixed 3456 NinjaScript DrawRectangle(...) and DrawRuler(...) in indicator and
DrawRuler(...) in strategy didn't work when there was a
default object definition in place for the object.
Fixed 3457 Historical Merging continuous contracts: sessions reaching over 12:00
Data AM of rollover date (in session definition time zone) are now
Manager included into the following contract, so complete session is
merged from following contract.
Fixed 3458 Historical The continuous contract merge feature for futures from our
Data data server did not merge accurately on all occasions

© 2011 NinjaTrader, LLC


60 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Release Notes 61

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.

NinjaTrader Version 7.0.0.9 Beta Release 9 - February 10th, 2010


Status Issue # Category Comments
Improved 3425 External External adapter now supports "random" mappings for
adapter currencies.
Changed 3434 Strategy Enums on strategies could cause issues when optimizing
Analyzer the strategy.
Fixed 3417 Hot Key Applied more restrictions in regards to valid key
Manager combinations.
Fixed 3421 Historical Grid->Export to Excel, file name not labeled by current date/
Data time.
Manager
Fixed 3422 NinjaScript Add(Instrument.Fullname...) did not work for multi-series
indicators indicator on MA.
Fixed 3423 Charts Non intra-day charts with period type > daily (e.g. weekly,
monthly, ...) didn't update on some connections.
Fixed 3424 Chart TraderChart trader button was enabled in SA after loading any
chart template
Fixed 3426 Charts Reload historical data could produce gaps in data on chart
Fixed 3427 Strategy Moving instrument in SA when chart template containing
Analyzer indicators on SA was applied crashed NT.
Fixed 3428 Charts Woodies pivots and pivots indicators could display different
values after pressing F5 on chart
Fixed 3429 Charts 'Indicator on indicator' did not work but threw exceptions.
Fixed 3430 Market NT could lock up on rapid order submission on replay.
Replay
Fixed 3431 Strategy Ctrl+M always opened the email dialog for the chart tab
Analyzer although a "grid" tab was topmost.
Fixed 3432 Session Session templates having one session only and starting on
Manager Sunday could be flawed.
Fixed 3433 Market Indicator did not maintain their custom settings when
Replay connecting to replay or on rewind.
Fixed 3435 Charts Revised automatic scaling of chart panels to bar series,
indicators and chart objects.
Fixed 3436 NinjaScript Properties having .NET objects like System.Drawing.Pen
strategies caused exceptions while persisting/restoring.
Fixed 3437 NinjaScript BarsSinceExit/Entry logic was off as multi series had been

© 2011 NinjaTrader, LLC


62 NinjaTrader Version 7

strategies on the same instrument.


Fixed 3438 Indicators Make sure OnStartUp() is called before the non-NS methods
GetMinMaxValues() and Plot() are called.
Fixed 3439 Strategy Added back the the same consistency checks on
Analyzer parameters which had been in place with 6.5
Fixed 3440 Charts Opening a chart with to date far in the future could cause
exception
Fixed 3441 Charts Switching period value of bars on futures with merge
settings while connected could result in faulty request to
data server
Fixed 3442 Market Settings the replay slider to beginning could move indicators
Replay to lower panel
Fixed 3443 Charts Strategies buttons on toolbar context menu were enabled
when connected though they should not be.

NinjaTrader Version 7.0.0.8 Beta Release 8 - February 2nd, 2010


Status Issue # Category Comments
Added 3414 NinjaScript Introduce an "OnStartUp" method which is called after
Initialize() but before any other event method call
Fixed 3396 ATM ATM strategies with no live orders had been recovered
Strategies inadvertently.
Fixed 3397 Hot Key Hot Key Manager still accepted CTRL+O/Z/A is typed in.
Manager
Fixed 3398 Market Strategies tab only should have "Replay101" selectable
Replay when connected to replay
Fixed 3399 Charts Reset in chart properties wasn't working properly
Fixed 3400 Charts Chart didn't scale to horizontal lines with AutoScale = true
Fixed 3401 NinjaScript FirstTickOfBar logic was broken.
indicators
Fixed 3402 Strategy SA had incorrect short cut for Right click->Edit
Analyzer
Fixed 3403 General Internal bars storing logic could be off on first bar of 16 bars
group when smallest difference of incoming prices are
smaller than tick size.
Fixed 3404 Market Applying a template with TotalRowEnabled to an MA where
Analyzer already has TotalRow enabled would throw an error.
Fixed 3405 Market Row positioning could be off when pressing F5 while blank
Analyzer rows had been on the MA.
Fixed 3406 Charts Intra day charts with sessions reaching over midnight build
first bars of rollover date (futures & sessions merge back
adjusted) or split/dividend adjusted value change date
(stocks & split and/or dividend adjust setting) wrong.
Fixed 3407 Chart TraderChart Trader context menu was only working properly when
bar series was on first panel
Fixed 3408 NinjaScript SubmitLive could submit exit orders with the same OCO ID.
strategies Now the strategy ID is attached to make the OCO ID unique.
Fixed 3409 Charts Price label for historical bar series wasn't painted for most
bar types.
Fixed 3411 PFG adapterFilter fills starting with "BACKUP"
Fixed 3412 NinjaScript Duplicate bars series now should work as expected.

© 2011 NinjaTrader, LLC


Release Notes 63

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

NinjaTrader Version 7.0.0.7 Beta Release 7 - January 27th, 2010


Status Issue # Category Comments
Improved 3338 Market Optimized historical data loading to prioritize requests with
Analyzer the longest look back period
Improved 3381 Simulator "Enforce immediate fills" is now effective on Currencies
Changed 3328 Instrument Local rollover offsets now only are overwritten as the
Manager contract months match in their rollover date.
Changed 3332 NinjaScript Added 1 to column and line numbers of the inline syntax
Editor checking errors to sync with the line/column numbers
provided by the actual compiler.
Changed 3361 Hot Key CTRL-Z, O, A no longer are valid hotkeys. CTRL-Z, I are
Manager hard coded to zoom in/out charts.
Changed 3389 Data Volume display now follows condensed formatting (e.g.
box\Market 0.01M instead of 10000)
Analyzer
Fixed 3283 General Introduced handling to avoid 'Collection was modified and
NullReferenceException' e.g. on Restore.
Fixed 3287 PFG adapterNT now filters unknown instrument types
Fixed 3288 Charts Exception when removing an object drawn by indicator or
strategy
Fixed 3289 Charts Placing anchors and moving objects didn't work properly
when drawn into right chart margin
Fixed 3290 NinjaScript Right click->Performance Viewer chart no longer holds any
strategies indicator from the underlying strategy
Fixed 3292 Charts Moving draw objects with more than one anchor left from
first bar wasn't working as expected
Fixed 3293 Strategy Save default for strategy did not save FillType,
Analyzer OptimizationType and OptimizationMethod
Fixed 3294 Charts Indicator on indicator where input was not pulled from
default plot0 did not work as expected.
Fixed 3295 Charts Exception when selecting ER2 on instrument lookup.
Fixed 3296 Charts When setting Label property of data series to empty string, it
does not work.
Fixed 3297 Market Custom label set in grid were not maintained if the .Name
Analyzer property was set in Initialize()
Fixed 3298 Charts Pressing "Set Default" on the chart shape properties dialog
would close the form.
Fixed 3299 Market Timestamps of recorded L2 data could be off since as
Replay session are rolled.
Fixed 3300 Market Changing an instrument by editing the respective cell would
Analyzer throw of label row management and results in exceptions on
saving the workspace

© 2011 NinjaTrader, LLC


64 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Release Notes 65

objects series bar series with lots of objects on.


Fixed 3325 General NT could lock up as replay data is downloaded and another
replay/historical data request was issued.
Fixed 3326 Chart Indicators with negative z-order could plot onto other panels
indicators than that which they are placed on.
Fixed 3327 Market L2 data was not recorded correctly as the data files rolled
Replay midnight EST.
Fixed 3329 Instrument Roll over offsets had not been calculated and persisted
Manager correctly if the future was not traded on Globex.
Fixed 3330 Instrument Sim feed start price was rounded to the nearest integer.
Manager
Fixed 3331 General Bootstrap installer setup.exe now comes with major version
7
Fixed 3333 Charts Reintroduced tolerance on loading bars when beginning of
requested bars is 4 days before first bar.
Fixed 3334 Chart Drawing regression channel on panel without bars didn't
objects work
Fixed 3335 Charts High/Low values for Renko bars had been off.
Fixed 3336 General Logic which should avoid unnecessary requests to provider
between historical data and pool data was broken for non
intra day.
Fixed 3337 Alerts Alert was swallowed when a workspace with a chart on
instrument was restored, which was not in database.
Fixed 3339 Charts Changing instrument on chart on typing instrument name +
exchange (e.g. 'GLD ARCA') ignored the exchange.
Fixed 3340 Chart Selecting an object, and using mouse wheel while outside of
objects chart brings up exception.
Fixed 3341 NinjaScript DrawRegion(...) called from strategy didn't work properly
strategy when only called once.
Fixed 3342 Chart Copy/paste of global chart objects didn't insert the object
objects properly on different charts than one, on which the copy/
paste is executed.
Fixed 3343 DTN adapterImprove handling as user has setup incorrect user/pwd in
account connections.
Fixed 3344 Executions "Price" column no longer is editable, but now shows prices
grid formatted correctly.
Fixed 3345 Chart Andrew's pitchfork lines could be plotted incomplete and
objects labels could have missed if anchors of objects were outside
of visible chart.
Fixed 3346 Market Order status events did not come in right sequence.
Replay
Fixed 3347 NinjaScript Resolved some persistence issues as strategies had
strategies properties with a custom type.
Fixed 3348 Charts Changing bar series period value while logarithmic scale is
set on a panel could bring the y positioning of objects or
orders (chart trader) off.
Fixed 3349 Market Fixed several problems in market replay
Replay
Fixed 3350 Historical Download tab could crash as there were instrument list with
Data the same instrument on different exchanges.
Manager

© 2011 NinjaTrader, LLC


66 NinjaTrader Version 7

Fixed 3351 Historical Instrument lists removed by Tools->Instrument manager


Data had been reflected in the download tab
Manager
Fixed 3352 SuperDOM In real slow markets, the DOM prices would not render until
ask price had been seen
Fixed 3353 Data grids Grid->Save as did not save the first column.
Fixed 3354 Chart TraderThe "hand" icon (when order is selected) was not reset as
the order was filled before clicking again.
Fixed 3355 Charts Labels of x axis on intra day charts could overlap or
disappear on extreme zoom out.
Fixed 3356 NinjaScript MaximumBarsLookBack settings did not make it to the
hosted data series.
Fixed 3357 MBT adapterOvernight position had not been reflected properly.
Fixed 3358 Session Session manager now displays the time value without the
Manager seconds fraction.
Fixed 3359 Chart Moving drawing objects far into the future didn't work for
objects multi series charts with very large time range
Fixed 3360 IQFeed Added checks to the account connection wizard to make
sure user/pwd are not empty.
Fixed 3362 Charts Line Break charts requested with bars back could be build
with too few bars on first request.
Fixed 3363 Charts Y value e.g. of cross hair could be off on logarithmic scale
after zoom in/out or scroll.
Fixed 3364 NinjaScript There had been some legacy references to "Category"
indicators which had been replaced by "GridCategory"
Fixed 3365 Market Market analyzer templates with column type 'TimeLastTick'
Analyzer weren't migrated properly on migrate from NT6.5 to NT7.
Fixed 3366 General Consecutive backups did not work.
Fixed 3367 Chart Ruler chart objects did measure the between the 1st and
objects 3rd anchor instead of the 1st and 2nd on equidistant charts.
Fixed 3368 Charts Charts didn't move to correct position when connecting to
MR or connecting to provider (e.g. SimFeed) after MR
Fixed 3369 Charts First session with session definition on same day as live
session was missing if end of session had same timestamp
as beginning of actual live session
Fixed 3370 Market Fixed issues related to total row
Analyzer
Fixed 3371 Market Market Replay on several consecutive days now loads data
Replay before actual replay day from repository when slider is
moved.
Fixed 3372 Chart TraderSim stop order were not visualized on Market Replay.
Fixed 3373 General Some captions did not have a form on 64bit Win7.
Fixed 3374 Market On Goto or Rewind indicators are now completely
Replay recalculated.
Fixed 3375 Charts Applying chart template with pivots indicator (which
calculates pivots from loads daily series) on chart with
session different than template session could crash NT.
Fixed 3376 NinjaScript Multi-series NinjaScript no longer allows duplicate bars
series.
Fixed 3377 Charts Reloading chart/switching period type/value on chart could
build spike when it was running into next session on live

© 2011 NinjaTrader, LLC


Release Notes 67

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

NinjaTrader Version 7.0.0.6 Beta Release 6 - December 21st, 2009


Status Issue # Category Comments
Added 3265 IB adapter Added support for SFB and OMX exchanges and SEK
currency.
Improved 3198 Strategy Select strategy settings are maintained in the strategy grid
Analyzer after compiling
Improved 3207 IQ Feed Updated to latest IQFeed API which supports 64-bit. Users
adapter must upgrade to 4.7.0.3 IQFeed Client Software and add
their user name/password to the Connection Wizard.
Changed 3228 Charts HeikenAshi now supports the same chart styles as minute
bars.
Fixed 3166 PFG adapterNow would reset internal position calculations and order
states on server reset. Users must upgrade to latest
PFGBEST.com API
Fixed 3194 General Global sim mode did not work as expected.
Fixed 3195 Help Guide Help window still was modal to CC, when activated by Help-
>Help

© 2011 NinjaTrader, LLC


68 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


Release Notes 69

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

© 2011 NinjaTrader, LLC


70 NinjaTrader Version 7

Fixed 3249 Charts Replaced Renko implementation by user contributed code.


Fixed 3250 Charts Chart settings on workspace could be overwritten with chart
defaults on open/switch workspace.
Fixed 3251 General Revised NT internal help system
Fixed 3252 Session Session definitions which would fall into the "1 hour gap" on
Manager switching from standard to daylight saving time could cause
exceptions.
Fixed 3253 Charts Bar series with period type days 2 and higher (also weekly,
monthly, ...) could have been build wrong for futures
instruments with merge settings true and for series build to
the actual date.
Fixed 3255 Data server Requests for historical data could kill the connection in case
the instrument was not in the server repository.
Fixed 3256 Charts Rolling the from data of bar series on charts didn't work
properly for charts which left open over midnight.
Fixed 3257 Charts Fixed scale is not reset to automatic when reloading
historical data, on connect or when a new bar series is
added.
Fixed 3258 General Enhanced tracing during db migration NT6.5 -> NT7
Fixed 3259 Historical Memory leak when import tick data if generate minute or
Data daily bars was checked.
Manager
Fixed 3260 Market Rewinding/restarting did not properly restart running
Replay strategies and could result in DB errors.
Fixed 3261 Charts Using a chart template with fixed panel scale which was
saved during e.g. German language settings active could
screw panel scaling.
Fixed 3262 IB adapter A 60 day request for 1 minute data could have forced pacing
violations.
Fixed 3263 Charts Chart panel properties: setting a horizontal grid line value
and setting a very high value for Fixed max right could hang
NT.
Fixed 3264 Database Opening a database with file size larger than 256 MB did
crash NT. Also migrating from a NT6.5 database with size
larger than 256 MB did not work.
Fixed 3266 Charts Global cross hair displayed two y axis price labels with price
label being off on receiving charts.
Fixed 3267 Drawing Inside right property of Fibonacci extension didn't work
objects properly if extend right was set to false.
Fixed 3268 Charts Pivots and WoodiesPivots: Loading the additional daily data
series could screw up NT internal series management.
Fixed 3269 Charts Avoid super fluent bars requests from provider/repository on
applying chart template on new chart.
Fixed 3270 Market Cell color conditions did not work as expected
Analyzer
Fixed 3271 Charts Copy/paste of drawing objects didn't work properly on
equidistant charts with non equally distributed bar times (e.
g. 10.000 volume)
Fixed 3272 General License restrictions did not always apply as license
changed from sim to direct edition.
Fixed 3273 Market Moving slider in MR could remove chart object which should

© 2011 NinjaTrader, LLC


Release Notes 71

Replay be drawn by indicator/strategy on last bar of chart or


execution which should be created by strategy also on last
bar of chart.
Fixed 3274 Charts Changed the sequence on which side of the receiving chart
(which both scales) the value from the sending chart (which
both scales) is displayed.
Fixed 3275 Charts If scale was reset from fixed to automatic and new label
width was smaller, there could have left a white margin
which was too large.
Fixed 3276 Chart TraderChart Trader bid/ask labels had not been reset properly as
data series was toggled which could result in "delayed"
updates.
Fixed 3277 BarChart Updated to latest BarChart API to support exchange native
adapter timestamps.
Fixed 3279 Charts Chart objects on first bar weren't displayed.
Fixed 3280 Charts Bars # in display box of ruler chart object could be off when
moving on equidistant charts, e.g. 1000 Volume.
Fixed 3281 Market Moving slider on MR with strategy active on non equidistant
Replay chart removed all executions and trade lines.
Fixed 3282 Basic Entry Increase/Decrease buttons did not work as expected
Fixed 3284 Charts Price marker was incorrectly formatted if on the left scale on
not the 1st series added to the panel
Fixed 3285 Market Corrupted data files could result in an inability to connect
Replay

NinjaTrader Version 7.0.0.5 Beta Release 5 - December 1st, 2009


Status Issue # Category Comments
Added 3061 Charts Added "Wick" pen to candle chart style.
Added 3139 Charts Added back chart template concept
Added 3062 Drawing Fibonacci circle supports optional 'scale Time and Price
objects values independently'
Added 3076 Drawing Improved behavior of Fibonacci Templates
objects
Added 3079 NinjaScript Added GetCurrent...(barsSeriesIndex) methods.
indicators
Added 3094 Historical As HDM grid is loaded the respective lowest level node in
Data the tree would get a suffix like “05.11.2009 (12345 items)”.
Manager
Added 3121 Charts Line Break and Renko bars will now update in realtime using
an incomplete last bar.
Improved 3058 Charts Improved BarTimer indicator.
Improved 3068 Database Added workaround to the resolve the "Failed to execute DB
job 'executionUpdateJob': ObjectSpace:Entity Object not
being Tracked " log errors.
Improved 3069 NinjaScript Improved low level session handling by providing Session.
GetNextBeginEnd. Also: NT internal Begin/EndTime no
longer is accessible
Improved 3070 NinjaScript NS strategies now would "tolerate" DateTime and enum
parameters.
Improved 3077 Session Added UTC (Coordinated universal time) to the list of

© 2011 NinjaTrader, LLC


72 NinjaTrader Version 7

Manager available time zones.


Improved 3101 Charts You now could type "XXX NYSE" to create XXX stock
instrument in Nyse.
Improved 3132 Drawing Fibonacci Templates and Properties Enhancements
objects
Improved 3152 NinjaScript Added exceptions in case of barsAgo > 255 for
MaximumBarsLook.256
Improved 3165 PFG adapterUpdated to latest 1.0.434
Changed 3149 Help Guide F1 help no longer is modal.
Changed 3171 TT adapter LastClose is now derrived from SettlementPrice vs
ClosingPrice
Fixed 3059 Historical If import a new instrument without clicking on the export/edit
Data tab; after a successful import the new instrument will be the
Manager only instrument shown until HDM restarted.
Fixed 3060 IB adapter Made sure AccountUpdate events only would be subscribed
for a new account after unsubscribing from old account
Fixed 3063 Market Changed the min/max of the date time control in market
Replay replay Goto dialog to 01/01/1800 and 12/31/2099.
Fixed 3064 Charts Chart objects drawn from an indicator could move panel
when other indicators have been deleted.
Fixed 3065 Charts Deleting indicator when chart objects/global chart objects on
higher panel could result in blank panels.
Fixed 3066 General Tools->Account connection->Close button had incorrect tool
tip.
Fixed 3067 Charts Remove panel on chart panel context menu didn't work
properly.
Fixed 3071 Charts Global chart objects could disappear on closing charts.
Fixed 3072 Charts Bar index could be off after switching equidistant property on
single series.
Fixed 3073 Charts Bar spacing could change on restore of non equidistant
chart with non equidistant chart template applied.
Fixed 3074 Charts Removed flickering in OHLC chart style when moving
canvas or clicking on chart
Fixed 3075 Indicators If indicator 'Label' is empty, indicator class name is used in
the UI.
Fixed 3078 General eSignal and IQFeed did not run as 32bit application on 64bit
windows
Fixed 3080 Charts Avoid redundant confirmation boxes on reloading historical
data.
Fixed 3081 Charts AutoScale on line types could crash NT on multi series
charts.
Fixed 3082 Charts NT could crash at connect/reload on multi series charts with
global chart objects on.
Fixed 3083 Charts Exception when trying to remove global chart objects on
multi series chart when there were several series with same
instrument on chart.
Fixed 3084 Database Tried to work around 'SQL Server Compact timed out
waiting for a lock' messages
Fixed 3085 Drawing Andrews pitchfork attached to a bar series could disappear
objects from chart when period value was switched.
Fixed 3086 Charts Executions from strategy on a multi series chart were not

© 2011 NinjaTrader, LLC


Release Notes 73

displayed on >= 2nd series when several series of same


instrument on chart.
Fixed 3087 Charts Chart region could disappear on multi series charts.
Fixed 3088 Charts removing of a bar series from multi series chart while
strategy running on chart could crash NT.
Fixed 3089 NinjaScript Amended existing 'Enabled' message. Added 'Disabled'
Strategies message.
Fixed 3090 Charts MultiColor Plot no longer works as expected in NT Beta 4
Fixed 3091 Drawing Left/Right alignment of fib levels not all aligned and changes
objects as you pan the chart
Fixed 3092 MBT adapterSeveral fixes on historical data requests.
Fixed 3093 Historical Delete Edit Logs node causing exception
Data
Manager
Fixed 3095 Charts Multi series indicator running on secondary series of a chart
loaded it's non primary series using instrument session and
not the session on chart.
Fixed 3096 Charts EquidistantBars property on multi series charts could be set
to true in chart properties after reset.
Fixed 3097 Chart TraderSwitching of instrument when chart trader enabled didn't
change the display of PnL appropriately.
Fixed 3098 Charts Strategies on chart haven't been removed when base bar
series was removed from chart.
Fixed 3099 NinjaScript Changed alignment of DrawTextFixed back to left aligned
(NT6.5 logic).
Fixed 3100 Charts LineOnClose chart style could crash NT when there were
no bars on chart.
Fixed 3102 Export to Export to excel throws exception when row count exceeds
Excel 65535 rows.
Fixed 3103 Market .Name property was not respected in all situations.
Analyzer
Fixed 3104 Charts DrawRegion and DrawText in indicator and strategies didn't
set area color to empty when default had been set to some
color.
Fixed 3105 Strategy Trades tab ->Right click-> chart did not respect chart series
Analyzer default settings
Fixed 3106 Charts Last bar of non intra-day chart with bars which contained
more than 1 day (e.g. 3 day, week, month) was missing.
Fixed 3107 Charts Extreme zooming out on non equidistant charts could result
in white chart.
Fixed 3108 General Typing some instrument text could crash NT
Fixed 3109 Charts Switching period type with mini instrument selector didn't
switch to first supported chart style when old chart style
wasn't supported.
Fixed 3110 Charts Arrow on top right of chart when chart not on last bar and
bar series price label could be off on ask/bid realtime charts
Fixed 3111 Charts Non equidistant chart with only one bar on it could crash NT.
Fixed 3112 NinjaScript IOrder parameter on OnOrderUpdate could have been
Strategies NULL.
Fixed 3113 Sim account Sim account did not work as expected on multi connection
setup

© 2011 NinjaTrader, LLC


74 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


Release Notes 75

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

© 2011 NinjaTrader, LLC


76 NinjaTrader Version 7

adapter Indices. Updated the Google Adapter to take these changes


into account.
Fixed 3173 Account Commission is displayed as % on the account
performance performance/trades tab. Will now match 6.5
implementation.
Fixed 3175 Printing Replaced all print dialogs by 64bit compatible version
Fixed 3176 Market Moving slider or right click->GoTo did not work as strategies
Replay have been running on the strategies grid.
Fixed 3177 NinjaScript IDataSeries now has a .IsValidPlot(int barIdx) method.
Fixed 3178 Strategy DataSeries->Value parameter was hidden inadvertently.
Analyzer
Fixed 3179 Charts Moving objects in the near of session break off non
equidistant charts (before following/after previous) session
break didn't work properly.
Fixed 3180 Control Changing pip size not reflected in limit price changes on
Center Control Center.
Fixed 3181 NinjaScript Fixed couple of issues related to back/bar/candleOutline
Strategies color on chart tab
Fixed 3182 Charts Modified icons for toolbar. Additionally added 'box' chart style
toolbar menu item.
Fixed 3183 Order entry When orders are being partially filled, changes to limit prices
are being overwritten.
Fixed 3184 Drawing Regression channel didn't work properly on multi series
objects charts with different bars #.
Fixed 3185 Charts Snap to price/snap to bar & price didn't work properly when
different scales (with different price ranges) on same panel
Fixed 3186 Drawing Flat wide triangles drawing objects with high pen width had
objects spikes on either side which are now cut.
Fixed 3187 General Avoid unnecessary log errors if NT is running in a multi
connection setup and one connection it shut down.
Fixed 3188 Charts Strategy toolbar item was displayed as enabled while not
connected or chart trader visible.
Fixed 3189 Charts Calculation of panel margins didn't work properly.
Fixed 3190 Google Disabled pseudo market data, since there is no predictable
adapter way to parse the HTML text.
Fixed 3191 Historical Meta Stock import didn't work when executed more than
Data once from the same HDM
Manager
Fixed 3192 Charts Max zoom out factor on non equidistant charts could be
different depending how fast mouse was moved.
Fixed 3193 Data server Misc. issues on data server

NinjaTrader Version 7.0.0.4 Beta Release 4 - November 4th, 2009


Status Issue # Category Comments
Added 3034 Market Available data in the Market Analyzer is now displayed in a
Analyzer multi-level grid
Added 3041 Charts Changed Kagi bars to use an updatable incomplete bar with
realtime data
Added 3056 Indicators Added property InHitTest to indicators to give the user
flexibility to leave out drawing objects from the indicator's

© 2011 NinjaTrader, LLC


Release Notes 77

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

© 2011 NinjaTrader, LLC


78 NinjaTrader Version 7

objects logarithmic scaling.


Fixed 3015 SuperDOM Several SuperDOM Issues
Fixed 3016 Drawing Select the fib tool and try to draw a retracement, the pen
objects cursor and the bottom of the retracement value are off quite
a bit.
Fixed 3017 Historical HDM edit tab was only deleting cache data when deleting
Data the root node not all associated data.
Manager
Fixed 3019 Charts Multiple session definitions on actual data could result in
missing data on chart.
Fixed 3020 Charts X axis could show too few labels on split sessions (multi
sessions per day)
Fixed 3021 SuperDOM On placing an order in the SuperDOM the instrument combo
box would have focus
Fixed 3022 Charts Sync up chart trade PnL and PnL on position on chart.
Fixed 3023 Automated Multi connection strategy could cause exception
Strategy
Fixed 3024 Strategy Compiling a strategy did not update the strategy properties
Analyzer
Fixed 3025 Strategy Combined results: ProfitFactor no longer is a weighted
Analyzer average but GrossProfit/-GrossLoss
Fixed 3026 Strategy Improvements on SA, MonteCarlo simulation
Analyzer
Fixed 3027 Strategy Backtesting a basked of instruments could not be aborted.
Analyzer
Fixed 3028 Chart TraderSelected strategy was not restore on reconnected.
Fixed 3029 General Quantity control could cause an exception.
Fixed 3030 Indicators Overhauled .Line style plotting to avoid funny rendering on
chart compression
Fixed 3033 .NET If .net draws dash-dot-dot-…, the line would look like a dash
when chart is scrunched.
Fixed 3035 Charts Handling bar series with very large days back value on multi
series chart could crash NT.
Fixed 3036 Charts Detection if same series already on chart on typing in period
value only didn't work properly on futures.
Fixed 3037 Charts Toolbar button displayed selected chart style wrong on hi lo
bar chart style and on ohlc chart style.
Fixed 3038 Indicators Reduced the y margin on top and bottom of indicators.
Fixed 3039 Indicators Labeling for Heiken-Ashi incorrect for periods greater than
1.
Fixed 3040 Charts Point and Figure not updating properly when Box Size = 1. If
you use 1x3, you still get a two by two movement.
Fixed 3043 Charts Objects drawn by indicator or strategies could be off on
multi series when not based on first bar series.
Fixed 3044 Charts Chart data on preday could have been missing on a session
definition spanning over midnight and having empty days (e.
g. 24/5).
Fixed 3045 Market Allow setting value before min date/after max date in replay
Replay connection -> goto dialog and popup error message if
before min/after max time.
Fixed 3046 Account Trade pairing could be off in using the same entry execution

© 2011 NinjaTrader, LLC


Release Notes 79

Performanc multiple times.


e
Fixed 3047 Indicators ZigZag indicator didn't show up as selected when it was
selected.
Fixed 3048 Charts LineOnClose chart style on empty chart yielded 'Parameter
is not valid' message in trace.
Fixed 3049 Drawing Copy and paste of a triangle not the same size and shape.
objects
Fixed 3050 Drawing Context menu for Fib Templates still visible for pitchfork and
objects gann fan properties.
Fixed 3051 Drawing Text chart object defaults not being restored properly
objects
Fixed 3052 Historical Tick sizes that have more than 4 significant figures are
Data being condensed in the edit grid of the HDM
Manager
Fixed 3053 Charts Changing period type via toolbar could crash NT when
saved default settings for period type existed.
Fixed 3054 Charts Chart objects drawn from indicators/strategies could have
been missing/on wrong panel when default settings had
been applied to chart object.
Fixed 3055 FX Pro FXPro did not maintain the selected account in a multi-
connection setup

NinjaTrader Version 7.0.0.3 Beta Release 3 - October 26th, 2009


Status Issue # Category Comments
Added 2948 NinjaScript Added LongSeries class
Improved 2960 NinjaScript NinjaScript Output window now would report an error
output message if output exceeded maximum threshold
window
Changed 2953 Instrument Instrument type combo box now is disabled in edit mode.
Manager
Changed 2955 PFG adapterTmp tick files created by PFG API are maintained in <my
documents>/tmp and only deleted on next NT restart.
Changed 2974 Charts Added back display update property
Changed 2976 Charts Removed PlotSessionBreaks property from charts.
Fixed 2922 Indicators Indicator plots with plot style square could disappear when
zoomed very far out.
Fixed 2923 Charts Mouse movment in x/y axis panned chart panned chart
instead of zooming after any dialog opened from shortcut
keys.
Fixed 2924 Charts Resize of chart on non equidistant bars didn't change the
displayed time range
Fixed 2925 Charts Changed chart panel property and description 'vertical grid
line interval' to 'horizontal grid line interval'.
Fixed 2926 Charts Bar series which is dragged and dropped is put on the same
scale justification as an already existing bar series on the
same panel.
Fixed 2927 Charts Box Style has leading box overlapping the prior box right
edge.
Fixed 2928 Charts Different bar series didn't get different z orders.

© 2011 NinjaTrader, LLC


80 NinjaTrader Version 7

Fixed 2929 NinjaScript Assigning .Panel property to indicators hosted by strategies


strategies did not work.
Fixed 2930 eSignal Requests for historical data starting before 1991 could yield
adapter unexpected results.
Fixed 2931 General NT could throw an exception when entering smaller letters in
the strategies grid dialog.
Fixed 2932 ZenFire Market data subscriptions on ZenFire did not work when
adapter instruments having multiple exchanges had been toggled by
link button.
Fixed 2933 Charts Chart Data Box not displaying some executions on a multi-
series chart
Fixed 2934 Charts Chart->Image->Send mail could fail if working directory was
<program files>.
Fixed 2935 Session Session manager would not allow a session crossing
Manager Sunday 12AM.
Fixed 2936 Charts Fibonaccii properties exception when turning on 'Extend left'
checkbox.
Fixed 2938 Historical Downloading historical data from our server could yield
Data UnauthorizedAccess exceptions on deleting the tmp files.
download
Fixed 2939 Charts Period value was not applied as selcted when changing
interval/period type from toolbar.
Fixed 2940 NinjaScript NinjaScript strategy persistence did not work as expected.
strategy
Fixed 2942 Charts Changing chart hot keys while chart was open might not
have been effective.
Fixed 2943 Charts Several session definitions on actual data could result in
missing data on chart.
Fixed 2944 Migration Migrating the 6.5 DB did not properly terminate and could
cause severe issues e.g. on connecting in NT7
Fixed 2945 Charts Editing horizontal line properties in dialog during time out of
session didn't work
Fixed 2946 Charts Chart horizontal line's autoscale property didn't work.
Fixed 2947 Charts IndicatorBase.BarsRequired did not work as expected on a
multi-series chart.
Fixed 2949 Market MA/Indicator columns: Plots have not been restored
Analyzer correctly on MA recovery and on applying templates.
Fixed 2950 Charts There could be gaps on chart on bar series with same
session definition and completely zoomed out.
Fixed 2951 Charts DrawTextFixed does not properly draw the background color
behind the text.
Fixed 2952 Charts Text focus w/ Edit Text Draw Tool
Fixed 2954 Data Merging data on continuous contracts could crash NT when
Manager latter contract contained no data
Fixed 2956 Strategy Several fixes on SA
Analyzer
Fixed 2957 Charts Global chart objects always had 'right' scale justification
Fixed 2958 Charts Settings of BarColor on CandleOutline chart style on one
bar affected all following bar's outline color.
Fixed 2959 Strategy Several issues on the GeneticOptimizer
Analyzer

© 2011 NinjaTrader, LLC


Release Notes 81

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

NinjaTrader Version 7.0.0.2 Beta Release 2 - October 19th, 2009


Statu Issue Category Comments
s #
Added2838 IB adapter Added support for VSE (Vienna Stock Exchange)
Added2853 NinjaScript .Name property can be set in Initialize() as a new approach to the
prior deprecated Display Name concept
Added2872 Charts Fibonacci draw object user defined templates
Added2921 Charts Added Box chart style
Added2844 T&S window Columns can now be visually enabled/disabled
Impro 2828 NinjaScript NS strategies overfill handling only would be triggered once per

© 2011 NinjaTrader, LLC


82 NinjaTrader Version 7

ved strategy to void lockup due to redundant strategy handling on


subsequent order events.
Impro 2859 Strategy The Summary tab now displays the actual optimized value per
ved Analyzer parameter when selecting optimization results
Impro 2874 BarChart. Supports pre/post market data
ved com adapter
Impro 2875 NinjaScript NinjaScript export process will now generate both a 32-bit and 64-
ved bit DLL provided that Remote Soft Protector with 64-bit support is
installed
Impro 2886 NinjaScript Support pre-compiler directives so that one source base is
ved possible for both NT 6.5 and NT 7 support
Impro 2894 IB adapter Workaround for TWS energy contracts so that IB API call backs
ved with incorrect expirations could be adjusted --> See CL symbol
mapping for example
Impro 2918 Charts Logarithmic scales now support negative values
ved
Chan 2841 NinjaScript Changed internal logic for overfill detection
ged
Chan 2847 General Prevent migration of NT 6.5 data when running 64-bit version for
ged the first time
Chan 2848 Strategy/ Having a newline in the description text (e.g. by pressing
ged Indicator CTRL+RETURN) would create code which does not compile.
Wizard
Chan 2909 TT adapter Restrict ICE support to TF
ged
Fixed 2827 Charts Chart flickering when saving or applying an indicator set
Fixed 2829 NinjaScript Text drawn from indicator/strategy with method DrawTextFixed
could have been off.
Fixed 2830 Charts Max. possible zoom out capability wasn't refreshed on deletion of
bar series.
Fixed 2831 Charts Mini instrument selector disapears behind chart with AlwaysOnTop
set to true on typing first letter.
Fixed 2833 Data Box Data Box Time stamps missing seconds for tick based Data
Fixed 2835 Strategy Strategy performance context menu item could have been disabled
Performanc
e window
Fixed 2837 Charts Historical bar requests with session end into next day (e.g. 24/7)
could have yielded one day too much on beginning and/or end.
Fixed 2839 Charts Chart objects drawn from indicator were drawn on first panel,
though DrawOnPricePanel was set to true and base series was on
different panel.
Fixed 2840 NinjaScript Objects drawn by indicators using DrawOnPricePanel could
disappear when base bar series changed panel.
Fixed 2845 Charts Chart series dialog: "..." button did not work as expected
Fixed 2846 NinjaScript Debug option was missing
Editor
Fixed 2849 NinjaScript Indicator wrapper code was not generated properly as a property
Editor has been commented out by "//".
Fixed 2852 NinjaScript Properties flagged by "GridCategory" which are not of type int or
double could cause exeception e.g. as the strategy is put on chart.
Fixed 2854 Charts Chart->Right click->Image->Save as pulled up wrong dialog.

© 2011 NinjaTrader, LLC


Release Notes 83

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

© 2011 NinjaTrader, LLC


84 NinjaTrader Version 7

series in indicator dialog could crash NT.


Fixed 2899 Charts Chart objects plotted by indicator with DrawOnPricePanel false
could show up on wrong panel.
Fixed 2900 Strategy Executions/trades on chart could have been off like entry/exit lines
Analyzer starting at wrong execution.
Fixed 2901 Strategy Incorrect data series had been loaded on chart tab when optimizing
Analyzer for data series
Fixed 2902 Session Session manager did not work on non-US machines.
Manager
Fixed 2903 Charts Disabled bringing up chart panel properties on double click.
Fixed 2905 Strategy SA chart could throw exception on middle mouse button
Analyzer
Fixed 2906 Charts Open chart until yesterday with session definition on yesterday
reaching over midnight and including actual time could crash NT.
Fixed 2907 Charts Chart series defaults had not been applied to the chart on the SA
Fixed 2910 NinjaScript Setting PriceType in Initialize() did not work.
indicators
Fixed 2911 Charts Drag and drop of bar series didn't include executions on dragged
bar series.
Fixed 2912 Charts Executions on chart series could get duplicates on deleting bar
series.
Fixed 2913 Charts Middle mouse button on panel with indicators only could crash NT.
Fixed 2914 Charts Deleting an indicator with bar series on panel with higher number
containing executions could crash NT.
Fixed 2915 Charts It was possible to select drawing objects from a different panel.
Fixed 2916 Charts @VolumeIndicator on chart could go off when it was 'inactive'.
Fixed 2917 Charts Indicator and strategy toolbar buttons are disabled while 'Loading
data' on chart is displayed.
Fixed 2919 Database Tools->Options->Data->Reset DB caused exception if DB held
ATM strategies.
Fixed 2920 NinjaScript Having the caret in the midst of the output text did not prevent
output output window window from scrolling as new text was added
window

© 2011 NinjaTrader, LLC


Part

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.

Advanced Trade Management (ATM)

ATM Strategy Parameters

ATM Strategy Parameters Overview of ATM Strategy parameters

ATM Strategy Selection Mode

ATM Strategy Selection Demonstrates the various ATM Strategy selection modes
Mode

ATM Strategy Templates

ATM Strategy Templates Demonstrates how to save ATM Strategy templates

ATM Strategy Example #1

ATM Strategy Example #1 Demonstrates how to build a basic ATM Strategy

ATM Strategy Example #2

ATM Strategy Example #2 Demonstrates how to build an ATM Strategy including auto
breakeven and auto trail stop features

Charts

Creating a Chart

Understanding the Chart Overview of items within a chart window


Display

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)

© 2011 NinjaTrader, LLC


Video Library 87

Working with Price Data

Data Series Window Overview of the Data Series window


Adding a Data Series Demonstrates how to add a Data Series
Editing Data Series Demonstrates how to edit Data Series
Parameters
Changing a Data Series Demonstrates how to change a Data Series
Removing a Data Series Demonstrates how to remove a Data Series

Working with Indicators

Understanding the Overview of the Indicators window


Indicators Window
Adding an Indicator Demonstrates how to add an indicator to a chart
Editing Indicator Demonstrates how to edit general and visual indicator
Parameters settings
Removing an Indicator Demonstrates how to remove an indicator from a chart

Working with Drawing Tools & Objects

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

Working with Automated Strategies

Data Box

Understanding the Mini Overview of the Mini Data Box


Data Box
Understanding the Data Overview of the Data Box
Box

Global Cross Hair

Understanding the Global Overview of the Global Cross Hair


Cross Hair

© 2011 NinjaTrader, LLC


88 NinjaTrader Version 7

Hot Key Manager

Working with Hot Keys

Working with Hot Keys Overview of the Hot Key Manager, assigning and removing
Hot Keys

Market Analyzer

Working with Instrument Rows

Working with Instrument Demonstrates how to add and remove various instrument
Rows rows

Working with Columns

Working with Columns Demonstrates how to add, customize, and remove columns

Creating Alert, Cell and Filter Conditions

Creating Alert Conditions Demonstrates how to create alert conditions


Creating Cell Conditions Demonstrates how to create cell conditions
Creating Filter Conditions Demonstrates how to create filter conditions

Market Replay

Set Up

Set Up Demonstrates how to set up Market Replay

Replay

Replay Demonstrates how to replay Market Replay data

SuperDOM

Price Ladder Display

Price Ladder Columns Overview of SuperDOM price ladder columns


Market Buttons and PnL Demonstrates how to use the Market buttons and view the
Display profit and loss display
Current Position Display Overview of the current position display
Adjusting the Price Ladder Demonstrates how to adjust the price ladder display
Display
Price Ladder Display Use this interactive review to test your knowledge of the
Interactive Review price ladder display

© 2011 NinjaTrader, LLC


Video Library 89

Static vs Dynamic Price Ladder Display

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

Order Display Overview of how orders are displayed


Order type Display Overview of order type display
Size Marker Display Overview of order size markers
Consolidated Order DisplayDemonstrates how to consolidate orders and the resulting
display
Order Display Interactive Use this interactive review to test your knowledge of the
Review SuperDOM order display

Submitting Orders

Submitting Orders Overview of submitting orders within the SuperDOM


Order Settings Overview of order settings
Submitting Limit Orders Demonstrates how to submit limit orders
Submitting Stop Market Demonstrates how to submit stop market orders
Orders
Submitting Stop Limit Demonstrates how to submit stop limit orders
Orders
Scaling In or Out of an Demonstrates how to scale into or out of an active ATM
Active ATM Strategy strategy
One Cancels Other Demonstrates how to enable and submit "one-cancels-
other" (OCO) orders
Simulated Stop Demonstrates how to enable and submit simulated stop
orders
Quick Buttons Demonstrates how to enable and use the quick buttons
Submitting Orders Use this interactive review to test your knowledge of
Interactive Review submitting orders in the SuperDOM

Modifying Orders

Modifying Orders Overview of modifying orders within the SuperDOM


Modifying the Price of Entry Demonstrates how to modify the price of entry and exit
and Exit Orders orders
Modifying the Price of Stop Demonstrates how to modify the price of stop loss and profit
Loss and Profit Target target orders
Orders
Modifying Order Size Demonstrates how to modify order size
Single Click Order Demonstrates how to use single click order modification
Modification with an ATM strategy
Modifying Orders Use this interactive review to test your knowledge of
Interactive Review modifying orders in the SuperDOM

© 2011 NinjaTrader, LLC


90 NinjaTrader Version 7

Cancelling Orders

Cancelling Orders Overview of cancelling orders within the SuperDOM


Cancelling Orders Use this interactive review to test your knowledge of
Interactive Review cancelling orders in the SuperDOM

Adding and Removing Targets

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

Market Display Overview of how market information is displayed within the


Basic Entry window

Submitting Orders

Submitting Orders Overview of order submission in the Basic Entry window

Modifying and Cancelling Orders

Modifying and Cancelling Demonstrates how to modify and cancel orders


Orders

Adding or Removing Targets

Adding or Removing Targets Demonstrates how to add or remove targets

Chart Trader

Order & Position Display

Order & Positions Display Overview of how orders and positions are displayed in the
Chart Trader window.

Submitting Orders

Submitting Orders Overview of order submission in the Chart Trader window

Modifying and Cancelling Orders

© 2011 NinjaTrader, LLC


Video Library 91

Modifying and Cancelling Demonstrates how to modify and cancel orders


Orders

Session Manager

Using the Session Manager

Creating a Session Template Demonstrates how to create a custom session template

Strategy Analyzer

Backtest a Strategy

Backtest a Strategy

Optimize a Strategy

Walk Forward Optimize a Strategy

Workspaces

Managing Workspaces

Managing Workspaces Overview of Workspaces

© 2011 NinjaTrader, LLC


Part

V
Risks of Electronic Trading with NinjaTrader 93

5 Risks of Electronic Trading with NinjaTrader


There are risks associated with electronic trading in general. Below are risks that you must
be aware of with respect to NinjaTrader.

OCO Handling (One Cancels Other)


NinjaTrader supports multiple different connectivity providers (brokers, exchange
gateways, and data feeds) that each have different levels of support for advanced order
handling features such as OCO orders. An OCO order is simply a group of linked orders
where if one is either filled or cancelled, all other orders that belong to it's OCO group
are cancelled. If your connectivity provider does not support OCO orders natively,
NinjaTrader will simulate them on your local PC. It is important to understand how these
order types behave.

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

© 2011 NinjaTrader, LLC


94 NinjaTrader Version 7

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

5. You now have an open short position 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.

NinjaTrader Volume Based Simulated Stop Orders


Please see this section of the Help Guide to understand the risks involved in using
volume based simulated stop orders.

© 2011 NinjaTrader, LLC


Part

VI
96 NinjaTrader Version 7

6 Copyrights
NinjaTrader, LLC acknowledges the following:

Trading Technologies, Inc.


NinjaTrader SuperDOM is licensed under U.S. Patent Nos. 6,766,304 and 6,772,132, U.K.
Patent Nos. GB 2,377,527 and GB 2, 390,451 and European Patent No. EP 1 319 211 from
Trading Technologies, Inc.

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/

THIS SOFTWARE IS PROVIDED "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 QUICKFIXENGINE.ORG 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.

openSmtp.net - C# SMTP library


Copyright (C) 2001-2004 Ian Stallings
OpenSmtp.Net is free software; you can redistribute it and/or modify it under the terms of the
Lesser GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

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

© 2011 NinjaTrader, LLC


Copyrights 97

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
-----------------------

Copyright (C) 1995-1998 Eric Young ([email protected])


All rights reserved.
This package is an SSL implementation written
by Eric Young ([email protected]).
The implementation was written so as to conform with Netscapes SSL.

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:

© 2011 NinjaTrader, LLC


98 NinjaTrader Version 7

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.]

© 2011 NinjaTrader, LLC


Part

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.

Getting Help & Support


Purchase NinjaTrader
Learning to Use NinjaTrader

7.1 Getting Help & Support


NinjaTrader Support Policy
It is critical that you can rely on the support and service you receive from your trading platform
provider. It is for this reason that NinjaTrader prides itself on its top quality support model that
ensures you receive lightning fast and accurate turn around to your support inquiries. We
have found that delivering support electronically allows us to provide high levels of service in a
cost efficient manner. Electronic support inquiries can be processed thirty times faster than
traditional telephone support models which ensures that you get the necessary information
when you need it. No more leaving messages in phantom voice mail boxes and no more
waiting for thirty minutes in a telephone queue! Does this mean we do not have telephone
support? Absolutely not! If we can't resolve your support inquiry electronically, we will be on
the telephone with you right away and if required, login remotely to your PC to expedite a
resolution!

So how do I get support?


This help guide is interlaced with over one hour of instructional video and images
Pressing F1 key anywhere in the NinjaTrader application will load context sensitive help
Daily live interactive online training sessions (schedule)
Some of our connectivity providers are staffed with NinjaTrader support specialists. Please
check with your provider to find out if they have live support for NinjaTrader.
NinjaTrader Support Forum available 24 hours a day 7 days a week
Send "Mail To Support" from the Help menu of the NinjaTrader application
Send an email to the NinjaTrader support team

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

© 2011 NinjaTrader, LLC


Introduction 101

followed by the About menu item)


Explanation of your problem

Current subscribers (evident by providing a license code) will receive priority support.

7.2 Purchase NinjaTrader


NinjaTrader is a free application for advanced charting, market analytics, system
development and trade simulation. Should you wish to trade live, please see our available
purchase options at our website.

You can also contact us at:

NinjaTrader, LLC
1236 Clarkson Street
Denver, CO 80218 USA

Send us an email

7.3 Learning to Use NinjaTrader


NinjaTrader provides a variety of ways for free and live users to learn the NinjaTrader
software including: User Help Guides, the Video Library, the Support Forum, and weekly free
live training sessions.

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!

User Help Guide


The user help guide contains sections on all of the features within NinjaTrader,
contains video links where applicable, and it also contains a search tab where you can
search by topic.
Click here to visit the page where you can download the PDF version of this help

© 2011 NinjaTrader, LLC


102 NinjaTrader Version 7

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!

NinjaTrader Support Forum

NinjaTrader Support Forum


The NinjaTrader Support Forum is available 24 hours a day 7 days a week.
The NinjaTrader Support Forum includes a comprehensive listing of all topics on all
aspects of the NinjaTrader platform.
The Support Forum is also a great resource for NinjaScript developers looking for a
community of fellow developers.
The Support Forum can be searched for specific items using the "search" feature,
which quickly resolves the majority of questions.
Take me to the NinjaTrader Support Forum!

Free Live Training Events!

NinjaTrader Product Training Classes


NinjaTrader offers free training events on various features within the software every
Monday through Friday.
These events allow users to see live product demonstrations and ask questions live
within the web room.
Take me to the schedule of free live training events!

NinjaTrader Partner Events


NinjaTrader is pleased to sponsor weekly partner events as a value added service for
our clients.
These events are intended to provide increased exposure to the various trading styles
and methods taught by our 3rd Party add on and Educational partners.
If you find value in these events, we hope you will attend them on a regular basis.
Email the NinjaTrader sales team today to be added to the partner event email list!

© 2011 NinjaTrader, LLC


Part

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:

External Data Feed Connection


Kinetick - End Of Day (Free)
Market Replay Connection
Simulated Data Feed Connection

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

Connecting to your Account


Multiple Connections
External Data Feed Connection
Market Replay Connection
Simulated Data Feed Connection
Connecting to Kinetick
Connecting to TradeStation
Connecting to Collective2

8.1.1 Connecting to your Account

Understanding account connections

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.

© 2011 NinjaTrader, LLC


Configuration 105

You can access broker/technology specific connection help information via the
NinjaTrader Connection Guide.

How to create an account connection

Creating an Account Connection


Within the Account Connection Set Up window you can establish a connection, add a
connection, change a connection or remove a connection. The following steps use
eSignal as the connectivity provider. This provider is used for demonstration purposes.

To create an account connection:

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...

2. Press the Add... button to launch the connection wizard.

© 2011 NinjaTrader, LLC


106 NinjaTrader Version 7

3. After pressing the Next button, you will be prompted to supply:

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.

© 2011 NinjaTrader, LLC


Configuration 107

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.

© 2011 NinjaTrader, LLC


108 NinjaTrader Version 7

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:

Connect to and trade through multiple brokers simultaneously


Connect to your broker and your data feed provider simultaneously

Primary and Secondary Data Feeds


You may or may not want to use your brokers data feed as your primary data feed. For
example, you may want to use eSignal as your primary data feed and your broker as back up.
If this is the case, connect to eSignal first and then establish your broker connection.
Whenever you request data for a particular market, NinjaTrader will request data from the
eSignal connection first and then your broker connection second if a market data request fails
from eSignal. During the connection creation process, you also have the ability to assign a
back up data feed connection. By doing so, you tell NinjaTrader to fail over to the back up data
feed if the primary feed is disconnected. This will only work if the back up data feed

© 2011 NinjaTrader, LLC


Configuration 109

connection is connected.

Connection Order is Significant


If you are establishing multiple connections that overlap in their provided market data
services, the connection order you establish is critical. NinjaTrader will check for required
market data services in the order your connections are established.

For example:

BrokerA - Provides real-time market and historical data


BrokerB - Provides only real-time market data

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.

This connection can be used for:

Offline simulated training and practice of NinjaTrader


Offline testing of strategies
Offline testing of trade automation using NinjaScript strategies or the NinjaTrader
Automated Trading Interface

© 2011 NinjaTrader, LLC


110 NinjaTrader Version 7

** This connection is a random internally generated market and has NO correlation to


real market data **

Sim Feed Start Price


The Simulated Data Feed will automatically use the last price from the last connection as
the starting price for the instrument.

Defining the Sim Feed Start Price


To manually set an instrument starting price for use with the Simulated Data Feed:

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.

© 2011 NinjaTrader, LLC


Configuration 111

8.1.6 Connecting to Kinetick

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.

How to connect to Kinetick for FREE end of day data

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)

To connect to Kinetick for FREE end of day data:


1. Left mouse click on the File menu from the Control Center
2. Select the Connect menu item
3. Left mouse click on the Kinetick - End Of Day (Free) menu item

© 2011 NinjaTrader, LLC


112 NinjaTrader Version 7

Please visit www.kinetick.com for information on signing up for real-time data.


8.1.7 Connecting to TradeStation
You can use NinjaTrader (even the free Simulation Edition) with TradeStation's real-time data
feed.

Initial Set Up
To set up the TradeStation connection:

1. NinjaTrader must be installed


2. Start TradeStation
3. Select the File menu from TradeStation and select the menu item Import/Export
EasyLanguage
4. Select the menu item Import EasyLanguage file (ELD, ELS or ELA)
5. Left mouse click the Next button
6. Select the file <NinjaTrader Installation Folder>\bin\AutoTrade\NINJATRADER.ELD"
7. Left mouse click the Next button
8. Left mouse click the Next button
9. Left mouse click the Finish button and confirm any upcoming query box by pressing the
OK button.

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...

© 2011 NinjaTrader, LLC


Configuration 113

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.

How does it work?

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.

How to set up the Account Groups

Collective 2 Setup Up
You must set up an Account Group(s) to instruct NinjaTrader to submit market orders to

© 2011 NinjaTrader, LLC


114 NinjaTrader Version 7

C2 servers. An Account Group accomplishes the following:

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

Anytime you execute a real-time order into an account(s) assigned to a C2 Account


Group from any order entry window, Automated Trading Interface or an automated
NinjaScript strategy, a C2 order will be submitted for all C2 enabled instruments. (See
the "How to enable an instrument" section below for more information)

Understanding Account Group Naming Conventions


The name of a C2 Account Group must be in the format below ensuring that you have
semicolons (;) between parameters:

C2;Strategyid;YourPassword;QuantityMultiplier

"C2" in the above example MUST be in caps since it is case sensitive.

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

© 2011 NinjaTrader, LLC


Configuration 115

Example #2
StrategyId = 98761
YourPassword = jump
Quantity multiplier of 0.5

How to enable an instrument

Enabling an Instrument
You must enable an instrument by 'tagging' the C2 symbol with an asterisk (*) prefix.

© 2011 NinjaTrader, LLC


116 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Configuration 117

NinjaTrader support team member.

Minimum System Requirements


Clear Browser Cache

8.2.1 Minimum System Requirements


To run NT your system must meet these specifications:

Windows XP, Windows Vista, Windows 7 or Windows 2003 Operating System


Minimum screen resolution of 1024 x 768
Minimum P4 Processor or higher
2GB RAM
Microsoft .NET Framework 3.5 (pre-installed on most PC’s or can be downloaded below)

Download Microsoft .NET Framework


8.2.2 Clear Browser Cache
How to clear your browser cache
In order to download or upgrade NinjaTrader you may need to clear your browser cache.
Common errors that occur when this is the case are Cabinet File Errors and errors involving
Temporary Files. If you receive one of these errors when installing or updating NinjaTrader
please follow the steps listed below to accomplish a successful download of the NinjaTrader
application.
Within your web browser (Internet Explorer for most users) select the menu Tools >
Internet Options
Delete your browsing history
Attempt the download again

If the above does not work then try:


Repeat above instructions
Use a different browser such as Firefox and attempt to download

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.

© 2011 NinjaTrader, LLC


118 NinjaTrader Version 7

General Tab
Strategies Tab
Simulator Tab
Log Tab
Commission Tab
ATI Tab
Data Tab
RSS Tab
Misc Tab

8.3.1 General Tab


The General tab sets general application options.

Sounds Enables or disables various application sound events


Confirm order Enables or disables order confirmation dialog window
placement
Use order entry hot Enables or disables order entry Hot Keys for order placement
keys
Use last price for PnL When enabled, the last trade price is used to calculate profit and loss
values
When disabled, the bid is used for long positions and the ask is used
for short positions

© 2011 NinjaTrader, LLC


Configuration 119

Apply commission to Enables or disables commissions to be included in profit and loss


PnL calculations displays
Use FIFO for position Enables or disables calculation of position average entry price based
avg. price calculations on the FIFO (First in First Out) method.
Show tools tips Enables or disables showing tools tips
8.3.2 Strategies Tab
The Strategies tab sets options regarding handling of ATM Strategies and NinjaScript
strategies for automated system trading.

Understanding the ATM 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.

Understanding the NinjaScript tab

© 2011 NinjaTrader, LLC


120 NinjaTrader Version 7

On Starting a Real-Time Strategy

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

© 2011 NinjaTrader, LLC


Configuration 121

strategy will only restart off a reestablished connection when


there have been fewer restart attempts than "Number of restart
attempts" within the last "Restarts within x minutes" time span.
Otherwise the strategy will just be stopped and no further restart
attempts will be taken.
Restarts within x Sets the number of minutes for the "Restarts within x minutes"
minutes time span used by "Number of restart attempts".
Handling Sets the NinjaScript strategy action to take after a disconnect:

KeepRunning: Keeps the strategy running and logs the


disconnect. When the connection is reestablished the
strategy will resume as if no disconnect occurred.

Recalculate: Strategies will attempt to recalculate its strategy


position when a connection is reestablished and held for
longer than 10 seconds. Recalculations will only occur if the
strategy was stopped based on the conditions below. Should
the connection be reestablished before the strategy was
stopped, the strategy will continue running without
recalculating as if no disconnect occurred.
If data feed disconnects for longer than the time
specified in “Disconnect delay seconds”, the strategy is
stopped and the disconnect is logged.
If the order feed disconnects and the strategy places an
order action while disconnected, the strategy is stopped
and the disconnect is logged.
If both the data and order feeds disconnect for longer
than the time specified in “Disconnect delay seconds”,
the strategy is stopped and the disconnect is logged.

StopStrategy: Automatically stops the strategy and logs the


disconnect when disconnected for more than "Disconnect
Delay Seconds". No action will be taken when a connection is
reestablished.

Order Handling

Cancel entry orders Enables or disables automatically cancelling of the NinjaScript


when a strategy is strategy entry orders when a strategy is disabled.
disabled
Cancel exit orders Enables or disables automatically cancelling of the NinjaScript
when a strategy is strategy exit orders when a strategy is disabled.
disabled
8.3.3 Simulator Tab
The Simulator tab sets options for the NinjaTrader simulation engine.

© 2011 NinjaTrader, LLC


122 NinjaTrader Version 7

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

*Delays are not used when connected to a Market Replay

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.

© 2011 NinjaTrader, LLC


Configuration 123

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

Resetting the Simulator


To reset a simulation account:

1. Adjust the Account settings to the desired values


2. Left mouse click on the Reset... button
3. Select the account to reset using the Simulation account drop down menu
4. Optionally enable Clear history to remove historical trade data and press the OK button

How the Margin parameters impact Account values


The margin parameters defined on this tab only impact trading on simulation accounts.
How the values influence things like cash value, buying power, excess equity, etc. is
dependent on the type of instrument being traded and the connection/brokerage being
used.

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

© 2011 NinjaTrader, LLC


124 NinjaTrader Version 7

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.

8.3.4 Log Tab


The Log tab sets properties for the log display in the Control Center window.

© 2011 NinjaTrader, LLC


Configuration 125

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

8.3.5 Commission Tab


The Commission tab allows you to set up global level commission rate information against
different instrument types and connectivity providers. Global commission rates can be
overridden by specifying instrument level commission rates. Therefore, when NinjaTrader
calculates a trade's commission costs, it will use a commission rate value at the instrument
level and if one does not exist, it will use the global commission rate.

To set commissions for backtesting purposes, set commissions for the "Simulator"
connectivity provider.

How to add a flat commission rate

Adding a Flat Commission Rate

© 2011 NinjaTrader, LLC


126 NinjaTrader Version 7

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."

How to add a tiered commission rate

Adding a Tiered Commission Rate


We are going to add a global tiered commission rate for trading stocks on our Market
Replay connection. The commissions are tiered from the top down. This means

© 2011 NinjaTrader, LLC


Configuration 127

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.

© 2011 NinjaTrader, LLC


128 NinjaTrader Version 7

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.

Understanding the General tab

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

Understanding the TradeStation tab

© 2011 NinjaTrader, LLC


Configuration 129

Detailed information on the TradeStation Email Interface can be found here.

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

© 2011 NinjaTrader, LLC


130 NinjaTrader Version 7

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.

Historical Chart Data


This section sets historical data handling procedures within NinjaTrader.

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

© 2011 NinjaTrader, LLC


Configuration 131

Merge policy Sets the merge policy for Futures contracts:


DoNotMerge: historical data is not merged
MergeBackAdjusted: NinjaTrader automatically merges and back
adjusts historical data
MergeNonBackAdjusted: NinjaTrader automatically merges, but does
not back adjust, historical data

For more information on merge policies please see the "Understanding


merge policies" section in this article.

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

Quote currencies (FX) in:


This setting enables or disables sub pip support for currency (forex) trading depending on
what your broker supports.
8.3.8 RSS Tab
The RSS tab enables or disables the RSS news feeds available in NinjaTrader.

© 2011 NinjaTrader, LLC


132 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


Configuration 133

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

© 2011 NinjaTrader, LLC


134 NinjaTrader Version 7

8.4 Performance Tips


There are many variables that contribute to overall performance of the NinjaTrader
application.

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

Chart Performance Tips


Set chart indicators "Calculate on bar close" property to a value of 'True'
Increase your chart refresh interval by increasing the value of the chart property "
Display update interval (sec)"
Reduce the number of bars on your chart (days back or bars back settings under "
Format Data Series" dialog window
Reduce the number of running indicators
If you are running a custom or 3rd party indicator or strategy, remove them to isolate if
these custom NinjaScript objects may be a CPU or memory drain

Lagging Market Data

Variables that can impact market data latency


Connecting wirelessly can drastically impact performance during heavy volume
periods. Depending on signal strength, your modem/router is unable to push all the
data through. This can be resolved by connecting directly into the modem/router via a
hard line.
Serious abnormal increases in market volume
Data provider servers could be lagging
Limited bandwidth internet service (56K dial up modem is not acceptable for example)
Inadequate PC hardware or running too many applications on your PC

Market Analyzer

Market Analyzer look back period


"# bars to look back" property set this number to the minimum number of bars
required to properly initialize any indicator columns. The higher the number, the longer

© 2011 NinjaTrader, LLC


Configuration 135

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

Logging and Printing


Extremely liberal use of Log() and Print() methods can represent a performance hit on
your PC as it takes memory and time to process each one of those method calls. When
running custom NinjaScript, especially when using CalculateOnBarClose = false, please
be mindful of how often Log() and Print() methods are processed as it can quickly
consume PC resources.
Log() method should not be used except for critical messages as each log entry
makes it to the Control Center log which stays active till the end of the day. Excessive
logging can result in huge amounts of memory being allocated just to display all the log
messages which would mean less memory for NinjaTrader to do other tasks.
Print() method can be used more liberally than the Log() method, but can still
represent a performance hit if used with extremely high frequency. Consider
decreasing the printing from your script if you experience slowdowns when running the
script.

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.

Time & Sales

Display Update Interval


Increase your Time & Sales refresh interval by increasing the value of the Time & Sales
property "Display update interval (sec)"

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.

© 2011 NinjaTrader, LLC


Part

IX
Operations 137

9 Operations

9.1 Account Groups


Account Groups allow you to group individual accounts into a group account. These account
groups will show up in any of the NinjaTrader order entry windows' account selection lists. If
selected, any order placed will be replicated and sent to each account that belongs to the
group.

NOTE: Subsequent cancellations and or order modifications will NOT be replicated against
each order, you must manage each replicated order individually.

Managing Account Groups

9.1.1 Managing Account Groups


Create Account Group
To create an Account Group:

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

© 2011 NinjaTrader, LLC


138 NinjaTrader Version 7

The "My Group" (in image above) account will now be available in all account selection lists in
all order entry interfaces.

Remove Account Group


To remove an Account Group:

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)

9.2 Advanced Trade Management (ATM)


NinjaTrader provides you with the flexibility to trade with or without an Advanced Trade
Management (ATM) Strategy. ATM Strategies are designed to provide discretionary
traders with semi-automated features to manage their positions. This is NOT to be confused
with NinjaScript Strategies for automated trading systems.

What is an ATM Strategy?


Before you enter a trade you already know where you are going to place your Profit Target
(s), where you will set your Stop Loss, and how many contracts you will trade. You may also
have rules and conditions for managing your trade such as; once there is 1 point in profit you
will move your Stop Loss to breakeven and once there is 2 points in profit you will move your
Stop Loss to protect 1 point in profit. These rules and conditions make up your personal
trade methodology, or as we call it, your strategy. In NinjaTrader, an ATM Strategy is a
collection of orders that represent your entries, exits, stops and targets along with sub-
strategies (Auto Breakeven, Auto Chase, Auto Trail etc...) that govern how these orders
are managed. By pre-defining your personal trading strategy in NinjaTrader, you are free to
concentrate on the trade and not on the management of orders and positions. NinjaTrader
does this all for you automatically.

© 2011 NinjaTrader, LLC


Operations 139

Do I have to use an ATM Strategy?


Absolutely not. NinjaTrader is incredibly flexible in that you can trade independent of an ATM
Strategy and manually submit and manage all of your own orders. You can also choose to
manage a portion of an open position by an ATM Strategy and leave another portion to be
managed independently. It's completely up to you.

What are the advantages to using an ATM Strategy?


There are several:
Reduce errors in order management
Speed (orders are submitted and modified at PC speed instead of human speed)
Discipline (less prone to applying 'too much' discretion)
Consistency with your trading
Reduces emotions

ATM Strategy Advanced Options


Definition and Benefits Auto Chase
ATM Strategy Parameters Auto Reverse
ATM Strategy Selection Mode Shadow Strategy
Stop Strategy
Auto Breakeven Misc
Auto Trail Close at Time
ATM Strategy Templates FAQ
Example #1
Example #2

9.2.1 ATM Strategy


What is an ATM Strategy?
An ATM Strategy is the master strategy that helps you automate the management of a
position. Let's break it down. In trading, a position is defined as the total contracts/shares held
long or short for a specific instrument in a specific account. An ATM Strategy can be thought
of as:

"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."

Let's assume the following:

We want to go long the S&P E-Mini for 5 contracts


We want a Stop Loss set 2.5 points from our entry price
We want a Profit Target set 5 points from our entry price

We just defined a set of conditions for the management of a 5 contract long position, or in

© 2011 NinjaTrader, LLC


140 NinjaTrader Version 7

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.

The Value of an ATM Strategy


Now that we understand what an ATM Strategy is, what exactly is the value of it? When
trading, one develops ideas and methods for entry and further management of their position.
The management of this position can be simple to complex and everything in between. The
ATM Strategy allows the trader to define the rules and conditions that govern the
management of the position. How many Profit Targets should there be and at what prices?
What Auto Trail Stop Loss setting should be used? When should a Stop Loss be moved to
breakeven? Should Profit Target orders chase the market if not filled? Should the Stop
Loss order trigger immediately on trade through or should NinjaTrader's leading edge
Simulated Stop order be used? An ATM Strategy also provides a layer of discretionary
automation and intelligence that takes responsibility of mundane order modifications which
can be inefficient, time consuming and error prone. When scaling into a position for example,
all of the Stop Loss and Profit Target orders will be automatically updated to reflect the new
position size. Changing order contract sizes will update the distribution of contracts on other
orders. Decrease your first Profit Target order by one contract and your second Profit
Target will automatically be increased by 1 contract. The bottom line is that a position
strategy thinks the way a trader thinks about managing their trade only 100x faster. It
performs a lot of the routine tasks for you allowing you to concentrate on what matters; the
trade itself.
9.2.1.1 ATM Strategy Parameters

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

© 2011 NinjaTrader, LLC


Operations 141

Understanding the ATM Strategy control list options

The Strategy Control List


The drop down list shown in the image below is very important to understand as it
defines how your orders will be handled once submitted. There are three main
categories of options that will be displayed in this drop down list; <None>, <Custom> or
strategy template names, and Active ATM Strategy Name(s).

<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.

<Custom> or ATM Strategy Template Names


When an ATM Strategy template name is selected, all of the parameters will update to
reflect your pre-defined ATM Strategy, or when <Custom> is selected, you have the
ability to define a new ATM Strategy on the fly. Once an order is submitted, the ATM
Strategy parameters specified will be initiated when the order is partially or completely
filled.

* Active ATM Strategy Names


All active (live and working) ATM Strategies will be displayed. If one is selected, any

© 2011 NinjaTrader, LLC


142 NinjaTrader Version 7

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.

Strategy Selection Mode Overview


The behavior of the strategy control list can be controlled automatically by selecting an
ATM Strategy Selection Mode.

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)

ATM Strategy Parameters


In the image right there are parameters that define how many Stop Loss and Profit
Target orders are automatically submitted, what prices they will be submitted at, and
any Stop Loss automation strategies that will be applied (such as Auto Trail, Auto
Breakeven etc...).

© 2011 NinjaTrader, LLC


Operations 143

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

Parameters can be entered as ticks, percent or absolute price. To change what


parameter type is used, access the entry window's properties via the right mouse click
context menu and change the "Parameter type" property.

For further reference, please look at the Strategy Examples located within the "ATM
Strategy" section of the user help guide.

Understanding the Advanced Options Display

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.

© 2011 NinjaTrader, LLC


144 NinjaTrader Version 7

9.2.1.2 ATM Strategy Selection Mode

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.

As a quick reminder, when the strategy control list is set to:


<None> - Orders submitted take no action once filled or part filled (no stops or targets are
placed)
<Custom> - Orders submitted will initiate the custom defined ATM Strategy (submission of
stops and targets) once filled or part filled
<My Strategy Template> - Orders submitted will initiate your user defined ATM Strategy
(submission of stops and targets) once filled or part filled
<* Active ATM Strategy X - My Strategy Template> - Existing ATM Strategy stop and
target orders will be amended once the submitted order is filled or part filled

There are three available ATM Strategy Selection Modes:


Select Active ATM Strategy on Order Submission
Keep Selected ATM Strategy Template on Order Submission
Display Selected ATM Strategy Only

Understanding the "Select Active ATM Strategy on Order Submission" mode

Select Active ATM Strategy on Order Submission


This mode will automatically select the newly created active ATM Strategy on entry
order submission in the ATM Strategy control list. This is the default setting upon initial
NinjaTrader installation.

Who is this mode designed for?


This mode is designed for traders who, by default, want the existing strategy Stop Loss
and Profit Targets to be automatically amended when they scale into or out of a
position being managed by an ATM Strategy.

Example (see image below)


1. A user defined ATM Strategy is selected.
2. Once the entry order is submitted, the ATM Strategy selection control automatically
selects the active ATM Strategy that you just created (<* Active ATM Strategy X - My
Strategy Template>).

© 2011 NinjaTrader, LLC


Operations 145

Understanding the "Keep Selected ATM Strategy Template on Order Submission"


mode

Keep Selected ATM Strategy Template on Order Submission


This mode will keep the currently selected ATM Strategy template selected in the
strategy control list upon order submission.

Who is this mode designed for?


This mode is designed for traders who by default, want to always create a new set of
Stop Loss and Profit Target brackets (new ATM Strategy) with each new order
placed. An example of this would be a trader who wanted a single bracket placed with a
Stop Loss of four ticks and a Profit Target of eight ticks. The trader wants to place two
entry limit orders, the first at a price of X and the second at a price of X - 2 ticks. The
purpose is to scale into an overall position but have the brackets be submitted and
calculated from each individual fill price of the two orders.

Example (see image below)


1. A user defined ATM Strategy is selected.
2. Once the entry order is submitted, there will be no change in selection in the ATM
Strategy control list. It will continue to look like the upper right image as the same ATM
Strategy is automatically reselected after each order.

© 2011 NinjaTrader, LLC


146 NinjaTrader Version 7

Understanding the "Display Selected ATM Strategy Only" mode

Display Selected ATM Strategy Only


This mode is an advanced mode and should only be used once you have become very
familiar with the NinjaTrader application.

Who is this mode designed for?


This mode is designed for traders who want to run concurrent ATM Strategies (trades)
in the same market. This mode will visually separate all concurrent running ATM
Strategies thereby allowing you to have multiple SuperDOMs open, tracking the same
market but displaying different trade strategies. A practical example might be that you
have taken a day long intra day swing trade against a fifteen minute chart for five
contracts. Throughout the day, you scalp the same market on a one minute time frame.
This mode allows you to have two SuperDOMs open, one allocated to manage and only
display your day long intra day swing trade, the other used to manage and only display
your scalp trades.

Example (see image below)


In the image right, you can see two separate SuperDOMs monitoring the same ES 03-
09 market. In the ATM Strategy control list, there are two different ATM Strategies
running and each is displayed separately in an individual SuperDOM. Orders, positions,
average entry and unrealized profit are displayed individually for each separate running
ATM Strategy.
When running multiple concurrent ATM Strategies by changing the selected active
strategy in the strategy control list you can change which strategy will be displayed

© 2011 NinjaTrader, LLC


Operations 147

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.

***** Risk *****


When a SuperDOM is set to this mode, it will only display orders associated to the
active selected ATM Strategy in the ATM Strategy control list. This means that if there

© 2011 NinjaTrader, LLC


148 NinjaTrader Version 7

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

A Stop Strategy is an extension of an ATM Strategy. It allows you to combine Auto


Breakeven, Auto Trail, and Simulated Stop strategies for the management and automatic
adjustment of your Stop Loss orders.

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.

9.2.1.3.1 Auto Breakeven

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.

Understanding the Auto Breakeven parameters

Auto Breakeven Parameters


Profit Trigger Sets the amount of profit required to move the Stop Loss to a
breakeven value
Plus Sets the amount added to the breakeven (average entry price for the
ATM Strategy position) value

© 2011 NinjaTrader, LLC


Operations 149

How to enable the Auto Breakeven


Auto Breakeven can be set before entering a position as part of a stop strategy, and
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 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.

Auto Breakeven Examples

Auto Breakeven Example #1


Profit Trigger - 8 ticks
Plus - 0 ticks
Average Entry - 1000 Long (SP Emini contract)
As soon as the market trades at 1002 (Average Entry + Profit Trigger = 1000 + 8 ticks
= 1002) NinjaTrader will move the Stop Loss order to 1000 (Average Entry + Plus =
1000 + 0 = 1000) and enter a log event in the Log tab.

Auto Breakeven Example #2


Profit Trigger - 10 ticks
Plus - 2 ticks
Average Entry - 10200 Short (DOW Emini contract)
As soon as the market trades at 10190 (Average Entry - Profit Trigger = 10200 - 10

© 2011 NinjaTrader, LLC


150 NinjaTrader Version 7

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.

Understanding the Auto Trail parameters

Auto Trail Parameters


Stop Loss Sets the value of the Stop Loss order as an offset
Frequency Sets the value of how frequent the Stop Loss order is adjusted
Sets the amount of profit required to trigger the initial Stop Loss
Profit Trigger
adjustment for the step

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.

© 2011 NinjaTrader, LLC


Operations 151

Auto Trail Examples

Auto Trail Example #1:


The settings in the image below are saying:

"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."

Average Entry - 1000 Long (SP Emini contract)

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.

Auto Trail Example #2 building on top of Example #1:


The settings in the image below are saying:

"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"

© 2011 NinjaTrader, LLC


152 NinjaTrader Version 7

Average Entry - 1000 Long (SP Emini contract)

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.

© 2011 NinjaTrader, LLC


Operations 153

9.2.1.5 Tutorial: ATM Strategy Example #1

ATM Strategy Example


Following is an example of how to create a simple 1 stop/1 target ATM Strategy and save
the strategy as a template. You can do this via any NinjaTrader order entry screen.

1. Set the order quantity to 1 contract


2. From the ATM Strategy control list select <Custom> and ensure that "1 Target" option is
selected
3. Set the Stop Loss value to 4 ticks
4. Set the Profit Target value to 8 ticks

This simple ATM Strategy will automatically submit a Stop Loss order 4 ticks from entry
and a Profit Target order 8 ticks from entry.

© 2011 NinjaTrader, LLC


154 NinjaTrader Version 7

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..."

5. Enter the name "8 Tick 1 Target"


6. Press the "Save" button

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.

© 2011 NinjaTrader, LLC


Operations 155

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.

© 2011 NinjaTrader, LLC


156 NinjaTrader Version 7

9.2.1.6 Tutorial: ATM Strategy Example #2

ATM Strategy Example


Following is an example of an ATM Strategy that will automatically submit 2 Stop Loss and
Profit Target brackets once the originating entry order is filled. This ATM Strategy includes
a Stop Strategy that will automatically adjust the Stop Loss orders using Auto Breakeven
and Auto Trail strategies.

1. Set the order quantity to 2 contracts


2. From the ATM Strategy control list select <Custom>
3. Select "2 Targets"
4. Set "Order qty" fields to 1 contract each (that represents 1 contract for the first Stop
Loss/Profit Target bracket and 1 for the 2nd)
5. Set the Stop Loss values to 5 ticks (you can set the 2nd Stop Loss to a wider value)
6. Set the first Profit Target to 8 ticks and the 2nd Profit Target to 12 ticks

7. Select <Custom> from the Stop Strategy control list under the first target.

© 2011 NinjaTrader, LLC


Operations 157

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..."

12. Enter the name "Basic Stop"


13. Press the "Save" button

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.

© 2011 NinjaTrader, LLC


158 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


Operations 159

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,

© 2011 NinjaTrader, LLC


160 NinjaTrader Version 7

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.

9.2.2.1 Auto Chase

Auto Chase will automatically adjust the price of a limit order as the market moves away
from it.

Auto Chase Parameters


Chase Limit The maximum amount that Auto Chase will adjust your limit order price
Chase Enables Auto Chase on your entry orders
Chase if touchedEnables Auto Chase if touched on your entry orders
Target Chase Enables Auto Chase if touched on your Profit Target orders

How does Chase work?


NinjaTrader will automatically adjust the price of your limit order with each tick the
market moves away from your order up until the Chase Limit amount is reached.

How does Chase if touched work?

© 2011 NinjaTrader, LLC


Operations 161

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.

How to enable the Auto Chase features

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.

Auto Chase examples

Auto Chase Example #1


Chase Limit - 5
Buy Limit Price - 1000 (SP Emini contract)
Chase - Enabled
Current Bid - 1000.25

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.

Auto Chase Example #2


Chase Limit - 5
Buy Limit Price - 1000 (SP Emini contract)
Chase if touched - Enabled

© 2011 NinjaTrader, LLC


162 NinjaTrader Version 7

Current Bid - 1000.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.

© 2011 NinjaTrader, LLC


Operations 163

9.2.2.3 Shadow Strategy

What is a Shadow Strategy?


Initiating a Shadow Strategy is a method for forward testing alternate trade management
ideas. As an example, you may have a method that is profitable, but you have some ideas on
how to increase its profitability. Maybe hold on to a few contracts for a higher target? With a
Shadow Strategy, you can set up an alternate ATM Strategy and link that to an ATM
Strategy that will be used for live trading. Every time you enter a position using your live
strategy, NinjaTrader opens a simulated position (e.g. Sim101 account) managed by your
Shadow Strategy. This allows you to forward test your concepts using the same entry
signals that trigger your live trades. Over time, a historical database of actual (live) and
Shadow (simulated) Strategies are compiled. You can then compare the live trades to the
shadow trades under the Performance Tab. The end result is that you will be shown what
ATM Strategy (over time) is more profitable. Changing your trade management logic without
truly understanding the impact of the changes is a risky shot in the dark. Shadow Strategies
give you the proof of concept needed to feel confident that your ATM Strategy changes make
sense.

© 2011 NinjaTrader, LLC


164 NinjaTrader Version 7

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.

How do I build a 4+ Profit Target ATM Strategy?


You may have a maximum of three Profit Targets per ATM Strategy, but you can
modify these targets quickly and easily with the Single Click Order Modification and
scale in and out as needed. With these methods you will be able to scale out contracts
as quickly as needed at any number of price points.

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!

Do I need to turn on OCO order to use the ATM Strategies?


No, the Stop Loss and Profit Target orders submitted automatically through an ATM
Strategy are OCO by default meaning that when your target is filled the stop will
automatically be cancelled. The OCO function in each of the order entry windows can
be used to manually link orders you place.

© 2011 NinjaTrader, LLC


Operations 165

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.

Here is how this is accomplished:

Open 2 SuperDOMs and set them both to the same market


Right click in one of the SuperDOMs and select the menu "Properties"
Set the 'ATM Strategy selection mode' parameter to "
DisplaySelectedAtmStrategyOnly"
Repeat the last two instructions on the second SuperDOM
Submit a buy order to open a long position in the first SuperDOM
Submit a sell order to open a short position in the second SuperDOM

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.

Can I have my Auto Trail loosen as I gain ticks in profit?


Your Stop Strategy will never move your Stop Loss backward. The Stop Strategy will
only move your stop closer to the current trading price.

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.

Why don't the following ATM Strategy parameters work?


1 Target 2 Target 3 Target
Qty: 1 1 1
Stop Loss: 10 8 6
Profit Target: 10 8 6

© 2011 NinjaTrader, LLC


166 NinjaTrader Version 7

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.

1 Target 2 Target 3 Target


Qty: 1 1 1
Stop Loss: 6 8 10
Profit Target: 6 8 10

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

How do I add an ATM Strategy to an open position?


In order to use an ATM Strategy you must have it selected before you enter your order.
There is not a way to add an ATM Strategy to an open position, however, you can
bracket an open position using the OCO function.

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

© 2011 NinjaTrader, LLC


Operations 167

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...

Using the Alerts Window

9.3.1 Using the Alerts Window


The Alerts window displays information for each alert that is triggered within NinjaTrader.

Alerts Window Layout


When an alert is triggered, the following information is available in the Alerts window:

1. Instrument name
2. Alert Priority
3. Time of the alert
4. User defined message

© 2011 NinjaTrader, LLC


168 NinjaTrader Version 7

Right Click Menu


Right mouse clicking within the Alerts window will bring up the following menu options:

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

9.3.2 Window Linking


Please see the Window Linking section of the Help Guide for more information about linking
the Alerts window.

9.4 Automated Trading


NinjaTrader provides methods for automated trading through NinjaScript or from an outside
source via the Automated Trading Interface (ATI).

© 2011 NinjaTrader, LLC


Operations 169

ATI Interface
File Interface
DLL Interface
eSignal Integration
TradeStation Integration
Running NinjaScript Strategies

9.4.1 Automated Trading Interface (ATI)


NinjaTrader's ATI (Automated Trading Interface) provides efficient protocols to
communicate trading signals from various external sources to NinjaTrader for the automation
of order execution.

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

Understanding the ATI Interface Options


What can I do and how? File
Commands and Valid Parameters DLL
Initialization
Trading currencies (FX) and options Integration
eSignal
TradeStation

9.4.1.1 What can I do and how?

What can I do through automation?

© 2011 NinjaTrader, LLC


170 NinjaTrader Version 7

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

NinjaTrader provides three options for communicating from an external application to


NinjaTrader for trade automation. The Email Interface requires absolutely no programming
experience whatsoever, other options require various levels of programming/scripting
experience.

Understanding the four interface options

TradeStation Email Interface


The TradeStation Email Interface allows you to take advantage of TradeStation's email
notification capabilities right out of the box. Run your TradeStation strategy in real time,
order signals are emailed within your computer (never leaves your PC) to NinjaTrader
which processes the order through to your broker.

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.

Which interface option should I use?

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

Other Charting Applications

© 2011 NinjaTrader, LLC


Operations 171

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.

Understanding parameters and valid values

Available Parameters and Valid Values

PARAMET VALID VALUES


ERS
COMMAND CANCEL, CANCELALLORDERS, CHANGE, CLOSEPOSITION,
CLOSESTRATEGY, FLATTENEVERYTHING, PLACE,
REVERSEPOSITION
ACCOUNT The name of the account the command is to be processed
INSTRUME Instrument name
NT
ACTION BUY, SELL
QTY Any integer value
ORDER MARKET, LIMIT, STOP, STOPLIMIT
TYPE
LIMIT Any decimal value (use decimals not commas 1212.25 for example)
PRICE
STOP Any decimal value
PRICE
TIF DAY, GTC
OCO ID Any string value
ORDER ID Any string value (must be unique for each line/file)
STRATEG Strategy template name (must exist in NinjaTrader)
Y
STRATEG Any string value (must be unique for each line/file)
Y ID

Understanding the parameters available to commands

Available Commands
The following table displays required (R) and optional (O) values for each different

© 2011 NinjaTrader, LLC


172 NinjaTrader Version 7

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

Understanding the commands


Following are the descriptions of each available command.

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).

© 2011 NinjaTrader, LLC


Operations 173

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:

© 2011 NinjaTrader, LLC


174 NinjaTrader Version 7

Default account = Sim101


A function call is made with "" empty string as the account name argument
Sim101 account is automatically used
Subsequent function calls must use empty string if you want to reference the Sim101
account
If you call a function and pass in the argument "Sim101", invalid information will be returned
9.4.1.4 Trading currencies (FX) and options

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.

Order Instruction Files (OIF)


Information Update Files
Automated Trading OIF Builder

9.4.1.5.1 Order Instruction Files (OIF)

OIFs must be written to the folder "My Documents\<NinjaTrader Folder>\incoming" and be


named oif*.txt. You can simply send an oif.txt file however, it is suggested that you increment
each OIF so that you end up with unique file names such as oif1.txt, oif2.txt, oif3.txt. The
reason is that if you send a lot of OIFs in rapid succession, you do run the risk of file locking
problems if you always use the same file name. This will result in a situation where your file is
not processed.

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 [].

© 2011 NinjaTrader, LLC


Operations 175

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.

Understanding order state files

Order State Files


Orders that are assigned an order ID value in the "PLACE" command will generate an
order state update file with each change in order state. The file name is 'orderId.txt'
where orderId is the order ID value passed in from the "PLACE" command. Possible
order state values can be found here. The format of this file is:

Order State;Filled Amount;Average FillPrice

Understanding position update files

Position Update Files

© 2011 NinjaTrader, LLC


176 NinjaTrader Version 7

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:

Market Position; Quantity; Average Entry Price

Valid Market Position values are either LONG, SHORT or FLAT.

Understanding connection state files

Connection State Files


Connection state files are written with each change of connection state. The name of the
file is ConnectionName.txt where connectionName is the name of the connection given
in the Connection Manager. The format of the file is:

Connection State

Valid connection state values are CONNECTED or DISCONNECTED.

9.4.1.5.3 Automated Trading OIF Builder

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.

© 2011 NinjaTrader, LLC


Operations 177

9.4.1.6 DLL Interface

The DLL Interface functions are contained in NTDirect.dll located in the C:


\WINDOWS\system32 folder. To view the DLL functions see the Functions section, then
you can view the eSignal Sample Code and TradeStation Sample Code for examples.

DLL Functions
Functions

Sample Code
eSignal Sample Code
TradeStation Sample Code

9.4.1.6.1 Functions

The DLL Interface functions are contained in NTDirect.dll located in the C:


\WINDOWS\system32 folder.

DLL Interface Functions


int Ask(string instrument, double price, int size)
Sets the ask price and size for the specified instrument. A return value of 0 indicates success
and -1 indicates an error.

int AskPlayback(string instrument, double price, int size, string


timestamp)

© 2011 NinjaTrader, LLC


178 NinjaTrader Version 7

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".

double AvgEntryPrice(string instrument, string account)


Gets the average entry price for the specified instrument/account combination.

double AvgFillPrice(string orderId)


Gets the average entry price for the specified orderId.

int Bid(string instrument, double price, int size)


Sets the bid price and size for the specified instrument. A return value of 0 indicates success
and -1 indicates an error.

int BidPlayback(string instrument, double price, int size, string


timestamp)
Sets the bid 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".

double BuyingPower(string account)


Gets the buying power for the specified account. *Not all brokerage technologies support this
value.

double CashValue(string account)


Gets the cash value for the specified account. *Not all brokerage technologies support this
value.

int Command(string command, string account, string instrument,


string action, int quantity, string orderType, double limitPrice,
double stopPrice,
string timeInForce, string oco, string orderId, string
strategy, string strategyId)
Function for submitting, cancelling and changing orders, positions and strategies. Refer to
the Commands and Valid Parameters section for detailed information. A return value of 0
indicates success and -1 indicates an error. The Log tab will list context sensitive error
information.

int ConfirmOrders(int confirm)


The parameter confirm indicates if an order confirmation message will appear. This toggles
the global option that can be set manually in the NinjaTrader Control Center by selecting the
Tools menu and the menu item Options, then checking the "Confirm order placement"
checkbox. A value of 1 sets this option to true, any other value sets this option to false.

int Connected(int showMessage)


Returns a value of zero if the DLL has established a connection to the NinjaTrader server
(application) and if the ATI is currently enabled or, -1 if it is disconnected. Calling any function
in the DLL will automatically initiate a connection to the server. The parameter showMessage
indicates if a message box is displayed in case the connection cannot be established. A

© 2011 NinjaTrader, LLC


Operations 179

value of 1 = show message box, any other value = don't show message box.

int Filled(string orderId)


Gets the number of contracts/shares filled for the orderId.

int Last(string instrument, double price, int size)


Sets the last price and size for the specified instrument. A return value of 0 indicates success
and -1 indicates an error.

int LastPlayback(string instrument, double price, int size, string


timestamp)
Sets the last 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".

double MarketData(string instrument, int type)


Gets the most recent price for the specified instrument and data type. 0 = last, 1 = bid, 2 =
ask. You must first call the SubscribeMarketData() function prior to calling this function.

int MarketPosition(string instrument, string account)


Gets the market position for an instrument/account combination. Returns 0 for flat, negative
value for short positive value for long.

string NewOrderId()
Gets a new unique order ID value.

string Orders(string account)


Gets a string of order ID's of all orders of an account separated by '|'. *If a user defined order
ID was not originally provided, the internal token ID value is used since it is guaranteed to be
unique.

string OrderStatus(string orderId)


Gets the order state (see definitions) for the orderId. Returns an empty string if the order ID
value provided does not return an order.

double RealizedPnL(string account)


Gets the realized profit and loss of an account.

int SetUp(string host, int port)


Optional function to set the host and port number. By default, host is set to "localhost" and
port is set to 36973. The default port number can be set via the General tab under Options. If
you change these default values, this function must be called before any other function. A
return value of 0 indicates success and -1 indicates an error.

string StopOrders(string strategyId)


Gets a string of order ID's of all Stop Loss orders of an ATM Strategy separated by '|'. Internal
token ID value is used since it is guaranteed to be unique.

string Strategies(string account)

© 2011 NinjaTrader, LLC


180 NinjaTrader Version 7

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 StrategyPosition(string strategyId)


Gets the position for a strategy. Returns 0 for flat, negative value for short and positive value
for long.

int SubscribeMarketData(string instrument)


Starts a market data stream for the specific instrument. Call the MarketData() function to
retrieve prices. Make sure you call the UnSubscribeMarketData() function to close the data
stream. A return value of 0 indicates success and -1 indicates an error.

string TargetOrders(string strategyId)


Gets a string of order ID's of all Profit Target orders of an ATM Strategy separated by '|'.
Internal token ID value is used since it is guaranteed to be unique.

int TearDown()
Disconnects the DLL from the NinjaTrader server. A return value of 0 indicates success and -
1 indicates an error.

int UnsubscribeMarketData(string instrument)


Stops a market data stream for the specific instrument. A return value of 0 indicates success
and -1 indicates an error.
9.4.1.6.2 eSignal Sample Code

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.

© 2011 NinjaTrader, LLC


Operations 181

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,
"Filled", DLL.STRING, DLL.STRING);
dll.addFunction("MarketPosition", DLL.INT, DLL.
STDCALL, "MarketPosition", DLL.STRING, DLL.STRING);
dll.addFunction("NewOrderId", DLL.STRING, DLL.
STDCALL, "NewOrderId");
dll.addFunction("Orders", DLL.STRING, DLL.
STDCALL, "Orders", DLL.STRING);
dll.addFunction("OrderStatus", DLL.STRING, DLL.
STDCALL, "OrderStatus", DLL.STRING, DLL.STRING);
dll.addFunction("RealizedPnL", DLL.STRING, DLL.
STDCALL, "RealizedPnL", DLL.DOUBLE);
dll.addFunction("SetUp", DLL.INT, DLL.STDCALL,
"SetUp", DLL.STRING, DLL.INT);
dll.addFunction("Strategies", DLL.STRING, DLL.
STDCALL, "Strategies", DLL.STRING);
dll.addFunction("StrategyPosition", DLL.INT, DLL.
STDCALL, "StrategyPosition", DLL.STRING);
dll.addFunction("TearDown", DLL.INT, DLL.STDCALL,
"TearDown");
}

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: " +

© 2011 NinjaTrader, LLC


182 NinjaTrader Version 7

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");
}
}
}

// Get the average entry price of a position of an


account. "account" is optional.
function NTAvgEntryPrice(account) {
return dll.call("AvgEntryPrice", getSymbol(),
account);
}

// Get the average fill price of an order at an


account.
function NTAvgFillPrice(orderId) {
return dll.call("AvgFillPrice", orderId,
account);
}

// Get the buying power of an account.


function NTBuyingPower(account) {
return dll.call("BuyingPower", account);
}

// Place a buy limit order. "orderId" is optional


(set to "" it not applicable).
function NTBuyLimit(orderId, quantity, limitPrice) {
return NTCommand("Place", "", "Buy", quantity,
"Limit", limitPrice, 0, "", "", orderId, "", "");
}

// Place a buy market order. "orderId" is optional


(set to "" it not applicable).
function NTBuyMarket(orderId, quantity) {
return NTCommand("Place", "", "Buy", quantity,
"Market", 0, 0, "", "", orderId, "", "");
}

// Place a buy stop order. "orderId" is optional (set


to "" it not applicable).
function NTBuyStop(orderId "Buy", quantity,

© 2011 NinjaTrader, LLC


Operations 183

"StopLimit", limitPrice, stopPrice, "", "", orderId,


"", "");
}

// Cancel an order by its order id.


function NTCancel(orderId) {
return NTCommand("Cancel", "", "", 0, "", 0, 0,
"", "", orderId, "", "");
}

// Cancel all orders at all accounts.


function NTCancelAllOrders() {
return NTCommand("CancelAllOrders", "", "", 0,
"", 0, 0, "", "", "", "", "");
}

// Get the cash value of an account.


function NTCashValue(account) {
return dll.call("CashValue", account);
}

// Change an order by its order id.


function NTChange(orderId, quantity, limitPrice,
stopPrice) {
return NTCommand("Change", "", "", quantity, "",
limitPrice, stopPrice, "", "", orderId, "", "");
}

// Close any position of the current instrument at an


account. "account" is optional (set to "" it not
applicable).
function NTClosePosition(account) {
return NTCommand("ClosePosition", account, "", 0,
"", 0, 0, "", "", "", "", "");
}

// Submits a NinjaTrader command.


function NTCommand(command, account, action,
quantity, orderType, limitPrice, stopPrice,
timeInForce, oco, orderId, template, strategy) {
return dll.call("Command", command, account,
getSymbol(), action, quantity, orderType,
limitPrice, stopPrice, timeInForce, oco,
orderId, template, strategy);
}

// Indicates if the connection to NinjaTrader is


established. 0 = connected, -1 not connected.
function NTConnected() {

© 2011 NinjaTrader, LLC


184 NinjaTrader Version 7

return (dll.call("Connected") == 0)
}

// Get the filled of an order at an account.


function NTFilled(orderId) {
return dll.call("Filled", orderId, account);
}

// Close all positions and cancels all order at all


account.
function NTFlattenEverything() {
return NTCommand("FlattenEverything", "", "", 0,
"", 0, 0, "", "", "", "", "");
}

// Get a double value by its name.


function NTGetDouble(name) {
return dll.call("GetDouble", name);
}

// Get an integer value by its name.


function NTGetInt(name) {
return dll.call("GetInt", name);
}

// Get a string value by its name.


function NTGetString(name) {
return dll.call("GetString", name);
}

// Get the market position of the current instrument


at na account. "account" is optional (set to "" it
not applicable).
function NTMarketPosition(account) {
return dll.call("MarketPosition", getSymbol(),
account);
}

// Get a new unqiue order id.


function NTNewOrderId() {
return dll.call("NewOrderId");
}

// Gets a string of order ids of all orders of an


account separated by '|'. If a user defined order id
was not originally provided, the internal token id
// value is used since it is guaranteed to be unique.
function NTOrders(account) {
return dll.call("Orders", account);

© 2011 NinjaTrader, LLC


Operations 185

// Get the current status of an order.


function NTOrderStatus(orderId) {
return dll.call("OrderStatus", orderId, account);
}

// Get the realized P&L of an account.


function NTRealizedPnL(account) {
return dll.call("RealizedPnL", account);
}

// Place a sell limit order. "orderId" is optional


(set to "" it not applicable).
function NTSellLimit(orderId, quantity, limitPrice) {
return NTCommand("Place", "", "Sell", quantity,
"Limit", limitPrice, 0, "", "", orderId, "", "");
}

// Place a sell market order. "orderId" is optional


(set to "" it not applicable).
function NTSellMarket(orderId, quantity) {
return NTCommand("Place", "", "Sell", quantity,
"Market", 0, 0, "", "", orderId, "", "");
}

// Place a sell stop order. "orderId" is optional


(set to "" it not applicable).
function NTSellStop(orderId, quantity, stopPrice) {
return NTCommand("Place", "", "Sell", quantity,
"Stop", 0, stopPrice, "", "", orderId, "", "");
}

// Place a sell stop limit order. "orderId" is


optional (set to "" it not applicable).
function NTSellStopLimit(orderId, quantity,
limitPrice, stopPrice) {
return NTCommand("Place", "", "Sell", quantity,
"StopLimit", limitPrice, stopPrice, "", "", orderId,
"", "");
}

// Gets a string of strategy IDs of all strategies of


an account separated by '|'. Duplicate ID values can
be returned if strategies were initiated outside of
the ATI.
function NTStrategies(account) {
return dll.call("Strategies", account);
}

© 2011 NinjaTrader, LLC


186 NinjaTrader Version 7

// Get the position of a strategy.


function NTStrategyPosition(strategyId) {
return dll.call("StrategyPosition", strategyId);
}

9.4.1.6.3 TradeStation Sample Code

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] }

DefineDLLFunc: "NtDirect.dll", int, "Command", lpstr,


lpstr, lpstr, lpstr, int, lpstr, double, double,
lpstr, lpstr, lpstr, lpstr, lpstr;

inputs: Cmd(string), Account(string), Action(string),


Quantity(numericsimple), OrderType(string),
LimitPrice(numericsimple), StopPrice(numericsimple),
TimeInForce(string), Oco(string), OrderId(string),
Template(string), Strategy(string);

NTCommand = Command(Cmd, Account, GetSymbolName,


Action, Quantity, OrderType, LimitPrice, StopPrice,
TimeInForce, Oco, OrderId, Template, Strategy);

9.4.1.7 eSignal Integration

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.

© 2011 NinjaTrader, LLC


Operations 187

Copy the file C:\Program Files\NinjaTrader Installation Folder\bin\AutoTrade\NTSample.efs


To the folder <eSignal Installation Folder>\Formulas\Download
In eSignal, right click on chart and select the menu Formula > Download > NTSample
9.4.1.7.2 Functions

*Submitting an account value is optional. If no account value is passed in as an argument,


pass in empty string "" and the default account is used as specified under the ATI tab.

Data Retrieval Functions


double NTAvgEntryPrice(string acccount)
Gets the average entry price for the selected instrument/account combination.

double NTAvgFillPrice(string orderId)


Gets the average fill price of an order.

bool NTConnected(int showMessage)


Gets the current connection state of the ATI. Returns true when connected, false when
disconnected. The parameter showMessage indicates if a message box is displayed in
case the connection can not be established. A value of 1 = show message box, any
other value = don't show message box.

int NTFilled(string orderId)


Gets the number of contracts/shares filled for the orderId.

int NTMarketPosition(string account)


Gets the market position for the selected instrument/account combination. Returns 0 for
flat, negative for short and positive for long.

string NTNewOrderId()
Gets a unique order ID.

string NTOrders(string account)


Gets a string of order ID's of all orders of an account separated by '|'. *If a user defined
order ID was not originally provided, the internal token ID value is used since it is
guaranteed to be unique.

string NTOrderStatus(string orderId)


Gets the order state (see definitions) for the orderId. Returns an empty string if the order
ID value provided does not return an order.

double NTRealizedPnL(string account)


Gets the realized profit and loss of an account.

string NTStopOrders(string strategyId)


Gets a string of order ID's of all Stop Loss orders of an ATM Strategy separated by '|'.

© 2011 NinjaTrader, LLC


188 NinjaTrader Version 7

Internal token ID value is used since it is guaranteed to be unique.

string NTStrategies(string account)


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.

string NTStrategyPosition(string strategyId)


Gets the position of a strategy. Returns 0 for flat, negative for short and positive for long.

string TargetOrders(string strategyId)


Gets a string of order ID's of all Profit Target orders of an ATM Strategy separated by '|'.
Internal token ID value is used since it is guaranteed to be unique.

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 NTCommand(string command, string account, string action,


int quantity, string orderType, double limitPrice, double
stopPrice,
string timeInForce, string oco, string orderId, string
strategy, string strategyId)
Function for submitting, cancelling and changing orders, positions and strategies. Refer
to the Commands and Valid Parameters section for detailed information. A return value
of 0 indicates success and -1 indicates an error. The Log tab will list context sensitive
error information.

int NTConfirmOrders(int enable)


Enables order confirmation dialog box. 0 = false, 1 = true. This is a global NinjaTrader
setting that can be also set in the Control Center window by left mouse clicking on the
Tools menu, selecting the Options menu item and then checking "Confirm Order
Placement."

int NTClosePosition(string account)


Closes the selected instrument/account position. A return value of 0 indicates success
and -1 indicates an error. Success indicates success in submitting the command NOT
that the position has in fact been closed.

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.

Order Modification Functions

© 2011 NinjaTrader, LLC


Operations 189

int NTCancel(string orderId)


Cancels an order by orderId. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order has in
fact been cancelled.

int NTChange(string orderId, int quantity, double limitPrice,


double stopPrice)
Change an order by orderId. If you want to change an order that was automatically
submitted by an internal NinjaTrader ATM Strategy, use the intCommand function and
pass in the strategyId and order name (STOP1 or TARGET1 etc) via the orderId
parameter. A return value of 0 indicates success and -1 indicates an error. Success
indicates success in submitting the command NOT that the order has in fact been
changed.

Order Placement Functions


* Submitting an orderId value is optional. Optionally leave it to empty string "".

int NTBuyLimit(string orderId, int quantity, double limitPrice)


Sends a buy limit order. A return value of 0 indicates success and -1 indicates an error.
Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTBuyMarket(string orderId, int quantity)


Sends a buy market order. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTBuyStop(string orderId, int quantity, double stopPrice)


Sends a buy stop order. A return value of 0 indicates success and -1 indicates an error.
Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTBuyStopLimit(string orderId, int quantity, double limitPrice,


double stopPrice)
Sends a buy stop limit order. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTSellLimit(string orderId, int quantity, double limitPrice)


Sends a sell limit order. A return value of 0 indicates success and -1 indicates an error.
Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTSellMarket(string orderId, int quantity)


Sends a sell market order. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order was
successfully submitted.

© 2011 NinjaTrader, LLC


190 NinjaTrader Version 7

int NTSellStop(string orderId, int quantity, double stopPrice)


Sends a sell stop order. A return value of 0 indicates success and -1 indicates an error.
Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTSellStopLimit(string orderId, int quantity, double limitPrice,


double stopPrice)
Sends a sell stop limit order. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order was
successfully submitted.

9.4.1.7.3 Sample Code

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.

/* 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.
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,

© 2011 NinjaTrader, LLC


Operations 191

"Filled", DLL.STRING, DLL.STRING);


dll.addFunction("MarketPosition", DLL.INT, DLL.
STDCALL, "MarketPosition", DLL.STRING, DLL.STRING);
dll.addFunction("NewOrderId", DLL.STRING, DLL.
STDCALL, "NewOrderId");
dll.addFunction("Orders", DLL.STRING, DLL.
STDCALL, "Orders", DLL.STRING);
dll.addFunction("OrderStatus", DLL.STRING, DLL.
STDCALL, "OrderStatus", DLL.STRING, DLL.STRING);
dll.addFunction("RealizedPnL", DLL.STRING, DLL.
STDCALL, "RealizedPnL", DLL.DOUBLE);
dll.addFunction("SetUp", DLL.INT, DLL.STDCALL,
"SetUp", DLL.STRING, DLL.INT);
dll.addFunction("StopOrders", DLL.STRING, DLL.
STDCALL, "StopOrders", DLL.STRING);
dll.addFunction("Strategies", DLL.STRING, DLL.
STDCALL, "Strategies", DLL.STRING);
dll.addFunction("StrategyPosition", DLL.INT, DLL.
STDCALL, "StrategyPosition", DLL.STRING);
dll.addFunction("TargetOrders", DLL.STRING, DLL.
STDCALL, "TargetOrders", DLL.STRING);
dll.addFunction("TearDown", DLL.INT, DLL.STDCALL,
"TearDown");
}

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: " +

© 2011 NinjaTrader, LLC


192 NinjaTrader Version 7

NTRealizedPnL("") + "\r\n");
}
}
}

// Get the average entry price of a position of an


account. "account" is optional.
function NTAvgEntryPrice(account) {
return dll.call("AvgEntryPrice", getSymbol(),
account);
}

// Get the average fill price of an order at an


account.
function NTAvgFillPrice(orderId) {
return dll.call("AvgFillPrice", orderId,
account);
}

// Get the buying power of an account.


function NTBuyingPower(account) {
return dll.call("BuyingPower", account);
}

// Place a buy limit order. "orderId" is optional


(set to "" it not applicable).
function NTBuyLimit(orderId, quantity, limitPrice) {
return NTCommand("Place", "", "Buy", quantity,
"Limit", limitPrice, 0, "", "", orderId, "", "");
}

// Place a buy market order. "orderId" is optional


(set to "" it not applicable).
function NTBuyMarket(orderId, quantity) {
return NTCommand("Place", "", "Buy", quantity,
"Market", 0, 0, "", "", orderId, "", "");
}

// Place a buy stop order. "orderId" is optional (set


to "" it not applicable).
function NTBuyStop(orderId, quantity, stopPrice){
return NTCommand("Place", "", "Buy", quantity,
"Stop", 0, stopPrice, "", "", orderId, "", "");
}

// Cancel an order by its order id.


function NTCancel(orderId) {
return NTCommand("Cancel", "", "", 0, "", 0, 0,
"", "", orderId, "", "");

© 2011 NinjaTrader, LLC


Operations 193

// Cancel all orders at all accounts.


function NTCancelAllOrders() {
return NTCommand("CancelAllOrders", "", "", 0,
"", 0, 0, "", "", "", "", "");
}

// Get the cash value of an account.


function NTCashValue(account) {
return dll.call("CashValue", account);
}

// Change an order by its order id.


function NTChange(orderId, quantity, limitPrice,
stopPrice) {
return NTCommand("Change", "", "", quantity, "",
limitPrice, stopPrice, "", "", orderId, "", "");
}

// Close any position of the current instrument at an


account. "account" is optional (set to "" it not
applicable).
function NTClosePosition(account) {
return NTCommand("ClosePosition", account, "", 0,
"", 0, 0, "", "", "", "", "");
}

// Submits a NinjaTrader command.


function NTCommand(command, account, action,
quantity, orderType, limitPrice, stopPrice,
timeInForce, oco, orderId, template, strategy) {
return dll.call("Command", command, account,
getSymbol(), action, quantity, orderType, limitPrice,
stopPrice, timeInForce, oco, orderId,
template, strategy);
}

// Indicates if the connection to NinjaTrader is


established. 0 = connected, -1 not connected.
function NTConnected() {
return (dll.call("Connected") == 0)
}

// Get the filled of an order at an account.


function NTFilled(orderId) {
return dll.call("Filled", orderId, account);
}

© 2011 NinjaTrader, LLC


194 NinjaTrader Version 7

// Close all positions and cancels all order at all


account.
function NTFlattenEverything() {
return NTCommand("FlattenEverything", "", "", 0,
"", 0, 0, "", "", "", "", "");
}

// Get a double value by its name.


function NTGetDouble(name) {
return dll.call("GetDouble", name);
}

// Get an integer value by its name.


function NTGetInt(name) {
return dll.call("GetInt", name);
}

// Get a string value by its name.


function NTGetString(name) {
return dll.call("GetString", name);
}

// Get the market position of the current instrument


at na account. "account" is optional (set to "" it
not applicable).
function NTMarketPosition(account) {
return dll.call("MarketPosition", getSymbol(),
account);
}

// Get a new unqiue order id.


function NTNewOrderId() {
return dll.call("NewOrderId");
}

// Gets a string of order ids of all orders of an


account separated by '|'. If a user defined order id
was not originally provided, the internal token id
// value is used since it is guaranteed to be unique.
function NTOrders(account) {
return dll.call("Orders", account);
}

// Get the current status of an order.


function NTOrderStatus(orderId) {
return dll.call("OrderStatus", orderId, account);
}

// Get the realized P&L of an account.

© 2011 NinjaTrader, LLC


Operations 195

function NTRealizedPnL(account) {
return dll.call("RealizedPnL", account);
}

// Place a sell limit order. "orderId" is optional


(set to "" it not applicable).
function NTSellLimit(orderId, quantity, limitPrice) {
return NTCommand("Place", "", "Sell", quantity,
"Limit", limitPrice, 0, "", "", orderId, "", "");
}

// Place a sell market order. "orderId" is optional


(set to "" it not applicable).
function NTSellMarket(orderId, quantity) {
return NTCommand("Place", "", "Sell", quantity,
"Market", 0, 0, "", "", orderId, "", "");
}

// Place a sell stop order. "orderId" is optional


(set to "" it not applicable).
function NTSellStop(orderId, quantity, stopPrice) {
return NTCommand("Place", "", "Sell", quantity,
"Stop", 0, stopPrice, "", "", orderId, "", "");
}

// Place a sell stop limit order. "orderId" is


optional (set to "" it not applicable).
function NTSellStopLimit(orderId, quantity,
limitPrice, stopPrice) {
return NTCommand("Place", "", "Sell", quantity,
"StopLimit", limitPrice, stopPrice, "", "", orderId,
"", "");
}

// Get a string of order IDs of all stop orders of a


strategy separated by '|'.
function NTStopOrders(strategyId) {
return dll.call("StopOrders", strategyId);
}

// Gets a string of strategy IDs of all strategies of


an account separated by '|'. Duplicate ID values can
be returned if strategies were initiated outside of
the ATI.
function NTStrategies(account) {
return dll.call("Strategies", account);
}

// Get the position of a strategy.

© 2011 NinjaTrader, LLC


196 NinjaTrader Version 7

function NTStrategyPosition(strategyId) {
return dll.call("StrategyPosition", strategyId);
}

// Get a string of order IDs of all target orders of


a strategy separated by '|'.
function NTTargetOrders(strategyId) {
return dll.call("TargetOrders", 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.

Email Interface DLL Based Integration


Overview Overview
Symbol Mapping Set Up
Running concurrent strategies Functions
Set Up Sample Code
Order Handling Options Running NT on a different PC than TS
Stop Order Handling Tips
Workspace Options

9.4.1.8.1 Email Interface

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.

© 2011 NinjaTrader, LLC


Operations 197

The interface works as follows:


1. You apply a strategy in your TradeStation chart that generates buy/sell orders
2. TradeStation will send email notification for Strategy Orders Activated, Filled, Cancelled
and Replaced to NinjaTrader
3. NinjaTrader will process these emails and execute them as orders either to the
NinjaTrader simulator or your live brokerage account
9.4.1.8.1.1 Symbol Mapping

Please see the TradeStation Symbol Mapping section.


9.4.1.8.1.2 Running concurrent strategies in the same market

NinjaTrader uses a number of different properties in the TradeStation generated email to


identify unique orders as they are sent to NinjaTrader.

These properties include


Instrument name
Action (Buy, Sell etc...)
Signal name
Workspace name

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

This will ensure accurate processing of your automated signals.


9.4.1.8.1.3 Set Up

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

© 2011 NinjaTrader, LLC


198 NinjaTrader Version 7

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

Setting Up Antivirus Software


9. Antivirus software which scans outgoing emailing can impair the link between TradeStation
and NinjaTrader. If your PC has Antivirus software installed and scans outgoing mail, each
mail notification sent from TradeStation to NinjaTrader will be scanned and therefore add
significant delay in automatically processing your trading signals. Please consult your
Antivirus software Help Guide to determine how to disable the scanning of outgoing email.

Setting Up TradeStation Workspace


10. Start TradeStation
11. Set up your workspace options

Setting Up TradeStation Email Notification


12. Add a TradeManager window to your workspace by clicking on the icon on the left pane
as per the image below.

© 2011 NinjaTrader, LLC


Operations 199

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"

15. Press the "Configure..." button to bring up the "Messaging" window

© 2011 NinjaTrader, LLC


200 NinjaTrader Version 7

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"

Setting Up a TradeStation Strategy


19. Open a chart(s) of the instrument that you will run your strategy on
20. Right click in the chart and select the menu name "Insert Strategy..." and select a
strategy

© 2011 NinjaTrader, LLC


Operations 201

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.

© 2011 NinjaTrader, LLC


202 NinjaTrader Version 7

Understanding submit market order on TradeStation fill

Submit market order on TS fill


Submits a market order when NinjaTrader receives a "strategy filled order" notification
email from TradeStation. This is the recommended option.

Understanding submit "as-is"

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.

Understanding submit and forget

Submit and forget


Submits orders as specified (limit, market stop, stop limit) when NinjaTrader receives a "
strategy active order" notification. There is a high probability that your TradeStation
strategy position size will be out of synchronization with your live brokerage account
using this option. It requires manual user interaction and is NOT recommended.

© 2011 NinjaTrader, LLC


Operations 203

Understanding synchronization time out

Synchronization Time Out


Excluding the "Submit and forget" option, NinjaTrader will notify you after the specified
number of seconds if an order is out of sync with TradeStation's reported order fill
amount. An example would be if TradeStation reported a market order fill of 1 contract,
NinjaTrader submits a market order but the order is not filled for some reason after the
specified amount of time, you will be notified.

How to enable order confirmation

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.

Understanding special handling for FX through GAIN Capital/FOREX.com

Special Handling for FX through GAIN Capital/FOREX.com


GAIN will reject a limit order to buy at the offer or above or to sell at the bid or below.
NinjaTrader can check the current market rate on limit order submission and
automatically convert to market if the limit price is invalid according to GAIN but in your
favor resulting in a fill. To have NinjaTrader check for these conditions, you must be
subscribed to rate data for the currency pair being traded. We suggest opening a Market
Analyzer (to open a Market Analyzer window select the File menu and then the menu
name New) and adding all traded currency pairs to this grid. This ensures that there is
available rate data for NinjaTrader to cross check an incoming limit price against.
9.4.1.8.1.5 Stop Order Handling

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.

© 2011 NinjaTrader, LLC


204 NinjaTrader Version 7

How to submit stop orders "as-is"

Submit "as-is"
Submits the stop order as specified.

How to convert to stop limit orders

Convert to stop limit


Will convert a stop order to a stop limit order. The limit price is calculated based on the
user defined "Limit price offset as ticks" value.

How to convert to simulated stop market

Convert to Simulated Stop Market


Submits a simulated stop market order which is a local PC held order that submits a
market order once the stop price is hit.

How to submit market order if stop order was rejected

Submit market order if stop order was rejected


Submits a market order in the event that a stop order is rejected for any reason.

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)

© 2011 NinjaTrader, LLC


Operations 205

4. Stop order rejected due to limit price worse than stop price --> Market order submitted
and likely filled (risky)

DISCLAIMER: If this option is enabled, it is your responsibility to ensure that your TS EL


code is sending valid stop prices to NinjaTrader otherwise you risk getting filled when
you may not want to.
9.4.1.8.1.6 Workspace Options

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

How to create a new TradeStation workspace


From within TradeStation, you can create a new workspace by left mouse clicking on
the menu File, selecting the menu name New, and then selecting the menu name
Workspace. This will create an untitled workspace in TradeStation. You must then left
mouse click on the menu File and select the menu name Save Workspace As... to
provide a workspace name following the naming conventions listed below.

Understanding workspace naming convention functions


The workspace name must contain "NinjaTrader;" (one word, without the quotations)
otherwise NinjaTrader will NOT process any trade signals received from TradeStation.

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

© 2011 NinjaTrader, LLC


206 NinjaTrader Version 7

workspace which would multiple the strategy contract amount by a factor of 2. The text
would look like "Account=YourAccount=2"

Aliases - Chart Instrument "A" then Execute Orders in Instrument "B"


You can redirect orders to a different instrument than the instrument that your
TradeStation strategy is actually running on. For example, you can run a strategy on
$SPX.X but have orders actually placed to the S&P Emini contract. The text would look
like "Map=$SPX.X,ESH09" where $SPX.X is the TradeStation chart instrument followed
by a comma and then ESH09 which is the S&P Emini March 2009 contract which is the
contract that will be traded. Since you can have multiple charts running in a workspace,
you can add multiple mapping relationships. For example "Map=$SPX.X,
ESH09,$COMPX,MSFT" would map the $SPX.X to ESH09 and $COMPX would map to
MSFT.

Workspace name examples

Workspace Name Examples


Following are samples of valid TradeStation workspace names. Remember, you will
separate functions with a semi colon ";".

The following workspace name routes orders to the Default account specified under
Tools --> Options --> ATI tab
NinjaTrader

The following workspace name routes orders to account # 1235


NinjaTrader;Account=1235

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

Understanding multiple workspaces

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.

© 2011 NinjaTrader, LLC


Operations 207

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

Installation procedure for installing the TradeStation EasyLanguage


NinjaTrader functions
1. NinjaTrader must be installed
2. Start TradeStation
3. Select the TradeStation main menu File and then select the menu name Import/Export
EasyLanguage
4. Select "Import EasyLanguage file (ELD, ELS or ELA)"
5. Click "Next"
6. Select the file "<NinjaTrader Installation Folder>\bin\AutoTrade\NINJATRADER.ELD"
7. Click "Next"
8. Click "Next"
9. Click "Finish" and confirm any upcoming query box by clicking "OK"
10. When you actually start creating EL scripts that communicate with NinjaTrader, ensure
that Automated Trading is enabled from within NinjaTrader, to do so press down on your left
mouse button on the menu File and select the menu name AT Interface.

*A collection of NinjaTrader functions and a sample strategy named "NTSample" are


imported and ready to be used.
9.4.1.8.2.2 Functions

*Submitting an account value is optional. If no account value is passed in as an argument,


pass in empty string "" and the default account is used as specified under the ATI tab.

Data Retrieval Functions


double NTAvgEntryPrice(string account)
Gets the average entry price for the selected instrument/account combination.

double NTAvgFillPrice(string orderId)


Gets the average fill price of an order.

bool NTConnected(int showMessage)


Gets the current connection state of the ATI. Returns true when connected, false when
disconnected. The parameter showMessage indicates if a message box is displayed in
case the connection can not be established. A value of 1 = show message box, any
other value = don't show message box.

int NTFilled(string orderId)


Gets the number of contracts/shares filled for the orderId/account combination.

int NTMarketPosition(string account)


Gets the market position for the selected instrument/account combination. Returns 0 for
flat, negative for short and positive for long.

© 2011 NinjaTrader, LLC


208 NinjaTrader Version 7

string NTNewOrderId
Gets a unique order ID.

string NTOrders(string account)


Gets a string of order ID's of all orders of an account separated by '|'. *If a user defined
order ID was not originally provided, the internal token ID value is used since it is
guaranteed to be unique.

string NTOrderStatus(string orderId)


Gets the order state (see definitions) for the orderId. Returns an empty string if the order
ID value provided does not return an order.

double NTRealizedPnL(string account)


Gets the realized profit and loss of an account.

string NTStopOrders(string strategyId)


Gets a string of order ID's of all Stop Loss orders of an ATM strategy separated by '|'.
Internal token ID value is used since it is guaranteed to be unique.

string NTStrategies(string account)


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.

string NTStrategyPosition(string strategyId)


Gets the position of a strategy. Returns 0 for flat, negative for short and positive for long.

string TargetOrders(string strategyId)


Gets a string of order ID's of all Profit Target orders of an ATM Strategy separated by
'|'. Internal token ID value is used since it is guaranteed to be unique.

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 NTCommand(string command, string account, string action,


int quantity, string orderType, double limitPrice, double
stopPrice,
string timeInForce, string oco, string orderId, string
strategy, string strategyId)
Function for submitting, cancelling and changing orders, positions and strategies. Refer
to the Commands and Valid Parameters section for detailed information. A return value
of 0 indicates success and -1 indicates an error. The Log tab will list context sensitive
error information.

int NTConfirmOrders(int enable)

© 2011 NinjaTrader, LLC


Operations 209

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 NTClosePosition(string account)


Closes the selected instrument/account position. A return value of 0 indicates success
and -1 indicates an error. Success indicates success in submitting the command NOT
that the position has in fact been closed.

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.

Order Modification Functions


int NTCancel(string orderId)
Cancels an order by orderId. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order has in
fact been cancelled.

int NTChange(string orderId, int quantity, double limitPrice,


double stopPrice)
Change and order by orderId. If you want to change an order that was automatically
submitted by an internal NinjaTrader strategy, use the intCommand function and pass in
the strategyId and order name (STOP1 or TARGET1 etc) via the orderId parameter. A
return value of 0 indicates success and -1 indicates an error. Success indicates
success in submitting the command NOT that the order has in fact been changed.

Order Placement Functions


* Submitting an orderId value is optional. Optionally leave it to empty string "".

int NTBuyLimit(string orderId, int quantity, double limitPrice)


Sends a buy limit order. A return value of 0 indicates success and -1 indicates an error.
Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTBuyMarket(string orderId, int quantity)


Sends a buy market order. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTBuyStop(string orderId, int quantity, double stopPrice)


Sends a buy stop order. A return value of 0 indicates success and -1 indicates an error.
Success indicates success in submitting the command NOT that the order was
successfully submitted.

© 2011 NinjaTrader, LLC


210 NinjaTrader Version 7

int NTBuyStopLimit(string orderId, int quantity, double


limitPrice, double stopPrice)
Sends a buy stop limit order. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTSellLimit(string orderId, int quantity, double limitPrice


)
Sends a sell limit order. A return value of 0 indicates success and -1 indicates an error.
Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTSellMarket(string orderId, int quantity)


Sends a sell market order. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTSellStop(string orderId, int quantity, double stopPrice)


Sends a sell stop order. A return value of 0 indicates success and -1 indicates an error.
Success indicates success in submitting the command NOT that the order was
successfully submitted.

int NTSellStopLimit(string orderId, int quantity, double


limitPrice, double stopPrice)
Sends a sell stop limit order. A return value of 0 indicates success and -1 indicates an
error. Success indicates success in submitting the command NOT that the order was
successfully submitted.

9.4.1.8.2.3 Sample Code

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] }

inputs: FastLength(9), SlowLength(18) ;


variables: FastAvg(0), SlowAvg(0), Success(0);

if LastBarOnChart and NTConnected(1) then begin


if NTMarketPosition("") = 0 then begin
{ place an order, if there is no position
yet }
if AverageFC(Close, FastLength) >
AverageFC(Close, SlowLength) then begin

© 2011 NinjaTrader, LLC


Operations 211

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;

9.4.1.8.2.4 Running NT on a different PC than TS

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:

DefineDLLFunc: "NtDirect.dll", int, "SetUp", lpstr, int

2. You must call the SetUp function before calling any other DLL function. Following is
sample code on how to accomplish this.

if CurrentBar = 1 then begin


SetUp("remote-machine-name-or-ip", 36973);
end;

Where remote-machine-name-or-ip is the name or IP address of your PC.

* You can see the NTExternalFeed strategy for an example.


9.4.1.8.2.5 Tips

Tips for the DLL based integration


1. You can set a default account by pressing down on your left mouse button on the menu
Tools and selecting the menu name Options. You will then select the ATI tab in the Options
window, and select your preferred default account from the Default Account control list.

© 2011 NinjaTrader, LLC


212 NinjaTrader Version 7

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.

Setting Real-Time Strategy Options


Running a NinjaScript Strategy from a
Chart
Running a NinjaScript Strategy from
the Strategies Tab
Running FX Strategies

9.4.2.1 Setting Real-Time Strategy Options

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.

How to run a NinjaScript strategy in a 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

© 2011 NinjaTrader, LLC


Operations 213

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

Running a NinjaScript Strategy (see image below)


To run a NinjaScript strategy within a chart:

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:

1. List of available strategies


2. List of applied strategies to run on the chart
3. Selected strategy's properties

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.

6. Press the "OK" button to run 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.

© 2011 NinjaTrader, LLC


214 NinjaTrader Version 7

Understanding strategy properties

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):

© 2011 NinjaTrader, LLC


Operations 215

Paramet Sets any strategy specific user


ers defined inputs
section
Account Sets the account the strategy will
execute orders in
Calculat If true, will only calculate the
e on bar strategy's value on the close of a
close bar. If false, will calculate the
strategy's value on each incoming
tick.
Enabled Enables or disables the active
strategy
Input Please see the Input series section
series for further information.
Label Sets a text label that will be
displayed on the chart to represent
the strategy
Maximu Sets the maximum number of
m bars historical bars to use for strategy
look calculations. The
back TwoHundredFiftySix setting is the
most memory friendly.
Min. Sets the minimum number of bars
bars required before the backtest will
required start processing
Fill Type Sets the algorithm for processing
and filling orders on the historical
data portion of the chart
Slippage Sets the slippage amount in ticks
for the historical portion of the chart
Entries Sets the maximum number of
per entries allowed per direction while
direction a position is active based on the
"Entry handling" property
Entry Sets the manner in how entry
handling orders are handled. If set to
"AllEntries", the 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 When enabled, open positions are
close closed on the last bar of a session
Exit on Sets the number of seconds prior
close to the end of a session when open

© 2011 NinjaTrader, LLC


216 NinjaTrader Version 7

seconds positions of a strategy will be


closed
Stop & Sets how stop and target orders
target are submitted
submiss
ion
Sync Enables or disables an automatic
account attempt to sync the account
position position and strategy position.
Set Sets how the order size is
order 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 Sets the order's time in force
force
9.4.2.3 Running a NinjaScriptStrategy from the Strategies Tab

You can run a NinjaScript strategy in real-time in a live or simulation account via the
Strategies tab of the Control Center.

How to run a NinjaScript strategy from the Strategies tab

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:

NinjaTrader MUST be connected to a live brokerage or market data vendor


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 first.
Strategies initiated from the Strategies tab will NOT appear in a chart
If running an FX strategy, please review the "Running FX Strategies" section for critical
information

Running a NinjaScript Strategy


To run a NinjaScript strategy from the Strategies tab:

1. Left mouse click on the Strategies tab found in the NinjaTrader Control Center

© 2011 NinjaTrader, LLC


Operations 217

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.

Understanding strategy properties

Strategy Properties (see image below)


The image below shows the adjustable properties for a strategy available in the
Strategies tab of the Control Center (see the "How to run a NinjaScript strategy in from
the Strategies tab" section above):

Parameters Sets any strategy specific user defined inputs


section
Price based on Sets the type of market data used to drive the Data Series.
Type Sets the bar type of the Data Series.
Value Sets the Data Series value.
Instrument(s) Sets the instrument(s) the strategy will run against
Days to load Sets the number of days to load data
Session template Sets the session time template for the Data Series. (See the "
Session Manager" section of the Help Guide for more information)
Account Sets the account the strategy will execute orders in
Calculate on bar If true, will only calculate the strategy's value on the close of a bar. If
close false, will calculate the strategy's value on each incoming tick.
Label Sets a text label that will be displayed on the chart to represent the
strategy
Maximum bars Sets the maximum number of historical bars to use for strategy
look back calculations. The TwoHundredFiftySix setting is the most memory
friendly.
Min. bars required Sets the minimum number of bars required before the backtest will
start processing
Fill Type Sets the algorithm for processing and filling orders on the historical
data portion of the chart
Slippage Sets the slippage amount in ticks for the historical portion of the chart
Entries per Sets the maximum number of entries allowed per direction while a
direction position is active based on the "Entry handling" property
Entry handling Sets the manner in how entry orders are handled. If set to
"AllEntries", the 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
Exit on close Sets the number of seconds prior to the end of a session when open

© 2011 NinjaTrader, LLC


218 NinjaTrader Version 7

seconds positions of a strategy will be closed


Stop & target Sets how stop and target orders are submitted
submission
Sync account Enables or disables an automatic attempt to sync the account
position position and strategy position.
Set order quantity Sets how the order size is determined, options are:
"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 force Sets the order's time in force

© 2011 NinjaTrader, LLC


Operations 219

9.4.2.4 Running FX Strategies

It is important to understand how order quantities behave when running a real-time FX


strategy in a live brokerage account. This is relevant for:

Currency and point based performance calculations


Actual order size being submitted to your live brokerage account

© 2011 NinjaTrader, LLC


220 NinjaTrader Version 7

Running FX NinjaScript Strategies in the Strategy Analyzer, Simulated Data


Feed Connection or Market Replay
Running an FX strategy in the Strategy Analyzer for a historical backtest, in real-time
connected to either the Simulated Data Feed or Market Replay order quantities will always
represent the total units of the base currency being traded. A lot size of one equals a base
currency unit of one and DOES NOT equal a typical "standard" lot size of 100,000.
Therefore, if you want to trade a standard lot you would use an order quantity of 100,000.

Running FX NinjaScript Strategies on a Live Brokerage Connection


Running an FX strategy on a live brokerage connection either in a live funded account or a
simulation (Sim101) account order quantities will reflect the lot size convention that your
brokerage trades in. For example, if your brokerage has a lot size of 1 that equals 100,000
units of the base currency (a "standard" lot) then use a value of 1 to trade 100,000 base units.

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.

9.5 Backup & Restore


The Backup and Restore utility provides an easy way to save and recover critical user
generated data files such as but not limited to, user preferences, historical trade data and
historical chart data. Backing up your data ensures that you are protected in case of software
or hardware failure.

Creating a Backup Archive


Restoring a Backup Archive

9.5.1 Creating a Backup Archive


Complete the following steps to create a Backup Archive.

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...

© 2011 NinjaTrader, LLC


Operations 221

2. The "Backup NinjaTrader" dialog window will appear


3. Select the items you wish to back up
4. Press the "Run Backup" button

© 2011 NinjaTrader, LLC


222 NinjaTrader Version 7

9.5.2 Restoring a Backup Archive


Complete the following steps to restore a Backup Archive.

1. From within the Control Center window select the File menu. Then select the menu
Utilities and the Restore... menu item

© 2011 NinjaTrader, LLC


Operations 223

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

© 2011 NinjaTrader, LLC


224 NinjaTrader Version 7

Working with Reload


Drawing Tools Historical Data
& Objects Window
Saving Chart Linking
Defaults How Bars are
Data Box Built
Global Cross Power Volume
Hair Indicators
Chart
Properties

9.6.1 Creating a Chart


The following section covers how to open a NinjaTrader chart.

How to open a new chart

Opening a New Chart


To create a new chart, select the File menu from the NinjaTrader Control Center, then
select the New menu and select the menu item Chart. The Data Series window will
open where you can choose an instrument and an optional Template to apply to the
chart. Please see the "Working with Price Data" page of the Help Guide for more
information.

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.

© 2011 NinjaTrader, LLC


Operations 225

Understanding the chart display

Chart Display Overview


Each NinjaTrader chart is a free floating window that can be manually resized by
dragging the edges of the window for arrangement within the open Workspace.

The chart image below displays some of the common features you will see inside a
NinjaTrader chart window:

1. Right mouse click Access to all chart features


context menu
2. Chart display area Main display area of a chart where all chart objects (Data Series,
Indicators and Drawing Tools) are plotted.
3. Data Series and More information on panels here.
Indicator panels
4. Link button Window linking links windows to use the same instrument and can
be applied to many NinjaTrader windows.
5. Data Series and Displays the Data Series or Indicator label followed by the applied
Indicator labels period and parameters in the upper left hand corner of the chart
display area. The Label is an adjustable parameter within the Data
Series and Indicators windows.

© 2011 NinjaTrader, LLC


226 NinjaTrader Version 7

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.

9.6.2 Navigating a Chart


The following section covers navigation and display of NinjaTrader charts.

How to change the horizontal scale and range of a chart

© 2011 NinjaTrader, LLC


Operations 227

Horizontal Scrolling (panning chart left or right)


You can pan the chart left or right via the following controls:

Horizontal chart scroll bar at bottom of chart


Left mouse click and hold on chart canvas and drag left or right
CTRL key + Left mouse click and hold in the x-axis (time axis) and drag left or right
Mouse scroll wheel scrolls the chart back and forth along the x-axis 3 bars at a time
CTRL key + mouse scroll wheel scrolls the chart back and forth 9 bars at a time
Left arrow key scrolls the chart back one bar at a time
Right arrow key scrolls the chart forward one bar at a time
Page Up scrolls the chart back one page at a time
Page Down scrolls the chart forward one page at a time
Home key scrolls the chart to the very beginning
End key scrolls the chart to the very end

Out of Range Icon


If the horizontal axis is scrolled to the left or right from its starting location, a "return" icon
will appear in the top right hand corner of the chart. Left mouse click on the icon to return
the horizontal axis to its original position before scrolling occurred.

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 +

© 2011 NinjaTrader, LLC


228 NinjaTrader Version 7

Up and CTRL + Down.

How to change the vertical scale and range of a chart

Vertical Scrolling (panning chart up or down)


To pan the chart up or down:

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:

© 2011 NinjaTrader, LLC


Operations 229

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:

How to zoom in and out in a chart

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.

© 2011 NinjaTrader, LLC


230 NinjaTrader Version 7

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.

How to change the bar spacing and width


Before changing bar spacing or width, you must select the Data Series you want to
adjust by left mouse clicking on it. If none is selected, the primary Data Series of the
chart will be adjusted.

Bar Spacing
To change the spacing between bars:

CTRL + Up arrow key decreases bar spacing


CTRL + Down arrow key increases bar spacing

Bar Width
To change the width of bars:

ALT + Up arrow key decreases bar width


ALT + Down arrow key increases bar width

Alternatively, left mouse click on the "Bar style" chart toolbar icon to access bar spacing
and width functions

© 2011 NinjaTrader, LLC


Operations 231

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.

© 2011 NinjaTrader, LLC


232 NinjaTrader Version 7

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 Context Menu


Right mouse click within the price scale to access the panel context menu. The
following actions are available:

Move Up Moves the panel up by one


Move Down Moves the panel down by one
Maximize Maximizes the panel (an "M" along with left and right arrows will
appear in the lower right of the chart. Clicking the "M" will restore the
panel and using the arrow buttons will toggle the maximized window
between Data Series)
Restore Restores the maximized window to the original size
Arrange All Arranges all panels to default proportions
Remove Deletes the panel from the chart
Properties Opens the panel properties window

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.

© 2011 NinjaTrader, LLC


Operations 233

The following properties can be adjusted:

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"

How to drag and drop chart objects

Drag and Drop


A Data Series or Indicator can be dragged and dropped to various areas of the chart to
quickly change which panel it is displayed in.

Left mouse click on a chart object within a chart and drag and drop to any of the
following areas of the chart:

1. Upper limit - Creates a new panel at the top of the chart


2. In between panels - Creates a new panel in between two existing panels
3. Lower limit - Creates a new panel at the bottom of the chart
4. Center area of a panel - Relocates the selected chart object to this panel and
automatically determines the most suitable scale justification
5. Left or right area of a panel - Relocates the selected chart object to this panel (unless
already in the selected panel) and changes the scale justification to the selected side
of the panel.

© 2011 NinjaTrader, LLC


234 NinjaTrader Version 7

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.

How to change the z-order (paint order) of a chart object

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).

© 2011 NinjaTrader, LLC


Operations 235

To adjust the z-order:

1. Select the chart object by left mouse clicking on it


2. Hold down the "Shift" key on your keyboard and roll the mouse scroll wheel to change
the z-order of the object. The current position out of the total number of levels in the z-
scale will be displayed.

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.

How to change the cursor type

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)

© 2011 NinjaTrader, LLC


236 NinjaTrader Version 7

9.6.3 Working with Price Data


Data Series are added, edited, and removed via the Data Series window.

Understanding the Data Series Window

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.

Accessing the Data Series Window


There are multiple ways to access the Data Series window:

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

Sections of the Data Series Window


The image below displays the five sections of the Data Series window.

1. List of instruments that can be added as Data Series objects


2. Current Data Series objects applied to the chart
3. Selected Data Series object's parameters
4. Selected parameter's description
5. Saved Chart Templates that can be applied to the new chart. See the "Chart
Templates" section of the Help Guide for more information.

© 2011 NinjaTrader, LLC


Operations 237

How to add a Data Series

Adding a Data Series


Multiple Data Series objects can be applied within a chart and a new panel is
automatically created for each Data Series added unless specified to an existing panel.
There are multiple ways to add a Data Series to a chart using the Data Series window:

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)

© 2011 NinjaTrader, LLC


238 NinjaTrader Version 7

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)

Instrument Lookup Window


To search for an instrument using the Instrument Lookup window:

1. Select the Type for the instrument


2. Enter text in the Name or Description field
3. Left mouse click the Search button. Instruments satisfying the search criteria are
listed.
4. Once you have located the instrument, double left mouse click and press the "Enter"
key to add the instrument as a Data Series.

© 2011 NinjaTrader, LLC


Operations 239

How to edit Data Series parameters

Editing a Data Series


Data Series parameters are available for configuration within the Data Series window
once it is added to the chart (see the "How to add a Data Series" section above).

To edit Data Series parameters:

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.

© 2011 NinjaTrader, LLC


240 NinjaTrader Version 7

Data Series Parameters

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

© 2011 NinjaTrader, LLC


Operations 241

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.

Note: Real-time executions are timestamped with your local PC


clock when they are placed. Should your PC clock be out of sync
with the timestamps of the Bars on the chart the executions may
appear to show up on the wrong bar. Please see the How Trade
Executions are Plotted article for more information.

Saving a Data Series Type Parameters as Defaults


You can optionally save your customized Data Series Type parameters as default.
Doing so will recall your customized settings the next time you add this specific Data
Series Type to a chart.
(Please see the "Saving Chart Defaults" section of the Help Guide for more information.)

How to change a Data Series

© 2011 NinjaTrader, LLC


242 NinjaTrader Version 7

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.

Changing an Instrument via Chart Toolbar


To change an instrument using the chart toolbar:

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.)

Changing an Interval via Chart Toolbar


To change an interval using the chart toolbar:

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.

Changing and Adding Instruments and Intervals via Keyboard


You can change instruments or intervals by pressing a letter or number key in a selected
chart. Within the window that appears, you can change the instrument, interval, or chart
type by using the following formats and pressing the "Enter" key when finished. If
multiple instruments are displayed in the chart, you can change a specific instrument by
left mouse clicking to select it before typing. If no instrument is selected, the primary
instrument is changed.

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

© 2011 NinjaTrader, LLC


Operations 243

series of primary minute chart of the primary instrument.


instrument
To add additional Type a plus sign (+) + the instrument and interval. Example: "
series of any +AAPL 5M" will add a 5 minute series of Apple stock. If no interval
instrument is provided, then the same interval as the primary series will be
added.

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.

Removing a Data Series

Removing a Data Series


There are three ways to remove a Data Series from your NinjaTrader chart:

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.

Working with multiple Data Series

Multiple Data Series


Multiple Data Series objects of all types can be be viewed within a single chart window.
There are several ways to add Data Series objects to the chart. Please see the "How to
add a Data Series" section above for more information.

The image below shows two Data Series plotted within one chart window:

1. ES 12-09 (1 Min)

2. NQ 12-09 (150 Tick)

© 2011 NinjaTrader, LLC


244 NinjaTrader Version 7

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.

Equidistant Bar Spacing


Equidistant Bar Spacing is a chart property that determines whether bars are plotted
with an equal distance from each other, or plotted on a horizontal axis with even time
spacing. The two images below display the same chart with the property set to
"True" (below left) and "False" (below right). When true, the distance between bars is
equal throughout the chart. When false, the distance between bars is not necessarily the
same. Bars are instead plotted on a fixed x-axis timeline where every inch along the axis
represents an equal amount of time. This allows for the benefit of being able to gauge
momentum on non-time based charts, such as tick or volume, by visualizing how long it
takes to finish building the next bar. Gaps may occur if no bar formed during the time
interval. Overlapping bars may occur if bars are formed near the same time period. Both
gaps and overlapping can be seen in the below right image. Equidistant Bar Spacing
can be enabled or disabled within the Chart Properties window.

© 2011 NinjaTrader, LLC


Operations 245

Equidistant Bar Spacing = True Equidistant Bar Spacing = False

Equidistant Bar Spacing with Multiple Data Series


When adding two or more Data Series to a chart, the property "Equidistant bar
spacing" will automatically be set to "False" within the Chart Properties window. This
is necessary so that mixed Data Series intervals, such as tick and minute, can now be
viewed without the natural distortion due to time differences.

Aggregated X-Axis Time Line


When using multiple Data Series with different session templates, NinjaTrader will
create an x-axis using the earliest begin time and latest end time of all session
templates applied to the Data Series objects on the chart. For example, if instrument A
has a session begin time of 7:00 AM and end time of 2:00 PM, instrument B has session
begin time of 8:00 AM and end time of 4:00 PM, the chart will have a session begin time
of 7:00 AM and end time of 4:00 PM.
9.6.4 Bar Types
NinjaTrader supports a large variety of chart bar Types. This page explains how each bar
type is created in a chart. Please see the Working with Price Data page for information on
how to change bar Types.

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.

Understanding Tick bars

Tick Bars

© 2011 NinjaTrader, LLC


246 NinjaTrader Version 7

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.

Understanding Volume bars

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.

© 2011 NinjaTrader, LLC


Operations 247

Understanding Range 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.)

© 2011 NinjaTrader, LLC


248 NinjaTrader Version 7

*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.

Understanding time based bars

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.

© 2011 NinjaTrader, LLC


Operations 249

Understanding Kagi bars

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.

© 2011 NinjaTrader, LLC


250 NinjaTrader Version 7

Understanding Renko bars

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.

© 2011 NinjaTrader, LLC


Operations 251

Understanding Point and Figure bars

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

© 2011 NinjaTrader, LLC


252 NinjaTrader Version 7

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.

Understanding Line Break bars

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.

© 2011 NinjaTrader, LLC


Operations 253

9.6.5 Working with Indicators


NinjaTrader comes with over 100 pre-built indicators. Indicators can be added, removed and
edited via the Indicators window.

Understanding the Indicators window

The Indicators window is used to add, remove and edit all indicators within a chart.

Accessing the Indicators Window


There are multiple ways to access the Indicators window:

Left click on the indicator icon in the chart toolbar


Right mouse click in the chart background when no chart object is selected and select
the menu Indicators
Double click on an indicator within a chart
Right click on a highlighted indicator within a chart and select the menu Properties
Use the default CTRL + I Hot Key when the chart has focus.

Sections of the Indicators Window


The image below displays the four sections of the Indicators window.

1. List of available indicators

© 2011 NinjaTrader, LLC


254 NinjaTrader Version 7

2. Current indicators applied to the chart


3. Selected indicator's parameters
4. Selected indicator or parameter's description

How to add an indicator

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)

© 2011 NinjaTrader, LLC


Operations 255

How to edit an indicator's parameters

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.

© 2011 NinjaTrader, LLC


256 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Operations 257

plotted by the indicator.


Plots Allows you to customize the appearance of the indicator by changing:
the Color, Dash style, Plot style, and Width.

Saving an Indicator's Parameters as Default


You can optionally save your customized indicator's parameters as default. Doing so will
recall your customized settings the next time you add this specific indicator to a chart.

Please see the Saving Chart Defaults section of the Help Guide for more information.

Indicator Input Series


The indicator Input Series window (image right) allows you to select the input series for
your indicator's calculations. To access this window left mouse click on the "..." button
within the Input series parameter. You can then select the Close, High, Low, Median,
Open, Typical, or Weighted value of any Data Series within a chart. Additionally, you
can also choose another indicator as the input series. When you select another
indicator as the input series, another Input Series window will appear where you can
define the input series for the second indicator. This allows you to nest multiple
indicators. Once you have selected the input series of your choice left mouse click the
OK button to exit the Input Series window.

How to remove an indicator

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.

Custom indicator development


In addition to the over 100 indicators that come pre-built with the NinjaTrader application,
you also have the ability to create custom indicators of your own. For example, you
could create your own custom multi-series indicators to apply to your NinjaTrader
charts.

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

© 2011 NinjaTrader, LLC


258 NinjaTrader Version 7

available.

9.6.6 Working with Drawing Tools & Objects


There are many customizable drawing tools and objects available to use in NinjaTrader
charts.

How to draw on a chart

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.

Accessing Drawing Objects


Drawing objects can be accessed in the following ways:

© 2011 NinjaTrader, LLC


Operations 259

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

Stay in Draw Mode


When "Stay in Draw Mode" is enabled from the Drawing Tools menu, drawing tools will
stay selected and can be used to draw multiple times without having to access the
Drawing Tools menu.

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.

To use the Ruler:

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.

© 2011 NinjaTrader, LLC


260 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Operations 261

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

Applying a Drawing Object to the Chart


To apply a drawing object to the chart:

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.

© 2011 NinjaTrader, LLC


262 NinjaTrader Version 7

Understanding snap mode

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

Understanding drawing object properties

© 2011 NinjaTrader, LLC


Operations 263

Each drawing tool can be customized using the Drawing Object Properties menu.

Accessing the Drawing Object Properties


To access a drawing object properties:

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

Drawing Object Properties Menu


Properties vary between drawing objects. There are common properties as shown in
the Line Properties image below and specific properties depending on the drawing
object.

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.

Color Sets the color of the drawing object


Width Sets the width of the drawing object
Dash Sets the drawing object dash style
Style
Attach to Applies the drawing object to the selected instrument on a single chart or all
charts with the same instrument. (see the "How to Enable a Global Drawing
Object" section below)
Lock Locks the drawing object on the chart which makes it immovable.
Auto Adds the drawing object to the auto-scaling in the chart.
Scale

© 2011 NinjaTrader, LLC


264 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Operations 265

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.

How to remove drawing objects

Removing Drawing Objects


To remove a single drawing object:

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

To remove multiple drawing objects at the same time:

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.

© 2011 NinjaTrader, LLC


266 NinjaTrader Version 7

Removing a global drawing object will remove the object from all charts.

Understanding Fibonacci drawing object templates

© 2011 NinjaTrader, LLC


Operations 267

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.

How to Save Fibonacci Templates


To save Fibonacci properties as a template:

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.

(Press the Remove button to delete the selected 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.

Understanding local vs. global drawing objects

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.

How to Enable a Global Drawing Object


To enable a global drawing object:

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.

© 2011 NinjaTrader, LLC


268 NinjaTrader Version 7

This is done to conserve PC resources.


9.6.7 Working with Automated Strategies
Automated NinjaScript strategies can be started within an open chart. Both real-time and
historical strategy trades will be shown.

Running a NinjaScript Strategy from a chart


Please see this section of the help guide for more information on running a NinjaScript
strategy from a chart.

Working with automated strategies in a chart

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.

Viewing automated strategies in a 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.

© 2011 NinjaTrader, LLC


Operations 269

Viewing strategy performance

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.

© 2011 NinjaTrader, LLC


270 NinjaTrader Version 7

9.6.8 Chart Templates


Chart Templates are a way to save user defined customized settings for future recall.

How to save a Chart Template

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.

Saving a Chart Template


To save a Chart Template:

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.

Chart Template Default


A Chart Template can be saved as the default template used for charts. Once saved,

© 2011 NinjaTrader, LLC


Operations 271

all new charts will use the default Chart Template.

To save a Chart Template as default:

1. Right mouse click within an open chart and select the Templates menu
2. Select the menu item Save as Default

How to load or remove a Chart Template

Loading a Chart Template


A Chart Template that was previously saved can be reloaded on any chart that has the
same number of Data Series as what was saved in the Chart Template . To load a
Chart Template:

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.

Removing a Chart Template


To remove a Chart Template from the list of saved templates:

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.

9.6.9 Saving Chart Defaults


NinjaTrader allows you to save many of your customized chart settings as default.

Understanding Data Series default settings


Each Period Type can have different default settings saved for the customizable Data
Series parameters. Once saved as default, the customized parameters will load when
the Period Type is selected.

What is Saved
All parameter settings are saved with the following exceptions:

End date will default to the current day's date


Label will default to the instrument name
Panel will stay on its current panel
Scale justification will default to "Right"
Session template will default to "<Use instrument settings>"

© 2011 NinjaTrader, LLC


272 NinjaTrader Version 7

Saving Custom Data Series Settings


To save Data Series parameters as default for a Period Type:

1. Set parameters to desired values


2. Right click within the parameters section of the Data Series window and select the
menu item Set Default For '(Type)' Period Type

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.

Understanding indicator default settings


Each individual indicator's parameters can be saved as default. Once saved as default,
the customized parameters will load whenever the specified indicator is added to a
chart.

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

Saving Custom Indicator Settings


To save Indicator parameters as default:

© 2011 NinjaTrader, LLC


Operations 273

1. Set parameters to desired values


2. Right click within the parameters section of the Indicators window and select the
menu item Set Default For (Indicator)

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.

Understanding strategy default settings


Each NinjaScript strategy's parameters can be saved as default. Once saved as default,
the customized parameters will load whenever the specified strategy is applied to the
chart.

What is Saved
All parameter settings are saved with the following exceptions:

Account defaults to the Sim101 account


Calculate on bar close defaults to True
Enabled defaults to False
Fill type defaults to Default

Saving Custom Strategy Settings


To save custom NinjaScript strategy parameters as default:

© 2011 NinjaTrader, LLC


274 NinjaTrader Version 7

1. Set parameters to desired values


2. Right click within the parameters section of the Strategies window and select the
menu item Set Default For (Strategy)

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.

Understanding chart property default settings


Customized chart property parameters can be saved as default. Once saved as default,
the customized parameters will load whenever a new chart is opened. The Chart
Properties window can be opened by left mouse clicking on the Properties icon in the
chart toolbar, by selecting the menu item Properties from the right click menu in the
chart, or via the CTRL + T Hot Key.

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.)

Saving Custom Chart Property Settings


To save custom chart parameters as default:

© 2011 NinjaTrader, LLC


Operations 275

1. Set parameters to the desired values


2. Left mouse click on the Set Default 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.

Understanding Drawing Object default settings


Drawing object properties can be saved as default. The saved properties will be applied
to any new drawing objects of the same type that are applied to the chart.

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.

© 2011 NinjaTrader, LLC


276 NinjaTrader Version 7

Properties within the Data tab are NOT saved.

Saving Drawing Object Default Settings


To save drawing object settings as default:

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.

Understanding the Mini Data Box

Opening the Mini Data Box


To access the Mini Data Box hover your mouse cursor over the chart panel you would
like to see values from and then press down on your middle mouse button. After
pressing and holding down your middle mouse button, the Mini Data Box will appear
with all of the bar data (Date/Time, Open, etc). You can then optionally continue holding
down your middle mouse button as you move to view values for other bars or release
your middle mouse button to hide the Mini Data Box once more.

Mini Data Box Display


The Mini Data Box displays the Date/Time, Open, High, Low, Close and Volume
information of the selected bar on the chart. This view is excellent for quick access to
information on a specific bar.

© 2011 NinjaTrader, LLC


Operations 277

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:

The date will be displayed first


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).

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.

Understanding the Data Box

Opening a Data Box


The Data Box displays all bar data and indicator values based on your mouse cursor
position. You can enable or disable this window via the right mouse click context menu,
the "Show Data Box" chart toolbar icon, or by using the shortcut keys CTRL+D. If you
have multiple charts open, the Data Box will display the values of the chart that your
mouse cursor is currently hovering over. Being able to use one Data Box for multiple
charts eliminates the need to open multiple Data Boxes and conserves monitor space.

© 2011 NinjaTrader, LLC


278 NinjaTrader Version 7

Data Box Display


The Data Box (image below) displays the date, and then all Data Series and indicator
information by panel number.

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.

© 2011 NinjaTrader, LLC


Operations 279

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.

Indicator Time Stamps on Multi-Series Charts


If an indicator is in a panel that does not include its underlying Data Series, the plot name
will have a time stamp to indicate what bar time the corresponding value belongs to.

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.

Data Box Options


To access the Data Box options press down on your right mouse button anywhere in
the Data Box to access the context menu.

The following options are available:


Always On Top When enabled will keep the Data Box as the top window in
your workspace so the values are always visible
Auto Size When enabled your data box will re-size as you move your
cursor between charts to meet each chart's display
requirements.
Show Data Series Labels Enables or Disables the display of the Data Series labels

© 2011 NinjaTrader, LLC


280 NinjaTrader Version 7

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.

How to enable the Global Cross Hair

Enabling the Global Cross Hair


There are multiple ways to enable the Global Cross Hair within a chart window:

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.

© 2011 NinjaTrader, LLC


Operations 281

How to use the Global Cross Hair

Using the Global Cross Hair


The Global Cross Hair must be enabled on more than one chart in order to view its
functionality.

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.

© 2011 NinjaTrader, LLC


282 NinjaTrader Version 7

Global Cross Hair Tips

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.

9.6.12 Trading from a Chart


Please see the Chart Trader section under Order Entry for more information on trading from
a chart.
9.6.13 Chart Properties
Many of the visual display settings of NinjaTrader charts can be customized using the Chart
Properties window.

How to access the Chart Properties window


The Chart Properties window can be accessed in the following ways:

1. Left mouse click the Properties button in the chart toolbar


2. Right mouse click within the chart and select the menu item Properties
3. Use the default CTRL + T Hot Key

© 2011 NinjaTrader, LLC


Operations 283

Available properties and definitions

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

© 2011 NinjaTrader, LLC


284 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Operations 285

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.

Volume Profile Indicator


The VolumeProfile indicator plots a real-time volume profile as a vertical histogram on a
chart. Each bar represents the volume (number of trades) that accumulate at each bar from
the time the indicator is started or re-started on the chart. Bars are color coded to represent
number of buys (trades at the ask or higher), sells (at the bid or lower) and neutrals (between
the market). This power volume indicator provides you with instant feedback to gauge where
support and resistance levels are and if their is accumulation or distribution taking place at
those levels. A cyan colored diamond is automatically drawn at the starting bar of the
VolumeProfile indicator.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.

Volume Zones Indicator


The VolumeZones indicator plots a horizontal histogram on the left side of a chart that
indicates volume levels on historical. The length of each bar represents the cumulative total
of all volume bars for the periods during which the closing price (user defined price type) fell
within the vertical price range of the histogram bar. Each bar is color coded to differentiate up
(Close > Open) and down (Close < Open) volume. This indicator is designed for use against
historical data only and NOT intended to be used on real-time data. Use the "Volume Profile
Indicator" for real-time data.
9.6.15 Reload Historical Data
While you are connected to a market data provider that supports historical data, right mouse
click within a chart to bring up the context menu and select the Reload All Historical Data
menu item. Historical data for the base interval unit (minute bars for a 5 minute chart for
example) will be reloaded for all charts of the same instrument.

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.

© 2011 NinjaTrader, LLC


286 NinjaTrader Version 7

9.6.16 Window Linking


Please refer to the Window Linking section of the Help Guide for more information on linking
chart windows.
9.6.17 How Bars are Built
NinjaTrader builds chart bars from the data provided by your data provider. There are multiple
elements in the bar building process that can influence how bars are built.

Understanding the variables involved in building chart bars

Bar Time Stamp


NinjaTrader stamps a bar with the closing time of the bar. For example, a minute bar with a
time of 9:31:00 AM has data from 9:30:00 AM through 9:30:59 AM. Using end of bar time
stamps is required in order to be able to plot multiple series of differing time frames within a
single chart all accurately synchronized to time.

Discrepancies Between Different Data Feeds


Different data feeds produce different charts, especially when using tick based intervals vs
time based intervals. Market data vendors each employ various methods for tick filtering,
throttling and time stamping. As a result, no data stream is 100% identical and thus can
cause subtle differences in charts. Since NinjaTrader supports many of the leading brokerage
and data feed technologies, it is highly likely that two traders using NinjaTrader on different
data feeds will have minor differences when plotting the same market and time interval.

Time Settings
Different session templates as well as the date range of data being plotted can affect the
chart display and indicator values.

Real-Time Tick Filter


If you have the real-time tick filter enabled, it is possible that your offset percent (the percent
away a tick is in value from the last traded price to be considered a bad tick) may be too tight
and thus a good tick (gap up/down on session open for example) could be excluded from the
bar.

Understanding the underlying base data type required for constructing various chart
bars

Base Data Types Used to Build Bars


A chart bar (period type) requires a base data type as its source for bar construction.
Following are NinjaTrader supported period types and their required base data type
values. A check mark represents the data base value that is needed to build the period
type.

Period type Base data type values


Tick Minute Daily

© 2011 NinjaTrader, LLC


Operations 287

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.

© 2011 NinjaTrader, LLC


288 NinjaTrader Version 7

Loading Historical Data


Please see the "Historical & Real-Time Data" section of the Help Guide for more
information.

9.6.18 How Trade Executions are Plotted


Trade executions in NinjaTrader are tied to specific timestamps based on when the
execution actually occurs as opposed to specific bars on the chart. NinjaTrader does it this
way to allow you the flexibility of using multiple charts of differing period types and still being
able to visualize where the trade executions occurred. The following article outlines some
scenarios with time based execution plotting.

Understanding trade executions and the local PC clock


When a trade execution occurs in NinjaTrader it is timestamped with your local PC clock's
time at that exact moment. One situation that can arise is that your PC clock is not in sync
with your data feed. When this happens the trade execution may be shown on the chart on a
bar where it seems like the fill is not feasible.

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.

© 2011 NinjaTrader, LLC


Operations 289

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.

Understanding trade executions on charts with tick based intervals


When using a chart with tick based intervals in NinjaTrader it is possible to have several bars
with the same timestamp. This usually happens during high volatility times when heavy
trading is happening within a very short amount of time. Since there are many bars with the
same timestamp, NinjaTrader can only plot the trade execution on the first bar with the
same timestamp of the execution since the executions are not tied to specific bars, but tied to
specific timestamps. This can appear as if the trade execution occurred with an invalid fill
price, but in reality the execution did occur on a valid price, just on a later bar with the same
timestamp.

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

© 2011 NinjaTrader, LLC


290 NinjaTrader Version 7

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.

9.7 Control Center


The NinjaTrader Control Center provides a centralized view of account, execution, order,
historical log, and position information. It also provides access to all of the various
NinjaTrader function windows and enables/disables global application features and
commands.

The Control Center can be broken down into three sections. The menu system, the
information tabs, and the status bar.

© 2011 NinjaTrader, LLC


Operations 291

Menu System Information Tabs

File menu Orders Tab


Tools menu Strategies Tab
Help menu Executions Tab
Positions Tab
Status Bar Accounts Tab
Account Performance Tab
Status Bar Log Tab

9.7.1 File Menu


The following menus and items are available via the File menu of the NinjaTrader Control
Center.

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

© 2011 NinjaTrader, LLC


292 NinjaTrader Version 7

Exit Exits the application


9.7.2 Tools Menu
The following menus and items are available via the Tools menu of the NinjaTrader Control
Center.

Instrument Opens the Instrument Manager


Manager
Historical Opens the Historical Data Manager
Data
Manager
Session Opens the Session Manager
Manager
Hot Key Opens the Hot Key Manager
Manager
New Creates a new NinjaScript indicator or strategy
NinjaScript
Edit Edits NinjaScript indicators and strategies
NinjaScript
Output Opens the NinjaScript output window
Window
Account Opens a wizard to create and manage account connections
Connection
s
Options Opens a window for managing application options

9.7.3 Help Menu


The following menus and items are available via the Help menu of the NinjaTrader Control
Center.

© 2011 NinjaTrader, LLC


Operations 293

Help Opens the application help guide


Search Opens the application help guide in search mode
Support Links to the NinjaTrader customer support center
Center
Mail to Sends email support request
Support
DownloadDownload the latest version of NinjaTrader
Site
Trade Purchase or lease a live NinjaTrader license for placing trades into your brokerage
Live account
License Sets the NinjaTrader license key
Key
3rd party Verification for 3rd party add on products
licensing
About About NinjaTrader

9.7.4 Orders Tab


The Orders tab is broken down into three sections: order grid, order entry, and market
display.

Understanding the order grid section

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.

© 2011 NinjaTrader, LLC


294 NinjaTrader Version 7

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.

Right Click Menu


Right mouse click within the order grid section to access the right click menu. The
following order grid specific features are available:

Cancel Order Cancels the selected order


Cancel All Cancels all working orders
Orders
Filter Only Displays only active orders
Active Orders
Filter By Filters orders by selected account
Account
Grid Sets grid properties

Understanding the order entry section

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.

© 2011 NinjaTrader, LLC


Operations 295

Submitting Orders
To submit an order:

1. Select the instrument


2. Set the desired order parameters
3. Left mouse click on the Buy or Sell button

Order Parameters

Order Type Sets the order type


Qty Sets the order quantity
Limit Price Sets the limit price
Stop Price Sets the stop price
TIF Sets the time in force
OCO *Sets an OCO (One cancels other) id
Account Sets the account the order will be submitted to

* 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.

Understanding the market display section

Market Display
The market display section shows market data for the currently selected instrument
from the order entry section. (See the section above).

9.7.5 Strategies Tab


The Strategies tab displays running and terminated strategies and allows you to view
strategy performance information.

Understanding the Strategies tab

Strategy Display
Active and stopped strategies are listed as a grid and can be started/stopped by left

© 2011 NinjaTrader, LLC


296 NinjaTrader Version 7

mouse clicking on the button in the Enabled column.

Green highlighted "Strategy" cell indicates a currently running strategy.


Yellow highlighted "Strategy" cell indicates the strategy is waiting until it reaches a flat
position to be in sync with the account position before fully starting. (Please see the
options Strategies Tab section for configuration options)
White highlighted "Strategy" cell indicates a disabled strategy.

Strategies using multiple instruments will be expandable so that each instrument's


strategy position can be viewed. In the image above, the first strategy is using ES 12-09
as well as MSFT which is shown below it.

Right Click Menu


Right mouse click in the grid display area to access the right click menu. The following
order grid specific features are available:

New Strategy... Run a new automated NinjaScript strategy


Edit Strategy Brings up the Edit Strategy window to edit the strategy parameters
for the selected strategy. (Only disabled strategies can be edited)
Enable Enables the strategy
Disable Disables the strategy
Remove Removes the selected strategy from the grid
Strategy Generates a performance report for the selected strategy (See the "
Performance How to view strategy performance" section below)

© 2011 NinjaTrader, LLC


Operations 297

Filter Only Active Displays only active strategies


Strategies
Filter By Account Sets which strategies to display by account
Grid Sets the grid properties

How to view strategy performance

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.

Historical - Generates performance data for historical data only.


9.7.6 Executions Tab
The Executions tab displays all executions in a data grid.

Understanding the Executions tab

Executions Data Grid


The current day's execution information will be shown in the data grid when connected
to your brokerage connection. Simulated trades (into any simulation account) will appear
when connected to any data feed connection.

© 2011 NinjaTrader, LLC


298 NinjaTrader Version 7

Right Click Menu


Right mouse clicking within the order grid opens the following menu:

Filter By Sets which executions to display by account


Account
Add Add an execution to the database (See the "How to add executions"
section below)
Remove Remove an execution from the database
Chart Opens a chart of the instrument at the time of the selected execution
Grid Sets the grid properties

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.

How to add executions

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.

To add an execution to the database:

1. Right mouse click in the Executions tab and select the Add... menu item. The Add
Execution window appears.

© 2011 NinjaTrader, LLC


Operations 299

2. Input your desired execution parameter values in the image below


3. Press the OK button

The execution is now added to the database and will be used in performance reporting.

9.7.7 Positions Tab


The Positions tab displays the current open positions in a data grid.

Positions Display
Open positions are displayed in the data grid.

Right Click Menu


Right mouse clicking within the order grid section opens the following menu:

© 2011 NinjaTrader, LLC


300 NinjaTrader Version 7

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.

9.7.9 Account Performance Tab


The Account Performance tab allows you to generate customized performance data
against your trade history for a selected account. Performance data is displayed in the
Performance Data tabs and as efficiency graphs.

Understanding the performance report

Performance Report
To generate a performance report:

1. Select the From and To date range for the report


2. Select the Mode for the performance data to be displayed in. The options are
Percent, Currency, Points.
3. Press the Generate button

Performance data is generated and displayed in the various Performance Data Tabs.

© 2011 NinjaTrader, LLC


Operations 301

Group trades by ATM strategy


When this option is selected, trades are reported based on ATM Strategies. For
example, if you have an ATM Strategy that had multiple entries and exits, all executions
are grouped and reported as one trade record under the Trades tab with single average
entry and exit prices.

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.

Understanding the Advanced menu

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.

1. Accounts Sets the account(s) to be included in the performance report


2. Sets the instruments to be included in the performance report
Instruments
3. TemplatesSets the ATM strategies to be included in the performance report
4. Providers Sets the connectivity providers to be included in the performance report
5. Type Sets the instrument type used to filter historical trade data for the
performance report
6. Compare Opens a new performance window to generate a new performance report
for comparison

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)

© 2011 NinjaTrader, LLC


302 NinjaTrader Version 7

9.7.9.1 Performance Data Tabs

The performance data tabs display historical trade performance data. This performance data
can be accessed from the following locations:

Account Performance tab


Strategies tab via the Strategy Performance menu
Strategy Analyzer

Understanding the Summary tab

Summary Tab
The Summary tab displays performance statistics.

© 2011 NinjaTrader, LLC


Operations 303

Understanding the Chart tab

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

© 2011 NinjaTrader, LLC


304 NinjaTrader Version 7

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.

Understanding the Graphs tab

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.

© 2011 NinjaTrader, LLC


Operations 305

Understanding the Executions tab

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:

1. Select the execution


2. Right mouse click and select the menu item Chart.

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.

Understanding the Trades tab

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:

1. Select the trade


2. Right mouse click and select the menu item Chart.

© 2011 NinjaTrader, LLC


306 NinjaTrader Version 7

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...

Understanding the Periods tab

Periods Tab
The Periods tab displays performance data in a data grid based on various time
periods.

Understanding the Orders tab

Orders Tab
The Orders tab displays all historical orders in a data grid.

Understanding the Journal tab

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.

9.7.9.2 Efficiency Graphs

Following are the formulas for the calculation of some of the efficiency performance graphs.

Assume the following:


- Enter long at price of 100
- Market moves down to a price of 90
- Market moves up to a price of 130
- Exit at a price of 110

Entry Efficiency is Calculated as:

(maximum price seen - entry price) / (maximum price seen - minimum price seen)
= (130 - 100) / (130 - 90)
= 75%

© 2011 NinjaTrader, LLC


Operations 307

= The entry took 75% of the trade range

Exit Efficiency is Calculated as:

(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

Total Efficiency is Calculated as:

(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 formulas are reversed for short


The blue line on any efficiency graph represents the average
9.7.9.3 Statistics Definitions

The following are definitions and formulas used for Account Performance statistics:

Understanding Average Time in Market

Average Time in Market


This statistic returns a value that gives you an idea of how long you can expect your
positions to be open. You can use this by manually closing out a position if you feel it has
been in the market for too long.

SUM(exit date – entry date) of all trades / # of trades

Understanding Average ETD

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.

CurreAverage MFE – Average Trade


ncy
Perc Average MFE – Average Trade
ent
Point Average MFE – Average Trade
s

© 2011 NinjaTrader, LLC


308 NinjaTrader Version 7

Understanding Average Losing Trade

Average Losing Trade


This statistic returns a value representing the average loss you experience from all of
your losing trades. It is useful for getting an idea of how much you could expect to lose
on losing trades.

CurreSUM(loss * quantity * point value) of all losing trades / #


ncy of losing trades
Perc SUM(profit * quantity / entry price) of all losing trades /
ent # of losing traded lots
Point SUM(profit * quantity) of all losing trades / # of losing
s trades
where loss is defined as (exit price – entry price) for long trades and as (entry price –
exit price) for short trades, and point value is defined as the monetary conversion of
each point (e.g. 100 for currency pairs).

Understanding Average MAE

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.

CurreSUM(MAE * quantity * point value) of all trades / # of


ncy trades
Perc SUM(MAE * quantity / entry price) of all trades / # of
ent traded lots
Point SUM(MAE * quantity) of all trades / # of trades
s
where MAE (max. adverse excursion) is defined as |worst price trade reached – entry
price|, quantity is defined as the number of contracts traded, and point value is defined
as the monetary conversion of each point (e.g. 100 for currency pairs).

Understanding Average MFE

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.

CurreSUM(MFE * quantity * point value) of all trades / # of


ncy trades
Perc SUM(MFE * quantity / entry price) of all trades / # of

© 2011 NinjaTrader, LLC


Operations 309

ent traded lots


Point SUM(MFE * quantity) of all trades / # of trades
s
where MFE (max. favorable excursion) is defined as (best price trade reached – entry
price), quantity is defined as the number of contracts traded, and point value is defined
as the monetary conversion of each point (e.g. 100 for currency pairs).

Understanding Average Trade

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.

CurreSUM(profit * quantity * point value) of all trades / # of


ncy trades
Perc SUM(profit * quantity / entry price) of all trades / # of
ent traded lots
Point SUM(profit * quantity) of all trades / # of trades
s
where profit is defined as (exit price – entry price) for long trades and as (entry price –
exit price) for short trades, quantity is defined as the number of contracts traded, and
point value is defined as the monetary conversion of each point (e.g. 100 for currency
pairs).

Understanding Average Winning Trade

Average Winning Trade


This statistic returns a value representing the average profit you experience from all of
your winning trades. It is useful for getting an idea of how much you could expect to earn
on winning trades.

CurreSUM(profit * quantity * point value) of all winning


ncy trades / # of winning trades
Perc SUM(profit * quantity / entry price) of all winning
ent trades / # of winning traded lots
Point SUM(profit * quantity) of all winning trades / # of winning
s trades
where profit is defined as (exit price – entry price) for long trades and as (entry price –
exit price) for short trades, quantity is defined as the number of contracts traded, and
point value is defined as the monetary conversion of each point (e.g. 100 for currency
pairs).

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.

© 2011 NinjaTrader, LLC


310 NinjaTrader Version 7

SUM(commission of all traded executions)

Understanding Cumulative Profit

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.

CurreSUM(profit * quantity * point value) of all trades


ncy
Perc PRODUCT(1 + profit / entry price) of all trades - 1
ent
Point SUM(profit * quantity) of all trades
s
where profit is defined as (exit price – entry price) for long trades and as (entry price –
exit price) for short trades, quantity is defined as the number of contracts traded, and
point value is defined as the monetary conversion of each point (e.g. 100 for currency
pairs).

Understanding Gross Loss

Gross Loss
This statistic returns a monetary value representing a summation of all the money lost
across all your trades with your strategy.

SUM(loss * quantity) of all losing trades


where loss is defined as (exit price – entry price) for long trades and as (entry price –
exit price) for short trades and quantity is defined as the number of contracts traded.

Understanding Gross Profit

Gross Profit
This statistic returns a monetary value representing a summation of all the money
earned across all your trades with your strategy.

SUM(profit * quantity) of all winning trades


where profit is defined as (exit price – entry price) for long trades and as (entry price –
exit price) for short trades and quantity is defined as the number of contracts traded.

Understanding Max. Drawdown

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.

Drawdown = local maximum account size – local minimum account

© 2011 NinjaTrader, LLC


Operations 311

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.

Understanding Profit Factor

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.

Gross Profit / Gross Loss

Understanding Profit Per Month

Profit Per Month


This statistic returns a value that can be used as a performance measure for your
strategy. It gives you an idea of how much profit you can expect to make per month.

Currecumulative profit / # of months


ncy
Perc (1 + cumulative profit)(1 / # of months) - 1
ent
Point cumulative profit / # of months
s

(See the cumulative profit statistic above for its definition.)

Understanding Ratio Avg Win / Avg Loss

Ratio Avg Win / Avg Loss


This statistic returns a ratio that can be used as a performance measure for your
strategy. A value greater than 1 signifies you win more than you lose. A value less than 1
signifies you lose more than you win.

Average Winning Trade / Average Losing Trade

Understanding Sharpe Ratio

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

© 2011 NinjaTrader, LLC


312 NinjaTrader Version 7

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.

(Profit per Month – risk free Rate of Return) / standard


deviation of monthly profits

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.

Right Click Menu


Right mouse clicking within the log display section opens the following menu:

Filter By Filter log events by the selected category


Category

© 2011 NinjaTrader, LLC


Operations 313

Grid properties Sets grid properties


9.7.11 Status Bar
The status bar provides current connection status information in the lower left hand corner of
the NinjaTrader Control Center. Progress for many actions such as downloading historical
data or backtesting will be shown on the lower right hand corner.

9.8 Data Grids


You will find the use of data grids throughout the NinjaTrader application.

Working with Data Grids

9.8.1 Working with Data Grids


All data grids found throughout NinjaTrader are customizable.

Data Grids
With a data grid you can:

Resize and hide columns


Export data to Excel
Save data as a file
Email the data as an image
Print data
Search data

Right Click Menu


Right mouse clicking within any data grid will bring up a menu with several grid actions. You
may want to export your execution history to Excel for further analysis as an example. Simply
go to any grid displaying execution history, right mouse click and select the Grid menu
followed by the menu item Export to Excel...

© 2011 NinjaTrader, LLC


314 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


Operations 315

9.9 Historical & Real-Time Data


This page contains information on historical and real-time data as provided by your
connectivity provider to NinjaTrader as well as information on filtering real-time data and
dividend/split adjusting historical data.

Understanding the data provided by your connectivity provider

Historical and Real-Time Data


NinjaTrader, LLC is not a market data provider. Historical data is provided by our
connectivity providers that offer historical data as part of their service. The table below
displays all NinjaTrader supported connectivity providers as well as the historical and
real-time data provided by each:

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

© 2011 NinjaTrader, LLC


316 NinjaTrader Version 7

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

NinjaTrader Converts Real-Time Data into Historical Data


NinjaTrader stores real-time incoming tick data to your local PC if you have a Chart or
Market Analyzer (must have an indicator column added) window open. This data can
then be used as historical data. For example, if you open a chart and let it run all day
long, the data collected today, will be available as historical data when you open the

© 2011 NinjaTrader, LLC


Operations 317

same chart tomorrow.

Connecting to your Broker and a Market Data Provider Simultaneously


If your broker technology does not support historical data, you can connect to a service
like eSignal at the same time as connecting to your broker so that you can receive
historical data. Please see the topic on Multiple Connections for additional information.

Create a Connection to Yahoo for Free Historical Daily Data


You can create a connection to Yahoo Finance via the Connection Guide. This
connection provides access to free historical daily data that can be used for system
development and backtesting.

When does NinjaTrader load historical data?


NinjaTrader loads data from your data provider whenever it determines it could
potentially not have all the data pertaining to the requested time period.

NinjaTrader will load data when:

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.

© 2011 NinjaTrader, LLC


318 NinjaTrader Version 7

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.

How to use the real-time Tick Filter

What is tick filtering?


Tick filtering is a function where each incoming tick is evaluated in relation to the last
known price and if it is outside of a user defined percentage value, the tick is thrown
away and not distributed to any NinjaTrader object that requires market data such as
advanced charts or strategies. This prevents data spikes from showing on your charts
and can also prevent unwanted actions taken by automated strategies due to a data
spike.

How does it work?


A bad tick is detected if the tick price is less than the last valid traded price - (last traded
Price * (1 - bad tick offset as %))
A bad tick detected if the tick price is greater than the last valid traded price + (last
traded Price * (1 + bad tick offset as %))
If a bad tick is detected but the prior two ticks were also bad ticks, then the tick being
processed is now a valid last traded price and is NOT filtered out

How do I enable tick filtering?


You can enable real-time tick filtering by selecting the Tools menu from the Control
Center window and selecting the Options menu item. The Options dialog window will
appear. Within the Options dialog window, left mouse click on the Data tab. Under the
Real-time data section you can place a check mark next to Filter bad ticks and set
the % off market value.

When should I used tick filtering?

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

Understanding splits and dividends

Splits and Dividends


NinjaTrader will split and dividend adjust historical data. This is primarily relevant for
backtesting. NinjaTrader uses a fixed level back adjustment of dividends. This means
that historical data is adjusted at the fixed amount of the dividend.

For example:

Day 1: Stock trades at $10.00


Day 2: Stock trades at $10.50
Day 3: Stock trades at $11.25
Day 4: Stock goes ex-dividend, the dividend is $0.75, and finishes trading at $10.50

© 2011 NinjaTrader, LLC


Operations 319

The dividend adjusted historical data now becomes:

Day 1: $9.25
Day 2: $9.75
Day 3: $10.50
Day 4: $10.50 (the ex-day is not adjusted)

Enabling Splits and Dividends


You can enable this data adjusting by selecting the Tools menu from the Control Center
and left mouse clicking on the Options menu item. Then select the Data tab and select
Adjust for splits and/or Adjust for dividends. Please note that should the historical
data you are using comes pre-adjusted you should not readjust them a second time.

Connectivity Split Adjusted Dividend Adjusted


Provider Intraday Daily Intraday Daily
Kinetick www.
NO YES NO NO
kinetick.com
BarChart YES YES YES YES
eSignal NO YES NO NO
Google YES YES NO NO
Interactive
---- ---- ---- ----
Brokers
IQFeed NO YES NO NO
MB Trading YES YES NO NO
TD Ameritrade ---- ---- ---- ----
TrackData NO NO NO NO
TradeStation YES YES YES YES
YAHOO NO NO NO NO

Adding Splits and Dividends


You must add splits and dividends per instrument in the Instrument Manager. Please
see the Adding Splits and Dividends section of the Help Guide for more information.

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

Understanding merge policies

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

© 2011 NinjaTrader, LLC


320 NinjaTrader Version 7

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.

9.10 Historical Data Manager


The Historical Data Manager provides access to all historical data used in NinjaTrader as
supplied from your historical market data provider and/or collected in from a real-time data
feed. The option to import, export, edit and download historical data are available within the
Historical Data Manger. The Historical Data Manager can be accessed by left mouse
clicking the Tools menu within the Control Center and selecting the menu item Historical
Data Manager...

Importing
Exporting
Editing
Download

© 2011 NinjaTrader, LLC


Operations 321

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.

Understanding the import options

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)

Generate 'Minute' Bars from Imported Tick Data:


Select this option to convert the tick data from the import file into historical 'Minute'
data. This allows any 'Minute' interval to be available within NinjaTrader.

Generate 'Day' Bars from Imported Tick or Minute Data:


Select this option to convert the tick or minute data from the import file into 'Day' data.
This allows the building of 'Day', 'Week', 'Month' and 'Year' bars within NinjaTrader.
(See the "Historical & Real-Time Data" section of the Help Guide for more information
on historical data.)

© 2011 NinjaTrader, LLC


322 NinjaTrader Version 7

Time Zone of Imported Data


Select the time zone of the data you are importing (not the time zone you are importing
to as all imported data will always be converted to local PC time.)

Understanding import file and data formats

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:

MSFT.Last.txt for Microsoft stock last price data


ES 12-09.Bid.txt for the S&P E-mini December contract bid price data
$EURUSD.Ask.txt for the Euro/U.S. dollar currency pair ask price data

Tick Format
Each tick must be on its own line and fields must be separated by semicolon (;).

The format is:


yyyyMMdd HHmmss;price;volume

Sample data:
20061107 000431;1383.00;1
20061107 000456;1383.25;25
20061107 000456;1383.25;36
20061107 000537;1383.25;14

Minute Bars Format


Each bar must be on its own line and fields must be separated by semicolon (;). Only 1
minute bars can be imported.

The format is:


yyyyMMdd HHmmss;open price;high price;low price;close price;volume

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

Daily Bars Format


Each bar must be on its own line and fields must be separated by semicolon (;). Only 1
day bars can be imported.

The format is:


yyyyMMdd;open price;high price;low price;close price;volume

© 2011 NinjaTrader, LLC


Operations 323

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

How to import historical data from a text file

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.

Importing Historical Text Data


To import historical data from a text file into NinjaTrader:

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.

How to import historical data from TradeStation

Importing TradeStation Historical Data


Make sure you have imported the NinjaTrader.ELD. If not, instructions can be found here
.

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".

© 2011 NinjaTrader, LLC


324 NinjaTrader Version 7

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.

1. Set the symbol


2. Set the interval to 1 Minute bars (do not set to any other interval)
3. Last date should be today's date
4. First date should be set to the first data you wish to download historical data for
5. Set the time zone to "Local"
6. Press the "OK" button
7. Right mouse button click in your TradeStation chart and select "Insert Strategies"
8. Select the "NTDataDownload" strategy
9. Press the "OK" button
10. Press the "CLOSE" button
11. The NTDataDownload strategy is now creating a file that contains historical data that
can be imported into NinjaTrader
12. Start NinjaTrader
13. Left mouse click the Tools menu and select the menu item Historical Data Manager.
Then select the Import tab and set the import settings. Left mouse click on the Start
Import button to import the downloaded historical data which will be visible in the
Import Historical Data window.

© 2011 NinjaTrader, LLC


Operations 325

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.

How to Export Historical Data


It is important to understand that the historical data you wish to export must currently be
saved in NinjaTrader as provided by the data provider or collected live. Please see the "
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.

To export historical data to a text file:

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.

© 2011 NinjaTrader, LLC


326 NinjaTrader Version 7

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.

How to edit historical data

Editing Historical Data


It is important to understand that the historical data you wish to edit must currently be
saved in NinjaTrader as provided by the data provider or collected live. Please see the "
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.

To edit historical data available within NinjaTrader:

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)

© 2011 NinjaTrader, LLC


Operations 327

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.

© 2011 NinjaTrader, LLC


328 NinjaTrader Version 7

Using the Edit Logs


Once any changes are saved to the historical data by pressing the Save button, an Edit
Logs node appears under the instrument node.

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.

How to delete historical data


Historical data saved in NinjaTrader can be deleted via the Edit tab of the Historical
Data Manager.

Deleting Historical Data


It is important to understand that the historical data you wish to delete must currently be
saved in NinjaTrader as provided by the data provider or collected live. Please see the "

© 2011 NinjaTrader, LLC


Operations 329

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.

To delete historical data saved in NinjaTrader:

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.

How to Download Historical Data


To download historical data:

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

© 2011 NinjaTrader, LLC


330 NinjaTrader Version 7

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.

Reloading Historical Data


Historical data can be reloaded into NinjaTrader from the data provider's server by pressing
the Reload All button under the Reload tab of the Historical Data Manager. Historical data
is only reloaded for currently active instruments (instruments receiving data in a NinjaTrader
window such as a chart, Market Analyzer, SuperDOM, etc.) while connected to a data
provider that supports historical data.

9.11 Hot Key Manager


NinjaTrader allows you to assign specific key strokes as Hot Keys in order to quickly
perform a task. Hot Key utilization includes, but is not limited to: opening new windows,
performing tasks within open windows, and placing orders in an order entry window. The Hot
Key Manager allows you to add and remove Hot Key assignments to various application
actions. You can access the Hot Key Manager by left mouse clicking in the Tools menu
within the NinjaTrader Control Center and selecting the menu item Hot Key Manager...

© 2011 NinjaTrader, LLC


Operations 331

Working with Hot Keys


Trading with Hot Keys

9.11.1 Working with Hot Keys


You can customize the Hot Keys by assigning the desired key stroke in the related action
field. You also have the ability to print the full list of actions and their related Hot Keys for
easy reference.

Understanding the Hot Key Manager

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.

Assigned Hot Keys


The assigned Hot Keys section displays the key stroke that is assigned to the action to
the left.

In the image below:


-Chart is the Active Window
-Line is an Available Action
-F2 is the Assigned Hot Key

© 2011 NinjaTrader, LLC


332 NinjaTrader Version 7

How to assign a Hot Key

Assigning a Hot Key


You can assign a key stroke as a Hot Key to the desired action by completing the
following steps:

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.

© 2011 NinjaTrader, LLC


Operations 333

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.

How to remove a Hot Key

Removing a Hot Key


There are two ways to remove a Hot Key:

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.

© 2011 NinjaTrader, LLC


334 NinjaTrader Version 7

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.

Understanding when Hot Keys are active

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.

© 2011 NinjaTrader, LLC


Operations 335

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.

How to print your Hot Keys for reference


NinjaTrader gives you the ability to print your assigned Hot Keys for convenient
reference.

Printing Hot Keys


To print a full list of your Hot Keys, right mouse click in the Hot Key Manager and
select the Print Hot Keys menu item.

9.11.2 Trading with Hot Keys


Hot Keys can be assigned to order actions and used to place orders within NinjaTrader order
entry windows.

Understanding the risks in using Hot Keys for order entry


Hot Keys are a powerful and versatile trading tool. However, misuse can lead to
unexpected trades and therefore loss of money. There are several features of the Hot
Keys that you should become familiar with before using them for order entry to limit the
risk of unexpected order placement.

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.

Using the incorrect Hot Key


It is imperative that you know what Hot Key performs what action. It is easy to confuse
Ctrl+B with Shift +B which may both enter different types of orders. For this reason, we
recommend printing your Hot Keys after assigning for easy reference. Please see the "
How to print your Hot Keys for reference" section of the Working with Hot Keys page of
the Help Guide.

© 2011 NinjaTrader, LLC


336 NinjaTrader Version 7

When Hot Keys are inactive


When you close the Hot Key Manager window, you will see the message shown in the
image to the right. A modal form is a window that is always on top and always selected.
(An example is the modal form message window itself.) It is important to understand that
ALL Hot Keys are inactive anytime a model form window is open.

How to enable Hot Key order entry

To enable order entry Hot Keys


From within the Control Center window select the Tools menu and then select the
menu name Options. Once in the General tab, select "Use order entry hot keys."

Assigning Hot Keys


1. Select Order Entry from the left menu in the Hot Key Manager window.
2. Left mouse click in the order action where you want to assign a Hot Key.
3. Left mouse click the drop down arrow.
4. Select the desired Modifier (Optional).
5. Select the desired Key and press the OK button.

© 2011 NinjaTrader, LLC


Operations 337

Understanding where Hot Key order entry is active


Order Entry Hot Keys will only submit from the the active order entry window. This is
important to understand, especially if using multiple order entry windows such as Chart
Trader and SuperDOMs.

Order Entry Windows


Below is a list of all of the order entry windows available in NinjaTrader.
Basic Entry
Chart Trader
FX Pro
SuperDOM
Control Center

Identifying the Active Window


The active window is usually the window that was last clicked on and has the top most
view. You will also notice that the active window's close button in the upper right hand
corner is red compared to an inactive window that has a grey close button.

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.

© 2011 NinjaTrader, LLC


338 NinjaTrader Version 7

Pre-defined order actions and definitions

Pre-defined order actions

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

© 2011 NinjaTrader, LLC


Operations 339

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.

"Last Order" Hot Key note:


For any Hot Key that references "last order," such as "Cancel last order," last order is
defined as:
The last order submitted that is not a stop or target order generated by an ATM Strategy

How to create custom order actions


NinjaTrader allows you to create custom order actions within the Order Entry section of
the Hot Key Manager.

To create a Custom Order action with an associated Hot Key


1. Select the Order Entry section of the Hot Key Manager.
2. Right click over any field in the Order Entry section and select the Add Custom
Order... menu item.
3. Select an Action.
4. Select an Order type (Limit offset allows you to enter the number of ticks your limit
order will be submitted away from the stop order when using a StopLimit Order type).
5. Select the price the order will be submitted at. You can choose a number of ticks
above (Plus) or below (Minus) the current Ask or Bid.
6. Press the OK button.

© 2011 NinjaTrader, LLC


340 NinjaTrader Version 7

To remove Custom Order actions


Right click in the Custom Order action field you wish to remove and select the Remove
Custom Order menu item.

9.12 Instrument Manager


NinjaTrader supports multiple connectivity providers and therefore manages a single
instrument instance (master instrument) which maintains the parameters required to
establish market data and order permissions through the various connectivity sources. The
Instrument Manager manages the instrument lists, edits instrument data and can add or
remove instruments from the database. A default database of commonly traded instruments
is installed with NinjaTrader. The Instrument Manager can be accessed by left mouse
clicking on the Tools menu within the NinjaTrader Control Center and selecting the menu
item Instrument Manager.

Searching for Instruments


Adding Splits and Dividends
Editing Instruments
Adding Commission Rates
Instrument Lists
Manage Database
TradeStation Symbol Mapping
Importing a List of Stock Symbols
Rolling Over a Futures Contract

© 2011 NinjaTrader, LLC


Operations 341

9.12.1 Searching for Instruments


NinjaTrader is installed with a database of the most commonly supported instruments that
you can search through.

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.

2. Enter any search parameters in either the Name or Description fields.

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.

© 2011 NinjaTrader, LLC


342 NinjaTrader Version 7

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.

9.12.2 Adding Splits and Dividends


You can automatically update an instrument with historical split and dividend adjustment data
from within the Instrument Editor. You can skip step 1 if you have already created a Yahoo
connection.

Adding Splits and Dividends


To automatically update an instrument with historical split and dividend data:

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.

© 2011 NinjaTrader, LLC


Operations 343

Understanding the Definition tab

Definition Tab
The Definition tab displays parameters that uniquely define an instrument.

Definition Tab Parameters


The following parameters are available for configuration within the Definition tab:

Master The NinjaTrader master name of the instrument


instrument
Instrument The instrument type (asset class)
type
Tick size The increment value the instrument trades in
Currency The currency the instrument trades in (Only relevant when using Interactive
Brokers. It doesn't matter what you select here when using other data
providers)
Point The currency value of 1 point of movement for the instrument

© 2011 NinjaTrader, LLC


344 NinjaTrader Version 7

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

Understanding the Misc tab

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.

© 2011 NinjaTrader, LLC


Operations 345

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.

© 2011 NinjaTrader, LLC


346 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Operations 347

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.

When NinjaTrader will calculate the Offset value locally:

The Offset field in the Contract Months window is blank


Historical data exists in the database for both the new and old contract near the
rollover date
The MergeBackAdjusted policy must be selected in the Data tab of the Options menu
You must be connected to your data provider and requesting data for the instrument

How NinjaTrader will calculate the Offset value locally:

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.

© 2011 NinjaTrader, LLC


348 NinjaTrader Version 7

Splits and Dividends


With an equity instrument selected, the Misc tab of the Instrument Editor will contain a
Splits & Dividends section. NinjaTrader will split and dividend adjust historical chart
data based on the information defined per instrument and if options are enabled to do so.
Some market data providers provide already adjusted data while others do not. Please
see the Adding Splits and Dividends page of the help guide for more information on
adding split and dividend data to an instrument.

9.12.4 Adding Commission Rates


You can add instrument level commission rates that override global commission settings. For
example, you may set up a global commission rate for trading futures of $4.00 per side
however you may have a reduced rate for trading the DOW Mini futures contract of $3.00 per
side in which case you need to add this rate the DOW Mini contract in the Instrument

© 2011 NinjaTrader, LLC


Operations 349

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:

Backtesting in the Strategy Analyzer


Quickly adding multiple instruments to the Market Analyzer window
The Default instrument list is used for quick access to commonly used instruments within
most NinjaTrader windows such as Charts or the SuperDOM
The RSS instrument list is used for streaming RSS feed news to the News window.

Understanding the Instrument Manager

Instrument Lists

1. Press the New button to create a new list


2. Press the Delete button to delete a list
3. Display all instrument lists

NOTE: The "Default" and "RSS" instrument lists cannot be deleted.

© 2011 NinjaTrader, LLC


350 NinjaTrader Version 7

Adding or Removing instruments

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:

1. Select the list you wish to add an instrument to


2. Select a master instrument in the instrument grid (See the Searching for Instruments
section of the Help Guide for more information)
3. Depending on the instrument type, parameter drop down lists will become enabled. In
the above example, the ES futures contract is selected which prompts you to enter
the Exchange and Expiry parameters you wish to use.
4. Left mouse click on the left arrow button

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:

© 2011 NinjaTrader, LLC


Operations 351

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

1. Press the New button which opens the Instrument Editor


2. Add instrument parameters including the symbol mapping for your connectivity provider(s)
3. Press the OK button

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. Select a master instrument in the instrument grid


2. Press the Delete button
9.12.7 TradeStation Symbol Mapping
The following section outlines the requirements for proper TradeStation to NinjaTrader
symbol mapping when using the Automated Trading Interface (both DLL or Email interface
) and/or using the TradeStation's market data through the External Data Feed Connection for
simulation.

Note: Mapping is NOT required for stocks or Forex symbols.

How to map an individual futures contract

Mapping an Individual Futures Contract


To send either market data via the NTExternalFeed strategy or orders through the ATI to
NinjaTrader from an individual futures contract such as the Emini S&P March contract
"ESH09" in TradeStation or the Euro FX March Contract "ECH09", you have to correctly
set up mapping within NinjaTrader. (Please see the Connection Guide for more
information on how to connect to a TradeStation data connection.)

For this example, let's map the "ECH06" contract.

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

© 2011 NinjaTrader, LLC


352 NinjaTrader Version 7

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 "EC"
6. Press the OK button

* 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.

* Most popular futures contracts already have mapping set up

How to map a continuous futures contract

Mapping a Continuous Futures Contract


NinjaTrader can map continuous contracts in one of two ways:

Automatically map to the next closest expiration date


User defined contract mapping

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

© 2011 NinjaTrader, LLC


Operations 353

* 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.

9.12.8 Importing a List of Stock Symbols


Importing a Stock List
Importing a list of stock symbols is an efficient way to add instruments to the Instrument
Manager in bulk.

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

The text file must contain valid symbols separated by either -

User defined character such as a semicolon or comma


White space
Carriage return

3. The symbols for import are listed in the editor


4. Select the exchange the instruments are traded on
5. Select the currency the instruments are traded in
6. Optionally add the instruments to an Instrument List (optionally create a new one)
7. Select a Session template for the instruments
8. Enter any user defined separator characters
9. Press the OK button to import

© 2011 NinjaTrader, LLC


354 NinjaTrader Version 7

9.12.9 Rolling Over a Futures Contract


Rolling Over a Futures Contract
To rollover a futures contract:

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

© 2011 NinjaTrader, LLC


Operations 355

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.

Using the Level II Window


Level II Properties

9.13.1 Using the Level II Window


You can have as many Level II windows open as you like, one for each instrument whose
market depth information you wish to analyze.

© 2011 NinjaTrader, LLC


356 NinjaTrader Version 7

Understanding the layout of the Level II window

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.

Price The bid price by ask price


Depth Number of market participants on the bid by ask price
Size The total number of shares/contracts on the bid by ask price
Spread The spread between the bid and ask price
Graph Visual display of either Size or Depth (number of market
participants)

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

© 2011 NinjaTrader, LLC


Operations 357

The Details section displays bid data on the left and ask data on the right.

ID The Market Maker or ECN identification


Price The bid or ask price
Size The number of shares/contracts at that price level available
for buy or sell by the specific Market Maker or ECN
Time The last time the bid/ask was refreshed by the Market Maker
or ECN

You can disable the Details section by clicking on your right mouse button and de-
selecting the menu item Show Details.

Selecting an instrument in the Level II window


You can select an instrument by clicking on your right mouse button and selecting the
menu Instruments.
9.13.2 Level II Properties
The Level II window can be customized through the Level II Properties window.

How to access the Level II Properties window


You can access the Level II properties dialog window by clicking on your right mouse
button and selecting the menu Properties.

Available properties and definitions

The following properties are available for configuration within the Level II Properties
window:

© 2011 NinjaTrader, LLC


358 NinjaTrader Version 7

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

How to set the default properties


Once you have your Level II properties set to your liking, you can left mouse click on the
"Set Default" button which will save these settings as the default settings used every

© 2011 NinjaTrader, LLC


Operations 359

time you open a new Level II 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.

9.14 Market Analyzer


The Market Analyzer window is a high powered quote sheet that enables real-time market
scanning of multiple instruments based on your own custom criteria. Display indicator,
market and trade data.

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

© 2011 NinjaTrader, LLC


360 NinjaTrader Version 7

9.14.1 Creating a Market Analyzer Window


The following section covers how to open NinjaTrader's Market Analyzer window.

How to open a new Market Analyzer window

Opening a New Market Analyzer


To open the Market Analyzer, select the File menu from the NinjaTrader Control
Center. Then select the file menu New and left mouse click on the menu item Market
Analyzer.

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.

Understanding the Market Analyzer display

Market Analyzer Display Overview


Each NinjaTrader Market Analyzer is a free floating window that can be manually
resized by dragging the edges of the window and moved by left mouse clicking and
dragging in the upper most margin for arrangement within the open Workspace.

The image below shows some of the common features of a Market Analyzer window:

1. Displays the column name


Columns
2. Displays the instrument name
Instrument
row
3. Label Displays a user defined label row.
row
4. Link Window linking links windows to the same instrument and can be applied to
button many NinjaTrader windows.
5. Total Displays the sum of all rows for a specific column. Can be applied in the
row Market Analyzer Properties window.

© 2011 NinjaTrader, LLC


Operations 361

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.

How to add instruments

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.

© 2011 NinjaTrader, LLC


362 NinjaTrader Version 7

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.

Adding an Instrument List


You can rapidly add a list of instruments to the Market Analyzer window.

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.

How to add Label rows


Label rows are user defined and can be used to separate groups of instruments in any
way (by asset class, instrument list, etc.).

Adding Label Rows in the Market Analyzer Window


Press down on your right mouse button inside the Market Analyzer window and select
the menu Add Label Row. Once the Label row is added you can type in any user
defined name.

© 2011 NinjaTrader, LLC


Operations 363

Dynamic Sorting within Label Rows


Instruments you drag or add under a Label row will "auto-sort" with only the other
instruments under the same Label row. For example, if you have one Label row for
futures and one for stocks, when you sort the columns, the instruments listed under the
futures label would be sorted only against other instruments under the futures label,
while instruments under the stocks label would be sorted only against instruments under
the stocks label. For more information on ranking and sorting within the Market
Analyzer see the Dynamic Ranking and Sorting section of the user help guide.

Aligning a Label Row


The label of a Label Row can be aligned to the left, center or right of the row. This is
done by right mouse clicking within the Market Analyzer and selecting the Properties
menu. Change the property Alignment to either "Left", "Center", or "Right".

How to add Blank rows

Adding Blank rows to the Market Analyzer window


Blank rows can be used to create space between instruments in the Market Analyzer
window or if you need to add more instruments. To add a Blank row press down on
your right mouse button in the Market Analyzer window and select the menu Add
Blank Row. The Blank row will be added above the row you right clicked in.

© 2011 NinjaTrader, LLC


364 NinjaTrader Version 7

How to move Instrument, Label and Blank rows

Moving Rows in the Market Analyzer Window


Instrument, Label and Blank rows can all be moved up or down within the Market
Analyzer window. To move a row in the Market Analyzer window press down and hold
on your left mouse button in the row you would like to move and drag it to the new
location. When your cursor is hovering over the new desired location release your left
mouse button to set the row down in the new location.

How to remove Instrument, Label and Blank rows

Removing Instrument, Label and Blank Rows


To remove an Instrument, Label or Blank row left mouse click on the row to select it
and then press the delete button on your keyboard, or press down on your right mouse
button within the row you want to remove and select the menu Remove Row.

How to add and remove a Total row

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.

Adding the Total row to the Market Analyzer window


To add a Total row in the Market Analyzer you must enable both the Total row and the

© 2011 NinjaTrader, LLC


Operations 365

columns you would like totalled with the following steps:

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.

Removing the Total row from the Market Analyzer window


To remove the Total row press down on your right mouse button inside the Market
Analyzer window and select the menu Properties. Scroll down to the Total Row
section and set the Enabled property to False. Then press the Apply button to apply
the changes or press the OK button to apply the changes and exit the Properties
window.

© 2011 NinjaTrader, LLC


366 NinjaTrader Version 7

Understanding Row Filtering

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.

To enable Row Filtering:


1. Press down on your right mouse button in the Market Analyzer window and select
the menu Row Filter.
2. To access the Columns menu where you can add filtering conditions to each column
press down on your right mouse button and select the menu Columns.

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.

Understanding the Columns window


The Columns window is used to add, remove, and edit columns within the Market
Analyzer window.

Accessing the Columns Window


To access the Columns window press down on your right mouse button in the Market
Analyzer window and select the menu item Columns...

Sections of the Columns Window


The image below displays the four sections of the Columns window.

1. List of available columns


2. Current columns applied to the Market Analyzer
3. Selected column's parameters
4. Selected parameter's description

© 2011 NinjaTrader, LLC


Operations 367

How to add columns


A wide variety of columns can be added to your Market Analyzer window allowing you
to see indicator, position, or price information at a glance.

Adding columns to the Market Analyzer window


To add a column to the Market Analyzer window:

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

© 2011 NinjaTrader, LLC


368 NinjaTrader Version 7

Adding an Indicator Column


To add an indicator column to the Market Analyzer 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

How to customize columns


Once you have added columns to your Market Analyzer window (see the "How to add
columns" section above) you can customize the column by editing the column's
parameters.

Editing a Column's Parameters


You can customize any column from the Columns window.

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

© 2011 NinjaTrader, LLC


Operations 369

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

Changing the Order and Width of Columns


To order columns in the Market Analyzer window you can use the arrows to the right of
the applied columns section (as shown by the green arrows on the image above).

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.

© 2011 NinjaTrader, LLC


370 NinjaTrader Version 7

How to remove columns

Columns can be removed from the Columns window or from the Market Analyzer
directly.

Removing Columns from the Market Analyzer Window


There are two ways to remove a column:

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.

Dynamic ranking and sorting


See the Dynamic Ranking and Sorting section of the user help guide for information on
sorting and raking your Market Analyzer columns.
9.14.4 Creating Alert, Cell and Filter Conditions
Market Analyzer columns can have alert, cell and filter conditions applied to them for a more
convenient display of information.

© 2011 NinjaTrader, LLC


Operations 371

Understanding alert conditions

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".

Creating an Alert Condition


To create an Alert Condition:

1. Open the Columns window


2. Select the column you would like to create an Alert Condition for in the applied
column section.
3. Under the Special parameters section select Alert conditions and then press the "...
" button

© 2011 NinjaTrader, LLC


372 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Operations 373

The example Alert Condition in the above image will:

Trigger the alert once the cell value is greater than 30


Display a lime green background with white text
Display "Trending" as the alert text
Re-arm the alert after 60 seconds has passed
Display a "Low" priority
Play an Alert Sound

You can remove an Alert Condition by pressing the Remove button.

Please note setting the "Re-arm after secs" property to a value of zero means the alert
will not re-arm once triggered.

Multiple Alert Conditions vs. Multiple Alerts


It is important not to confuse multiple Alert Conditions with multiple alerts. You can
have one alert per Market Analyzer column and each alert can have multiple
conditions. Conditions are evaluated from top to bottom.

Assume you have an alert with the following conditions defined:

Alert if value is greater than 30

© 2011 NinjaTrader, LLC


374 NinjaTrader Version 7

Alert if value is greater than 100

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:

Alert if value is greater than 100


Alert if value is greater than 30

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.

Understanding cell conditions

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.

Creating Cell Conditions


To create a Cell Condition:

1. Open the Columns window


2. Select the column you would like to create a Cell Condition for in the applied column
section.
3. Under the Special parameters section select Cell conditions and then press the "..."
button

© 2011 NinjaTrader, LLC


Operations 375

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

© 2011 NinjaTrader, LLC


376 NinjaTrader Version 7

The example Cell Condition in the above image will:

Trigger once the cell value is greater than 30


Display a lime green background with black text
Display "Greater than 30" as the text

You can remove a Cell Condition by pressing the Remove button.

Multiple Cell Conditions


Cell Conditions are evaluated from top to bottom.

Assume you have the following conditions defined:

Change cell if value is greater than 30


Change cell if value is greater than 100

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:

© 2011 NinjaTrader, LLC


Operations 377

Change cell if value is greater than 100


Change cell if value is greater than 30

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.

Understanding filter conditions

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.

Creating Filter Conditions


To create a Filter Condition:

1. Open the Columns window


2. Select the column you would like to create a Filter Condition for in the applied
column section.
3. Under the Special parameters section select Filter conditions and then press the "
..." button

© 2011 NinjaTrader, LLC


378 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


Operations 379

The example Filter Condition in the above image will:

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

You can remove a Filter Condition by pressing the Remove button.

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.

How to Enable Automatic Ranking and Sorting


To enable ranking and sorting for a column:

1. To set the column you wish to sort press down on your left mouse button in the column

© 2011 NinjaTrader, LLC


380 NinjaTrader Version 7

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.

9.14.6 Market Analyzer Properties


The Market Analyzer can be customized to your preferences in the Market Analyzer
Properties window.

How to access the Market Analyzer properties window


To access the Market Analyzer Properties window, press down on your right mouse
button inside the Market Analyzer window and select the menu Properties...

Available properties and definitions


The following properties are available for configuration within the Market Analyzer
Properties window

© 2011 NinjaTrader, LLC


Operations 381

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

© 2011 NinjaTrader, LLC


382 NinjaTrader Version 7

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

Properties can be saved within a Market Analyzer Template.

9.14.7 Working with Templates


NinjaTrader allows you to save your customized Market Analyzer layout as a template that
can be loaded in an open Market Analyzer or set as the default for new Market Analyzer
windows.

How to save a Market Analyzer Template

What is Saved
The following are saved within a Market Analyzer template:

Column layout
Column parameters and conditions
Market Analyzer properties

Saving a Market Analyzer Template


To save a Market Analyzer template (shown in the image below):

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)

© 2011 NinjaTrader, LLC


Operations 383

5. Enter a name for your Market Analyzer template and press the OK button.

How to load a Market Analyzer Template

Loading a Market Analyzer Template


To load a saved Market Analyzer template:

1. Right mouse click within the Market Analyzer


2. Select the menu item Templates
3. Select the menu item Load...

© 2011 NinjaTrader, LLC


384 NinjaTrader Version 7

4. Select the template you wish to load from the drop down menu and press the OK
button

How to remove a Market Analyzer Template

Removing a Market Analyzer Template


To remove a saved Market Analyzer template:

1. Right mouse click within the Market Analyzer


2. Select the menu item Templates
3. Select the menu item Load...
4. Select the template you wish to remove from the drop down menu and press the
Remove button.
9.14.8 Performance Tips
The following performance tips are specific to the Market Analyzer window.

Market Analyzer Look Back Period


"# bars to look back" property determines the minimum number of bars required to properly
initialize any indicator columns. 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.

Number of Instruments and Columns.


The Market Analyzer has no limit to the number of instruments that can be added. It is
important to monitor computer resources to understand your PC's limit.
The Market Analyzer has no limit to the number of columns, specifically indicator
columns, that can be added. Depending on the indicator and the "# of bars to look back
property" described above, it may take a few seconds to calculate the indicator. This time is
multiplied by the number of instruments in the Market Analyzer which can result in a few
minutes of loading time. Decrease the number of instruments or indicator columns to
lessen this loading time.

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.

Indicator Calculate on Bar Close Parameter


All indicators added to the Market Analyzer have the parameter "Calculate on bar close" set
to "False" as default. This allows for a tick-by-tick calculation. Setting this property to "True"
by selecting the indicator within the Columns window will only calculate the indicator value

© 2011 NinjaTrader, LLC


Operations 385

on the bar close. This may help with PC performance.


9.14.9 Reloading Indicators & Columns
When compiling custom NinjaScript indicators and columns, the Market Analyzer window
will not automatically reload the changes. To force a reload of any changed indicators or
columns you must select the menu item Reload NinjaScript via the right mouse button
context menu or alternatively, press the "F5" Hot Key.
9.14.10 Window Linking
Please see the Window Linking section of the Help Guide for more information on linking the
Market Analyzer window.

9.15 Market Replay


Market Replay is the ability to record market data and replay it at another time. It is the same
idea as recording your favorite TV show during the day and watching it at some other more
convenient time. Unlike most products that only allow you to replay one market at a time,
NinjaTrader provides synchronous replay of any and all recorded markets and delivers this
market data to all NinjaTrader windows as if it was happening in real-time. Therefore, you can
have multiple SuperDOMs and charts replaying different markets all at the same time. You
can trade in simulation against this data at varying levels of replay speed.

NOTE: Market Replay is not supported in the NinjaTrader Direct Edition.

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.

How to enable the Market Replay recorder

Enabling the Replay Recorder


To enable 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

© 2011 NinjaTrader, LLC


386 NinjaTrader Version 7

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)

How to record live market data

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.

How to download replay data from the NinjaTrader server

Downloading Replay Data


NinjaTrader offers a limited amount of replay data free to download. Only the most
common instruments are currently available.

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.

© 2011 NinjaTrader, LLC


Operations 387

To download replay data:

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.

How to connect to Market Replay data

Connecting to Replay Data


To connect to Market Replay data:

1. Left mouse click on the File menu in the Control Center


2. Select the menu item Connect
3. Select the menu item Market Replay Connection

"Connected - Replay" should now show in the lower left hand corner of the NinjaTrader
Control Center.

How to work with replay data

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.

© 2011 NinjaTrader, LLC


388 NinjaTrader Version 7

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:

Play button Starts the market replay


Pause button Pauses the market replay
Speed control button Each successive click increases the speed of the playback
Slide control button Selects a point in time to start replay (sliding during playback will
reset the Replay101 account trade history)

Right Click Menu


Right mouse clicking in the Replay control window will bring up the right click menu with
the two following menu items:

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.

© 2011 NinjaTrader, LLC


Operations 389

Understanding how the Market Replay works

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

© 2011 NinjaTrader, LLC


390 NinjaTrader Version 7

file of the replay data and restoring this to another PC.

9.16 News & RSS


The News window allows you to display, filter and create alerts for real-time news. You will
receive real-time news if are subscribed to a news service through a market data vendor or
broker and news can be received through various RSS feeds which are configurable in the
RSS Tab of the Options menu. The News 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 News...

News Window

9.16.1 News Window


News sent from the connectivity provider or via an RSS feed is displayed in the News
window. Alerts and filters can be configured based on keywords in the news headline.

Understanding the News Window

News Window Display


The News window is divided into the following sections:

1. Select user defined filters


2. Enable or disable user defined alerts
3. List of real-time news headlines
4. Displays the news story for the selected news headline

© 2011 NinjaTrader, LLC


Operations 391

Right Click Menu


Right mouse click in the upper left hand corner of the News window to access the right
click menu. From this menu you can choose to show the news story related to the
selected headline and create, format and delete alerts and filters.

How to receive news from the RSS feed

RSS Feed Setup


To view news stories and headlines in the News window from an RSS feed:

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.

How to create a filter condition

© 2011 NinjaTrader, LLC


392 NinjaTrader Version 7

Creating a Filter Condition


A filter will only display news items if they meet your user defined conditions. You can
define a filter by:

Keyword
Filtering on a specified instrument list
Filtering on a specified set of news providers

To create a filter condition within the News window:

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.

How to create an alert condition

Creating an Alert Condition


An alert will visually and audibly notify you when your Keyword has been found within a
news headline.

Alerts can be defined by:

Keyword
Filtered on a specific instrument list
Filtered on a specified set of news providers

To create an alert condition within the News window:

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.

The following options can be configured in the General tab:

Name Sets the name of the alert


Keyword Sets the keyword that triggers the alert
From instrument list Confines the alert to a specified instrument list
Enable linking Enables or disables alert window linking

© 2011 NinjaTrader, LLC


Operations 393

Alert keywords can be filtered using the Provider tab.

The following alert properties can be configured in the Alert tab:

Color for Sets the alert background color


background
Color for foreground Sets the alert text color
Priority Sets a user defined priority
Sound file Sets the sound file that will play when the alert is triggered

© 2011 NinjaTrader, LLC


394 NinjaTrader Version 7

9.16.2 Window Linking


Please see the Window Linking section of the Help Guide for more information on linking the
News window.

9.17 Order Entry


NinjaTrader provides four graphical interfaces for order, position, and ATM Strategy
management. These are the Basic Entry, Chart Trader, FX Pro, and SuperDOM windows.
These interfaces provide complete functionality for the management of orders, positions and
discretionary exit and stop strategies in a highly visual and efficient manner. The majority of
your time using NinjaTrader will be spent in one of these four interfaces if you are primarily a
discretionary trader. Although the Basic Entry, Chart Trader, and SuperDOM interfaces
can be used to trade any of the NinjaTrader supported asset classes, the Basic Entry
window is geared towards trading equities, the SuperDOM is geared towards trading futures,
and the FX Pro window is used for FOREX instruments only.

Order Entry Windows


Basic Entry
Chart Trader
FX Pro
SuperDOM

9.17.1 Simulated Stop Orders


A Simulated Stop order (SS) is a conditional locally held (PC simulated) order type that
allows you to execute either a market or a limit order once the market touches your order

© 2011 NinjaTrader, LLC


Operations 395

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.

Understanding the benefits of the Simulated Stop

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)

Understanding the risks of the Simulated Stop

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.

Understanding the SS Volume Trigger

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.

Simulated Stop examples

Buy Stop Market Example


Order Type - Buy Stop Market

© 2011 NinjaTrader, LLC


396 NinjaTrader Version 7

Stop Price - 1000


Volume Trigger - 500

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.

Buy Stop Limit Example


Order Type - Buy Stop Limit
Stop Price - 1000
Limit Price - 1001
Volume Trigger - 500000

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.

Sell Stop with Improved Limit Price Example


Order Type - Sell Stop Limit
Stop Price - 999
Limit Price - 1000
Volume Trigger - 600

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.

Understanding when to avoid using Simulated Stop orders

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.

Why is FIFO important?

© 2011 NinjaTrader, LLC


Operations 397

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.

How does NinjaTrader preserve FIFO?


All NinjaTrader order entry interfaces simplify the visualization of orders. Let's say that
you have a buy limit order for 1 contract, and then want to modify this order from 1
contract to 2 contracts. Most other programs will simply change this order directly, but
behind the scenes (at the broker's order servers) what is really happening is that the
original order is cancelled (removed from the line) and then a new order for 2 contracts
is submitted which then goes to the back of the line putting you at a disadvantage.
Imagine waiting in the grocery store check out line for ten minutes. You forgot to get
some bread, you leave the line in order to get the bread that you wanted (changing your
order) and upon your return to the check out line, you have to start at the back of the line
and wait all over again! With NinjaTrader, when you modify the order from 1 contracts to
2 contracts, an additional order for 1 contract is submitted. Now you have the original
order for 1 contract waiting in the middle of the line somewhere and the new order for 1
contract at the back of the line. Your original order is not penalized and you maintain your
position in line. The opposite is true for decreasing an order size. Although there are two
working orders NinjaTrader consolidates the display so it looks as if there is only one
order working. You decide to decrease the order size from 2 contracts back to 1.
NinjaTrader will modify the newest orders first and the oldest orders last in order to
preserve your FIFO status. Following our example, the second order that was placed
would be cancelled and you would be left with the original order for 1 contract with its
maintained position in the order queue.
9.17.3 Closing a Position or ATM Strategy Position
Closing a position or ATM Strategy with the Close button
In all NinjaTrader order entry windows there are "CLOSE" action buttons which will close a
position or an ATM Strategy depending on which mouse button is pressed (the left mouse
button will close the current position and cancel any working orders associated with the
instrument/account combination and the middle mouse button (scroll wheel) will close the
selected active ATM Strategy position only).

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

© 2011 NinjaTrader, LLC


398 NinjaTrader Version 7

Trading and Interactive Brokers where the previously described process is used.)

Why not just submit a market order?


A lot of traders consume near 100% of their available margin. For example, you may have 1
contract position with one stop and target that consumes 90% of your margin. If you close a
position by submitting a market order, the market order will get rejected due to insufficient
funds and therefore cause grief if getting out of the position is critical.

The NinjaTrader approach offers several benefits:


Modifying existing limit orders avoids the potential problem of breaching your account
margin limitations when closing a position
With some brokers, modifying existing orders is more efficient than submitting new orders
by up to 500 milliseconds
Cancellation of non essential orders unlocks available margin that could potentially get
consumed if a market order is required to close out any remaining contracts that are not
covered by existing limit orders

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.

NinjaTrader Order State Definitions


Order State Definition Color Code
Initialized Order information validated on Yellow
local PC
PendingSubmit Order submitted to the Orange
connectivity provider
Accepted Order confirmation received by Light blue
broker
Working Order confirmation received by Green
exchange
PendingChang Order modification submitted to Orange
e the connectivity provider
PendingCancel Order cancellation submitted to Red
the connectivity provider/exchange
Cancelled Order cancellation confirmed Red
cancelled by exchange
Rejected Order rejected locally, by Red
connectivity provider or exchange
PartFilled Order partially filled Red

© 2011 NinjaTrader, LLC


Operations 399

Filled Order completely filled Green


9.17.6 Basic Entry
The Basic Entry order entry window is comprised of several components: market display,
Order Grid, action buttons, as well as order entry and ATM Strategy management.

Display Order Management


Market Display Selecting Instruments and Accounts
Order Grid Display Submitting Orders
Modifying and Cancelling Orders
Misc Action Buttons
Window Linking Adding and Removing Targets
Properties

9.17.6.1 Market Display

Understanding the market display region of the Basic Entry window


The market display region of the Basic Entry window is used to display market prices and
position information.

1. Current best ask price and size


2. Current best bid price and size
3. Last traded price and size
4. Market position (FLAT or green background with position size for long, red background for
short)
5. Position average entry price
6. Unrealized profit or loss for current position (Clicking on this cell with your left mouse
button will change the display between points, currency and percent)

© 2011 NinjaTrader, LLC


400 NinjaTrader Version 7

9.17.6.2 Order Grid Display

Understanding the Order Grid display


The Order Grid display represents orders in a consolidated format. Orders of the same
price, type, and function (entry, Stop Loss, Profit Target) are grouped together and
displayed in one row.

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.

9.17.6.3 Selecting Instruments and Accounts

NinjaTrader makes changing instruments and accounts quick and easy with separate menus
located directly within the Basic Entry window.

© 2011 NinjaTrader, LLC


Operations 401

How to select an instrument


The "Instrument" drop down list contains the instruments from the Default Instrument
List you have set up in the Instrument Manager. To change an instrument you can either
select an instrument from this list, or type in the name of an instrument directly such as
"MSFT" for Microsoft.

How to select an account


A list of all connected accounts will be listed in the "Account" drop down list. To change
the account select the account you wish to trade through via this drop down list.

9.17.6.4 Submitting Orders

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.

Understanding order settings

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

© 2011 NinjaTrader, LLC


402 NinjaTrader Version 7

How to submit orders with the Quick Buttons

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

How to submit custom orders

Custom Orders
You can place a custom order by setting order parameters.

1. Select the order Type


2. Set the limit price if applicable (middle click in the field to retrieve the last traded price)
3. Set the stop price if applicable (middle click in the field to retrieve the last traded price)
4. Left mouse click either the "BUY" or "SELL" button

© 2011 NinjaTrader, LLC


Operations 403

How to scale in or out of an active ATM Strategy

Scaling in or out of an active ATM Strategy


When you have an active ATM Strategy selected in the strategy control list, orders
submitted scale into or out of the strategy. Once filled or partially filled, the 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 Basic Entry 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 Basic Entry "Scale quantity" property is set to a value of one, when
an active ATM Strategy is selected in the strategy control list, the Basic Entry "Order
qty" field will be set to a value of one automatically.

Understanding the OCO (One Cancels Other) function

OCO Orders (One Cancels Other)


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 Basic
Entry window and select the menu name "OCO Order" or use the short cut key
CTRL+Z.

© 2011 NinjaTrader, LLC


404 NinjaTrader Version 7

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.

Break Out/Fade Entry Example


One of the great features of NinjaTrader is its ability to submit two entry orders, one of
which will cancel if the other is filled.

You can accomplish a breakout/breakdown approach by:

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.

How to submit Simulated Stop Orders (Simulated Order)

Simulated Stop Orders (Simulated Order)

© 2011 NinjaTrader, LLC


Operations 405

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

How to modify and cancel 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 left clicking in the "Remaining" column, typing in a
new quantity value and pressing the "Enter" key on your keyboard.

9.17.6.6 Action Buttons

How to use the action buttons


1. Clicking on the "BE" (break-even) button with your left mouse button will adjust any stop
orders in the opposite direction of your open position (if position is long it will adjust stop sell
orders) to the positions average entry price. Clicking on this button with your middle mouse
button (scroll wheel) will only adjust any Stop Loss orders associated to the selected active
ATM Strategy in the strategy drop down list. Orders resting at a better price than the average
entry price will NOT be modified.

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

© 2011 NinjaTrader, LLC


406 NinjaTrader Version 7

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.

9.17.6.7 Adding or Removing Targets

How to add or remove targets


If you have an active ATM Strategy displayed in the Basic Entry window, 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 that
you can exit the final contract at a higher price. You can add or remove a target via the right
mouse click context menu when an active ATM Strategy is selected in the strategy control
list.

It is important to understand the following logic:


You can have a maximum of 3 Profit Targets (if you had 3 Profit Targets and the first
two Profit Targets are filled you can not split the 3rd target)
If you have 1 Profit Target and you remove a Profit Target, you will be left with a Stop
Loss order only
New Profit Targets are added 4 ticks from your current outside Profit Target for futures,
$0.20 for stocks

© 2011 NinjaTrader, LLC


Operations 407

9.17.6.8 Window Linking

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.

© 2011 NinjaTrader, LLC


408 NinjaTrader Version 7

9.17.6.9 Basic Entry Properties

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.

How to access the Basic Entry Properties window


You can access the Basic Entry properties dialog window by clicking on your right
mouse button within the Basic Entry window and selecting the menu Properties.

Available properties and definitions

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

© 2011 NinjaTrader, LLC


Operations 409

Advanced Enables or disables the display of Basic Entry advanced options


options
Caption bar Sets the text displayed in the caption bar of the Basic Entry
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)
Profit/loss Sets the display unit for profit and loss
display unit
Scale Quantity Sets the scale order quantity amount.
Show realized Displays realized profit and loss for the selected account when flat
P/L 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)
Strategy Sets the behavior mode of the price ladder display and strategy
selection mode selector (see more)
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.

How to set the default properties

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.

Order & Position Display


Collapsed View
Submitting Orders
Modifying and Cancelling Orders
Action Buttons
Properties

© 2011 NinjaTrader, LLC


410 NinjaTrader Version 7

9.17.7.1 Order & Position Display

Orders and positions within Chart Trader are displayed in a highly visual manner.

Understanding order display

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.

Limit Order Default color is cyan with the text "LMT"


Stop Market
Default color is pink with text "STP"
Order
Stop Limit
Default color is violet with text "SLM"
Order
Market Market orders are not displayed (see Control Center Orders Tab for more
Order information)
Stop Loss
Default color is red
Order
Profit Target
Default color is lime
Order

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.

1. Buy stop limit order for 1 contract at a price of 1136.00


2. Buy stop market order for 1 contract at a price of 1135.00
3. Buy limit order for 1 contract at a price of 1131.00

© 2011 NinjaTrader, LLC


Operations 411

Understanding Position Display

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.

1. Two profit target orders (T1 and T2)


2. Average position and PnL flag for 2 contracts long
3. Stop loss order (S1)*
4. Current position size
5. Average position price
6. PnL

* The stop loss order is actually comprised of two orders as indicated by the letter "s"
next to the qty number "2".

© 2011 NinjaTrader, LLC


412 NinjaTrader Version 7

9.17.7.2 Collapsed View

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.

9.17.7.3 Submitting Orders

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

© 2011 NinjaTrader, LLC


Operations 413

for a complete understanding of order submission and subsequent actions that you can have
NinjaTrader automate.

How to submit an order

Submitting Orders
To submit an order using Chart Trader:

1. Set the "Qty" field

2. Set the 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
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

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.

© 2011 NinjaTrader, LLC


414 NinjaTrader Version 7

*A more thorough explanation of these concepts are found under the Position Strategy
section.

Understanding order menus

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.

© 2011 NinjaTrader, LLC


Operations 415

Stop Limit Order


When submitting a stop limit order, a numeric field (image above) will appear that
represents the number of ticks away you wish the limit price of the stop limit order to be
placed at. Either by using your mouse scroll wheel or clicking on the up/down arrows in
the numeric field, set the number of ticks and press the "checkmark" button to complete
the order submission. Pressing the "X" button will cancel the order submission
operation. For example, if you intend to have an order with a stop price of 1000 and a
limit price of 1001 (4 ticks spread for the S&P E-mini contract), you would set the
numeric field value to 4. Following the same example and submitting a sell stop limit,
setting the numeric field value to 4 would result in a stop price of 1000 and a limit price of
999.

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.

© 2011 NinjaTrader, LLC


416 NinjaTrader Version 7

Understanding the Quick Buttons

Quick Buttons
You can quickly submit orders via the Chart Trader control's Quick Buttons.

Button Actions

Buy Market - Submits buy order at market

Sell Market - Submits sell order at market

Buy Ask - Submits buy limit order at ask price

Sell Ask - Submits sell limit order at ask price

Buy Bid - Submits buy limit order at bid price

Sell Bid - Submits sell limit order at bid price

How to scale in or out of an active strategy

Scaling In or Out of an Active Strategy


When you have an active strategy selected in the strategy control list, 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 Chart

© 2011 NinjaTrader, LLC


Operations 417

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.

Understanding "One Cancels Other" (OCO) orders

OCO Orders (One Cancels Other)


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, 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)

Understanding simulated stop orders

Simulated Stop Orders (Simulated Order)


To submit a simulated stop order (entry and exit NOT stop loss; simulated stop loss
orders are enabled via a stop strategy), you must enable simulated order mode via the
right mouse click menu and selecting the Simulated Order menu item, or use the
shortcut key CTRL+A. All stop orders placed while this indicator is lit will be submitted
as a simulated stop order.

One of the powerful features of simulated stop orders is that you can submit a "negative

© 2011 NinjaTrader, LLC


418 NinjaTrader Version 7

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.

How to modify an order price

Modifying Order Price


To modify the price of an order, left click with your mouse on the order line or the right
section of the label. A ghost order line will appear and display the number of ticks you
are away from the inside market.

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.

© 2011 NinjaTrader, LLC


Operations 419

How to modify an order size

Modifying Order Size


To modify the size of an order:

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.

How to cancel an order

Cancelling an Order
To cancel an order:

Left mouse click on the red X on the order marker.

© 2011 NinjaTrader, LLC


420 NinjaTrader Version 7

9.17.7.5 Action Buttons

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.

9.17.7.6 Chart Trader Properties

Many of the visual display settings of Chart Trader can be customized using the Chart
Trader Properties window.

How to access the Chart Trader Properties window

© 2011 NinjaTrader, LLC


Operations 421

To access 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...

Available properties and definitions

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

© 2011 NinjaTrader, LLC


422 NinjaTrader Version 7

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.

How to set the default properties


Once you have your Chart Trader Properties set to your liking, you can left mouse
click on the Set Default button which will save these settings as the default settings
used every time you enable Chart Trader.

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.

© 2011 NinjaTrader, LLC


Operations 423

Display Order Management


Overview Selecting Instruments and Accounts
Submitting Orders
Misc Modifying and Cancelling Orders
Properties Adding and Removing Targets

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

© 2011 NinjaTrader, LLC


424 NinjaTrader Version 7

* 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.

Understanding how orders are displayed in the FX Pro window

Order Grid Display


The Order Grid display represents orders in a consolidated format. Orders of the same
price, type, and function (entry, Stop Loss, Profit Target) are grouped together and

© 2011 NinjaTrader, LLC


Operations 425

displayed in one row.

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.

Understanding how Level II (market depth) is displayed in the FX Pro window

Level II (Market Depth) Display


The Level II panel displays bid and ask market depth data color coded by price. The
Level II display can be enabled/disabled by right mouse clicking inside the Level II
display and selecting the menu item Show Level II.

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

© 2011 NinjaTrader, LLC


426 NinjaTrader Version 7

* 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.

Market Display Definitions


1. The current spread between the best bid and best ask (the image below is showing a
spread of 8 sub pips (8/10 of a pip)
2. Position information
3. Last tick directional arrow
4. The handle of the current bid (current ask is on the right side of the blue "X")
5. The current bid
6. Sub pip value, so the current bid is 1.2840 and 3/10 of a pip displayed as 1.2840'3
7. Current bid size displayed as 3M (in millions)

* 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.

© 2011 NinjaTrader, LLC


Operations 427

How to select an instrument


The "Instrument" drop down list contains currency pairs from the Default Instrument
List that you have set up in the Instrument Manager. To change instruments select
another instrument from this list.

How to select an account


A list of all connected accounts will show in the "Account" drop down list. To change the
account select the account you wish to trade through via this drop down list.

9.17.8.3 Submitting Orders

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.

Understanding order settings

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

© 2011 NinjaTrader, LLC


428 NinjaTrader Version 7

under the ATM 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: stops and targets are submitted from a predefined
user template
3. Enter an order with any of the methods described below

How to submit orders with the Quick Buttons

Quick Order Buttons


You can enter limit orders at the inside market rapidly by pressing down on your left
mouse button on either the BID or OFFER buttons.

BID Places a buy limit order at the best bid price


OFFER Places a sell limit order at the best ask price

How to submit custom orders

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

© 2011 NinjaTrader, LLC


Operations 429

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.

How to scale in or out of an active ATM Strategy

Scaling in or out of an active ATM Strategy


When you have an active strategy selected in the ATM Strategy control list (see the
image below) orders submitted scale into or out of the strategy. Once filled or partially
filled, the 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 FX Pro 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 FX Pro "Scale quantity" property is set to a
value of one, when an active strategy is selected in the ATM Strategy control list, the
FX Pro "Qty" field will be set to a value of one automatically.

Understanding the OCO (one cancels other) function

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.

© 2011 NinjaTrader, LLC


430 NinjaTrader Version 7

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.

Break Out/Fade Entry Example


One of the great features of NinjaTrader is its ability to submit two entry orders, one of
which will cancel if the other is filled.

You can accomplish a breakout/breakdown approach by:

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.

How to submit Simulated Stop orders (Simulated Order)


To submit a Simulated Stop Order (entry and exit NOT stop loss; simulated stop loss
orders are enabled via a stop strategy) you must enable simulated order mode via the
right mouse click context menu by selecting the Simulated Order menu item. The "so
" (Simulated Order indicator) will light up green. All stop orders placed while this indicator

© 2011 NinjaTrader, LLC


Operations 431

is lit will be submitted as Simulated Stop orders.


9.17.8.4 Modifying and Cancelling Orders

How to modify or cancel orders


You can modify orders directly in the FX Pro order grid.

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

How to add or remove targets


If you have an active ATM Strategy displayed in the FX Pro window, you can add or remove
targets. For example, you may have a 2 lot position with 1 Stop Loss and Profit Target for 2
lots each. You may decide to split this target (add target) so that you can exit the final lot at a
higher price.

To add a target to an active strategy:


1. Right mouse click within the FX Pro window
2. Select the menu item Add Target

To remove a target from an active strategy:


1. Right mouse click within the FX Pro window
2. Select the menu item Remove Target

It is important to understand the following logic:


You can have a maximum of 3 targets (if you had 3 and the first two targets are filled you
can not split the 3rd target)

© 2011 NinjaTrader, LLC


432 NinjaTrader Version 7

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

9.17.8.6 FX Pro Properties

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.

How to access the FX Pro Properties window

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.

Available properties and definitions

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

© 2011 NinjaTrader, LLC


Operations 433

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

How to set the default properties

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.

Display Order Management


Price Ladder Display Instrument and Account Selection
Static Vs Dynamic Submitting Orders
Order Display Modifying Orders
Cancelling Orders
Misc Action Buttons
Window linking Adding/Removing Targets
Properties

© 2011 NinjaTrader, LLC


434 NinjaTrader Version 7

9.17.9.1 Price Ladder Display

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.

Understanding the function of each column in the Price Ladder display

The price ladder is broken down into three functional columns.

BUY Column
The left column is the BUY column which is used to:

Submit buy orders


Modify buy orders
Display the total contracts on the bid at their respective prices (also known as market
depth)

PRICE Column
The center column, known as the PRICE column, is used to:

Modify stop loss and profit target orders


Display market prices
Display the current bid, ask, and last traded prices

SELL Column
The right column is the SELL column which is used to:

Submit sell orders


Modify sell orders
Display the total contracts on the ask at their respective prices (also known as market
depth)

© 2011 NinjaTrader, LLC


Operations 435

Understanding how market data is displayed


The Price Ladder display section of the SuperDOM displays the current inside market
and market depth. Various aspects of this display can be user defined in the SuperDOM
Properties window.

The following market data items can be displayed:

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

© 2011 NinjaTrader, LLC


436 NinjaTrader Version 7

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.

Market (left cell)


Submits buy market, limit at ask, or limit at bid orders

PnL (center cell)


Displays unrealized profit or loss for the current position

Market (right cell)


Submits sell market, limit at ask, or limit at bid orders

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.

How to display the daily high and low prices

© 2011 NinjaTrader, LLC


Operations 437

Daily High and Low


The market's daily high and low can be optionally displayed.

You can set this option and customize the color of the markers in the SuperDOM
Properties dialog window.

Understanding how position and profit & loss information is displayed

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

Current Position Display


The cell between the CLOSE button and the REV button will tell you your current
position.

© 2011 NinjaTrader, LLC


438 NinjaTrader Version 7

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.

How to adjust the Price Ladder display

Adjusting the Price Ladder display

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.

© 2011 NinjaTrader, LLC


Operations 439

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.2 Static vs Dynamic Price Ladder Display

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.

Understanding the Static Price Ladder display

Static

The inside market (ask/bid and last price) climb up and down the Price Ladder in
response to a change in market price.

The price rows are static (do not change).

Understanding the Dynamic Price Ladder display

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

© 2011 NinjaTrader, LLC


440 NinjaTrader Version 7

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.

In the image below:

1. Best bid
2. Net change (last traded price) from the time the display was suspended
3. Best ask

9.17.9.3 Selecting Instruments and Accounts

NinjaTrader makes changing instruments and accounts quick and easy with separate menus
located directly within the SuperDOM.

How to select an instrument

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.

How to select an account


A list of all connected accounts will be listed in the "Account" drop down menu. To
change the account select the account you wish to trade via this drop down menu.

© 2011 NinjaTrader, LLC


Operations 441

9.17.9.4 Order Display

Orders are displayed in a highly visual manner. Different order types and order objectives
(stop loss or profit target orders) are uniquely color coded.

Understanding how orders are displayed

Order Display
All orders are displayed by coloring a cell or group of cells within the Price Ladder

1) Limit Order Default color is cyan with the text "LMT"


2) Stop Market Order Default color is pink with text "STP"
3) Stop Limit Order Default color is violet with text "SLM"
4) Market Order Color not displayed but quantity and order state displayed in the
bottom row
5) Stop Loss Order Default color is red (Only displayed in an active ATM Strategy)
6) Profit Target Order Default color is lime(Only displayed in an active ATM Strategy)

The image below shows a working limit, stop market, and stop limit order for one
contract each.

© 2011 NinjaTrader, LLC


442 NinjaTrader Version 7

Understanding how the quantity and state of an order are displayed

Size Marker - Order State Color Definitions


There is also an associated Size Marker which displays the remaining contracts to be
filled for the order(s) at the corresponding price. The color of the Size Marker indicates
the current order(s) state. In the image to the right, three contracts are remaining to be
filled and are working at the exchange.

Orange Pending Submit, Pending Change


Lime Working (at the exchange)
Grayish Blue Accepted (resting on your connectivity providers order servers or your
local PC)
Red Pending Cancel
Yellow Simulated Stop Order

Understanding how multiple orders at the same price are displayed

Consolidated Order Display


The SuperDOM will consolidate the display of all orders resting at the same price and
mark an "s" within the Size Marker display to indicate that there are multiple orders
stacked at that price. The Size Marker then indicates the cumulative remaining

© 2011 NinjaTrader, LLC


Operations 443

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

Stop Loss and Profit Target display


Orders submitted as Stop Loss and Profit Target orders are uniquely displayed by
coloring all three cells in the price row where the order(s) are working. This makes it
very easy to visualize your stop and profit objectives relative to the current market. All
other orders are displayed by coloring a single cell in either the BUY or SELL column.

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.

© 2011 NinjaTrader, LLC


444 NinjaTrader Version 7

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

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

© 2011 NinjaTrader, LLC


Operations 445

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.

How to submit a limit order

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.

How to submit a stop market order

To submit a stop market order, select either the BUY column for buy orders or the

© 2011 NinjaTrader, LLC


446 NinjaTrader Version 7

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.

How to submit a stop limit order

Stop Limit Order


To submit a stop limit 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) in the
cell that corresponds to the price you wish the stop limit order to be submitted at. A
numeric field (image lower right) will appear that represents the number of ticks away
you wish the limit price of the stop limit order to be placed at. Either by using your mouse
scroll wheel or clicking on the up/down arrows in the numeric field, set the number of
ticks and press the "check mark" button to complete the order submission. Pressing the
"x" button will cancel the order submission operation. For example, if you intend to have
an order with a stop price of 1000 and a limit price of 1001 (4 ticks spread for the SP
Emini contract) you would set the numeric field value to 4. Following the same example
submitting a sell stop limit, setting the numeric field value to 4 would result in a stop
price of 1000 and a limit price of 999.

© 2011 NinjaTrader, LLC


Operations 447

Negative Stop Limit Offset


You will notice that there are also 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 orders by putting the SuperDOM into simulated order mode. You can
enable this by clicking on your right mouse button within the border of the SuperDOM
and selecting the menu item Simulated Order or via the shortcut key CTRL + A.

Single Click Stop Limit Orders


If you generally place stop limit orders using the same offset between limit and stop
price, you can enable single click submission of stop limit orders by setting the "Stop
limit offset" property to an integer value via the SuperDOM properties. By default, this
setting is set to "Off" which forces the numeric field (image above right) to display.
Setting this property to a value of 1 would instantly place a stop limit order with a stop
price of X and a limit price of X + 1 for buy orders or X - 1 for sell orders.

How to scale in or out of an active ATM strategy

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.

Understanding the OCO order (one cancels other) function

OCO Orders (One Cancels Other)


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

© 2011 NinjaTrader, LLC


448 NinjaTrader Version 7

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.

Break Out/Fade Entry Example


One of the great features of NinjaTrader is its ability to submit two entry orders, one of
which will cancel if the other is filled.

You can accomplish a breakout/breakdown approach by:

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.

© 2011 NinjaTrader, LLC


Operations 449

For a market fade approach just substitute limit orders for stop orders.

Using the OCO Function to Bracket an Open Position


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

© 2011 NinjaTrader, LLC


450 NinjaTrader Version 7

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 to submit simulated stop orders (Simulated Order)

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.

© 2011 NinjaTrader, LLC


Operations 451

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.

How to submit orders with the Quick Buttons

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

© 2011 NinjaTrader, LLC


452 NinjaTrader Version 7

Removing Targets section of the user help guide.

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.

How to modify the price of entry and exit orders

Modifying entry and exit orders


Pending orders in NinjaTrader may be modified by clicking to select the order and
clicking once more at the new price point. This approach is more effective than drag and
drop because it eliminates the potential errors made by accidentally letting go of your
mouse button and dropping an order on the wrong price.
1. Click using your left mouse button on the order you wish to modify.

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

© 2011 NinjaTrader, LLC


Operations 453

Modifying Stop Loss and Profit Target orders


1. Click with your left mouse button in the center column on the Stop Loss or Profit
Target order you want to modify.

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.

How to modify the size of an order

Modifying the size of an order


To modify the size of an order, click on the Size Marker (marked by the red arrow in the
image below) with your left mouse button or your middle mouse button. Using your left
mouse button will increment the quantity field by 1, middle mouse button will decrement
the quantity field by 1.

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

© 2011 NinjaTrader, LLC


454 NinjaTrader Version 7

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

Single Click Order Modification


You have the option of enabling Single Click Order Modification for ATM Stop Loss
and Profit Target orders via the SuperDOM Properties dialog window accessible by
right mouse click context menu. This is an advanced feature that can provide you with
the clear advantage of efficiently modifying orders in fast moving markets. If you are a
scalper then this option is for you.

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.

© 2011 NinjaTrader, LLC


Operations 455

9.17.9.7 Cancelling Orders

There are several options for cancelling orders within the NinjaTrader SuperDOM.

How to cancel orders

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.

© 2011 NinjaTrader, LLC


456 NinjaTrader Version 7

How to Add or Remove Targets


It is important to understand the following logic:
You can have a maximum of 3 targets (if you had 3 and the first two targets are filled you
can not split the 3rd target)
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 ticks from your current outside target for futures, $0.20 for stocks

Two Methods for Adding and Removing Targets


There are two locations within the SuperDOM where you can add or remove a target.
1. Pressing down on the Left mouse button on the "+ TARGET" (to add) or "- TARGET" (to
remove) buttons when "Show Quick Buttons" is set to True in the SuperDOM properties
dialog window

2. Right mouse click context menu.

© 2011 NinjaTrader, LLC


Operations 457

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.

How to access the SuperDOM properties menu


You can access the SuperDOM properties dialog window by clicking on your right
mouse button within the SuperDOM border and selecting the menu Properties.

© 2011 NinjaTrader, LLC


458 NinjaTrader Version 7

Available properties and definitions

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

© 2011 NinjaTrader, LLC


Operations 459

Last trade Sets the color of the last trade marker


color
Limit order Sets the color of a limit order
color
Price column Sets the color of the price column
color
Profit target Sets the color of a profit target
color
Sell column Sets the color of the sell column
color
Simulation Sets the color of the SuperDOM background when a simulation account
color (Sim101) is selected
Stop limit order Sets the color of a stop limit order
color
Stop loss color Sets the color of a stop loss order
Stop market Sets the color of a stop market order
order color
Advanced Enables or disables the display of SuperDOM advanced options
options
ATM Strategy Sets the behavior mode of the price ladder display and strategy selector
selection mode (more information here)
Auto center Enables or disables auto centering of the last traded price when it trades
price outside of range
Caption bar Sets the text displayed in the caption bar of the SuperDOM
display
Font Sets the font
Last trade When true, the last trade volume is displayed in the center price column
displayed in otherwise it is displayed in either the buy or sell column
price column
Middle mouse When true, the middle mouse button (scroll wheel) is used for
button is stop submitting stop market orders otherwise a stop limit order is submitted
market
Number of Sets the number of price rows in the SuperDOM price ladder
price rows
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 Sets the display unit for profit and loss
unit
Relocate Relocates the center "C" button to the top center of the price ladder
center button display
Scale quantity Sets the scale order quantity amount
Show Enables or disables cumulative market depth to be shown
cumulative
depth
Show daily Enables or disables the daily high and low markers to be shown
high/low

© 2011 NinjaTrader, LLC


460 NinjaTrader Version 7

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.

How to set the default properties


Once you have your SuperDOM Properties set to your liking, you can left mouse click
on the Set Default button which will save these settings as the default settings used
every time you open a new SuperDOM window.

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.18 Session Manager


The Session Manager window is used to create and configure Session Templates.
Session Templates are set up to contain the session start and end times of a specific
market or instrument. NinjaTrader comes with pre-loaded Session Templates for the most
commonly traded markets.

Using the Session Manager

9.18.1 Using the Session Manager


Within the Session Manager, Session Templates holding session definitions for each day
of the week can be created and edited based on any time zone.

Understanding Session Templates

© 2011 NinjaTrader, LLC


Operations 461

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.

Where Session Templates can be Applied


Session Templates can be applied in the following NinjaTrader dialogue windows under
the property "Session template":

Chart panel via the Data Series window


Market Analyzer via the Market Analyzer Properties window
Strategy Analyzer window when configuring backtesting
Strategies tab of the Control Center when starting a strategy

How to create and edit a Session Template

Creating a Session Template


If your desired session settings are not found within the pre-loaded Session Templates,
you can create a new template which will be added to the Session template drop down
menu.

To create a Session Template:

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.

© 2011 NinjaTrader, LLC


462 NinjaTrader Version 7

*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.

Working with Session Templates


A saved Session Template can be selected via the Session template drop down
menu at the top of the Session Manager. The template as well as individual session
definitions can then be configured.

Editing Session Templates

© 2011 NinjaTrader, LLC


Operations 463

Session Templates can be edited in the following ways:

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.

Editing Session Definitions


Individual session definitions can be edited in the following ways:

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.

Simulation Accounts Paper Trading


The Sim101 Account Live/Simulation Environment
Multiple Simulation Accounts Global Simulation mode
Trading in Simulation

9.19.1 The Sim101 Account


What is the Sim101 account?
The Sim101 account is a default account that represents your own simulated account
through which you place simulated trades. The Sim101 account behaves identical to a live
account in that it has a cash balance, profit and loss and other financial parameters. For
example, when placing orders to the simulator, the Sim101 account is checked to ensure that
you are not exceeding your buying power.

How to customize the Sim101 account


You can set initial Sim101 account values, reset simulator values, clear order history, and set
simulation engine parameters. To access these settings open the Control Center window
select the Tools menu and then select the menu name Options, once in the Options
window select the Simulator Tab.

© 2011 NinjaTrader, LLC


464 NinjaTrader Version 7

9.19.2 Multiple Simulation Accounts


You can create an unlimited number of simulation accounts in NinjaTrader.

How to create multiple simulation accounts

Steps to Create Multiple Simulation Accounts


1. Open the NinjaTrader Control Center.
2. Select the Tools menu.
3. Select the menu item Options.
4. Once the Options window opens select the Simulator Tab.
5. Left click on the Accounts button.
6. Type in the name of your new account (user defined) and click the Save button.

The account will be active the next time you connect to a data provider.

Which users can create multiple simulation accounts?

Free License Users


Free license users are limited to the single Sim101 account and cannot create
multiple simulation accounts
You can upgrade to the paid license at anytime buy purchasing a live license.

Live License Users


Live license users can create an unlimited number of simulation accounts.
These accounts will show when you are connected alongside with the Sim101
account and any available connected brokerage accounts.
9.19.3 Live/Simulation Environment
NinjaTrader is a true mixed live/simulation platform. You can have multiple entry windows
open and using the account drop down menu, simultaneously route orders to your live broker
in one window while routing orders to the simulator in another. This provides you the flexibility
to trade live while testing different methods or ideas in simulation.
9.19.4 Global Simulation Mode
What is Global Simulation Mode?
When Global Simulation Mode is enabled, all order entry interfaces (SuperDOM, Chart
Trader, etc.) will be set exclusively to the Sim101 account. Enabling this is not necessary in
order to route orders through simulation, because you can still set any order entry interface to
the Sim101 account individually. However, Global Simulation Mode provides you a method
to ensure that you do not accidentally place an order to your live trading account.

How to enable or disable Global Simulation mode


1. From the NinjaTrader Control Center select the File menu.
2. Then select the menu item Global Simulation Mode
3. When the check mark appears next to the menu item Global Simulation Mode it is

© 2011 NinjaTrader, LLC


Operations 465

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.

9.19.5 Trading in Simulation


NinjaTrader routes orders based on the account that you select in any of the order entry
interfaces (SuperDOM, Chart Trader, etc.). Simulation is no different. You can select the
Sim101 account from any of the NinjaTrader order entry interfaces to submit your orders in
simulation. When selecting the Sim101 account in any of the NinjaTrader order entry
interfaces, the background color will change to the user defined simulation mode color which
is a dark slate gray by default.

9.20 Strategy Analyzer


The Strategy Analyzer allows you to run historical analysis on your NinjaScript based
automated trading strategies. The Strategy Analyzer can be opened by left mouse clicking
on the File menu within the NinjaTrader Control Center, selecting the menu item New and
then selecting the menu item Strategy Analyzer.

Strategy Analyzer Layout


Backtest a Strategy
Optimize a Strategy
Walk Forward Optimize a Strategy
Basket Test
Reviewing Performance Results
Saving Performance Results

© 2011 NinjaTrader, LLC


466 NinjaTrader Version 7

Monte Carlo Simulation


Discrepancies: Real-Time vs
Backtest

9.20.1 Strategy Analyzer Window


Layout
The Strategy Analyzer contains the following items:

1. Toolbar

The Strategy Analyzer toolbar contains the following items (in order from left to right):

Load saved backtest results


Save backtest results
Open the NinjaScript output window (for debugging a strategy)
Run backtest
Run optimization
Run walk forward test
Create new strategy
Edit strategy
Delete strategy
Calculate mode

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.

© 2011 NinjaTrader, LLC


Operations 467

9.20.2 Backtest a Strategy

A backtest allows you to analyze the historical performance of a strategy. In order to run a
backtest you will need:

Access to historical data


Custom NinjaScript *strategy

*There are several pre-defined sample strategies that are installed with NinjaTrader that you
can explore.

How to run a backtest

Start a Backtest
To run a Backtest of a strategy:

© 2011 NinjaTrader, LLC


468 NinjaTrader Version 7

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.

Understanding historical processing options

Historical Fill Processing


NinjaTrader provides two system fill algorithms that can be used in a backtest. In
addition, if you have some experience programming, you can script your own algorithm.

The two system fill algorithms are:

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)

© 2011 NinjaTrader, LLC


Operations 469

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.

Special Circumstance with Forex backtests


During a backtest order quantity is an absolute value, which is in most cases different
than in a real-time brokerage account. As an example, 1 traded FX lot at a live brokerage
account might be the equivalent to 100,000 of notional value (check with your broker)
however, in backtest a value of 1 is a literal value of 1 and not 100,000. Thus if you want
to trade 100,000 in a backtest, you need to put in a value of 100,000. Just remember that
if you convert your strategy from backtest to live you will need to amend the order
quantities appropriately. (Please see the Running FX Strategies section for more
information).

Understanding backtest properties

Backtest Properties
The following properties are available within the Backtest window:

© 2011 NinjaTrader, LLC


470 NinjaTrader Version 7

Parameters Sets any strategy specific user defined inputs


Price based Sets the type of market data used to drive the Data Series
on
Type Sets the bar type of the Data Series.
Value Sets the Data Series value.
From Sets the start date for the backtest period
To Sets the end date for the backtest period
Session Sets the session time template for the Data Series. (See the "Session
template Manager" section of the Help Guide for more information)
Include Include commission in the backtest performance results (See the "
commission Commission Tab" section of the Help Guide for more information)
Label Sets a text value that will be displayed on the chart to represent the
strategy
Maximum Max number of bars used for calculating an indicator's value. The
bars look "TwoHundredFiftySix" setting is the most memory friendly.
back

© 2011 NinjaTrader, LLC


Operations 471

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:

Access to historical data


Custom NinjaScript *strategy
A thorough understanding of the Strategy Analyzer's backtesting capabilities

*There are several pre-defined sample strategies that are installed with NinjaTrader that you
can explore.

How to run an Optimization

Start an Optimization
To run an Optimization:

© 2011 NinjaTrader, LLC


472 NinjaTrader Version 7

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.

Setting the Test Range


The strategy input parameters can be expanded to display the following sub-parameters:

Min. value - The starting value you want to test


Max. value - The last value to test
Increment - The increment value (step value) used to increment the starting value by for
each subsequent optimization pass

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.

© 2011 NinjaTrader, LLC


Operations 473

Setting the Best Result Criterion


Optimization is based on the best result criterion you select. If you set the property
"Optimize on..." to "Max. net profit", the optimizer will seek the optimal input values that
return the maximum profit possible. There are over 10 different optimization criterion you
can select. Please see the "Understanding Optimization properties" section below for
more information.

The Best Optimization Result


Once the optimization process is complete, you will see a "Instruments" tab and a
"Optimizer" tab. The "Instruments" tab will display the best optimization result for each
unique instrument that was selected for optimization. Selecting each result row will
display the performance data for that instrument.

The Top Optimization Results


The Optimizer tab will display the top number of results based on the value you set for
the "Keep best # results" property in the Optimizer dialog window. The column
Parameters displays the optimized input values.

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

© 2011 NinjaTrader, LLC


474 NinjaTrader Version 7

Understanding optimization properties

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.

The following Optimization specific properties are available:

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.

Understanding the Genetic Algorithm

Overview
The general idea of how the GA solves an optimization problem is analogous to the

© 2011 NinjaTrader, LLC


Operations 475

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.

Note: It is important to understand that GA will find approximate optimum solutions.


Since it does not test every combination possible there is no guarantee its solutions are
absolute optimums.

How the GA calculates


The GA determines its solution through the following steps:

1. Begin with an initial population size consisting of randomly selected individuals


(parameter setting combinations)
2. Compute the fitness (Optimize on...) for each individual in the population and assign
probabilities to the population based on the fitness results. More fit results have more
probability in being selected for breeding of the next generation.
3. Generate a new population for the next generation by selecting individuals from the
prior generation to produce offspring via crossover and mutation (see below)
4. Repeat from step 2 till you reach the number of generations in your test

Crossover and Mutation


Crossover is the process in generating offspring that are not 100% identical to their
parents. It is done by taking half of the parameter settings from parent A and mixing it
with the other half from parent B. Crossover allows GA to test different combinations of
parameters and hone in on the optimal solution. Crossover alone however will eventually
yield identical offsprings in the population through several generations and so through
mutation, some random parameter settings will be interjected in a few of the offsprings
to allow for an adaptive quality to the algorithm.

How to run a Genetic optimization


Please see the "Optimize a Strategy" article for how to run an optimization.

When you select the Genetic optimizer you will see the following optimization properties:

© 2011 NinjaTrader, LLC


476 NinjaTrader Version 7

GO: # of Sets the number of generations to test


Generations
GO: Each new generation is created from a combination of randomly
Crossover generated offspring and offspring created from combining (crossing over)
Rate (%) parent parameters. Crossover Rate determines the percentage of the
new generation that is generated from the crossover process.
GO: Sets the number of combinations to test in each generation. The higher
Generation the size, the more variety of combinations to test.
Size
GO: Minimum If this performance value is reached before all generations are evaluated
Performance the optimizer will end and present results immediately. Value of 0 means
no minimum performance is in use.
GO: Mutation Sets the probability that a crossover offspring will contain some mutated
Rate (%) parameters
GO: Mutation Sets the maximum offset from crossover values that an offspring marked
Strength (%) for mutation can have its parameters changed
GO: Reset When each new generation is created, all individuals from previous
Size (%) generations are possible parents for the new offsprings. If the top
performing x% (stability size %) of individuals from the newly created
generation is the same as the top performing x% of parents, reset all
parents and repopulate a new generation randomly while leaving only the
top performing y% of parents (reset size %) for future generations.
GO: Stability See "GO: Reset Size %"
Size (%)
Keep best # Sets the number of best results to display
results
Optimize data If set to true, the Data Series Value property will be available for
series optimization (Not supported for Kagi, PointAndFigure, and Line Break
period Types)
Optimize on... Sets the optimization criterion to base the optimization results on. This is
the "fitness function" for the GA.
Optimizer Sets the optimization algorithm that is used. NinjaTrader comes with
"Default" and "Genetic" optimizer algorithms.

© 2011 NinjaTrader, LLC


Operations 477

9.20.4 Walk Forward Optimize a Strategy


Walk Forward optimization is the process by which you optimize strategy input parameters
on a historical segment of market data, then test the strategy forward in time on data
following the optimization segment using the optimized input values. The central idea is that
you evaluate strategy performance data on the test data, not the data used in the
optimization. This process is then repeated by moving the optimization and test segments
forward in time. To run a walk forward optimization you will need:

Access to historical data


Custom NinjaScript *strategy
A thorough understanding of the Strategy Analyzer's backtesting and optimization
capabilities

*There are several pre-defined sample strategies that are installed with NinjaTrader that you
can explore.

How to run a Walk Forward Optimization

Start a Walk Forward Optimization


To start a Walk Forward optimization:

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.

Understanding the Walk Forward properties

Walk Forward Properties

© 2011 NinjaTrader, LLC


478 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


Operations 479

1. Each instrument's backtest results are displayed individually

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...

9.20.7 Saving Performance Results


Test results can be saved and loaded for future reference.

How to save test results

Saving Test Results


To save test results:

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

© 2011 NinjaTrader, LLC


480 NinjaTrader Version 7

How to load saved test results

Loading Test Results


To load test results:

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.

© 2011 NinjaTrader, LLC


Operations 481

9.20.8 Monte Carlo Simulation


Monte Carlo Simulation is a mathematical technique used to study data that is highly
random in nature. When used for trading, it is a method of randomizing trade results and
running those results in a series of simulations to analyze the probability of multiple
outcomes. This type of analysis will help you recognize if your strategy runs the risk of wiping
out your account before it can turn a profit or not. Monte Carlo Simulation can be accessed
by right mouse clicking in any Trades tab in NinjaTrader.

Running a Monte Carlo Simulation

9.20.8.1 Running a Monte Carlo Simulation

The following page covers how to set up and run NinjaTrader's Monte Carlo Simulation

Understanding Monte Carlo simulation

What is Monte Carlo Simulation?


Monte Carlo Simulation is a mathematical technique that uses repeated random
sampling to compute a range of possible results with their respective probability.
NinjaTrader runs Monte Carlo Simulation by randomly combining the trade results in a
defined series of simulations. A graph of the results are plotted with the statistic values
or Profit/Loss on the Y - axis and the probability on the X - axis as a percentage.

Why use Monte Carlo Simulation?


Although a backtest of a NinjaScript strategy may produce profitable results, those
results may have just been due to good luck. In real life, you may have a string of bad
trades that can wipe out the account before the good trades appear, therefore it would
be helpful to understand the probability of such a string of bad trades. Monte Carlo
Simulation will randomize your trade results over and over again in multiple simulations
to provide you with a normal distribution of simulation performance. The trader can use
this information to see the top or bottom percent of trades (outliers) that will cause the
most variability in the strategy as well as the most statistically probable results.

How to run a Monte Carlo simulation

Monte Carlo Simulation window


To open the Monte Carlo Simulation window:

1. Run a Backtest, Optimization, Walk-Forward Optimization, or run an Account


Performance report.
2. Left mouse click on the Trades tab within any of the reports
3. Right mouse click in the data grid and select the item Monte Carlo Simulation...

© 2011 NinjaTrader, LLC


482 NinjaTrader Version 7

Running a Monte Carlo Simulation


To run a 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.

Monte Carlo Simulation Parameters


The following parameters are adjustable when running a Monte Carlo Simulation:

Graph Sets the statistic to generate the report on


Mode Sets the unit type the results are displayed in
Winning/ Sets the results to show only winners, only loser, or both
Losing
Long/Short Sets the results to show only long trades, only short trades, or both
Remove Removes the top % outliers from the results
winning
outliers (%)
Remove Removes the bottom % outliers from the results
losing outliers
(%)
# of Sets the # of simulations to run
simulations
# of trades Sets the # of trades in each simulation (will default to the # of trades in
per simulation the Trades tab)

Understanding the Monte Carlo Simulation report

Monte Carlo Simulation Report


The results of the Monte Carlo Simulation are displayed in a graph below the
parameters.

© 2011 NinjaTrader, LLC


Operations 483

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.

Getting Filled on an Order


During a backtest you can select conservative or liberal fill algorithms which will produce
different results. Fills are determined based on 4 data points, OHLC of a bar since that is
the only information that is known during a backtest.
During simulation using real-time live market data or Market Replay, the fill algorithm is
dynamic in that it uses incoming market data (both price and volume) to determine if an
order should be filled or not.
During real-time live brokerage trading, orders are filled according to market dynamics.

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.

© 2011 NinjaTrader, LLC


484 NinjaTrader Version 7

The Fill Price of Orders


During a backtest assumptions are made on the fill price of an order is based on the OHLC
of a bar and the price of the order itself. You can also have differences depending on which
fill algorithm you choose.
During simulation using real-time market data or Market Replay, the fill price is based on
incoming market data and volume, you may receive better or worse fill prices dependant on
where the bid or ask price is and what volume is available at this market prices.
During real-time brokerage trading, orders are filled according to market dynamics.

As you can see, there are three different models on what price an order can be filled at.

Running a Strategy at the Close of a Bar or Tick by Tick


During backtest, strategies can ONLY be processed at the close of each bar
During real-time operation, you have a choice to run a strategy tick by tick (
CalculateOnBarClose set to false) which can produce different results. This is because
you can have a signal that executes an order at the close of a bar but when running tick by
tick, while in a bar a signal condition can be true although its false at the close of the same
bar.

Differences in chart data


If you run a strategy in real-time on DAY1 and then DAY2, you are now backtesting your
strategy on DAY1 data instead of processing like it did in real-time so there could be
differences. You should understand how chart bars are built.
If using tick based charts, all it takes is a single tick difference between real-time and
historical data to generate completely different looking charts. This in turn would impact the
calculations of your strategy should the data sets be different.

9.21 Strategy Wizard


The Strategy Wizard is used to generate NinjaScript based strategies for automated
systems trading. The Strategy Wizard can be opened by left mouse clicking on the Tools
menu within the NinjaTrader Control Center, selecting the menu item New NinjaScript and
selecting the menu item Strategy...

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

© 2011 NinjaTrader, LLC


Operations 485

Strategy Actions

9.21.1 Wizard Screens


Whether you are going to self program your strategy or use the wizard exclusively, a strategy
is always initially created via the Strategy Wizard.

Understanding the Opening screen

Opening Screen Layout


This is the first screen in the Strategy Wizard.

1. Press the Help button to open the NinjaTrader Help Guide


2. Press the View Code... button at any time to view the wizard generated NinjaScript
code
3. Press the Unlock Code button at any time to open the NinjaScript editor and edit your
strategy code.
Once the code is unlocked, you can no longer use the wizard for subsequent
strategy editing
4. Press the Compile button at any time to compile your strategy code.

© 2011 NinjaTrader, LLC


486 NinjaTrader Version 7

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...".

Understanding the General screen

General Screen Layout


The General screen is where you enter the name and description of your strategy.

1. Sets the name of the strategy


2. Sets the description of the strategy
3. Enables or disables the default setting for CalculateOnBarClose (can override when
starting a strategy)

Understanding the User Defined Inputs screen

Defined Inputs Screen


This screen allows you to define user defined inputs of your strategy. User defined
inputs are important if you require input values that may vary the performance of your
strategy. If for example you have a simple moving average cross over system, you may
want to create an input for the fast moving average and another for the slow moving

© 2011 NinjaTrader, LLC


Operations 487

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.

1. Sets the name of the input


2. Sets the value type of the input to either "int" (integer value - whole numbers) or a
"double" (double value - decimals) or a "bool" (true or false) or a "string"
3. Sets the default value of the input
4. Sets the minimum value of the input
5. Sets the description for the input

Understanding the Conditions and Actions screen

Conditions and Actions


This screen allows you to set conditions and subsequent actions that control the flow of
your strategy.

Conditions - Take the specified action when true


Actions - Execute an action (submit orders, draw objects on the chart etc...) based on
its parent condition evaluating to true

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.

© 2011 NinjaTrader, LLC


488 NinjaTrader Version 7

1. Selects the condition set you wish to edit


2. Displays conditions associated with the currently selected condition set
3. Add or delete a condition
4. Edits the currently selected condition
5. Displays the actions associated with the currently selected condition set
6. Add or delete an action
7. Edits the currently selected action

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.

© 2011 NinjaTrader, LLC


Operations 489

Understanding the Stops and Targets screen

Stops and Targets Screen


This screen allows you to set stop loss, trail stop and profit target orders that are
automatically submitted and managed once your strategy opens a position.

1. Displays stops and targets associated with your strategy


2. Adds or deletes a stop or target
3. Edits the selected stop or target

© 2011 NinjaTrader, LLC


490 NinjaTrader Version 7

Understanding the Finish screen

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.

9.21.2 Condition Builder


The Condition Builder is a very powerful feature that allows you to define complex
conditions for your automated trading systems without having to know how to program.

Understanding the Condition Builder

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

© 2011 NinjaTrader, LLC


Operations 491

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

2 < 7 (2 is less than 7)

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

How to make price data comparisons

Price Data Comparisons


You can compare a bar's price data such as checking for a higher close. The following

© 2011 NinjaTrader, LLC


492 NinjaTrader Version 7

is an an example and represents one of many possible combinations.

1. Expand the Price data category and select the Close.


2. Select the > (greater than) relational operator
3. Expand the Price data category and select the Close.
4. Set the Bars ago parameter to a value of "1"

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"

How to offset an item value

Offsetting an Item Value


You can offset the value of most items available in the Condition Builder. An offset is a
value that is added or subtracted from the actual item's value. When an item is selected
such as an indicator or price data, the Offset type and Offset parameters become
visible in the window directly below the item selected. This is shown as numbers 5 and 6

© 2011 NinjaTrader, LLC


Operations 493

in the image below.

Offset type can be set to:

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.

The following is an example and represents one of many possible combinations:

1. Expand the Price data category and select the Close


2. Select the > (greater than) relational operator
3. Expand the Price data category and select the High
4. Set the Bars ago parameter to a value of "1"
5. Set the Offset type parameter to Ticks
6. Set the Offset parameter to a value of "1"

© 2011 NinjaTrader, LLC


494 NinjaTrader Version 7

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"

How to make indicator to value comparisons

Indicator to Value Comparisons


You can compare an indicator's value to a numeric value. This can come in handy if you
wanted to check if ADX is over a value of 30 (trending) or if Stochastics is under a value
of 20 (oversold) or any other conditions you can think of.

The following is an an example and represents one of many possible combinations:

1. Expand the Indicators category and select the ADX indicator


2. Set the item parameters
3. Select the > (greater than) relational operator
4. Expand the Misc category and select Numeric value
5. Enter the numeric value

© 2011 NinjaTrader, LLC


Operations 495

Once the OK button is pressed, a condition is created that would translate to the
following:

"Current value of a 14 period ADX is greater than 30"

How to compare plot values of multi-plot indicators

Comparing Plot Values of Multi-Plot Indicators


You can compare plots in the same indicator or select any individual plot within an
indicator to create a condition.

The following is an example and represents one of many possible combinations.

1. Expand the Indicators category and select the Stochastics indicator


2. Set the indicator input parameters and select the K plot (blue arrow)
3. Select the > (greater than) relational operator
4. Expand the Indicators category and select the Stochastics indicator
5. Set the indicator input parameters and select the D plot (blue arrow)

© 2011 NinjaTrader, LLC


496 NinjaTrader Version 7

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"

How to use user defined inputs & variables

User Defined Inputs & Variables


User defined inputs are simply variables that can be used in place of absolute values.
They increase the flexibility of your strategy since you can substitute a variable for the
period parameter of a simple moving average instead of provide an absolute value.

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

© 2011 NinjaTrader, LLC


Operations 497

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.

User defined inputs are created from the wizard screen


User variables can be set in the strategy logic through the Condition Builder (see the
sections above)

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.

1. Expand the Price data category and select the Close.


2. Select the > (greater than) relational operator
3. Expand the Indicators category and select the SMA indicator
4. Set the Period parameter to a user defined input by pressing the "..." button to open
the Value window
5. Expand the User defined inputs category and select the value MAPeriod and press
the OK button

© 2011 NinjaTrader, LLC


498 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


Operations 499

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"

How to create a cross over condition

Cross Over Conditions


You can check for either a CrossAbove or CrossBelow condition with a user defined
look back period. The look back period sets the number of bars to look back to check for
the cross over condition.

The following is an an example and represents one of many possible combinations.

1. Expand the Indicators category and select the EMA indicator


2. Set the Period parameter to a value ("9" is used in this example)
3. Select CrossAbove
4. Set the Look back period
5. Expand the Indicators category and select the EMA indicator
6. Set the Period parameter to a value ("20" is used in this example)

© 2011 NinjaTrader, LLC


500 NinjaTrader Version 7

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"

How to use indicator inputs in other indicators

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!

The following example is an example of applying a simple moving average (SMA) to a 14


period ADX indicator and is one of many possible combinations.

1. Expand the Indicator category and select SMA indicator


2. Set Input series to the ADX indicator by pressing the "..." button to open the Value
window
3. Select the ADX indicator and set any properties in the Parameters window

© 2011 NinjaTrader, LLC


Operations 501

4. Press the OK button

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.

© 2011 NinjaTrader, LLC


502 NinjaTrader Version 7

Once the OK button is pressed, a condition is created that would translate to the
following:

"Current value of a 14 period simple moving average of a 14 period ADX is


greater than 30"

How to check for volume expansion

Checking for Volume Expansion


You can compare if the current bar's volume is greater than the prior bar's volume plus
an offset amount.

The following is an an example and represents one of many possible combinations.

1. Expand the Indicators category and select the VOL indicator


2. Select the >= (greater than or equal to) relational operator
3. Expand the Indicators category and select the VOL indicator
4. Set the Bars ago parameter to a value of "1"
5. Set Offset type parameter to Percent
6. Set the Offset parameter to a value of "3"

© 2011 NinjaTrader, LLC


Operations 503

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%"

How to create market position comparisons

Creating Market Position Comparisons


You can compare a strategy state information such as but not limited to market position
or position size.

The following is an an example and represents one of many possible combinations.

1. Expand the Strategy category and select Current market position.


2. Select the == (equals to) relational operator
3. Expand the Strategy category and select Flat

© 2011 NinjaTrader, LLC


504 NinjaTrader Version 7

Once the OK button is pressed, a condition is created that would translate to the
following:

"Current market position equals flat"

How to create time comparisons

Creating Time Comparisons


You can compare a bar's time data to a user defined time or date value.

The following is an an example and represents one of many possible combinations.

Note: Time series represents a collection of bar Date/Time values of a bar series

1. Expand the Time category and select Time series


2. Select the >= (greater than or equal to) relational operator
3. Expand the Time category and select Time value
4. Set the Value parameter to a user defined value of "10:00 AM"

© 2011 NinjaTrader, LLC


Operations 505

Once the OK button is pressed, a condition is created that would translate to the
following:

"Current bar's time is greater or equal to 10:00 AM"

9.21.3 Strategy Actions


The Strategy Action window allows you to select actions to execute.

Understanding the Strategy Action window

Strategy Action Window


The Strategy Action window allows you to select actions to execute. Actions are
executed when a strategy condition is true. The Strategy Action window can be
accessed via the Conditions and Actions wizard screen or the right mouse button
click menu of the NinjaScript Editor.

Within a NinjaScript strategy you can invoke miscellaneous actions, submit various

© 2011 NinjaTrader, LLC


506 NinjaTrader Version 7

order types for entering and exiting market positions, and have access to various
drawing methods as shown in the images below.

How to enter a market position

Entering a Market Position


Using the various Order management actions, you can enter a position using market,
limit, stop market and stop limit orders.

Following is an example and represents one of many possible combinations.

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

© 2011 NinjaTrader, LLC


Operations 507

*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.

5. Expand the Price data category and select Bid


6. Set the Offset type to Ticks and enter a value of "-1" for Offset (see "How to offset
an item value" section of the Condition Builder page of the Help Guide for more
information)

© 2011 NinjaTrader, LLC


508 NinjaTrader Version 7

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"

How to exit a market position

Exiting a Market Position


Using the various Order management actions, you can exit a position using market,
limit, stop market and stop limit orders.

Following is an an example and represents one of many possible combinations.

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.

© 2011 NinjaTrader, LLC


Operations 509

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'."

How to draw on a chart

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.

Following is an an example and represents one of many possible combinations.

1. Expand the Drawing category and select Diamond


2. Set the Tag parameter with a user defined name that identifies this drawing object.
Providing a tag is of value if you are going to draw more than one of the same draw type
object (Diamond in this case) on the same bar.
3. Optionally set Auto Scale to "True" to include the Diamond as part of the chart's auto

© 2011 NinjaTrader, LLC


510 NinjaTrader Version 7

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"

9.22 Time & Sales


The Time & Sales window displays the current Bid/Ask price and volume as well as color
coded last traded time, price and size. You can optionally filter for large trades (BLOCKS) by
setting the block size in the Time & Sales Properties dialog window.

© 2011 NinjaTrader, LLC


Operations 511

Using the Time & Sales Window


Time and Sales Properties

9.22.1 Using the Time & Sales Window


You can have as many Time & Sales windows open as you like at anytime, one for each
instrument whose trade information you wish to analyze.

Opening a Time and Sales window


You can access a Time and Sales window from within the NinjaTrader Control Center
window by left mouse clicking on the menu File, selecting the menu New, and then selecting
the menu item Time And Sales.

How to Select an Instrument


You can select an instrument by right mouse clicking within the Time & Sales window and
then selecting the menu item Instruments -->.

How to Configure Columns


You can enable or disable the Time, Price, Volume, and Block columns by right mouse
clicking within the Time & Sales window and then selecting the menu item Columns...

© 2011 NinjaTrader, LLC


512 NinjaTrader Version 7

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.

How to access the Time and Sales Properties window


You can access the Time & Sales Properties menu by right clicking in the Time and
Sales window and selecting the menu name Properties.

Available properties and definitions

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

© 2011 NinjaTrader, LLC


Operations 513

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)

How to set the default properties


Once you have your Time & Sales properties set to your liking, you can left mouse click
on the "Set Default" button which will save these settings as the default settings used
every time you open a new Time & Sales window.

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.

9.23 Window Linking


Many windows in NinjaTrader can be linked by instrument allowing synchronous changing of
instruments in all linked windows.

Linking Windows

9.23.1 Linking Windows


Charts, Order entry, Alerts, Time and Sales, News and Market Analyzer windows all have link
buttons in the top right hand corner (L). 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 that if
you change, or select, an instrument in one window, all other linked windows will also change
to that instrument.

© 2011 NinjaTrader, LLC


514 NinjaTrader Version 7

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

9.24.1 Managing Workspaces

To access all workspace management functions, open the NinjaTrader Control Center,
select the File menu, and then the menu name Workspaces.

© 2011 NinjaTrader, LLC


Operations 515

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

How to quickly switch between Workspaces

Quickly Switching Between Workspaces


Pressing SHIFT+F3 keys together will cycle to the next open workspace.

How to create a Workspace

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)

© 2011 NinjaTrader, LLC


516 NinjaTrader Version 7

How to save a Workspace

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

How to open a Workspace

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

How to close a 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.

How to delete a Workspace

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

© 2011 NinjaTrader, LLC


Part

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 as Source Files

© 2011 NinjaTrader, LLC


NinjaScript 519

You may want to provide other NinjaTrader


users with source files of your NinjaScript
indicators or strategies in a format where
they are able to view and edit them.

1. From the Control Center window select


the menu File > Utilities > Export
NinjaScript to open the "Export
NinjaScript" dialog window

2. Select the option "Export selected source


files"

3. Enter a user defined file name

4. Select all of the files that you want to


export and either double click on them or
press the ">" button

5. A list of all files that will be exported

6. Press the "Export" button to export the


selected files

7. A NinjaScript Archive File (.zip) file will be


created in My Documents\<NinjaTrader
Folder>\bin\Custom\ExportNinjaScript

8. The file can be imported by another


NinjaTrader application on a different PC

Note: The NinjaScript Archive File (.zip)


generated through this process is
compatible with both 32-bit and 64-bit
versions of NinjaTrader.

Exporting NinjaScript Indicators or Strategies as Assembly

© 2011 NinjaTrader, LLC


520 NinjaTrader Version 7

You may want to provide other NinjaTrader


users with access to your proprietary
indicators or strategies in a secure format
preventing them from being able to see your
proprietary source code. You can do this by
exporting your NinjaScript indicators as a
compiled Microsoft .NET assembly (DLL)
file.

This is a great distribution option if your


proprietary indicator or strategy files do
not reference external DLL's
If your proprietary indicator or strategy
references external DLL's then its advised
to create your own custom installer

1. From the Control Center window select


the menu File > Utilities > Export
NinjaScript to open the "Export
NinjaScript" dialog window
2. Select the option "Export compiled
assembly of selected source files".
3. You can optionally select "Protect
compiled assemblies" (For information on
protection see the "Protection/DLL
Security page)
4. Enter a user defined file name
5. Select all of the files that you want to
export and either double click on them or
press the ">" button
6. A list of all files that will be exported
7. Optionally enter information that
describes the assembly
8. Press the "Export" button to export the
selected files
9. A NinjaScript Archive File (.zip) file will be
created in My Documents\<NinjaTrader
Folder>\bin\Custom\ExportNinjaScript
10.The file can be imported by another
NinjaTrader application on a different PC

Note: When exporting a protected


assembly the generated .zip will contain a
x86 (32-bit) and x64 (64-bit) version of the
DLLs. When a user installs this .zip, both
assemblies are installed and NinjaTrader
will automatically load the correct one based
on if the user is in 32-bit or 64-bit mode.

© 2011 NinjaTrader, LLC


NinjaScript 521

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:

NinjaScript Compile Error

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.

© 2011 NinjaTrader, LLC


522 NinjaTrader Version 7

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:

"3/6/2009 9:25:30 AM|2|4|Error compiling export assembly: C:


\Users\NinjaTrader\Documents\NinjaTrader 7\bin\Custom\Indicator\MyCustomIndicator.
cs(42,18) : error CS0118: NinjaTrader.Indicator.SMA is a type but is used like a variable"

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.

If you experience this error, please follow this procedure:

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”

© 2011 NinjaTrader, LLC


NinjaScript 523

4. Add the indicator that was referenced in the error to the export list along with your
custom NinjaScript by pressing the > button

© 2011 NinjaTrader, LLC


524 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 525

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.

© 2011 NinjaTrader, LLC


526 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 527

10.1.5.1 Licensing/User Authentication

NinjaTrader provides a free vendor license management service for user authentication to
qualified 3rd party developers.

The service includes the following features:

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

See the section "Best Practices for 3rd Party Developers".


10.1.5.3 Distribution Procedure

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.

Creating the distribution package


To create a distribution package, please follow the steps shown here for creating a Export file
containing your NinjaScript indicators and/or strategies.

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

© 2011 NinjaTrader, LLC


528 NinjaTrader Version 7

strategies are NOT necessarily compatible with NinjaTrader Version 6.5.

Adding custom assemblies or native DLLs


1. Locate your base .zip distribution package
2. Open the .zip
3. Add to the .zip file your assemblies and/or your DLL files to the root directory of the .
zip. These files cannot be behind any extra directory structures and must be directly in
the root of the .zip

For custom assemblies, you will also need to add to the root of the .zip a .txt file called
AdditionalReferences.txt

1. Bring up the Windows Start Menu


2. Go to the Run field and type "notepad" without the quotes and press Enter
3. In Notepad, type the name of your custom assembly and then save the file as a text
file with the name "AdditionalReferences".

Ex: If your custom assembly's name was MyCustomAssembly.dll and


MyCustomAssembly.cs, in the AdditionalReferences.txt file you would type
"MyCustomAssembly" without the quotes.

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

Adding chart templates


If you are distributing an indicator package, you may also want to distribute a prebuilt
Chart Template that your customers can use to quickly bring up preferred settings for
your chart setup.

1. Locate your base .zip distribution package


2. Open the .zip
3. Create a new directory called "templates" without the quotes
4. Navigate into the "templates" directory and create another new directory called "Chart"
5. Navigate into the "Chart" directory. Copy the .xml chart templates you wish to
distribute from My Documents\NinjaTrader 7\templates\Chart to this directory in the .zip

Adding Market Analyzer templates


If you are distributing a market scanner type package, you may also want to distribute a
pre-built Market Analyzer Template that your customers can use to quickly bring up
preferred settings for use with your product.

1. Locate your base .zip distribution package


2. Open the .zip
3. Create a new directory called "templates" without the quotes
4. Navigate into the "templates" directory and create another new directory called
"MarketAnalyzer"

© 2011 NinjaTrader, LLC


NinjaScript 529

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.

Display Coding Assistance


Editor Components Intellisense
Auto Inserting Actions and Conditions
Errors/Debugging Code Snippets
Compile Errors
Visual Studio Debugging
Compile Error Codes

10.2.1 NS Editor Components


Overview
The NinjaScript Editor is a powerful scripting editor that allows you to create custom
indicators and strategies efficiently.
1. Caption bar - Displays file type (strategy or indicator) and file name
2. Tool bar - Moving your mouse over each icon will display the function of the icon button
3. Line numbers
4. Line modification marking - Yellow flags unsaved line modifications where green flags
saved modifications

© 2011 NinjaTrader, LLC


530 NinjaTrader Version 7

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.

How to access the Intellisense list box


Within the NinjaScript Editor you can type "this." to bring up the Intellisense list box.
The list box contains all methods (functions) and properties available for use. You can
select a method or property by simply selecting it via your mouse, or scrolling with your
up or down arrow key. Pressing either the "Tab" or "Enter" key will automatically insert
the code into the NinjaScript Editor. While in the list box, you can press any letter key
to rapidly scroll down to the next property or method beginning with the letter of the key
you pressed.

© 2011 NinjaTrader, LLC


NinjaScript 531

In the image below:


1. A property
2. A method

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.

Pressing CTRL-space bar after any text will always either


Bring up the Intellisense list box with related methods and properties

© 2011 NinjaTrader, LLC


532 NinjaTrader Version 7

Automatically insert code if the text can uniquely identify a method or property

Understanding Method Description and Signatures

When selecting a method


1. Type in "(" to display the method description and signature
2. A light yellow colored frame will appear with the method description and available
signatures
3. In the image below you will see "2 of 2" which means that we are looking at the 2nd of
2 available method signatures. You can scroll through all available signatures by
pressing on the arrow up and down keys.

What is a method signature?


A method signature is a common term used in object-orientated programming to
uniquely identify a method. This usually includes the method name, the number and type
of its parameters and its return type.
From the image above, the DMI() method which represents the Dynamic Momentum
Index indicator has two method signatures:

DMI(int period)
DMI(IDataSeries inputData, int period)

How to access the method and property descriptions

Accessing Method and Property Descriptions


You can hover your mouse cursor over any method or property in the NinjaScript
Editor to display any associated description.

© 2011 NinjaTrader, LLC


NinjaScript 533

10.2.3 Automatically Inserting Actions and Conditions

The NinjaScript Editor can automatically


generate code for you. You can access this
option by clicking on your right mouse button
within the NinjaScript Editor window and
selecting either the menu name "Insert
Action..." and/or "Insert Condition...". These
features can help you in your learning curve of
NinjaScript and C# and also provide correct
syntax in the event that you need a little
assistance.

Note: This feature is only available when


editing NinjaScript strategies

Using the image below for an example


1. After typing in "if (" right mouse button click and select "Insert Condition..."
2. The Condition Builder will appear which allows you to point and click to create
conditions. Below we have build a condition that checks to see if the 5 period EMA has
crossed above the 15 period EMA within the last bar.
3. Press "OK" to have the Condition Builder generate the NinjaScript program code

© 2011 NinjaTrader, LLC


534 NinjaTrader Version 7

4. The result is the code generated below.

10.2.4 Code Snippets


Code Snippets can provide you with useful code templates to speed up your coding
process.

Understanding Code Snippet shortcuts

You can quickly add commonly used methods and code structures via

© 2011 NinjaTrader, LLC


NinjaScript 535

Short cut characters


Clicking on your right mouse button and selecting the menu name "Insert Code
Snippet"
Pressing the F2 key on your keyboard

How to use Code Snippet shortcuts via the keyboard

Using the keyboard


Enter the text in the left column and press the "Tab" key within the NinjaScript Editor.

Current Bar Values


cb CurrentBar
o Open[0]
h High[0]
l Low[0]
v Volume[0]

Previous Bar Values


c1 Close[1]
o1 Open[1]
h1 High[1]
l1 Low[1]
v1 Volume[1]

Arithmetic
abs Math.Abs(value)
min Math.Min(value1, value2)
max Math.Max(value1, value2)

Control Statements
if if (expression)
{

}
else
{

for for (int index = 0; index < count; index++)


{

switch switch (expression)


{
case value1:

© 2011 NinjaTrader, LLC


536 NinjaTrader Version 7

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);

How to insert Code Snippets via the mouse or F2 key

Via mouse or pressing the F2 key


1. Right mouse click in the NinjaScript Editor and select the menu name "Insert Code
Snippet"

2. A menu will display all available code snippets.

© 2011 NinjaTrader, LLC


NinjaScript 537

10.2.5 Compile Errors


When compiling a custom indicator or strategy it is possible and likely that you
will generate compile errors.
NinjaTrader will compile ALL NinjaScript files NOT only the file you are working on
A list of compile errors for all files will be displayed in the lower portion of the NinjaScript
Editor
Double click on an error to load the problem file and highlight the problem area
Click on the error code to bring up Help Documentation on a specific error

The image below illustrates a compile error


1. Section where compile errors are displayed. Errors in the current loaded file are color
coded a light color while errors in other files have a darker color code.
2. The file that contains the error
3. A description of the error
4. A error code link that will open the Help Guide with any relevant error code information
5. Line number and column number of the error
6. Error is underlined with a red wavy line

The error highlighted by icon (6) below shows that the expression is not closed with a
semicolon. The expression should be:

double myValue = SMA(20)[0];

© 2011 NinjaTrader, LLC


538 NinjaTrader Version 7

10.2.6 Visual Studio Debugging


You can debug your NinjaScript objects using Microsoft Visual Studio 2005 or
higher.
"Debug Mode" disabled so your DLL is compiled as a release version.
The Express versions of Visual Studio are not supported
NinjaScript objects are compiled into a single DLL, when debugging, a Debug DLL is
created which does carry performance impact. Please ensure once you are done with
debugging that you recompile with "Debug Mode" disabled so your DLL is compiled as a
release version.

1. In the NinjaScript Editor enable "Debug Mode". Be sure to compile the NinjaScript
assembly afterwards by pressing "F5" on your keyboard.

© 2011 NinjaTrader, LLC


NinjaScript 539

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

© 2011 NinjaTrader, LLC


540 NinjaTrader Version 7

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)

© 2011 NinjaTrader, LLC


NinjaScript 541

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

© 2011 NinjaTrader, LLC


542 NinjaTrader Version 7

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 Code Explanation


Strings cannot be compared with relational operators (<, >, <=, >=, ==, !=) to other object
types. Strings can only be compared to other strings and only through the use of equality
operators (==, !=).

Error Description #1
Operator '==' cannot be applied to operands of type 'string' and 'int'

// Erroneous Sample Code – Cannot compare a string to an integer


if ("string" == 5)

// Resolution Sample Code – Compare a string with another string


if ("string" == intValue.ToString());

Error Description #2
Operator ‘<’ cannot be applied to operands of type ‘string’ and ‘double’

// Erroneous Sample Code - Cannot compare a string to a double


if ("string" >= 1.2)

// Resolution Sample Code - Testing to see if the strings are not


the same
if ("string" != "string2")

Error Description #3
Operator ‘>’ cannot be applied to operands of type ‘string’ and ‘string’

© 2011 NinjaTrader, LLC


NinjaScript 543

// Erroneous Sample Code - Cannot quantitatively compare a string


to another string
if ("string" > "string2")

// Resolution Sample Code - Testing to see if both strings are the


same
if ("string" == "string2")

Additional Error Descriptions


Operator ‘<’ cannot be applied to operands of type ‘string’ and ‘string’
Operator ‘<=’ cannot be applied to operands of type ‘string’ and ‘string’
Operator ‘>=’ cannot be applied to operands of type ‘string’ and ‘string’
10.2.7.2 CS0021

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.

Error Code Explanation


This is a common error when calling indicators methods. It occurs when an indicator is called
without its required parameter arguments before accessing an indexed value.

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];

// Resolution Sample Code - SMA() properly called


double value = SMA(14)[0];

Example #2
// Erroneous Sample Code - EMA is an indicator and requires
parameter arguments
double maDelta = EMA[0] - EMA[1];

// Resolution Sample Code - SMA() properly called with an overload


method (one of several variations)
double maDelta = EMA(High, 14)[0] - EMA(High, 14)[1];

© 2011 NinjaTrader, LLC


544 NinjaTrader Version 7

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.

Error Code Explanation


This error can occur when you try to convert from one 'type' to another 'type'.

To fix this error, ensure that you are assigning the correct value type.

Error Description #1
Cannot implicitly convert type 'int' to 'bool'

// Erroneous Sample Code - 'CurrentBar' is an integer


if (CurrentBar)

// Resolution Sample Code - Compares an integer with another


integer
if (CurrentBar < 1)

Error Description #2
Cannot implicitly convert type 'double' to 'bool'

// Erroneous Sample Code – Close[0] returns a double value


if (Close[0])

// Resolution Sample Code – Compares a double with another double


if (Close[0] > Close[1])

Error Description #3
Cannot implicitly convert type 'NinjaTrader.Indicator.SMA' to 'double'

// Erroneous Sample Code - Incorrect since assigning an indicator


to a variable of double type
double myValue = SMA(20);

// Resolution Sample Code - Correct expression since we are


accessing the current bar's value of the SMA indicator
double myValue = SMA(20)[0];
10.2.7.4 CS0103

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.

Error Code Explanation


When a variable is used before declaration, the compiler will not know what it is. This error is
also commonly invoked by typos.

© 2011 NinjaTrader, LLC


NinjaScript 545

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)

// Resolution Sample Code - 'CurrentBar' exists since it is spelled


correctly
if (CurrentBar < 10)

Example #2
// Erroneous Sample Code - 'newVariable' is not declared
newVariable = 10;

// Resolution Sample Code - 'newVariable' is now declared as an


integer
int newVariable = 10;
10.2.7.5 CS0117

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.

Error Code Explanation


This error can occur when you try to use a method or access an exposed property that does
not exist for your particular object.

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);

// Resolution Sample Code - DataSeries using the Set() method


Plot0.Set(SMA(5)[0]);

Error Description #2
'NinjaTrader.Indicator.CurrentDayOHL' does not contain a definition for 'CurentOpen'
// Erroneous Sample Code - CurrentDayOHL()’s property is

© 2011 NinjaTrader, LLC


546 NinjaTrader Version 7

'CurrentOpen' not 'CurentOpen' (typo)


double value = CurrentDayOHL().CurentOpen[0];

// Resolution Sample Code - 'CurrentOpen' property available


double value = CurrentDayOHL().CurrentOpen[0];

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.

Error Code Explanation


This error can happen when you use a '()' instead of '[]' for indexing when you reference
indicators or properties.

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'

// Erroneous Sample Code - Miscall of Close property due to use of


round brackets
double value = Close(0);

// Resolution Sample Code - Proper call of Close property


double value = Close[0];

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.

Error Code Explanation


This error is most common when you try to assign values to a particular DataSeries index
through the use of assignment operators (=). Since DataSeries objects have their values set
through the Set() method, you cannot modify the value after it has been set through the use of
assignment operators.

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

© 2011 NinjaTrader, LLC


NinjaScript 547

// Erroneous Sample Code - Cannot reassign values to DataSeries


indexed value
Close[0] = 25;

// Resolution Sample Code - Assigns value to a DataSeries


myClose.Set(25);

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])

// Resolution Sample Code - Properly compares two DataSeries values


if (Close[0] == Open[0])
10.2.7.8 CS0201

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.

Error Code Explanation


This error can occur when you make a statement solely from an indicator or variable call.

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

// Erroneous Sample Code - Statement that does nothing


SMA(5)[0];

// Resolution Sample Code - 'currentSMA' takes on the current bar's


SMA(5) value
double currentSMA = SMA(5)[0];
10.2.7.9 CS0234

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 Code Explanation


This error can occur when an imported DLL (could be a 3rd party indicator) you are
referencing no longer exists/has been removed.

To resolve this the DLL must be re-imported.

© 2011 NinjaTrader, LLC


548 NinjaTrader Version 7

To re-import a 3rd party dll:


1. Open the NinjaScript Editor via Tools > Edit NinjaScript and selecting any indicator or
strategy
2. Right mouse click in the NinjaScript Editor and select the menu name "References"
3. In the "References" dialog window press the button "Add"
4. Select the 3rd party DLL

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.

Error Code Explanation


This error can occur when you miscall a method such as indicator methods.

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;

// Resolution Sample Code - SMA() indicator method is properly


called
double myValue = SMA(5)[0];

Example #2
// Erroneous Sample Code - ToString is a method and requires round
brackets () to be properly called
string str = Close[5].ToString;

// Resolution Sample Code - ToString() is properly called

© 2011 NinjaTrader, LLC


NinjaScript 549

string str = Close[5].ToString();


10.2.7.12 CS0443

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 Code Explanation


This error is most commonly invoked when no index value is used inside the indexing
brackets.

Please ensure you place a value inside the '[]'.

Error Description #1
Syntax error, value expected

// Erroneous Sample Code - Missing index value


double myValue = SMA(20)[];

// Resolution Sample Code - 'myValue' takes on the current bar's


SMA(20) value
double myValue = SMA(20)[0];
10.2.7.13 CS0665

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.

Error Code Explanation


This error can occur when you mistake using assignment (=) instead of checking for equality
(==).

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
=?

// Erroneous Sample Code - Incorrect since the expression is


assigning a value of 'true' to the property Historical
if (Historical = true)
// Do something

// Resolution Sample Code - Correct


if (Historical == true)
// Do something

© 2011 NinjaTrader, LLC


550 NinjaTrader Version 7

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 Code Explanation


This error can be invoked when statements are not ended properly.

All statement lines must be closed with a semicolon.

Error Description #1
; expected

// Erroneous Sample Code - Statement is not closed


double myValue = SMA(20)[0]

// Resolution Sample Code - Statement is closed


double myValue = SMA(20)[0];
10.2.7.15 CS1501

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.

Error Code Explanation


This error can occur when you use use an overload (method parameter signature) that does
not exist. This could either be because you are passing in 3 arguments when the method only
requires 2.

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];

// Resolution Sample Code - SMA() has an overload consisting of 2


arguments
double myValue = SMA(Close, 5)[0];

Example #2
// Erroneous Sample Code - EMA() does not contain an overload that
has 0 arguments

© 2011 NinjaTrader, LLC


NinjaScript 551

double myValue = EMA()[0];

// Resolution Sample Code - EMA() has an overload consisting of 1


argument
double myValue = EMA(5)[0];

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.

Error Code Explanation


This error can occur when you pass in incorrect parameter object types into a method such
as an indicator.

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

// Erroneous Sample Code - Close is a DataSeries object type and is


not a valid value to the Set() method
Plot0.Set(Close);

// Resolution Sample Code - The Set() method takes a double value


so pass in Close[0]
Plot0.Set(Close[0]);

Error Description #2
The best overloaded method match for 'NinjaTrader.Indicator.Indicator.SMA(NinjaTrader.
Data.IDataSeries, int)' has some invalid arguments

// Erroneous Sample Code - Using an integer when the first


parameter should be a DataSeries
double myValue = SMA(5, 5);

// Resolution Sample Code - 'myValue' will take the value of the


current bar's SMA
double myValue = SMA(Close, 5)[0];
10.2.7.17 CS1503

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

© 2011 NinjaTrader, LLC


552 NinjaTrader Version 7

any case, the examples below provide a reference of coding flaw possibilities.

Error Code Explanation


This error can occur when you try to assign a value to a DataSeries that is not a double value
type.

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'

// Erroneous Sample Code - Cannot pass in a string to a DataSeries


Set() method
Value.Set("Close[0]");

// Resolution Sample Code - Sets DataSeries to the current bar's


Close value
Value.Set(Close[0]);

Error Description #2
Argument '1': cannot convert from 'NinjaTrader.Indicator.SMA' to 'double'

// Erroneous Sample Code - Cannot pass in a DataSeries object to a


DataSeries Set() method
Values[0].Set(SMA(20));

// Resolution Sample Code - Sets DataSeries to the current bar's


SMA(20) value
Values[0].Set(SMA(20)[0]);
10.2.7.18 CS1513

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.

Error Code Explanation


This error is most common with chaining if-else or loop statements.

Please check all code segments and statements are closed. Every opening curly brace '{'
needs a matching closing curly brace '}' .

Error Description #1
} expected

// Erroneous Sample Code - If statement is not closed


if (CurrentBar < 1)
{

© 2011 NinjaTrader, LLC


NinjaScript 553

// 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.

Error Code Explanation


This error can happen when a DataSeries is compared to another object via the use of
relational operators. Relational operators (==, <, >, <=, >=) can be used to compare the
values of the DataSeries but not the DataSeries object itself.

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'

// Erroneous Sample Code - DataSeries objects cannot be compared


with integers
if (Close == 5)

// Resolution Sample Code - Checks to see if the current close is


equal to 5
if (Close[0] == 5)

Error Description #2
Operator '==' cannot be applied to operands of type 'int' and 'NinjaTrader.Data.IDataSeries'

// Erroneous Sample Code - DataSeries objects cannot be compared


with each other
if (Close > Open)

// Resolution Sample Code - Checks to see if the current bar’s


close is greater than the current bar’s open
if (Close[0] > Open[0])

Error Description #3
Operator '>' cannot be applied to operands of type 'NinjaTrader.Data.IDataSeries' and
'NinjaTrader.Data.IDataSeries'

© 2011 NinjaTrader, LLC


554 NinjaTrader Version 7

// Erroneous Sample Code - DataSeries objects cannot be compared


with doubles
while (Low < Close[1])

// 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.

Error Code Explanation


DataSeries objects cannot be converted to another object type implicitly. You cannot simply
assign the DataSeries object to an integer or a double. Please keep in mind that this does not
mean the DataSeries cannot carry values that are integers or doubles, it just means you
cannot assign the DataSeries itself to an integer or double.

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'

// Erroneous Sample Code - Cannot set a DataSeries object to a


double value
double closeValue = Close;

// Resolution Sample Code - Assign the value at index 0 (current


bar)
double closeValue = Close[0];

Additional Error Descriptions


Cannot implicitly convert type 'double' to 'NinjaTrader.Data.IDataSeries'
Cannot implicitly convert type 'NinjaTrader.Data.IDataSeries' to 'int'
Cannot implicitly convert type 'int' to 'NinjaTrader.Data.IDataSeries'
Cannot implicitly convert type 'NinjaTrader.Data.IDataSeries' to 'bool'
Cannot implicitly convert type 'bool' to 'NinjaTrader.Data.IDataSeries'
10.2.7.21 NT1503

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.

Error Code Explanation


This error can occur when you try to set the value of a DataSeries object to another

© 2011 NinjaTrader, LLC


NinjaScript 555

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'

// Erroneous Sample Code – Cannot set a DataSeries to another


DataSeries
Value.Set(Low);

// Resolution Sample Code – Assign the value at index 1 (previous


bar)
Value.Set(Low[1]);

Additional Error Descriptions


Argument '1': cannot convert from 'int' to 'NinjaTrader.Data.IDataSeries'
10.2.7.22 NoDoc

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.

10.3 Educational Resources


The following pages contain valuable resources for learning basic through intermediate skills
in building custom indicators and strategies within NinjaTrader. Continuing education and
resources can be found on the NinjaTrader Support Forum.

Development Tutorials
Basic Programming Concepts Indicators
Developing Indicators Strategies
Developing Strategies

Reference
Reference Samples
Tips

10.3.1 Basic Programming Concepts


NinjaScript is an extension of the Microsoft C# programming language. There is a wealth of
resources available online for learning the C# language. If you have limited programming
experience, do not let C# scare you. NinjaScriptprovides a layer of convenience allowing you
to focus on your trading ideas and not programming. Spend some time and go through some
of our own tutorials for developing custom indicators and strategies.

© 2011 NinjaTrader, LLC


556 NinjaTrader Version 7

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

10.3.1.1 Basic Syntax

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.

This is clear and easy to understand. If you only wrote:

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");

© 2011 NinjaTrader, LLC


NinjaScript 557

The above code block encloses two statements in curly braces.

User Defined Comments


You can add your own comments to your code.
Use the "//" characters for single line comments.
Example:

// The following code encloses two statements with


curly braces
if (x == 5)
{
Print("NinjaTrader");
Print("NinjaScript");
}
You can enclose several comment lines using the "/*" characters to start the comment block
and then using the "*/" characters to end the comment block.

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".

Variables and Value Types


A variable is a place holder that stores information into computer memory. A variable is
unique analogous to your mailing address. Use variables to store and access data. There are
many variable types that you can use in the C# language. The following are a few of the
basics:

string
Stores textual data

double
Stores floating point values

integer
Stores whole number values

bool
Stores either true or false

© 2011 NinjaTrader, LLC


558 NinjaTrader Version 7

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.

// Declaring a string variable


string myString = "NinjaTrader";

// Declaring a double variable


double myDouble = 2.5;

// Declaring an integer variable


int myInteger = 1;

// Declaring a bool variable


bool learningIsFun = true;

// Declaring an object type variable using a Simple


Moving Average indicator
SMA mySMA = new SMA(Close, 20);

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

// Example of using arithmetic operators


int myInteger = 0;
myInteger = 5 + (3 * 4);
Print(myInteger.ToString());
The above example would print a value of 17 to the NinjaTrader output window. The System.
Math class provides additional math functions.
For example:

// Example of using the ABS method of the System.Math


class

© 2011 NinjaTrader, LLC


NinjaScript 559

double myDouble = Math.Abs(5 - 6);


Print(myDouble.ToString());

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

// Example of using logical operators


int myInteger = 3;
string myString = "NinjaTrader";
if (myInteger == 3 && myString == "NinjaTrader")
{
Print("true");
}

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

// Example of using relational operator


string myString = "NinjaTrader";
if (myString != "trading")
{
Print("Variable myString does not equal
trading");
}

// Second example of using a relational operator in


conjunction with logical operator
double myDouble = 1000.25;

if (myDouble < 1000 || myDouble > 1001)


{
// Note that since myDouble does not satisfy the
if-statement, no printout will be seen
Print("Variable myDouble is between 1000 and
1001");
}

Assignment

© 2011 NinjaTrader, LLC


560 NinjaTrader Version 7

= 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

?:

// Example of a conditional operator


int myInteger = (10 > 12 ? 3 : 4);
Print(myInteger.ToString());

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.

// Example of string concatenation


string wordOne = "Ninja";
string wordTwo = "Trader";
Print(wordOne.ToString() + wordTwo.ToString());

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.

// Single case condition


int x = 0;
if (x == 0)
{
Print("NinjaTrader");
}
The above example will print NinjaTrader to the NinjaTrader output window since x does equal
0.

// Either/Or decision
int x = 1;
if (x == 0)

© 2011 NinjaTrader, LLC


NinjaScript 561

{
Print("NinjaTrader");
}
else
{
Print("NinjaScript");
}

The above example will print NinjaScript to the NinjaTrader output window.

// Multiple case decision


int x = 2;
if (x == 0)
{
Print("NinjaTrader");
}
else if (x == 1)
{
Print("NinjaScript");
}
else
{
Print("NinjaTrader Rules!");
}
The above example will print NinjaTrader Rules! to the NinjaTrader output window.

The switch Statement


The switch statement executes a set of logic depending on the value of a given parameter.

// 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

© 2011 NinjaTrader, LLC


562 NinjaTrader Version 7

looping command in only a few lines of code.

While Loop

while (Boolean expression)


{
//Do something here
}

Example:

// Print NinjaTrader 100 times to the output window


int x = 0;
while (x < 100)
{
Print("NinjaTrader");
x = x + 1;
}

Do Loop

do
{
//Do something here
}
while (Boolean expression)

Example:

// Print NinjaTrader 100 times to the output window


int x = 0;
do
{
Print("NinjaTrader");
x = x + 1;
}
while (x < 100)

For Loop

for (initializer; boolean expression; iterator)


{
//Do something here
}

Example:

© 2011 NinjaTrader, LLC


NinjaScript 563

// Print NinjaTrader 100 times to the output window


for (int x = 0; x < 100; x++)
{
Print("NinjaTrader");
}

Foreach Loop

foreach (type identifier in boolean expression)


{
// Do something here
}

Example:

Lets say you wanted to count the number of oatmeal cookies in a cookie jar.

// Count the number of oatmeal cookies in the cookie


jar
int oatmealCookies = 0;
foreach (cookie in cookieJar)
{
if (cookie.Type == Oatmeal)
{
oatmealCookies = oatmealCookies + 1;
}
}
Print("There are " + numberOatmeal.ToString() +
"oatmeal cookies in the cookie jar.");

Break and Continue

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.

// Exit the infinite loop after the first iteration


while (0 == 0)
{
Print("NinjaTrader");
break;
}

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.

© 2011 NinjaTrader, LLC


564 NinjaTrader Version 7

// Never prints NinjaTrader


for (int x = 0; x < 100; x++)
{
continue;
Print("NinjaTrader");
}

10.3.1.4 Functions and Methods Explained

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] [Return Data Type] [Name] (Optional parameters)

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

Method With No Return Type

// This method prints out the data and time


private void PrintDateTime()
{
Print(DateTime.Now.ToString());
}
The above method has no return type so we use the keyword "void", we provide a user
defined method name PrintDateTime and since there are no parameters we complete the
declaration with "()". The method code itself is then enclosed within curly braces.

Method With a Return Type

// This method performs a calculation and returns a


double value
private double Multiply(double input)
{
return input * 10;

© 2011 NinjaTrader, LLC


NinjaScript 565

}
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.

Calling a Method within a Method

// This method performs a calculation and returns a


double value
private double Multiply(double input)
{
PrintDateTime();
return input * 10;
}

Building on our examples from above, we added a call to the PrintDateTime() method within
our Multiply method.

When to use Methods


Using methods is a great way to logically organize blocks of code. If you find that you are
performing the same calculations in different parts of your script it also makes sense to
encapsulate the repetitive code into a 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.

// Calculates the average range of the past three


bars
private double AverageRange()
{
return ((High[1] - Low[1]) + (High[2] - Low[2])
+ (High[3] - Low[3])) / 3 ;
}

We can then reference the AverageRange method anywhere else in our script like the
example below shows.

// Example method that calls the AverageRange()


method twice

© 2011 NinjaTrader, LLC


566 NinjaTrader Version 7

private void ExampleMethod()


{
if (High[0] - Low[0] > AverageRange())
{
Print("The current bar range is greater
than the 3 bar average range of " +
AverageRange().ToString());
}
}

Declaring Variables within a Method


You can declare variables within a method. These variables are local in scope which means
they can only be accessed within the method and not outside of it such as your main script.

// Example method using a variable


private double MyMethod()
{
double myDouble = 100.25
return myDouble * 10;
}

10.3.2 Developing Indicators


The building blocks of any automated trading system are indicators. NinjaScript allows you to
develop custom indicators in rapid time. A few key points are:

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

Custom indicator development follows a logical progression.

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

© 2011 NinjaTrader, LLC


NinjaScript 567

calculation logic is contained within this method.

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.

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

10.3.2.1 Developing Outside of the NinjaScript Editor

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 see the additional information on this subject.


10.3.3 Developing Strategies
NinjaScript allows you to develop custom strategies in rapid time by using over 100 built-in
system indicators, 3rd party indicators or custom indicators. NinjaScript strategies are
compiled and run natively within the NinjaTrader application providing the highest
performance possible.

Please take the time to review this section including the Strategy Development Process.

© 2011 NinjaTrader, LLC


568 NinjaTrader Version 7

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.

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.3.1 The Strategy Development Process

Describe your Strategy


Describing your strategy means creating a set of objective rules that define the conditions
used to enter and exit a market. Describing your strategy always starts with the wizard and
then provides the following choices:

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.

Backtest and Optimize your Strategy


Once you have completed describing your strategy you can then test it against historical data
to objectively determine how the strategy performed on a specific market(s) in the past.

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.

See special instructions on running FX strategies.

Real-Time Test your Strategy


It is critical that before you deploy your strategy against your live trading account, that you test
it in real-time operation to ensure that the mechanics (operation) of your strategy behaves as
you would expect it to. In addition, you can also forward test your strategy using real-time
market data against the NinjaTrader trade simulation engine. NinjaTrader provides several
options for real-time testing:

© 2011 NinjaTrader, LLC


NinjaScript 569

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.

Running on your Live Trading Account


Now that you have described, backtested and real-time tested your strategy, you are ready to
automate your strategy against your live trading account. A few tips you should know:

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

An important concept to understand prior to using NinjaScript strategies in a real-time trading


environment (live brokerage account, for example) is the difference between a Strategy
Position and an 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

© 2011 NinjaTrader, LLC


570 NinjaTrader Version 7

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

An extremely common scenario…


An extremely common scenario is starting a NinjaScript strategy in the middle of a trading
session, such as one hour after the session has begun. The NinjaScript strategy is run on
each historical bar for the 1st hour of the session (it will actually run on all historical data
loaded in a chart) to determine the current position state it would be in if it had been running
live since the start of the session. This position state then becomes the Strategy Position
for your strategy. Let us assume that during the historical hour your strategy would have
entered a LONG 1 position and the position is still open. This would mean the Strategy
Position is LONG 1 and since this trade was not actually executed on an account, your
Account Position is FLAT.

What can you do in this case?


If you want your Account Position to match your Strategy Position, you will need to place a
manual order into the account the strategy is running on. Continuing from the above example,
you would need to place a 1-lot market order for the market being traded into the account the
strategy is running on. Alternatively, new to NinjaTrader 7 is the ability to have your account
automatically synced to your strategy position on strategy startup. To use this feature, please
set "Sync account position" to true in the Strategy dialogue window. For more information on
this feature please see the article here about syncing Account Positions to Strategy Positions
.

What if I do not sync my account?


The resulting behavior when the Strategy Position and Account Position are out of sync is
when your strategy (continuing with the example above) closes the long position with a sell
order it would bring the Strategy Position to flat and your Account Position to SHORT 1.
10.3.3.3 Syncing Account Positions

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.

© 2011 NinjaTrader, LLC


NinjaScript 571

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.

On startup the strategy will begin executing orders immediately.

Any active orders on the account previously generated by the strategy that does not

© 2011 NinjaTrader, LLC


572 NinjaTrader Version 7

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.

On startup the strategy will begin executing orders immediately.

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.

© 2011 NinjaTrader, LLC


NinjaScript 573

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

There is a Clear Line...


There is a clear line between a NinjaScript Strategy and an ATM Strategy. The use model for
creating an ATM Strategy within a NinjaScript Strategy is when you want to
programmatically monitor and generate an entry signal and then manualy manage the
resulting open position via an ATM Strategy in one of NinjaTrader's order entry windows.

!!! 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.

© 2011 NinjaTrader, LLC


574 NinjaTrader Version 7

Fill Types
Optimizer Type

10.3.4.1 Fill Types

Custom Fill Algorithms


In addition to the two system fill types (Default and Liberal) you can also script custom fill
algorithms using any code/text editor.

Copy the file "Documents\<NinjaTrader Folder>\bin\Custom\Type\@LiberalFillType.cs" and


provide a new name excluding the "@" sign such as "Documents\<NinjaTrader
Folder>\bin\Custom\Type\MyFillType.cs".

Then within your code editor:

1. Provide a new display name for example rename "Liberal" to "MyFill"


2. Provide a new class name for example rename "LiberalFillType" to "MyFillType"
3. Code your fill algorithm within the Fill() method
4. Once complete, open any indicator or strategy within the NinjaTrader NinjaScript Editor and
compile. This will compile the new fill algorithm and make it available within any backtest
dialog window.

10.3.4.2 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.

© 2011 NinjaTrader, LLC


NinjaScript 575

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.

Best Practices for 3rd Party Developers


C# Method (Functions) Reference
Code Breaking Changes for NinjaTrader 7
Multi-threading Consideration for NinjaScript
Multi-Time Frame & Instruments
User Defined Methods
Using 3rd Party Indicators
Using Historical Bid/Ask Series

10.3.6.1 Best Practices for 3rd Party Developers

The following are what we suggest for best practices.

Do not deploy NinjaScript Source Files


If you are a commercial vendor, you should never distribute the NinjaScript .cs source code
files even if your IP is contained within an assembly or proprietary DLL. Source code files are
editable by users and can result in unnecessary support issues.

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”.

Clean up your resources


Always free up resources such as external windows DLL's or license management related
resources. Resources should be freed within the Dispose() method. NinjaTrader calls this
method as an indicator or strategy is no longer used.

User Authentication Trigger


If you have proprietary user authentication process ensure that it is triggered within the
OnStartUp() method. This ensures that users are not forced to endure unnecessary delays

© 2011 NinjaTrader, LLC


576 NinjaTrader Version 7

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.

User Authentication Check State


A license check should only be performed once and maintain its check state.

User Authentication Time Out


A license check should have a time out in case of internet issues. This ensures that
NinjaTrader does not lock up.

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.

These are the following folder names:


Documents\NinjaTrader 6.5\bin\Custom
Documents\NinjaTrader 7\bin\Custom

Test on Windows XP, Vista, 7 and 2000


NinjaTrader customers run on XP, Vista, 7 and 2000 and you should make sure that your
indicators, custom installers and external DLLs (if any are used) properly run on all operating
systems.

Expose Indicator States


If your proprietary indicator acts as a trend state (green bars are bullish, red bearish) its good
practice to expose the indicators's state so that consumers of your indicators can use them
within their own custom indicator or strategy.
10.3.6.2 C# Method (Functions) Reference

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.

Complete list of classes in the Microsoft .NET environment.

MSDN (Microsoft Developers Network) C# Language Reference


Keywords
Operators
Arrays

© 2011 NinjaTrader, LLC


NinjaScript 577

System.Math
Provides constants and static methods for trigonometric, logarithmic, and other common
mathematical functions.
Full list of member of the System.Math class.

// Example of the Max method of the System.Math class


int myInteger = Math.Max(10, 20);
Print("The larger value between 10 and 20 is " +
myInteger.ToString());

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.

// Example of the Now property member of the System.


DateTime structure
DateTime startTime = DateTime.Now;
Print("Time elapsed is " + DateTime.Now.Subtract
(startTime).TotalMilliseconds.ToString() + "
milliseconds.");

System.String
Represents text; that is, a series of unicode characters.
Full list of members of the System.String class.

// Example of the ToUpper() method of the System.


String class
string myString = "ninjatrader";
Print("The following word is in uppercase " +
myString.ToUpper());

10.3.6.3 Code Breaking Changes for NinjaTrader 7

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

© 2011 NinjaTrader, LLC


578 NinjaTrader Version 7

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:

8/20/2010 12:14:29 PM|3|128|Error on calling 'OnBarUpdate' method for strategy


'SampleStrategy/1740b50bfe5d4bd896b0533725622400': The process cannot access
the file 'c:\sample.txt' because it is being used by another process.
10.3.6.5 Multi-Time Frame & Instruments

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

Understanding this Section (MUST READ)


As we move through this section, the term "primary Bars" will be used and for the purpose of
clarification, this will always refer to the first Bars object loaded into a script. For example, if
you apply a script on MSFT 1 minute chart, the primary Bars would be MSFT 1 minute data
set.

This section is written in sequential fashion. Example code is re-used and built upon from sub
section to sub section.

Adding Additional Bars Object to NinjaScript


Additional Bars are added to a script via the Add() method in the Initialize() method.
When a Bars object is added to a script, it is also added to the BarsArray array. What is
that you ask? Think of it like a container in the script that holds all Bars objects added to
the script. It's no different than a bucket of golf balls in your garage. As a Bars object is
added to the script, it's added to this container, BarsArray, and given an index number
so we can retrieve this Bars object later. Don't sweat this if it sounds complex, its quite
easy once you see it in practical use. It's explained in greater detail later in this 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.

© 2011 NinjaTrader, LLC


NinjaScript 579

protected override void Initialize()


{
Add(PeriodType.Minute, 3);
Add("AAPL", PeriodType.Minute, 1);
}

How Bar Data is Referenced


Understanding how multi-time frame bars are processed and what OHLCV data is
referenced is critical.

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.

© 2011 NinjaTrader, LLC


580 NinjaTrader Version 7

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.

A quick example to illustrate the point:

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.

Using Bars Objects as Input to Indicator Methods


In the sub section above, the concept of index values was introduced. This is a critical
concept to understand since it is used consistently when working with multi-Bars script.

Let's demonstrate this concept:

Carrying on from the example above, our primary Bars is set from a MSFT 1 minute
chart

MSFT 1 minute Bars is given an index value of 0

In the Initialize() method we added a MSFT 3 minute Bars object and an AAPL 1 minute
Bars object to the script

MSFT 3 minute Bars is given an index value of 1


AAPL 1 minute Bars is given an index value of 2

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.

© 2011 NinjaTrader, LLC


NinjaScript 581

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:

ADX(14)[0] > 30 && ADX(BarsArray[2], 14)[0] > 30

The above expression in English would translate to:

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.

protected override void OnBarUpdate()


{
// Checks to ensure all Bars objects contain
enough bars before beginning
if (CurrentBars[0] <= BarsRequired ||
CurrentBars[1] <= BarsRequired || CurrentBars[2]
<= BarsRequired)
return;
}

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.

protected override void OnBarUpdate()


{
// Checks to ensure all Bars objects contain
enough bars before beginning
if (CurrentBars[0] <= BarsRequired ||
CurrentBars[1] <= BarsRequired || CurrentBars[2]
<= BarsRequired)
return;

if (BarsInProgress == 0)
{

© 2011 NinjaTrader, LLC


582 NinjaTrader Version 7

if (CCI(20)[0] > 200 && CCI(BarsArray


[1], 20)[0] > 200
&& CCI(BarsArray[2], 20)[0] > 200)
{
// Do something
}
}
}

True Event Driven OnBarUpdate() Method

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.

protected override void OnBarUpdate()


{
// Checks to ensure all Bars objects contain
enough bars before beginning
if (CurrentBars[0] <= BarsRequired ||
CurrentBars[1] <= BarsRequired || CurrentBars[2]
<= BarsRequired)
return;

// Checks if OnBarUpdate() is called from an


update on the primary Bars
if (BarsInProgress == 0)
{
if (Close[0] > Open[0])
// Do something
}

// Checks if OnBarUpdate() is called from an


update on MSFT 3 minute Bars
if (BarsInProgress == 1)
{
if (Close[0] > Open[0])
// Do something

© 2011 NinjaTrader, LLC


NinjaScript 583

// Checks if OnBarUpdate() is called from an


update on AAPL 1 minute Bars
if (BarsInProgress == 2)
{
if (Close[0] > Open[0])
// Do something
}
}

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

© 2011 NinjaTrader, LLC


584 NinjaTrader Version 7

are actual meaningful data values.

Accessing the Price Data in a Multi-Bars NinjaScript


As you probably know already, you can access the current bar's closing price with the
following statement:

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];

The following example demonstrates various ways to access price data.

protected override void OnBarUpdate()


{
// Checks to ensure all Bars objects contain
enough bars before beginning
if (CurrentBars[0] <= BarsRequired ||
CurrentBars[1] <= BarsRequired || CurrentBars[2]
<= BarsRequired)
return;

// Checks if OnBarUpdate() is called from an


update on the primary Bars
if (BarsInProgress == 0)
{
double primaryClose = Close[0];
double msft3minClose = Closes[1][0];
double aapl1minClose = Closes[2][0];

// primaryClose could also be expressed


as
// primaryClose = Closes[0][0];
}

© 2011 NinjaTrader, LLC


NinjaScript 585

// Checks if OnBarUpdate() is called from an


update on MSFT 3 minute Bars object
if (BarsInProgress == 1)
{
double primaryClose = Closes[0][0];
double msft3minClose = Close[0];
double aapl1minClose = Closes[2][0];
}
}

Entering, Exiting and Retrieving Position Information


This section is relevant for NinjaScript strategies only. Entry and Exit methods are
executed within the BarsInProgress context. Let's demonstrate with an example:

protected override void OnBarUpdate()


{
// Checks to ensure all Bars objects contain
enough bars before beginning
if (CurrentBars[0] <= BarsRequired ||
CurrentBars[1] <= BarsRequired || CurrentBars[2]
<= BarsRequired)
return;

// Checks if OnBarUpdate() is called from an


update on the primary Bars
if (BarsInProgress == 0)
{
// Submits a buy market order for MSFT
EnterLong();
}

// Checks if OnBarUpdate() is called from an


update on AAPL 1 minute Bars object
if (BarsInProgress == 2)
{
// Submits a buy market order for AAPL
EnterLong();

// Submits a buy market for MSFT when


OnBarUpdate() is called for AAPL
EnterLong(0, 100, "BUY MSFT");
}
}

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

© 2011 NinjaTrader, LLC


586 NinjaTrader Version 7

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.

MSFT position is given an index value of 0


AAPL position is given an index value of 1

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.

protected override void OnBarUpdate()


{
// Checks to ensure all Bars objects contain
enough bars before beginning
if (CurrentBars[0] <= BarsRequired ||
CurrentBars[1] <= BarsRequired || CurrentBars[2]
<= BarsRequired)
return;

// Checks if OnBarUpdate() is called from an


update on the primary Bars
if (BarsInProgress == 0 && Positions[1].
MarketPosition != MarketPosition.Flat)
{
// Submits a buy market order for MSFT
EnterLong();
}

// Checks if OnBarUpdate() is called from an


update on AAPL 1 minute Bars
if (BarsInProgress == 2)
{
// Submits a buy market order for AAPL

© 2011 NinjaTrader, LLC


NinjaScript 587

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.

Sample 1 - Using the strategy UserDefinedMethods.cs file


Sample 2 - Using a separate file for user defined methods

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.

© 2011 NinjaTrader, LLC


588 NinjaTrader Version 7

Creating A Separate File Per User Defined Method (Function)


If you do not want to have one file that manages all of your user defined methods, you can
create a separate file for each user defined method.

1. Via Tools-->Edit NinjaScript-->Indicators open the "UserDefinedMethods" file


2. From within the NinjaScript Editor, right click and select the menu "Save As..."
3. From within the Dialog window, enter a name, for example "MyMethod"
4. Add your user defined method and then compile
10.3.6.6.1 Sample 1

The following sample illustrates two user defined methods within the strategy
UserDefinedMethods.cs file. You can add methods or edit methods by:

1. Tools-->Edit NinjaScript-->Strategy... select UserDefinedMethods


2. Add or edit your method
3. From within the NinjaScript Editor, right click and select the menu "Compile"

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

© 2011 NinjaTrader, LLC


NinjaScript 589

The following image illustrates the use of the two user defined methods from above in a
custom strategy.

© 2011 NinjaTrader, LLC


590 NinjaTrader Version 7

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.

1. Tools-->Edit NinjaScript-->Strategy... select UserDefinedMethods


2. From within the NinjaScript Editor, right click and select the menu "Save As..."
3. Enter the name "ValidTradeTime" and press "OK"
4. Add the following code in the NinjaScript Editor

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.

© 2011 NinjaTrader, LLC


NinjaScript 591

10.3.6.7 Using 3rd Party Indicators

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

How to add a reference

© 2011 NinjaTrader, LLC


592 NinjaTrader Version 7

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.

2. A References window will appear

3. Press the Add... button and select the 3rd


party vendor DLL file

4. You will see a reference to the 3rd party


vendor DLL in the References window

5. Press the OK button

You will now be able to access the indicator


methods provided by the 3rd party vendor

10.3.6.8 Using Historical Bid/Ask Series

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

© 2011 NinjaTrader, LLC


NinjaScript 593

What this means is that:


- The exact sequence of a mix of bid/ask/last events will not be maintained while processing
the historical data from multiple series.
- The exact sequence of the bid/ask/last events in relation to themselves individually will be
maintained while processing the historical data from multiple series.
10.3.7 Tutorials
The following tutorials demonstrate building both indicators and strategies in NinjaTrader over
several skill levels. 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
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

© 2011 NinjaTrader, LLC


594 NinjaTrader Version 7

10.3.7.1.1 Beginner - Using price variables

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 Indicator Properties and Name


Below you will define your indicators name and several indicator properties.

© 2011 NinjaTrader, LLC


NinjaScript 595

3. Enter the information as shown above


4. Press the "Next >" button

Defining Input Parameters


Below you will define your indicator's input parameters. These are any parameters that can
be changed by the user and used in the calculation of the indicators value(s). If your indicator
does not require any parameters leave the "Name" fields blank.

© 2011 NinjaTrader, LLC


596 NinjaTrader Version 7

5. This indicator does not require any input parameters


6. Press the "Next >" button

Defining Plots
Below you will define how your indicator is plotted on a chart.

© 2011 NinjaTrader, LLC


NinjaScript 597

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

Defining Oscillator Lines


Below you will define any required oscillator lines. This would be the "Zero" line in the CCI
indicator for example. If your indicator does not require any oscillator lines leave the "Name"
fields blank.

© 2011 NinjaTrader, LLC


598 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 599

Your primary area of concern will be sections "2" and "3".

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:

// Set the value


Plot0.Set(Open[0] == Close[0] ? 1 : 0);

© 2011 NinjaTrader, LLC


600 NinjaTrader Version 7

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.

The syntax for a conditional operator is the following:

Expression ? value 1 : value2

Translated to English it is saying:

if the expression is true ? use value 1 : otherwise use value 2

translated one last time to our indicator logic:

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.

© 2011 NinjaTrader, LLC


NinjaScript 601

Once applied to a chart, it can look something like the image below.

© 2011 NinjaTrader, LLC


602 NinjaTrader Version 7

Congratulations, you just completed building a custom indicator!


10.3.7.1.2 Beginner - Indicator on Indicator

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.

© 2011 NinjaTrader, LLC


NinjaScript 603

1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button

Defining Indicator Properties and Name


Below you will define your indicators name and several indicator properties.

3. Enter the information as shown above


4. Press the "Next >" button

Defining Input Parameters


Below you will define your indicator's input parameters. These are any parameters that can
be changed by the user and used in the calculation of the indicators value(s). If your indicator
does not require any parameters leave the "Name" fields blank.

© 2011 NinjaTrader, LLC


604 NinjaTrader Version 7

5. 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.

© 2011 NinjaTrader, LLC


NinjaScript 605

7. Enter the information as shown above.


8. Press the "Next >" button

Defining Oscillator Lines


Below you will define any required oscillator lines. This would be the "Zero" line in the CCI
indicator for example. If your indicator does not require any oscillator lines leave the "Name"
fields blank.

© 2011 NinjaTrader, LLC


606 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 607

Your primary area of concern will be sections "2" and "3".

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.

Calculating the Average


NinjaTrader has built in indicators that you can reference in your calculations. Since we are
calculating a simple moving average of volume it would make sense for us to use the built in
SMA indicator and Volume indicators.

Replace the wizard generated code with the following code into the OnBarUpdate() method in

© 2011 NinjaTrader, LLC


608 NinjaTrader Version 7

the NinjaScript Editor:

// Calculate the volume average


double average = SMA(VOL(), Period)[0];

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:

// Set the calculated value to the plot


Plot0.Set(average);

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.

© 2011 NinjaTrader, LLC


NinjaScript 609

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.

© 2011 NinjaTrader, LLC


610 NinjaTrader Version 7

Congratulations, you just completed building a custom indicator!


10.3.7.1.3 Intermediate - Your ow n SMA

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.

© 2011 NinjaTrader, LLC


NinjaScript 611

1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button

Defining Indicator Properties and Name


Below you will define your indicators name and several indicator properties.

3. Enter the information as shown above


4. We have checked the option "Overlay on price" which means that this will be a price
overlay indicator (will plot on top of the price data instead of in its own indicator panel)
5. Press the "Next >" button

Defining Input Parameters


Below you will define your indicator's input parameters. These are any parameters that can
be changed by the user and used in the calculation of the indicators value(s). If your indicator
does not require any parameters leave the "Name" fields blank.

© 2011 NinjaTrader, LLC


612 NinjaTrader Version 7

6. Enter the information as shown above


7. Press the "Next >" button

Defining Plots
Below you will define how your indicator is plotted on a chart.

© 2011 NinjaTrader, LLC


NinjaScript 613

8. Enter the information as shown above.


9. Press the "Next >" button

Defining Oscillator Lines


Below you will define any required oscillator lines. This would be the "Zero" line in the CCI
indicator for example. If your indicator does not require any oscillator lines leave the "Name"
fields blank.

© 2011 NinjaTrader, LLC


614 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 615

Your primary area of concern will be sections "2" and "3".

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.

Are there enough bars?


Replace the wizard generated code with the following code into the OnBarUpdate() method in
the NinjaScript Editor:

© 2011 NinjaTrader, LLC


616 NinjaTrader Version 7

// Do not calculate if we don't have enough bars


if (CurrentBar < Period) return;

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.

Getting a sum of closing prices


Enter the following code into the OnBarUpdate() method and below the code snippet you
entered above:

// Get a sum of prices over the specified period


double sum = 0;
for (int barsAgo = 0; barsAgo < Period; barsAgo++)
{
sum = sum + Input[barsAgo];
}

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.

for (int barsAgo = 0; barsAgo < Period; barsAgo++)


{
sum = sum + Input[barsAgo];
}

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....

What the loop is saying is:

1. the number of bars ago is now zero


2. as long as the number of bars ago is less than the moving average period, then go to line 3
otherwise this loop is finished
3. get the price Input[number of bars ago] and add it to the running sum total
4. add one to the number of bars ago (if number of bars ago was zero it will now be one)
5. go to to line 2

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.

© 2011 NinjaTrader, LLC


NinjaScript 617

* 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.

The final calculation


Enter the following code into the OnBarUpdate() method and below the code snippet you
entered above:

// Calculate and set the 'average' value to the


'Plot0' property
Plot0.Set(sum / Period);

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.

// Do not calculate if we don't have enough bars


if (CurrentBar < Period) return;

© 2011 NinjaTrader, LLC


618 NinjaTrader Version 7

// Calculate and set the 'average' value to the


'Plot0' property
Plot0.Set(SUM(Input, Period) / Period);
10.3.7.1.3.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.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.

© 2011 NinjaTrader, LLC


NinjaScript 619

Congratulations, you just completed building a custom indicator!


10.3.7.1.4 Intermediate - Historical Custom Data Series

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--

© 2011 NinjaTrader, LLC


620 NinjaTrader Version 7

>Indicator... menu
2. Press the "Next >" button

Defining Indicator Properties and Name


Below you will define your indicators name and several indicator properties.

3. Enter the information as shown above


4. Press the "Next >" button

Defining Input Parameters


Below you will define your indicator's input parameters. These are any parameters that can
be changed by the user and used in the calculation of the indicators value(s). If your indicator
does not require any parameters leave the "Name" fields blank.

© 2011 NinjaTrader, LLC


NinjaScript 621

5. 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.

© 2011 NinjaTrader, LLC


622 NinjaTrader Version 7

7. Enter the information as shown above


8. Press the "Next >" button

Defining Oscillator Lines


Below you will define any required oscillator lines. This would be the "Zero" line in the CCI
indicator for example. If your indicator does not require any oscillator lines leave the "Name"
fields blank.

© 2011 NinjaTrader, LLC


NinjaScript 623

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.

© 2011 NinjaTrader, LLC


624 NinjaTrader Version 7

Your primary area of concern will be sections "2" and "3".


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.4.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
do our calculations.

Creating DataSeries Object


1. Declare a variable ("myDataSeries" used in this example) of type DataSeries that will hold
a DataSeries object within the region "Variables"
2. Create a new DataSeries object and assigning it to the DataSeries variable within the
Initialize() method

© 2011 NinjaTrader, LLC


NinjaScript 625

#region Variables
private DataSeries myDataSeries; // Declare a
DataSeries variable
#endregion

protected override void Initialize()


{
myDataSeries = new DataSeries(this); // this
refers to the indicator/strategy itself
// and
syncs the DataSeries object to historical
// data
bars
}

Storing calculations in the DataSeries object


Now that we have our DataSeries object we can store double values into it. For this example
we will store a simple Close minus Open calculation.
Enter the following code into the OnBarUpdate() method:

// Calculate the range of the current bar and set the


value
myDataSeries.Set(Close[0] - Open[0]);

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.

Using DataSeries values


With our new DataSeries object we can continue with further calculations easily. We can
now use our DataSeries object as input to an indicator method such as SMA or instead of
always writing Close[0] - Open[0] we can substitute our DataSeries object instead as per the
example below.

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

// Add the bar's range to the SMA value


Plot0.Set(SMA(SMAPeriod)[0] + myDataSeries[0]);

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.

© 2011 NinjaTrader, LLC


626 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 627

Once applied to a chart, it can look something like the image below.

© 2011 NinjaTrader, LLC


628 NinjaTrader Version 7

Congratulations, you just completed building a custom indicator!


10.3.7.1.5 Advanced - Custom Plot Colors via Thresholds

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

© 2011 NinjaTrader, LLC


NinjaScript 629

indicator.

1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button

Defining Indicator Properties and Name


Below you will define your indicators name and several indicator properties.

3. Enter the information as shown above


4. Press the "Next >" button

Defining Input Parameters


Below you will define your indicator's input parameters. These are any parameters that can
be changed by the user and used in the calculation of the indicators value(s). If your indicator
does not require any parameters leave the "Name" fields blank.

© 2011 NinjaTrader, LLC


630 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 631

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

Defining Oscillator Lines


Below you will define any required oscillator lines. This would be the "Zero" line in the CCI
indicator for example. If your indicator does not require any oscillator lines leave the "Name"
fields blank.

© 2011 NinjaTrader, LLC


632 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 633

Your primary area of concern will be sections "2" and "3".


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. The default value of the "Period" and "Smooth" parameters are 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.5.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 the ROC value.

Setting Plot Thresholds


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

© 2011 NinjaTrader, LLC


634 NinjaTrader Version 7

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:

// Set the threshold values for each plot


Plots[0].Min = 0;
Plots[1].Max = 0;

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.

Completing the Indicator


This indicator is actually quite simple in its implementation. The last thing we need to do is
add the calculation code and set the value of ROC to both our plot lines.
Replace the wizard generated code with the following code into the OnBarUpdate() method in
the NinjaScript Editor:

© 2011 NinjaTrader, LLC


NinjaScript 635

// Are there enough bars


if (CurrentBar < Period) return;

// Set the plot values


AboveZero.Set(ROC(Period)[0]);
BelowZero.Set(ROC(Period)[0]);

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.

© 2011 NinjaTrader, LLC


636 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 637

Congratulations, you just completed building a custom indicator!


10.3.7.1.6 Advanced - Custom Draw ing

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.

© 2011 NinjaTrader, LLC


638 NinjaTrader Version 7

1. Within the NinjaTrader Control Center window select the Tools-->New NinjaScript--
>Indicator... menu
2. Press the "Next >" button

Defining Indicator Properties and Name


Below you will define your indicators name and several indicator properties.

3. Enter the information as shown above


4. Press the "Next >" button

Defining Input Parameters


Below you will define your indicator's input parameters. These are any parameters that can
be changed by the user and used in the calculation of the indicators value(s). If your indicator
does not require any parameters leave the "Name" fields blank.

© 2011 NinjaTrader, LLC


NinjaScript 639

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.

© 2011 NinjaTrader, LLC


640 NinjaTrader Version 7

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

Defining Oscillator Lines


Below you will define any required oscillator lines.

© 2011 NinjaTrader, LLC


NinjaScript 641

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.

© 2011 NinjaTrader, LLC


642 NinjaTrader Version 7

Your primary area of concern will be sections "2" and "3".


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.6.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 the CCI value and set the conditions used to set custom drawing.

Initializing the Indicator

© 2011 NinjaTrader, LLC


NinjaScript 643

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:

// Set the pen used to draw the plot as a dashed line


Plots[2].Pen.DashStyle = DashStyle.Dash;

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:

// Set line drawing thresholds which give the visual


effect of
// multi colored lines based on indicator values
Plots[0].Min = 70;
Plots[1].Max = 70;
Plots[1].Min = -70;
Plots[2].Max = -70;

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:

© 2011 NinjaTrader, LLC


644 NinjaTrader Version 7

// Do not calculate if we don't have enough bars


if (CurrentBar < Period) return;

// Calculate CCI value


double value = CCI(Period)[0];

// Use an if branch to set an indicator panel back


ground color and bar color
if (value > 200)
{
BackColor = Color.PaleGreen;
BarColor = Color.Yellow;
CandleOutlineColor = Color.Black;
}
else if (value > 150)
{
BackColor = Color.PaleGreen;
}
else if (value < -200)
{
BackColor = Color.Pink;
BarColor = Color.Yellow;
CandleOutlineColor = Color.Black;
}
else if (value < -150)
{
BackColor = Color.Pink;
}

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.

if (value > 200)


{
BackColor = Color.PaleGreen;
BarColor = Color.Yellow;
CandleOutlineColor = Color.Black;
}

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.

A list of available colors can be found here.

© 2011 NinjaTrader, LLC


NinjaScript 645

Each successive else if branch checks the value of value and sets custom drawing
properties.

Setting the plot values


Enter the following code in the OnBarUpdate() method and below the code entered above:

// Set the plot value


Above.Set(value);
Neutral.Set(value);
Below.Set(value);

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:

© 2011 NinjaTrader, LLC


646 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 647

Once applied to a chart, it can look something like the image below.

© 2011 NinjaTrader, LLC


648 NinjaTrader Version 7

Congratulations, you just completed building a custom indicator!


10.3.7.2 Strategies

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)

10.3.7.2.1 Beginner - Simple MA Cross Over

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

© 2011 NinjaTrader, LLC


NinjaScript 649

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:

Allow you to create a functional strategy without any programming


Generate the required NinjaScript code that will serve as the foundation for your custom
strategy for further coding

1. Within the NinjaTrader Control Center window select the Tools > New NinjaScript >
Strategy... menu
2. Press the "Next >" button

© 2011 NinjaTrader, LLC


650 NinjaTrader Version 7

3. Enter the information as shown above


4. Press the "Next >" button

Defining Input Parameters


Below you will define your strategy's input parameters. These are any input parameters that
can be changed by the user when running or backtesting a strategy. If your strategy does not
require any parameters leave the "Name" fields blank.

5. Add the inputs as per the image above


6. Press the "Next >" button

Defining Conditions and Actions


Below you can define conditions that trigger user defined actions such as placing orders,
drawing on a chart or creating an alert.

Notice how there are two buttons on the screen below:

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

© 2011 NinjaTrader, LLC


NinjaScript 651

construction and editing.

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

© 2011 NinjaTrader, LLC


652 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 653

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

© 2011 NinjaTrader, LLC


654 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 655

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.

The Entry and Exit Condition


Enter the code contained within the OnBarUpdate() method in the image below into the
OnBarUpdate() method in the NinjaScript Editor:

© 2011 NinjaTrader, LLC


656 NinjaTrader Version 7

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

To accomplish this we used the following methods:

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

The strategy code is now complete and needs to be compiled.

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.

© 2011 NinjaTrader, LLC


NinjaScript 657

10.3.7.2.2 Intermediate - RSI w ith Stop Loss & Profit Target

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:

Allow you to create a functional strategy without any programming


Generate the required NinjaScript code that will serve as the foundation for your custom
strategy for further coding

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

© 2011 NinjaTrader, LLC


658 NinjaTrader Version 7

3. Enter the information as shown above


4. Press the "Next >" button

Defining Input Parameters


Below you will define your strategy's input parameters. These are any input parameters that
can be changed by the user when running or backtesting a strategy. If your strategy does not
require any parameters leave the "Name" fields blank.

© 2011 NinjaTrader, LLC


NinjaScript 659

5. Add the inputs as per the image above


6. Press the "Unlock Code" button to launch the NinjaScript Editor.
10.3.7.2.2.2 Entering Strategy Logic

Using the Initialize() Method to Configure the Strategy


The Initialize() method is called once prior to running a strategy and can be used to set
properties or call methods in preparation for running a strategy.

Enter the code contained within the Initialize() method in the image below into the Initialize()
method in the NinjaScript Editor.

© 2011 NinjaTrader, LLC


660 NinjaTrader Version 7

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.

The method signature for the RSI() indicator is:

RSI(int period, int smooth)

It is valid to have used the Add() method in the following manner:

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.

Using the OnBarUpdate() Method for the Core Strategy Logic


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.

Enter the code contained within the OnBarUpdate() method in the image below into the

© 2011 NinjaTrader, LLC


NinjaScript 661

OnBarUpdate() method in the NinjaScript Editor:

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

if RSI crosses above a value of 20 within the last bar, go long

To accomplish this we used the following methods and properties:

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

The strategy code is now complete and needs to be compiled.

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.

© 2011 NinjaTrader, LLC


662 NinjaTrader Version 7

10.4 Language Reference


10.4.1 Alphabetical Reference
AB C D E F G HIJ K L MNO P Q R S T UVW XYZ

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

© 2011 NinjaTrader, LLC


NinjaScript 663

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)

© 2011 NinjaTrader, LLC


664 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 665

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

© 2011 NinjaTrader, LLC


666 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 667

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)

© 2011 NinjaTrader, LLC


668 NinjaTrader Version 7

Most Recent Occurence (MRO)


Moving Average - Double Exponential (DEMA)
Moving Average - Exponential (EMA)
Moving Average - Hull (HMA)
Moving Average - Kaufman's Adaptive (KAMA)
Moving Average - Mesa Adaptive (MAMA)
Moving Average - Simple (SMA)
Moving Average - T3 (T3)
Moving Average - Triangular (TMA)
Moving Average - Triple Exponential (TEMA)
Moving Average - Triple Exponential (TRIX)
Moving Average - Variable (VMA)
Moving Average - Volume Weighted (VWMA)
Moving Average - Weighted (WMA)
Moving Average - Zero Lag Exponential (ZLEMA)

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

© 2011 NinjaTrader, LLC


NinjaScript 669

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)

© 2011 NinjaTrader, LLC


670 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 671

Woodies CCI
Woodies Pivots

Z
ZigZag

10.4.2 Alert & Debug


The following section documents methods available on both Indicators and Strategies that
deal with alert and debugging.
10.4.2.1 Alert()

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

© 2011 NinjaTrader, LLC


672 NinjaTrader Version 7

// 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.

NinjaTrader.Cbi.LogLevel.Alert (will also generate a


pop up message window with log text)
NinjaTrader.Cbi.LogLevel.Error
NinjaTrader.Cbi.LogLevel.Information
NinjaTrader.Cbi.LogLevel.Warning

Examples
// Generates a log message
Log("This is a log message", NinjaTrader.Cbi.
LogLevel.Information);

// Generates a log message with a notification window


Log("This will generate a notification window as
well", NinjaTrader.Cbi.LogLevel.Alert);
10.4.2.4 PlaySound()

Definition
Plays a .wav file

© 2011 NinjaTrader, LLC


NinjaScript 673

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");

// Prints the current bar SMA value to the output


window
Print(SMA(Close, 20)[0]);

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

© 2011 NinjaTrader, LLC


674 NinjaTrader Version 7

you would get

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

© 2011 NinjaTrader, LLC


NinjaScript 675

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

Referencing Price Type Data

Price Type Syntax Editor Shortcut Definition


Close[int
Close barsAgo] "c" + Tab Key Last traded price of a bar
Open[int
Open barsAgo] "o" + Tab Key Opening price of a bar
High[int
High barsAgo] "h" + Tab Key Highest traded price of a bar
Low[int
Low barsAgo] "l" + Tab Key Lowest traded price of a bar
Volume[int Number of shares/contracts traded of
Volume "v" + Tab Key
barsAgo] a bar
Input[int
Input barsAgo] "i" + Tab Key *Default price type of a 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:

High[1] < High[0];

You could write a statement to calculate the average closing price of the last three bars like

© 2011 NinjaTrader, LLC


676 NinjaTrader Version 7

this:

( Close[2] + Close[1] + Close[0] ) / 3;

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.

Referencing Indicator Data


NinjaScript includes a library of built in indicators that you can access. Please see the
Indicator Methods reference section for clear definitions for how to access each indicator.

All indicator values can be accessed in the following way:

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:

Close[0] > SMA(20)[0];

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:

Close[0] > SMA(High, 20)[0];

You could write a statement to see if a 14 period CCI indicator is rising like this:

CCI(14)[0] > CCI(14)[1];

Value of a 10 period CCI 1 bar ago = CCI(10)[1]

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

© 2011 NinjaTrader, LLC


NinjaScript 677

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.

* For adding Bars of special types please use these methods:


AddKagi()
AddLineBreak()
AddPointAndFigure()
AddRenko()

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

* Please see the article here on using Bid/Ask


series.

Examples

© 2011 NinjaTrader, LLC


678 NinjaTrader Version 7

protected override void Initialize()


{
// Add a 5 minute Bars object - BarsInProgress
index = 1
Add(PeriodType.Minute, 5);

// Add a 100 tick Bars object for the ES 12-06


contract - BarsInProgress index = 2
Add("ES 12-06", PeriodType.Tick, 100);
}

protected override void OnBarUpdate()


{
// Ignore bar update events for the
supplementary Bars object added above
if (BarsInProgress == 1 || BarsInProgress == 2)
return;

// Go long if we have three up bars on all bars


objects
if (Close[0] > Open[0] && Closes[1][0] > Opens
[1][0] && Closes[2][0] > Opens[2][0])
EnterLong();
}
10.4.3.3 AddKagi()

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"

© 2011 NinjaTrader, LLC


NinjaScript 679

basePeriodType The underlying period type of the Kagi such as:


PeriodType.Day
PeriodType.Minute
PeriodType.Tick
PeriodType.Volume
basePeriodTypeValue The underlying period interval such as "3" for 3
minute bars
reversal Required price movement in the reversal direction
before a reversal is identified on the chart
reversalType Possible values are:
ReversalType.Percent
ReversalType.Tick
marketDataType Possible values are:
MarketDataType.Ask
MarketDataType.Bid
MarketDataType.Last

* Please see the article here on using Bid/Ask


series.

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);
}

protected override void OnBarUpdate()


{
// Ignore the primary Bars object and only
process the Kagi Bars object
if (BarsInProgress == 1)
{
// Do something;
}
}
10.4.3.4 AddLineBreak()

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.

© 2011 NinjaTrader, LLC


680 NinjaTrader Version 7

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

* Please see the article here on using Bid/Ask


series.

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);
}

protected override void OnBarUpdate()


{
// Ignore the primary Bars object and only
process the Point-and-Figure Bars object
if (BarsInProgress == 1)
{
// Do something;

© 2011 NinjaTrader, LLC


NinjaScript 681

}
}
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.

Possible values are:


PointAndFigurePriceType.Close
PointAndFigurePriceType.HighsAndLows
marketDataType Possible values are:
MarketDataType.Ask
MarketDataType.Bid
MarketDataType.Last

© 2011 NinjaTrader, LLC


682 NinjaTrader Version 7

* Please see the article here on using Bid/Ask


series.

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);
}

protected override void OnBarUpdate()


{
// Ignore the primary Bars object and only
process the Point-and-Figure Bars object
if (BarsInProgress == 1)
{
// Do something;
}
}
10.4.3.6 AddRenko()

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

© 2011 NinjaTrader, LLC


NinjaScript 683

marketDataType Possible values are:


MarketDataType.Ask
MarketDataType.Bid
MarketDataType.Last

* Please see the article here on using Bid/Ask


series.

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);
}

protected override void OnBarUpdate()


{
// Ignore the primary Bars object and only
process the Point-and-Figure Bars object
if (BarsInProgress == 1)
{
// Do something;
}
}
10.4.3.7 Bars

Definition
Bars objects represent the bars of data being processed by your indicator or strategy.

Methods and Properties


BarsSinceSession Number of bars that have elapsed since session
start
GetBar Returns the bar index based on time
GetDayBar Returns a Bar object that represents a trading day
whose properties for open, high, low, close, time
and volume can be accessed.
FirstBarOfSession Value indicating if the bar is the first bar of a session
PercentComplete Value indicating the completion percent of a bar
Session Session information of the Bars object
TickCount Total number of ticks of the current bar
TotalTicks Cumulative total of all ticks of all sessions

10.4.3.7.1 BarsSinceSession

Definition
The number of bars that have elapsed since the session started.

© 2011 NinjaTrader, LLC


684 NinjaTrader Version 7

Property Value
An int value representing the number of bars elapsed.

Syntax
Bars.BarsSinceSession

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be a Bar object which
holds the CurrentBid property. Should you wish to access this property elsewhere, check for
null reference first. e.g. if (Bars != null)
10.4.3.7.2 GetBar()

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.

Method Return Value


An int value that represents the bar index value.

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));

// Print out the 9 AM bar closing price


Print("The close price on the 9 AM bar was: " +
Close[barsAgo].ToString());
}

© 2011 NinjaTrader, LLC


NinjaScript 685

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.

Method Return Value


See below.

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

The property below returns a DateTime structure:


Bars.GetDayBar(int sessionsAgo).Time

The property below returns an int value:


Bars.GetDayBar(int sessionsAgo).Volume

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.

© 2011 NinjaTrader, LLC


686 NinjaTrader Version 7

Syntax
Bars.FirstBarOfSession

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be a Bar object which
holds the FirstBarOfSession property. Should you wish to access this property elsewhere,
check for null reference first. e.g. if (Bars != null)
10.4.3.7.5 PercentComplete

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

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be a Bar object which
holds the PercentComplete property. Should you wish to access this property elsewhere,
check for null reference first. e.g. if (Bars != null)
10.4.3.7.6 Session

Definition
Contains session template information.

Syntax
Bars.Session

Methods and Properties


GetNextBeginEnd Returns the next session's begin and end date/time
TemplateName Session template's name
TimeZoneInfo Time zone of the session template
10.4.3.7.6.1 GetNextBeginEnd

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

© 2011 NinjaTrader, LLC


NinjaScript 687

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;

protected override void OnBarUpdate()


{
// On the start of a new session, get the next
begin or end session time and its corresponding
paired session begin/end time.
if (Bars.FirstBarOfSession)
Bars.Session.GetNextBeginEnd(Time[0], out
sessionBegin, out sessionEnd);

Print("Session Start: " + sessionBegin + "


Session End: " + sessionEnd);
}
10.4.3.7.6.2 TemplateName

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

© 2011 NinjaTrader, LLC


688 NinjaTrader Version 7

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());

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be a Bar object which
holds the TickCount property. Should you wish to access this property elsewhere, check for
null reference first. e.g. if (Bars != null)
10.4.3.7.8 TotalTicks

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

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be a Bar object which
holds the TotalTicks property. Should you wish to access this property elsewhere, check for
null reference first. e.g. if (Bars != null)

© 2011 NinjaTrader, LLC


NinjaScript 689

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);
}

protected override void OnBarUpdate()


{
// Ignore bar update events for the
supplementary Bars object added above
if (BarsInProgress == 1)
return;

// Pass in a Bars object as input for the simple


moving average method
// Checks if the 20 SMA of the primary Bars is
greater than
// the 20 SMA of the secondary Bars added above
if (SMA(20)[0] > SMA(BarsArray[1], 20)[0])
EnterLong();
}
10.4.3.9 BarsInProgress

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

© 2011 NinjaTrader, LLC


690 NinjaTrader Version 7

Bars and instrument the script is running on.

See additional information on running multi-bars scripts.

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);
}

protected override void OnBarUpdate()


{
// Check which Bars object is calling the
OnBarUpdate() method
if (BarsInProgress == 0)
{
// A value of zero represents the primary
Bars which is the ES 12-06
// 1 minute chart.
// Do something within the context of the 1
minute Bars here
}
else if (BarsInProgress == 1)
{
// A value of 1 represents the secondary 5
minute bars added in the Initaliaze()
// Do something within the context of the 5
minute Bars
}
}
10.4.3.10 BarsPeriod

Definition
The primary Bars object period type and interval.

NOTE: This property should NOT be accessed within the Initialize() method.

© 2011 NinjaTrader, LLC


NinjaScript 691

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

© 2011 NinjaTrader, LLC


692 NinjaTrader Version 7

objects this represents the "boxSize" parameter


- When using Renko Bars objects this
represents the "brickSize" parameter
BarsPeriod.Value2 Only relevant for PointAndFigure Bars objects.
Returns an integer value representing the
"reveresal" parameter.

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);
}

protected override void OnBarUpdate()


{
// Print out 5, the value of the secondary bars
object
if (BarsInProgress == 1)

© 2011 NinjaTrader, LLC


NinjaScript 693

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.

Creating BoolSeries Objects


To create a BoolSeries object:

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

// Create a BoolSeries object and assign it to the


variable
protected override void Initialize()
{
myBoolSeries = new BoolSeries(this); // "this"
refers to the indicator, or strategy
// itself.
This syncs the BoolSeries object
// to
historical data bars
}

* BoolSeries objects can be used on supplementary series in a multi-time frame and


instrument strategy. Please see our support forum NinjaScript reference samples section for
further information.

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

© 2011 NinjaTrader, LLC


694 NinjaTrader Version 7

// Create a BoolSeries object and assign it to the


variable
protected override void Initialize()
{
// MaximumBarsLookBack determines how many
values the BoolSeries will have access to
myBoolSeries = new BoolSeries(this,
MaximumBarsLookBack.Infinite);
}

Setting Values - BoolSeries.Set() & BoolSeries.Reset()


You can set value (plug in a value) into a BoolSeries object by calling the Set() method.

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.

protected override void OnBarUpdate()


{
// Is the close > than the open
myBoolSeries.Set(Close[0] > Open[0] ? true :
false);
}

BoolSeries.Set(int barsAgo, bool value)


You can also set the value for historical bars by including a "barsAgo" value that represents
the number of bars ago that you want the bool value to be stored at.

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.

Checking for Valid Values


It is possible that you may use a BoolSeries object but decide not to set a value for a specific
bar. However, you should not try to access a BoolSeries value that has not been set.
Internally, a dummy value does exists, but you want to check to see if it was a valid value that
you set before trying to access it for use in your calculations.

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.

© 2011 NinjaTrader, LLC


NinjaScript 695

protected override void OnBarUpdate()


{
// Prints the current and last bar value
Print("The values are " + myBoolSeries[0] + " "
+ myBoolSeries[1]);
}

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]

© 2011 NinjaTrader, LLC


696 NinjaTrader Version 7

returns a double value representing the price of the referenced bar.

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);
}

protected override void OnBarUpdate()


{
// Compares the primary bar's close price to the
5-minute bar's close price
if (Closes[0][0] > Closes[1][0])
Print("The current bar's close price is

© 2011 NinjaTrader, LLC


NinjaScript 697

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.

Method Return Value


An int value representing the number of occurrences found

Syntax
CountIf(Condition condition, int lookBackPeriod)

The syntax for condition must be written in the following manner:


delegate { return your true/false condition;}

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();

© 2011 NinjaTrader, LLC


698 NinjaTrader Version 7

10.4.3.18 CrossAbove()

Definition
Checks for a cross above condition over the specified bar look back period.

Method Return Value


This method returns true if a cross above condition occured; otherwise, false.

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();

// Go long if 10 EMA crosses above 20 EMA within the


last bar
if (CrossAbove(EMA(10), EMA(20), 1))
EnterLong();

// Go long we have an up bar and the 10 EMA crosses


above 20 EMA within the last 5 bars
if (Close[0] > Open[0] && CrossAbove(EMA(10), EMA
(20), 5))
EnterLong();
10.4.3.19 CrossBelow()

Definition
Checks for a cross below condition over the specified bar look back period.

Method Return Value


This method returns true if a cross above condition occured; otherwise, false.

Syntax
CrossBelow(IDataSeries series1, double value, int lookBackPeriod)
CrossBelow(IDataSeries series1, IDataSeries series2, int

© 2011 NinjaTrader, LLC


NinjaScript 699

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();

// Go short if 10 EMA crosses below 20 EMA within the


last bar
if (CrossBelow(EMA(10), EMA(20), 1))
EnterShort();

// Go short we have a down bar and the 10 EMA crosses


above 20 EMA within the last 5 bars
if (Close[0] < Open[0] && CrossBelow(EMA(10), EMA
(20), 5))
EnterShort();
10.4.3.20 CurrentBar

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)

© 2011 NinjaTrader, LLC


700 NinjaTrader Version 7

return;

// Indicator logic calculation code...


}
10.4.3.21 CurrentBars

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);
}

protected override void OnBarUpdate()


{
// Checks to make sure we have at least 20
(default value of BarsRequired)
// or more bars in both Bars objects before
continuing.
if (CurrentBars[0] < BarsRequired || CurrentBars
[1] < BarsRequired)
return;

// Script logic calculation code...


}
10.4.3.22 DataSeries Class

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

© 2011 NinjaTrader, LLC


NinjaScript 701

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.

Creating DataSeries Objects


When creating custom indicators, DataSeries objects are automatically created for you by
calling the Add() method and can be subsequently referenced by the Value and/or Values
property. However, you may have a requirement to create a DataSeries object to store values
that are part of an overall indicator value calculation. This can be done within a custom
indicator or strategy.

To create a DataSeries object:

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

// Create a DataSeries object and assign it to the


variable
protected override void Initialize()
{
myDataSeries = new DataSeries(this); // "this"
refers to the indicator, or strategy
// itself.
This syncs the DataSeries object
// to
historical data bars
}

* DataSeries objects can be used on supplementary series in a multi-time frame and


instrument strategy. Please see our support forum NinjaScript reference samples section for
further information.

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

© 2011 NinjaTrader, LLC


702 NinjaTrader Version 7

#endregion

// Create a DataSeries object and assign it to the


variable
protected override void Initialize()
{
// MaximumBarsLookBack determines how many
values the DataSeries will have access to
myDataSeries = new DataSeries(this,
MaximumBarsLookBack.Infinite);
}

Setting Values - DataSeries.Set() & DataSeries.Reset()


You can set value (plug in a value) into a DataSeries object by calling the Set() method.

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.

protected override void OnBarUpdate()


{
// Calculate the range of the current bar and
set the value
myDataSeries.Set(High - Low);
}

DataSeries.Set(int barsAgo, double value)


You can also set the value for historical bars by including a "barsAgo" value that represents
the number of bars ago that you want the double value to be stored at.

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.

Checking for Valid Values


It is possible that you may use a DataSeries object but decide not to set a value for a specific
bar. However, you should not try to access a DataSeries value that has not been set.
Internally, a dummy value does exists, but you want to check to see if it was a valid value that
you set before trying to access it for use in your calculations.

DataSeries.ContainsValue(int barsAgo)

© 2011 NinjaTrader, LLC


NinjaScript 703

Returns a true or false value.

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.

protected override void OnBarUpdate()


{
// Prints the current and last bar value
Print("The values are " + myDataSeries[0] + " "
+ myDataSeries[1]);
}

Methods that Accept DataSeries as Arguments


All indicator methods accept DataSeries objects as arguments. Carrying from the prior
examples, let's print out the 10 period simple moving average of range.

protected override void OnBarUpdate()


{
// Calculate the range of the current bar and
set the value
myDataSeries.Set(High - Low);

// Print the current 10 period SMA of range


Print("Value is " + SMA(myDataSeries, 10)[0]);
}
10.4.3.23 DateTimeSeries Class

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.

Creating DateTimeSeries Objects


To create a DateTimeSeries object:

1. Define a variable ("myDateTimeSeries" used in this example) of type DateTimeSeries that


will hold a DateTimeSeries object
2. In the Initialize() method, create a new DateTimeSeries object and assign it to the
"myDateTimeSeries" variable

#region Variables
private DateTimeSeries myDateTimeSeries; // Define a
DateTimeSeries variable
#endregion

// Create a DateTimeSeries object and assign it to

© 2011 NinjaTrader, LLC


704 NinjaTrader Version 7

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
}

* DateTimeSeries objects can be used on supplementary series in a multi-time frame and


instrument strategy. Please see our support forum NinjaScript reference samples section for
further information.

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

// Create a DateTimeSeries object and assign it to


the variable
protected override void Initialize()
{
// MaximumBarsLookBack determines how many
values the DateTimeSeries will have access to
myDateTimeSeries = new DataSeries(this,
MaximumBarsLookBack.Infinite);
}

Setting Values - DateTimeSeries.Set() & DateTimeSeries.Reset()


You can set value (plug in a value) into a DateTimeSeries object by calling the Set() method.

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.

protected override void OnBarUpdate()


{
// Store the current time
myDateTimeSeries.Set(DateTime.Now);

© 2011 NinjaTrader, LLC


NinjaScript 705

DateTimeSeries.Set(int barsAgo, DateTime value)


You can also set the value for historical bars by including a "barsAgo" value that represents
the number of bars ago that you want the DateTime value to be stored at.

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.

Checking for Valid Values


It is possible that you may use a DateTimeSeries object but decide not to set a value for a
specific bar. However, you should not try to access a DataTimeSeries value that has not
been set. Internally, a dummy value does exists, but you want to check to see if it was a valid
value that you set before trying to access it for use in your calculations.
DateTimeSeries.ContainsValue(int barsAgo)
Returns a true or false value.

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.

protected override void OnBarUpdate()


{
// Prints the current and last bar value
Print("The values are " + myDateTimeSeries[0] +
" " + myDateTimeSeries[1]);
}

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

© 2011 NinjaTrader, LLC


706 NinjaTrader Version 7

Examples

protected override void OnBarUpdate()


{
// If it's Monday, do not trade.
if (Time[0].DayOfWeek == DayOfWeek.Monday)
return;
}
10.4.3.25 Falling()

Definition
Checks for a falling condition which is true when the current value is less than the value of 1
bar ago.

Method Return Value


This method returns true if a falling condition is present; otherwise, false.

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

© 2011 NinjaTrader, LLC


NinjaScript 707

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;
}

// Process exit signals tick by tick


if (CCI(20)[0] > 250)
ExitLong();
}
10.4.3.27 FloatSeries Class

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.

Creating FloatSeries Objects


To create a FloatSeries object:
1. Define a variable ("myFloatSeries" used in this example) of type FloatSeries that will hold a
FloatSeries object
2. In the Initialize() method, create a new FloatSeries object and assign it to the
"myFloatSeries" variable

#region Variables
private FloatSeries myFloatSeries; // Define a
FloatSeries variable
#endregion

// Create a FloatSeries object and assign it to the


variable
protected override void Initialize()
{
myFloatSeries = new FloatSeries(this); // "this"
refers to the indicator, or strategy
//
itself. This syncs the FloatSeries object
// to

© 2011 NinjaTrader, LLC


708 NinjaTrader Version 7

historical data bars


}

* FloatSeries objects can be used on supplementary series in a multi-time frame and


instrument strategy. Please see our support forum NinjaScript reference samples section for
further information.

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

// Create a FloatSeries object and assign it to the


variable
protected override void Initialize()
{
// MaximumBarsLookBack determines how many
values the FloatSeries will have access to
myFloatSeries = new FloatSeries(this,
MaximumBarsLookBack.Infinite);
}

Setting Values - FloatSeries.Set() & FloatSeries.Reset()


You can set value (plug in a value) into a FloatSeries object by calling the Set() method.

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.

protected override void OnBarUpdate()


{
float range = (float) (High[0] - Low[0]);
myFloatSeries.Set(range);
}

FloatSeries.Set(int barsAgo, float value)


You can also set the value for historical bars by including a "barsAgo" value that represents
the number of bars ago that you want the bool value to be stored at.

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

© 2011 NinjaTrader, LLC


NinjaScript 709

want to store a value for the current bar. Reset() will reset the current index value to null.

Checking for Valid Values


It is possible that you may use an FloatSeries object but decide not to set a value for a
specific bar. However, you should not try to access a FloatSeries value that has not been
set. Internally, a dummy value does exists, but you want to check to see if it was a valid value
that you set before trying to access it for use in your calculations.

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.

protected override void OnBarUpdate()


{
// Prints the current and last bar value
Print("The values are " + myFloatSeries[0] + " "
+ myFloatSeries[1]);
}

10.4.3.28 FundamentalDataEventArgs

Definition
Represents a change in fundamental data and is passed as a parameter in the
OnFundamentalData() method.

Methods and Parameters


DateTimeValue A DateTime structure representing the time
DoubleValue A double value representing fundamental data
FundamentalDataTyp Possible values:
e
AverageDailyVolume
Beta
CalendarYearHigh
CalendarYearHighDate
CalendarYearLow
CalendarYearLowDate
CurrentYearsEarningsPerShare
FiveYearsGrowthPercentage
High52Weeks
High52WeeksDate
HistoricalVolatility
Low52Weeks
Low52WeeksDate
NextYearsEarningsPerShare

© 2011 NinjaTrader, LLC


710 NinjaTrader Version 7

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.

Method Return Value


A double value representing the current ask price. Note: When accessed during a historical
backtest, the close price of the evaluated bar is substituted.

Syntax
GetCurrentAsk()
GetCurrentAsk(int barSeriesIndex)
10.4.3.30 GetCurrentAskVolume()

Definition
Returns the current ask volume.

Method Return Value


A long value representing the current ask volume. Note: When accessed during a historical
backtest, the volume of the evaluated bar is substituted.

Syntax
GetCurrentAskVolume()
GetCurrentAskVolume(int barSeriesIndex)

© 2011 NinjaTrader, LLC


NinjaScript 711

10.4.3.31 GetCurrentBid()

Definition
Returns the current bid price.

Method Return Value


A double value representing the current bid price. Note: When accessed during a historical
backtest, the close price of the evaluated bar is substituted.

Syntax
GetCurrentBid()
GetCurrentBid(int barSeriesIndex)
10.4.3.32 GetCurrentBidVolume()

Definition
Returns the current bid volume.

Method Return Value


A long value representing the current bid volume. Note: When accessed during a historical
backtest, the volume of the evaluated bar is substituted.

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.

Method Return Value


A double value representing the median price.

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:

© 2011 NinjaTrader, LLC


712 NinjaTrader Version 7

" + GetMedian(Open, 10).ToString());


10.4.3.34 High

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;

// Checks for higher highs


if (High[0] > High[1] && High[1] > High[2])
Print("Two successive higher highs");

// Gets the current value of a 20 period SMA of


high prices
double value = SMA(High, 20)[0];
Print("The value is " + value.ToString());
}

10.4.3.35 HighestBar()

Definition
Returns the number of bars ago the highest price value occurred for the lookback period.

Method Return Value


An int value that represents number of bars ago.

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...

© 2011 NinjaTrader, LLC


NinjaScript 713

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);
}

protected override void OnBarUpdate()


{
// Compares the primary bar's high price to the
5-minute bar's high price
if (Highs[0][0] > Highs[1][0])
Print("The current bar's high price is
greater");
}

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

© 2011 NinjaTrader, LLC


714 NinjaTrader Version 7

many different applications.

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.

private double DoubleTheValue(IDataSeries priceData)


{
return priceData[0] * 2;
}

protected override void OnBarUpdate()


{
Print(DoubleTheValue(Close));
Print(DoubleTheValue(SMA(20)));

© 2011 NinjaTrader, LLC


NinjaScript 715

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.

protected override void OnBarUpdate()


{
// Only set our plot if the input is a valid
value
if (Input.IsValidPlot(CurrentBar))
Plot0.Set(Input[0]);
}
10.4.3.39 Initialize()

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.

Method Return Value


This method does not return a value.

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

© 2011 NinjaTrader, LLC


716 NinjaTrader Version 7

data the strategy is run against


// set by the UI takes the index of 0.
Add(Instrument, PeriodType.Minute, 5);
}
10.4.3.40 Input

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.

Methods and Properties


Expiry Expiration date of the futures contract
FullName Full name of the instrument
MasterInstrument.Compare() Compares two price values with respect to
the Instrument TickSize
MasterInstrument. Type of instrument
InstrumentType
MasterInstrument.Name Database name of the instrument (e.g.

© 2011 NinjaTrader, LLC


NinjaScript 717

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

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be an Instrument
object. Should you wish to access this property elsewhere, check for null reference first. e.g.
if (Instrument != null)
10.4.3.41.2 FullName

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

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be an Instrument
object. Should you wish to access this property elsewhere, check for null reference first. e.g.
if (Instrument != null)
10.4.3.41.3 MasterInstrument.Compare()

Definition
Compares two price values with respect to the Instrument TickSize to ensure accuracy when
dealing with floating point math.

Method Return Value


An int value.

A value of "1" is returned if price1 is greater than price2


A value of "-1" is returned if price1 is less than price2

© 2011 NinjaTrader, LLC


718 NinjaTrader Version 7

A value of "0" if price1 is equal to price2

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.

Possible values are:


InstrumentType.Currency
InstrumentType.Future
InstrumentType.Index
InstrumentType.Option
InstrumentType.Stock

Syntax
Instrument.MasterInstrument.InstrumentType

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be an Instrument
object. Should you wish to access this property elsewhere, check for null reference first. e.g.
if (Instrument != null)
10.4.3.41.5 MasterInstrument.Name

Definition
Returns the NinjaTrader database name of an instrument. For example, "MSFT", "ES", "ER2"
etc...

Property Value

© 2011 NinjaTrader, LLC


NinjaScript 719

A string representing the name of the instrument.

Syntax
Instrument.MasterInstrument.Name

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be an Instrument
object. Should you wish to access this property elsewhere, check for null reference first. e.g.
if (Instrument != null)
10.4.3.41.6 MasterInstrument.PointValue

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

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be an Instrument
object. Should you wish to access this property elsewhere, check for null reference first. e.g.
if (Instrument != null)
10.4.3.41.7 MasterInstrument.Round2TickSize()

Definition
Returns a value that is rounded to the nearest valid value evenly divisible by the instrument's
tick size.

Method Return Value


A double value.

Syntax
Instrument.MasterInstrument.Round2TickSize(double price)

Parameters
price A double value representing a price

Additional Access Information


This property can be accessed without a null reference check in the OnBarUpdate() event
handler. When the OnBarUpdate() event is triggered, there will always be an Instrument
object. Should you wish to access this property elsewhere, check for null reference first. e.g.
if (Instrument != null)

© 2011 NinjaTrader, LLC


720 NinjaTrader Version 7

10.4.3.42 IntSeries Class

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.

Creating IntSeries Objects


To create a IntSeries object:

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

// Create a IntSeries object and assign it to the


variable
protected override void Initialize()
{
myIntSeries = new IntSeries(this); // "this"
refers to the indicator, or strategy
// itself.
This syncs the IntSeries object
// to
historical data bars
}

* IntSeries objects can be used on supplementary series in a multi-time frame and


instrument strategy. Please see our support forum NinjaScript reference samples section for
further information.

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

// Create a IntSeries object and assign it to the


variable

© 2011 NinjaTrader, LLC


NinjaScript 721

protected override void Initialize()


{
// MaximumBarsLookBack determines how many
values the IntSeries will have access to
myIntSeries = new IntSeries(this,
MaximumBarsLookBack.Infinite);
}

Setting Values - IntSeries.Set() & IntSeries.Reset()


You can set value (plug in a value) into a IntSeries object by calling the Set() method.

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.

protected override void OnBarUpdate()


{
int rangeInTicks = (int) ((High[0] - Low[0]) /
TickSize);
myIntSeries.Set(rangeInTicks);
}

IntSeries.Set(int barsAgo, int value)


You can also set the value for historical bars by including a "barsAgo" value that represents
the number of bars ago that you want the bool value to be stored at.

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.

Checking for Valid Values


It is possible that you may use an IntSeries object but decide not to set a value for a specific
bar. However, you should not try to access a IntSeries value that has not been set. Internally,
a dummy value does exists, but you want to check to see if it was a valid value that you set
before trying to access it for use in your calculations.

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.

protected override void OnBarUpdate()


{

© 2011 NinjaTrader, LLC


722 NinjaTrader Version 7

// Prints the current and last bar value


Print("The values are " + myIntSeries[0] + " " +
myIntSeries[1]);
}

10.4.3.43 Least Recent Occurence (LRO)

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.

Method Return Value


An int value representing the number of bars ago. Returns a value of -1 if the specified test
condition did not evaluate to true within the look back period.

Syntax
LRO(Condition condition, int instance, int lookBackPeriod)

The syntax for condition must be written in the following manner:

delegate { return your true/false condition;}

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

© 2011 NinjaTrader, LLC


NinjaScript 723

for related information.

Creating LongSeries Objects


To create a LongSeries object:

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

// Create a LongSeries object and assign it to the


variable
protected override void Initialize()
{
myLongSeries = new LongSeries(this); // "this"
refers to the indicator, or strategy
// itself.
This syncs the LongSeries object
// to
historical data bars
}

* LongSeries objects can be used on supplementary series in a multi-time frame and


instrument strategy. Please see our support forum NinjaScript reference samples section for
further information.

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

// Create a LongSeries object and assign it to the


variable
protected override void Initialize()
{
// MaximumBarsLookBack determines how many
values the LongSeries will have access to
myLongSeries = new LongSeries(this,

© 2011 NinjaTrader, LLC


724 NinjaTrader Version 7

MaximumBarsLookBack.Infinite);
}

Setting Values - LongSeries.Set() & LongSeries.Reset()


You can set value (plug in a value) into a LongSeries object by calling the Set() method.

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.

protected override void OnBarUpdate()


{
long doubleVolume = (long) (Volume[0] * 2);
myLongSeries.Set(doubleVolume);
}

LongSeries.Set(int barsAgo, bool value)


You can also set the value for historical bars by including a "barsAgo" value that represents
the number of bars ago that you want the bool value to be stored at.

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.

Checking for Valid Values


It is possible that you may use an LongSeries object but decide not to set a value for a
specific bar. However, you should not try to access a LongSeries value that has not been
set. Internally, a dummy value does exists, but you want to check to see if it was a valid value
that you set before trying to access it for use in your calculations.

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.

protected override void OnBarUpdate()


{
// Prints the current and last bar value
Print("The values are " + myLongSeries[0] + " "
+ myLongSeries[1]);
}

© 2011 NinjaTrader, LLC


NinjaScript 725

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];

// Low price of 10 bars ago


double barLowPrice = Low[10];

// Current bar value of a 20 period exponential


moving average of low prices
double value = EMA(Low, 20)[0];

10.4.3.46 LowestBar()

Definition
Returns the number of bars ago the lowest price value occured for the lookback period.

Method Return Value


An int value that represents number of bars ago.

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());

© 2011 NinjaTrader, LLC


726 NinjaTrader Version 7

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);
}

protected override void OnBarUpdate()


{
// Compares the primary bar's low price to the
5-minute bar's low price
if (Lows[0][0] > Lows[1][0])
Print("The current bar's low price is
greater");
}
10.4.3.48 MarketDataEventArgs

Definition
Represents a change in level one market data and is passed as a parameter in the
OnMarketData() method.

Methods and Parameters


MarketDataType Possible values are:
MarketDataType.Ask
MarketDataType.Bid
MarketDataType.DailyHigh
MarketDataType.DailyLow
MarketDataType.DailyVolume
MarketDataType.Last
MarketDataType.LastClose (prior session close)

© 2011 NinjaTrader, LLC


NinjaScript 727

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.

Methods and Parameters


MarketDataType Possible values are:
MarketDataType.Ask
MarketDataType.Bid
MarketMaker A string representing the market maker id
Position An int value representing the zero based position
in the depth ladder.
Operation Represents the action you should take when
building a level two book.
Possible values are:
Operation.Insert
Operation.Remove
Operation.Update
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

© 2011 NinjaTrader, LLC


728 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 729

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];

// Median price of 10 bars ago


double barMedianPrice = Median[10];

// Current bar value of a 20 period exponential


moving average of median prices
double value = EMA(Median, 20)[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);
}

protected override void OnBarUpdate()


{

© 2011 NinjaTrader, LLC


730 NinjaTrader Version 7

// Compares the primary bar's median price to


the 5-minute bar's median price
if (Medians[0][0] > Medians[1][0])
Print("The current bar's median price is
greater");
}

10.4.3.53 Most Recent Occurence (MRO)

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.

Method Return Value


An int value representing the number of bars ago. Returns a value of -1 if the specified test
condition did not evaluate to true within the look back period.

Syntax
MRO(Condition condition, int instance, int lookBackPeriod)

The syntax for condition must be written in the following manner:

delegate { return your true/false condition;}

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

© 2011 NinjaTrader, LLC


NinjaScript 731

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.

Method Return Value


This method does not return a value.

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;

// Compares the primary bar's low price to the


5-minute bar's low price
if (Low[0] > Lows[1])
Print("The current bar's low price is
greater");
}
10.4.3.55 OnFundamentalData()

Definition
The OnFundamentalData() method is called for every change in fundamental data for the
underlying instrument.

Programming to this method is considered advanced programming and exposed for


experienced programmer
This method is not called on historical data (backtest)

Method Return Value


This method does not return a value.

Method Parameters
FundamentalDataEventArgs e

Syntax
You must override the method in your strategy or indicator with the following syntax.

protected override void OnFundamentalData(FundamentalDataEventArgs e)

© 2011 NinjaTrader, LLC


732 NinjaTrader Version 7

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.

Programming to this method is considered advanced programming and exposed for


experienced programmer
This is a real-time data stream and can be CPU intensive if your program code is compute
intensive (not optimal)
This method is not called on historical data (backtest)

Method Return Value


This method does not return a value.

Method Parameters
MarketDataEventArgs e

Syntax
You must override the method in your strategy or indicator with the following syntax.

protected override void OnMarketData(MarketDataEventArgs e)


{

© 2011 NinjaTrader, LLC


NinjaScript 733

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);
}

Additional Reference Samples


Additional reference code samples are available the NinjaScript Educational Resources
section of our support forum.

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.

Programming to this method is considered advanced programming and exposed for


experienced programmer
This is a real-time data stream and can be CPU intensive if your program code is compute
intensive (not optimal)
This method is not called on historical data (backtest)

Method Return Value

© 2011 NinjaTrader, LLC


734 NinjaTrader Version 7

This method does not return a value.

Method Parameters
MarketDepthEventArgs e

Syntax
You must override the method in your strategy or indicator with the following syntax.

protected override void OnMarketDepth(MarketDepthEventArgs e)


{

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);
}

Additional Reference Samples


Additional reference code samples are available the NinjaScript Educational Resources
section of our support forum.

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.

© 2011 NinjaTrader, LLC


NinjaScript 735

Method Return Value


This method does not return a value.

Syntax
You must override the method in your strategy or indicator with the following syntax.

protected override void OnStartUp()


{

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.

Method Return Value


This method does not return a value.

Syntax
You must override the method in your strategy or indicator with the following syntax.

protected override void OnTermination()


{

Examples
protected override void OnTermination()
{
// Clean up your resources here
}
10.4.3.60 Open

Definition
A collection of historical bar opening prices.

© 2011 NinjaTrader, LLC


736 NinjaTrader Version 7

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];

// Opening price of 10 bars ago


double barOpenPrice = Open[10];

// Current bar value of a 20 period simple moving


average of opening prices
double value = SMA(Open, 20)[0];

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);
}

protected override void OnBarUpdate()

© 2011 NinjaTrader, LLC


NinjaScript 737

{
// 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.

Method Return Value


This method returns true if a rising condition is present; otherwise, false.

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.

Method Return Value


This method returns a double value indicating the slope 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

© 2011 NinjaTrader, LLC


738 NinjaTrader Version 7

Examples
// Prints the slope of the 20 period simple moving
average of the last 10 bars
Print(Slope(SMA(20), 10, 0));

10.4.3.64 StringSeries Class

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.

Creating StringSeries Objects


To create a StringSeries object:

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

// Create a StringSeries object and assign it to the


variable
protected override void Initialize()
{
myStringSeries = new StringSeries(this); //
"this" refers to the indicator, or strategy
//
itself. This syncs the StringSeries object
// to
historical data bars
}

* StringSeries objects can be used on supplementary series in a multi-time frame and


instrument strategy. Please see our support forum NinjaScript reference samples section for
further information.

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.

© 2011 NinjaTrader, LLC


NinjaScript 739

#region Variables
private StringSeries myStringSeries; // Define a
StringSeries variable
#endregion

// Create a StringSeries object and assign it to the


variable
protected override void Initialize()
{
// MaximumBarsLookBack determines how many
values the StringSeries will have access to
myStringSeries = new StringSeries(this,
MaximumBarsLookBack.Infinite);
}

Setting Values - StringSeries.Set() & StringSeries.Reset()


You can set value (plug in a value) into a StringSeries object by calling the Set() method.

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.

protected override void OnBarUpdate()


{
// Just store some text
myStringSeries.Set(CurrentBar.ToString());
}

StringSeries.Set(int barsAgo, string value)


You can also set the value for historical bars by including a "barsAgo" value that represents
the number of bars ago that you want the string value to be stored at.

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.

Checking for Valid Values


It is possible that you may use a StringSeries object but decide not to set a value for a
specific bar. However, you should not try to access a StringSeries value that has not been
set. Internally, a dummy value does exists, but you want to check to see if it was a valid value
that you set before trying to access it for use in your calculations.

StringSeries.ContainsValue(int barsAgo)
Returns a true or false value.

© 2011 NinjaTrader, LLC


740 NinjaTrader Version 7

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.

protected override void OnBarUpdate()


{
// Prints the current and last bar value
Print("The values are " + myStringSeries[0] + "
" + myStringSeries[1]);
}

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());

// Prints the value of the current bar low less one


tick size
double value = Low[0] - TickSize;
Print(value.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)

© 2011 NinjaTrader, LLC


NinjaScript 741

Examples
// Prints the current bar time stamp
Print(Time[0].ToString());

// Checks if current time is greater than the bar


time stamp
if (DateTime.Now.Ticks > Time[0].Ticks)
Print("Do something");

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);
}

protected override void OnBarUpdate()


{
// Compares the primary bar's time to the 5-
minute bar's time
if (Times[0][0].Ticks > Times[1][0].Ticks)
Print("The current bar's time is greater");
}
10.4.3.68 ToDay()

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

© 2011 NinjaTrader, LLC


742 NinjaTrader Version 7

otherwise use this method and the ToTime() method.

Integer representation of day is in the following format yyyyMMdd where January 8, 2007
would be 20070108.

Method Return Value


An int value that represents the date.

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.

Method Return Value


An int value that represents the time.

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)

© 2011 NinjaTrader, LLC


NinjaScript 743

{
// 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.

Method Return Value


This method does not have a return value.

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");
}

private void MyCustomHandler(object state)


{
Print((string) state + " " + CurrentBar.ToString
());
}
10.4.3.71 Typical

Definition
A collection of historical bar typical prices. Typical price = (High + Low + Close) / 3.

© 2011 NinjaTrader, LLC


744 NinjaTrader Version 7

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];

// Typical price of 10 bars ago


double barTypicalPrice = Typical[10];

// Current bar value of a 20 period exponential


moving average of typical prices
double value = EMA(Typical, 20)[0];

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);
}

protected override void OnBarUpdate()


{

© 2011 NinjaTrader, LLC


NinjaScript 745

// Compares the primary bar's typical price to


the 5-minute bar's typical price
if (Typicals[0][0] > Typicals[1][0])
Print("The current bar's typical price is
greater");
}

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");

// Is the current volume greater than the 20


period moving average of volume
if (Volume[0] > SMA(Volume, 20)[0])
Print("Increasing 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

© 2011 NinjaTrader, LLC


746 NinjaTrader Version 7

Volumes[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);
}

protected override void OnBarUpdate()


{
// Compares the primary bar's volume to the 5-
minute bar's volume
if (Volumes[0][0] > Volumes[1][0])
Print("The current bar's volume price is
greater");
}

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];

// Weighted price of 10 bars ago


double barWeigthedPrice = Weighted[10];

// Current bar value of a 20 period exponential


moving average of weighted prices
double value = EMA(Weighted, 20)[0];

© 2011 NinjaTrader, LLC


NinjaScript 747

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);
}

protected override void OnBarUpdate()


{
// Compares the primary bar's weighted price to
the 5-minute bar's weighted price
if (Weighteds[0][0] > Weighteds[1][0])
Print("The current bar's weighted price is
greater");
}
10.4.4 Drawing
You can use NinjaScript to draw custom shapes, lines, text and colors on your price and
indicator panels from both Indicators and Strategies .

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.

© 2011 NinjaTrader, LLC


748 NinjaTrader Version 7

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;

// Sets the back color to the default color set in


the chart properties dialog window
BackColor = Color.Empty;

© 2011 NinjaTrader, LLC


NinjaScript 749

// Sets the back color to maroon when the closing


price is less than the 20 period SMA // and to lime
green when above (see image below)
BackColor = SMA(20)[0] >= Close[0] ? Color.Maroon :
Color.LimeGreen;

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;

© 2011 NinjaTrader, LLC


750 NinjaTrader Version 7

// Sets the back color to the default color set in


the chart properties dialog window
BackColorAll = Color.Empty;

// Sets the back color to pink when the closing price


is less than the 20 period SMA
// and to lime green when above (see image below)
BackColorAll = SMA(20)[0] >= Close[0] ? Color.Pink :
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

© 2011 NinjaTrader, LLC


NinjaScript 751

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;

// Sets the color of the background on the previous


bar as orange on all chart panels.
BackColorAllSeries[1] = Color.Orange;
10.4.4.5 BackColorSeries

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;

// Sets the color of the background on the previous


bar as orange
BackColorSeries[1] = Color.Orange;
10.4.4.6 BarColor

Definition
Sets the color of a price bar.

Property Value
A color structure that represents the color of this price bar.

Syntax
BarColor

© 2011 NinjaTrader, LLC


752 NinjaTrader Version 7

Examples
// Sets the bar color to yellow
BarColor = Color.Yellow;

// Sets the bar color to its default color as defined


in the chart properties dialog
BarColor = Color.Empty;

// Sets the bar color to yellow if the 20 SMA is


above the 50 SMA and the closing
// price is above the 20 SMA (see image below)
if (SMA(20)[0] > SMA(50)[0] && Close[0] > SMA(20)[0])
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;

// Sets the color of the previous bar to orange.


BarColorSeries[1] = Color.Orange;
10.4.4.8 CandleOutlineColor

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.

© 2011 NinjaTrader, LLC


NinjaScript 753

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;

// Sets the outline color of the previous bar to


blue.
CandleOutlineColorSeries[1] = Color.Blue;

10.4.4.10 Custom Drawing

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

© 2011 NinjaTrader, LLC


754 NinjaTrader Version 7

TickCounter
VolumeZones
10.4.4.11 DrawAndrewsPitchfork()

Definition
Draws an Andrew's Pitchfork.

Method Return Value


An IAndrewsPitchfork object that represents the draw object.

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.

© 2011 NinjaTrader, LLC


NinjaScript 755

Method Return Value


An IArc object that represents the draw object.

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)

Note: Drawing objects with y values very far off the


visible canvas can lead to performance hits.
Fancier DashStyles like DashDotDot will also
require more resources than simple DashStyles like
Solid.
width The width of the draw object

© 2011 NinjaTrader, LLC


756 NinjaTrader Version 7

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.

Method Return Value


An IArrowDown object that represents the draw object.

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);

// Paints a blue down arrown on a three bar reversal


pattern (see image below)
if (High[2] > High[3] && High[1] > High[2] && Close
[0] < Open[0])
DrawArrowDown(CurrentBar.ToString(), true, 0,
High[0] + TickSize, Color.Blue);

© 2011 NinjaTrader, LLC


NinjaScript 757

10.4.4.14 DrawArrowLine()

Definition
Draws an arrow line.

Method Return Value


An IArrowLine object that represents the draw object.

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)

Note: Drawing objects with y values very far off the


visible canvas can lead to performance hits.
Fancier DashStyles like DashDotDot will also

© 2011 NinjaTrader, LLC


758 NinjaTrader Version 7

require more resources than simple DashStyles like


Solid.
width The width of the draw object

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.

Method Return Value


An IArrowUp object that represents the draw object.

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.

© 2011 NinjaTrader, LLC


NinjaScript 759

Method Return Value


An IDiamond object that represents the draw object.

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.

Method Return Value


An IDot object that represents the draw object.

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

© 2011 NinjaTrader, LLC


760 NinjaTrader Version 7

"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 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.

Method Return Value


An IEllipse object that represents the draw object.

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

© 2011 NinjaTrader, LLC


NinjaScript 761

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
// 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.

Method Return Value


An IExtendedLine object that represents the draw object.

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

© 2011 NinjaTrader, LLC


762 NinjaTrader Version 7

startY The startying 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 termiante
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)

Note: Drawing objects with y values very far off the


visible canvas can lead to performance hits.
Fancier DashStyles like DashDotDot will also
require more resources than simple DashStyles like
Solid.
opacity Sets the level of transparency for the fill color. Valid
values between 1 - 10.

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.

Method Return Value


An IFibonacciCircle object that represents the draw object.

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.

© 2011 NinjaTrader, LLC


NinjaScript 763

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 teh draw object will terminate
endY The end y value co-ordinate where the draw object
will terminate

Examples
// Draws a fibonnaci circle
DrawFibonacciCircle("tag1", true, 10, Low[10], 0,
High[0]);
10.4.4.21 DrawFibonacciExtensions()

Definition
Draws a fibonacci extension.

Method Return Value


An IFibonacciExtensions object that represents the draw object.

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

© 2011 NinjaTrader, LLC


764 NinjaTrader Version 7

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
DrawFibonacciExtensions("tag1", true, 4, Low[4], 3,
High[3], 1, Low[1]);

10.4.4.22 DrawFibonacciRetracements()

Definition
Draws a fibonacci retracement.

Method Return Value


An IFibonacciRetracements object that represents the draw object.

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

© 2011 NinjaTrader, LLC


NinjaScript 765

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.

Method Return Value


An IFibonacciTimeExtensions object that represents the draw object.

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.

© 2011 NinjaTrader, LLC


766 NinjaTrader Version 7

Method Return Value


An IGannFan object that represents the draw object.

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.

Method Return Value


An IHorizontalLine object that represents the draw object.

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)

© 2011 NinjaTrader, LLC


NinjaScript 767

dashStyle DashStyle.Dash
DashStyle.DashDot
DashStyle.DashDotDot
DashStyle.Dot
DashStyle.Solid
(reference)

Note: Fancier DashStyles like DashDotDot will


require more resources than simple DashStyles like
Solid.
width The width of the draw object

Examples
// Draws a horizontal line
DrawHorizontalLine("tag1", 1000, Color.Black);
10.4.4.26 DrawLine()

Definition
Draws a line between two points.

Method Return Value


An ILine object that represents the draw object.

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

© 2011 NinjaTrader, LLC


768 NinjaTrader Version 7

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)

Note: Drawing objects with y values very far off the


visible canvas can lead to performance hits.
Fancier DashStyles like DashDotDot will also
require more resources than simple DashStyles like
Solid.
width The width of the draw object

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()
{

© 2011 NinjaTrader, LLC


NinjaScript 769

if (DrawObjects["someTag"] != null &&


DrawObjects["someTag"].DrawType == DrawType.Line)
{
// Do something
}
}

// Example #2: Number of draw objects on a chart


protected override void OnBarUpdate()
{
if (DrawObjects.Count == 3)
{
// Do something
}
}

// Example #3: Looping through the collection to find


specific draw objects
protected override void OnBarUpdate()
{
// Loops through the DrawObjects collection
foreach (IDrawObject draw in DrawObjects)
{
// Finds line objects that are attached
globally to all charts of the same instrument
if (draw.Tag.StartsWith("@") && draw is
ILine)
{
ILine globalLine = (ILine) draw;

// Changes the line color and prints


its starting and end points
globalLine.Pen.Color = Color.Black;
Print("Start: " + globalLine.
StartBarsAgo + " End: " + globalLine.EndBarsAgo);
}

// Finds non-global line objects


else if (draw is ILine)
{
ILine drawnLine = (ILine) draw;

// Determines if this is a manually


drawn or script generated line
Print("Line Object: " + draw.Tag + "
Manually Drawn: " + draw.UserDrawn);
}
}
}

© 2011 NinjaTrader, LLC


770 NinjaTrader Version 7

10.4.4.28 DrawRay()

Definition
Draws a line which has an infinite end point in one direction.

Method Return Value


An IRay object that represents the draw object.

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)

Note: Drawing objects with y values very far off the


visible canvas can lead to performance hits.
Fancier DashStyles like DashDotDot will also
require more resources than simple DashStyles like
Solid.
width The width of the draw object

© 2011 NinjaTrader, LLC


NinjaScript 771

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.

Method Return Value


An IRectangle object that represents the draw object.

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.

© 2011 NinjaTrader, LLC


772 NinjaTrader Version 7

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);

// Draws a blue rectangle from the low 10 bars back


to the high of 5 bars back with
// a fill color or pale green with a transparency
level of 2
DrawRectangle("tag1", false, 10, Low[10] - TickSize,
5, High[5] + Ticksize, Color.PaleGreen, Color.
PaleGreen, 2);
10.4.4.30 DrawRegion()

Definition
Draws a region on a chart.

Method Return Value


An IRegion object that represents the draw object.

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.

© 2011 NinjaTrader, LLC


NinjaScript 773

endBarsAgo The end bar (x axis co-ordinate) where the draw


object will terminate
endTime The end time where the draw object will terminate
series, series1, Any DataSeries type object such as an indicator,
series2 Close, High, Low etc.. The value of the object will
represent a y value.
y Any double value
outlineColor Region outline color (reference)
areaColor Region fill color (reference)
areaOpacity Sets the level of transparency for the fill color. Valid
values between 1 - 10.

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.

Method Return Value


An IRegressionChannel object that represents the draw object.

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

© 2011 NinjaTrader, LLC


774 NinjaTrader Version 7

lowerDashStyle, int lowerWidth)

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)

Note: Fancier DashStyles like DashDotDot will


require more resources than simple DashStyles like
Solid.
upperColor, The line colors (reference)
middleColor,
lowerColor
upperWidth, The line width
middleWidth,
lowerWidth

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.

Method Return Value


An IRuler object that represents the draw object.

© 2011 NinjaTrader, LLC


NinjaScript 775

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.

Method Return Value


An ISquare object that represents the draw object.

Syntax
DrawSquare(string tag, bool autoScale, int barsAgo, double y, Color
color)

© 2011 NinjaTrader, LLC


776 NinjaTrader Version 7

DrawSquare(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 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.

Method Return Value


An IText object that represents the draw object.

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

© 2011 NinjaTrader, LLC


NinjaScript 777

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.
text The text you wish to draw
barsAgo The 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.
time The time where the draw object will be drawn.
y The y co-ordinate location the object will be drawn
yPixelOffset The offset value in pixels from within the text box
area
textColor The draw object color (reference)
font The type of font used (reference)
alignment StringAlignment.Center
StringAlignment.Far
StringAlignment.Near
(reference)
outlineColor Text box outline color (reference)
areaColor Text box fill color (reference)
areaOpacity Sets the level of transparency for the fill color. Valid
values between 1 - 10.

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.

Method Return Value


An ITextFixed object that represents the draw object.

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

© 2011 NinjaTrader, LLC


778 NinjaTrader Version 7

time, a new draw object will be created each time.


text The text you wish to draw
TextPosition TextPosition.BottomLeft
TextPosition.BottomRight
TextPosition.Center
TextPosition.TopLeft
TextPosition.TopRight
textColor The draw object color (reference)
font The type of font used (reference)
outlineColor Text box outline color (reference)
areaColor Text box back color (reference)
areaOpacity Sets the level of transparency for the fill color. Valid
values between 1 - 10.

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.

Method Return Value


An ITriangle object that represents the draw object.

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

© 2011 NinjaTrader, LLC


NinjaScript 779

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
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
// 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.

Method Return Value


An ITriangleDown object that represents the draw object.

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

© 2011 NinjaTrader, LLC


780 NinjaTrader Version 7

color The draw object color (reference)

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.

Method Return Value


An ITriangleUp object that represents the draw object.

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.

© 2011 NinjaTrader, LLC


NinjaScript 781

Method Return Value


An IVerticalLine object that represents the draw object.

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)

Note: Fancier DashStyles like DashDotDot will


require more resources than simple DashStyles like
Solid.
width The width of the draw object

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.

Methods and Properties


Anchor1BarsAgo An int value representing the number of bars ago
of the 1st anchor point
Anchor1Time A DateTime structure representing the time of the
1st anchor point
Anchor1Y A double value representing the y value of the 1st
anchor point
Anchor2BarsAgo An int value representing the number of bars ago

© 2011 NinjaTrader, LLC


782 NinjaTrader Version 7

of the 2nd anchor point


Anchor2Time A DateTime structure representing the time of the
2nd anchor point
Anchor2Y A double value representing the y value of the 2nd
anchor point
Anchor3BarsAgo An int value representing the number of bars ago
of the 3rd anchor point
Anchor3Time A DateTime structure representing the time of the
3rd anchor point
Anchor3Y A double value representing the y value of the 3rd
anchor point
CalculationMethod Possible values:

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]);

// Print the number of bars ago the first anchor


point is located at
Print(pitchfork.Anchor1BarsAgo);
}
10.4.4.41 IArc

Definition
Represents an interface that exposes information regarding an Arc IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
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

© 2011 NinjaTrader, LLC


NinjaScript 783

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);

// Print the number of bars ago the starting


point is located at
Print(arc.StartBarsAgo);
}
10.4.4.42 IArrowDown

Definition
Represents an interface that exposes information regarding an Arrow Down IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object
Color A Color structure representing the color of the draw
object
Time A DateTime structure representing the time of the
draw object
Y An int value representing the y value of the draw
object

Examples
protected override void OnBarUpdate()
{
// Draws an Arrow Down
IArrowDown arrow = DrawArrowDown("tag1", true,
0, High[0] + TickSize, Color.Red);

// Print the number of bars ago of the draw


object
Print(arrow.BarsAgo);
}

© 2011 NinjaTrader, LLC


784 NinjaTrader Version 7

10.4.4.43 IArrowLine

Definition
Represents an interface that exposes information regarding an Arrow Line IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
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
Pen The Pen object used to draw the object

Examples
protected override void OnBarUpdate()
{
// Draws an Arrow Line
IArrowLine arrow = DrawArrowLine("tag1", false,
10, 1000, 0, 1001, Color.LimeGreen, DashStyle.Dot,
2);

// Print the number of bars ago the starting


point is located at
Print(arrow.StartBarsAgo);
}
10.4.4.44 IArrowUp

Definition
Represents an interface that exposes information regarding an Arrow Up IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object
Color A Color structure representing the color of the draw
object
Time A DateTime structure representing the time of the
draw object
Y An int value representing the y value of the draw
object

© 2011 NinjaTrader, LLC


NinjaScript 785

Examples
protected override void OnBarUpdate()
{
// Draws an Arrow Up
IArrowUp arrow = DrawArrowUp("tag1", true, 0,
Low[0] - TickSize, Color.Red);

// Print the number of bars ago of the draw


object
Print(arrow.BarsAgo);
}
10.4.4.45 IDiamond

Definition
Represents an interface that exposes information regarding a Diamond IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object
Color A Color structure representing the color of the draw
object
Time A DateTime structure representing the time of the
draw object
Y An int value representing the y value of the draw
object

Examples
protected override void OnBarUpdate()
{
// Draws a diamond
IDiamond diamond = DrawDiamond("tag1", true, 0,
Low[0] - TickSize, Color.Red);

// Print the number of bars ago of the draw


object
Print(diamond.BarsAgo);
}
10.4.4.46 IDot

Definition
Represents an interface that exposes information regarding a Dot IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object

© 2011 NinjaTrader, LLC


786 NinjaTrader Version 7

Color A Color structure representing the color of the draw


object
Time A DateTime structure representing the time of the
draw object
Y An int value representing the y value of the draw
object

Examples
protected override void OnBarUpdate()
{
// Draws a dot
IDot dot = DrawDot("tag1", true, 0, Low[0] -
TickSize, Color.Red);

// Print the number of bars ago of the draw


object
Print(dot.BarsAgo);
}
10.4.4.47 IDrawObject

Definition
Represents an interface that exposes information regarding a draw object.

Methods and Properties


AutoScale A bool value representing if the draw object will be
included in the y-axis scale
DrawType Possible values are:

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

© 2011 NinjaTrader, LLC


NinjaScript 787

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.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
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

© 2011 NinjaTrader, LLC


788 NinjaTrader Version 7

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);

// Print the number of bars ago the starting


point is located at
Print(ellipse.StartBarsAgo);
}
10.4.4.49 IExtendedLine

Definition
Represents an interface that exposes information regarding an Extended Line IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
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
Pen The Pen object used to draw the object

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);

© 2011 NinjaTrader, LLC


NinjaScript 789

// Print the number of bars ago the starting


point is located at
Print(extLine.StartBarsAgo);
}
10.4.4.50 IFibonacciCircle

Definition
Represents an interface that exposes information regarding a Fibonacci Circle IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
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
ShowText A bool value representing if text will be drawn
along with the draw object

Examples
protected override void OnBarUpdate()
{
// Draws a Fibonacci Circle
IFibonacciCircle fibCircle = DrawFibonacciCircle
("tag1", true, 10, Low[10], 0, High[0]);

// Print the starting time the circle is located


at
Print(fibCircle.StartTime);
}
10.4.4.51 IFibonacciExtensions

Definition
Represents an interface that exposes information regarding a Fibonacci Extensions
IDrawObject.

Methods and Properties


Anchor1BarsAgo An int value representing the number of bars ago
of the 1st anchor point
Anchor1Time A DateTime structure representing the time of the
1st anchor point

© 2011 NinjaTrader, LLC


790 NinjaTrader Version 7

Anchor1Y A double value representing the y value of the 1st


anchor point
Anchor2BarsAgo An int value representing the number of bars ago
of the 2nd anchor point
Anchor2Time A DateTime structure representing the time of the
2nd anchor point
Anchor2Y A double value representing the y value of the 2nd
anchor point
Anchor3BarsAgo An int value representing the number of bars ago
of the 3rd anchor point
Anchor3Time A DateTime structure representing the time of the
3rd anchor point
Anchor3Y A double value representing the y value of the 3rd
anchor point
ExtendLeft A bool value representing if the object will extend
to the left
ExtendRight A bool value representing if the object will extend
to the right
ShowText A bool value representing if text will be drawn
along with the draw object

Examples
protected override void OnBarUpdate()
{
// Draws a Fibonacci Extension
IFibonacciExtensions fibExt =
DrawFibonacciExtensions("tag1", true, 4, Low[4], 3,
High[3], 1, Low[1]);

// Print the number of bars ago the starting


point is located at
Print(fibExt.StartBarsAgo);
}
10.4.4.52 IFibonacciRetracements

Definition
Represents an interface that exposes information regarding a Fibonacci Retracements
IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
starting point
EndBarsAgo An int value representing the number of bars ago

© 2011 NinjaTrader, LLC


NinjaScript 791

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
ExtendLeft A bool value representing if the object will extend
to the left
ExtendRight A bool value representing if the object will extend
to the right
ShowText A bool value representing if text will be drawn
along with the draw object

Examples
protected override void OnBarUpdate()
{
// Draws a Fibonacci Retracement
IFibonacciRetracements fibRetracements =
DrawFibonacciRetracements("tag1", true, 10, Low[10],
0, High[0]);

// Print the number of bars ago the starting


point is located at
Print(fibRetracements.StartBarsAgo);
}
10.4.4.53 IFibonacciTimeExtensions

Definition
Represents an interface that exposes information regarding a Fibonacci Time Extensions
IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
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
ShowText A bool value representing if text will be drawn
along with the draw object

© 2011 NinjaTrader, LLC


792 NinjaTrader Version 7

Examples
protected override void OnBarUpdate()
{
// Draws a Fibonacci Time Extension
IFibonacciTimeExtensions fibTimeExt =
DrawFibonacciTimeExtensions("tag1", 10, Low[10], 0,
High[0]);

// Print the number of bars ago the starting


point is located at
Print(fibTimeExt.StartBarsAgo);
}
10.4.4.54 IGannFan

Definition
Represents an interface that exposes information regarding a Gann Fan IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object
Time A DateTime structure representing the time of the
draw object
Y An int value representing the y value of the draw
object
GannFanDirection Possible values:

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]);

// Print the number of bars ago of the draw


object
Print(gann.BarsAgo);
}

© 2011 NinjaTrader, LLC


NinjaScript 793

10.4.4.55 IHorizontalLine

Definition
Represents an interface that exposes information regarding a Horizontal Line IDrawObject.

Methods and Properties


Y An double value representing the y-value the
object is drawn at
Pen The Pen object used to draw the object

Examples
protected override void OnBarUpdate()
{
// Draws a Horizontal Line
IHorizontalLine hLine = DrawHorizontalLine
("tag1", 1000, Color.Black);

// Print the y-value the line is drawn at


Print(hLine.Y);
}
10.4.4.56 ILine

Definition
Represents an interface that exposes information regarding a Line IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
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
Pen The Pen object used to draw the object

Examples
protected override void OnBarUpdate()
{
// Draws a Line
ILine line = DrawLine("tag1", false, 10, 1000,
0, 1001, Color.LimeGreen, DashStyle.Dot, 2);

© 2011 NinjaTrader, LLC


794 NinjaTrader Version 7

// Print the time the starting point is located


at
Print(line.StartTime);
}
10.4.4.57 IRay

Definition
Represents an interface that exposes information regarding a Ray IDrawObject.

Methods and Properties


Anchor1BarsAgo An int value representing the number of bars ago
of the 1st anchor point
Anchor1Time A DateTime structure representing the time of the
1st anchor point
Anchor1Y A double value representing the y value of the 1st
anchor point
Anchor2BarsAgo An int value representing the number of bars ago
of the 2nd anchor point
Anchor2Time A DateTime structure representing the time of the
2nd anchor point
Anchor2Y A double value representing the y value of the 2nd
anchor point
Pen The Pen object used to draw the object

Examples
protected override void OnBarUpdate()
{
// Draws a ray
IRay ray = DrawRay("tag1", 10, 1000, 0, 1001,
Color.LimeGreen);

// Print the number of bars ago the 2nd anchor


point is located at
Print(ray.Anchor2BarsAgo);
}
10.4.4.58 IRectangle

Definition
Represents an interface that exposes information regarding a Rectangle IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the

© 2011 NinjaTrader, LLC


NinjaScript 795

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);

// Print the number of bars ago the starting


point is located at
Print(rectangle.StartBarsAgo);
}
10.4.4.59 IRegion

Definition
Represents an interface that exposes information regarding a Region IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
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
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
Y A double representing a y-value the draw object is
drawn to

© 2011 NinjaTrader, LLC


796 NinjaTrader Version 7

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);

// Print the number of bars ago the starting


point is located at
Print(region.StartBarsAgo);
}
10.4.4.60 IRegressionChannel

Definition
Represents an interface that exposes information regarding a Regression Channel
IDrawObject.

Methods and Properties


StartBarsAgo An int value representing the number of bars ago
of the starting point
StartTime A DateTime structure representing the time of the
starting point
StartY A double value representing the y value of the
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
Pen The Pen object used to draw the middle line of the
object
PenLower The Pen object used to draw the lower line of the
object
PenUpper The Pen object used to draw the upper line of the
object
PriceType Possible values are:

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

© 2011 NinjaTrader, LLC


NinjaScript 797

ExtendLeft A bool value representing if the object will extend


to the left
ExtendRight A bool value representing if the object will extend
to the right
StdDevLower A double value representing the standard deviation
distance to the lower line
StdDevUpper A double value representing the standard deviation
distance to the upper line

Examples
protected override void OnBarUpdate()
{
// Draws a rectangle
IRegressionChannel regression =
DrawRegressionChannel("tag1", 10, 0, Color.Blue);

// Print the number of bars ago the starting


point is located at
Print(regression.StartBarsAgo);
}
10.4.4.61 IRuler

Definition
Represents an interface that exposes information regarding a Ruler IDrawObject.

Methods and Properties


Anchor1BarsAgo An int value representing the number of bars ago
of the 1st anchor point
Anchor1Time A DateTime structure representing the time of the
1st anchor point
Anchor1Y A double value representing the y value of the 1st
anchor point
Anchor2BarsAgo An int value representing the number of bars ago
of the 2nd anchor point
Anchor2Time A DateTime structure representing the time of the
2nd anchor point
Anchor2Y A double value representing the y value of the 2nd
anchor point
Anchor3BarsAgo An int value representing the number of bars ago
of the 3rd anchor point
Anchor3Time A DateTime structure representing the time of the
3rd anchor point
Anchor3Y A double value representing the y value of the 3rd
anchor point

© 2011 NinjaTrader, LLC


798 NinjaTrader Version 7

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]);

// Print the number of bars ago the starting


point is located at
Print(ruler.StartBarsAgo);
}
10.4.4.62 ISquare

Definition
Represents an interface that exposes information regarding a Square IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object
Color A Color structure representing the color of the draw
object
Time A DateTime structure representing the time of the
draw object
Y An int value representing the y value of the draw
object

Examples
protected override void OnBarUpdate()
{
// Draws a square
ISquare square = DrawSquare("tag1", true, 0, Low
[0] - TickSize, Color.Red);

// Print the number of bars ago of the draw


object
Print(square.BarsAgo);
}
10.4.4.63 IText

Definition
Represents an interface that exposes information regarding a Text IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object

© 2011 NinjaTrader, LLC


NinjaScript 799

Time A DateTime structure representing the time of the


draw object
Y An int value representing the y value of the draw
object
YPixelOffset An int value representing the offset value in pixels
from within the text box area
Alignment Possible values are:

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);

// Print the text drawn on the chart


Print(text.Text);
}
10.4.4.64 ITextFixed

Definition
Represents an interface that exposes information regarding a Text Fixed IDrawObject.

Methods and Properties


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
TextPosition Possible values are:

TextPosition.BottomLeft
TextPosition.BottomRight

© 2011 NinjaTrader, LLC


800 NinjaTrader Version 7

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);

// Print the text drawn on the chart


Print(textFixed.Text);
}
10.4.4.65 ITriangle

Definition
Represents an interface that exposes information regarding a Triangle IDrawObject.

Methods and Properties


Anchor1BarsAgo An int value representing the number of bars ago
of the 1st anchor point
Anchor1Time A DateTime structure representing the time of the
1st anchor point
Anchor1Y A double value representing the y value of the 1st
anchor point
Anchor2BarsAgo An int value representing the number of bars ago
of the 2nd anchor point
Anchor2Time A DateTime structure representing the time of the
2nd anchor point
Anchor2Y A double value representing the y value of the 2nd
anchor point
Anchor3BarsAgo An int value representing the number of bars ago
of the 3rd anchor point
Anchor3Time A DateTime structure representing the time of the
3rd anchor point
Anchor3Y A double value representing the y value of the 3rd
anchor point
AreaColor A bool value representing if the object will extend
to the left
AreaOpacity An int value representing the opacity of the area
color
Pen The Pen object used to draw the object

© 2011 NinjaTrader, LLC


NinjaScript 801

Examples
protected override void OnBarUpdate()
{
// Draws a Triangle
ITriangle tri = DrawTriangle("tag1", 4, Low[4],
3, High[3], 1, Low[1], Color.Blue);

// Print the number of bars ago the first anchor


point is located at
Print(tri.Anchor1BarsAgo);
}
10.4.4.66 ITriangleDown

Definition
Represents an interface that exposes information regarding a Triangle Down IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object
Color A Color structure representing the color of the draw
object
Time A DateTime structure representing the time of the
draw object
Y An int value representing the y value of the draw
object

Examples
protected override void OnBarUpdate()
{
// Draws a Triangle Down
ITriangleDown triangle = DrawTriangleDown
("tag1", true, 0, Low[0] - TickSize, Color.Red);

// Print the number of bars ago of the draw


object
Print(triangle.BarsAgo);
}
10.4.4.67 ITriangleUp

Definition
Represents an interface that exposes information regarding a Triangle Up IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object

© 2011 NinjaTrader, LLC


802 NinjaTrader Version 7

Color A Color structure representing the color of the draw


object
Time A DateTime structure representing the time of the
draw object
Y An int value representing the y value of the draw
object

Examples
protected override void OnBarUpdate()
{
// Draws a Triangle Up
ITriangleUp triangle = DrawTriangleUp("tag1",
true, 0, Low[0] - TickSize, Color.Red);

// Print the number of bars ago of the draw


object
Print(triangle.BarsAgo);
}
10.4.4.68 IVerticalLine

Definition
Represents an interface that exposes information regarding a Vertical Line IDrawObject.

Methods and Properties


BarsAgo An int value representing the number of bars ago
of the draw object
Time A DateTime structure representing the time of the
draw object
Pen The Pen object used to draw the object

Examples
protected override void OnBarUpdate()
{
// Draws a Vertical Line
IVerticalLine vLine = DrawVerticalLine("tag1",
10, Color.Black);

// Print the number of bars ago the line is


located at
Print(vLine.BarsAgo);
}
10.4.4.69 InHitTest

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

© 2011 NinjaTrader, LLC


NinjaScript 803

select the indicator or not.

NOTE: Please see the CustomPlotSample indicator for an example.

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

© 2011 NinjaTrader, LLC


804 NinjaTrader Version 7

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)

NOTE: To add Bars objects to your indicator see this article.

Parameters
plot A Plot object
line A Line object

Examples
// Adds a blue line style plot
Add(new Plot(Color.Blue, "myPlot"));

// Adds a blue historgram style plot


Add(new Plot(Color.Blue, PlotStyle.Bar, "myPlot"));

// Adds a blue line style plot with a thickness of 3


Add(new Plot(new Pen(Color.Blue, 3), "myPlot"))

// Adds an oscillator line at a value of 30


Add(new Line(Color.Gray, 30, "Lower"));

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

© 2011 NinjaTrader, LLC


NinjaScript 805

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.

protected override void Initialize()


{
// Add three plots and associated DataSeries
objects
Add(new Plot(Color.Blue, "PlotA")); // Defines
the plot for Values[0]
Add(new Plot(Color.Red, "PlotB")); // Defines
the plot for Values[1]
Add(new Plot(Color.Green, "PlotC")); // Defines
the plot for Values[2]
}
10.4.5.2 AutoScale

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.

© 2011 NinjaTrader, LLC


806 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 807

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

protected override string FormatPriceMarker(double price)


{

© 2011 NinjaTrader, LLC


808 NinjaTrader Version 7

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)

© 2011 NinjaTrader, LLC


NinjaScript 809

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]
}

// Dynamically change the upper line's color and


thickness based on the indicator value
protected override void OnBarUpdate()
{
if (Value[0] > 70)
Lines[1].Pen = new Pen(Color.Blue, 3);
else
Lines[1].Pen = new Pen(Color.Gray, 1);
}
10.4.5.11 LinesConfigurable

Definition
If true, any indicator line(s) are configurable within the indicator dialog window.

© 2011 NinjaTrader, LLC


810 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 811

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

© 2011 NinjaTrader, LLC


812 NinjaTrader Version 7

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"));
}

protected override void OnBarUpdate()


{
// Sets values to our two plots
Upper.Set(SMA(High, 20)[0]);
Lower.Set(SMA(Low, 20)[0]);

// Color the Upper plot based on plot value


conditions
if (Rising(Upper))
PlotColors[0][0] = Color.Blue;
else if (Falling(Upper))
PlotColors[0][0] = Color.Red;
else
PlotColors[0][0] = Color.Yellow;

// Color the Lower plot based on plot value


conditions
if (Rising(Lower))
PlotColors[1][0] = Color.Blue;
else if (Falling(Lower))

© 2011 NinjaTrader, LLC


NinjaScript 813

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]
}

// Dynamically change the primary plot's color based


on the indicator value
protected override void OnBarUpdate()
{
if (Value[0] > 70)
Plots[0].Pen = new Pen(Color.Blue);
else
Plots[0].Pen = new Pen(Color.Red);
}
10.4.5.17 PlotsConfigurable

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

© 2011 NinjaTrader, LLC


814 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 815

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.

© 2011 NinjaTrader, LLC


816 NinjaTrader Version 7

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;

protected override void OnBarUpdate()


{
if (CurrentBar < 20)

© 2011 NinjaTrader, LLC


NinjaScript 817

return;

tripleValue = SMA(20)[0] * 3;
Value.Set(SMA(20)[0]);
}

public double TripleValue


{
get
{
Update();
return tripleValue;
}
}
10.4.5.23 Value

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;

// Checks the indicator primary value 1 bar ago


and sets the value of the indicator
// for the current bar being evaluated
if (Value[1] < High[0] - Low[0])
Value.Set(High[0] - Low[0]);
else
Value.Set(High[0] - Close[0]);
}

Tips
1. The DataSeries object referenced by this property is created by calling the Add() method.

© 2011 NinjaTrader, LLC


818 NinjaTrader Version 7

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;

// Checks the indicator's secondary value 1 bar


ago and sets the value of the indicator
// for the current bar being evaluated
if (Values[1][1] < High[0] - Low[0])
Value.Set(High[0] - Low[0]);
else
Value.Set(High[0] - Close[0]);
}
10.4.5.25 VerticalGridLines

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()
{

© 2011 NinjaTrader, LLC


NinjaScript 819

Add(new Plot(Color.Orange, "SMA"));


VerticalGridLines = false; // Vertical grid
lines will not plot on the indicator panel
}

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.

// Printing the current value of the 10 period SMA of


closing prices
// using the default input.
double value = SMA(10)[0];
Print("The current SMA value is " + value.ToString
());

Price Series
Open, High, Low, Close and Volume can all be used as input for an indicator method.

// Passing in the a price series of High prices and


printing out the current value of the
// 14 period simple moving average
double value = SMA(High, 14)[0];
Print("The current SMA value is " + value.ToString
());

Indicator
Indicators can be used as input for indicators.

// Printing the current value of the 20 period simple


moving average of a 14 period RSI
// using a data series of closing prices
double value = SMA(RSI(Close, 14), 20)[0];
Print("The current SMA value is " + value.ToString
());

© 2011 NinjaTrader, LLC


820 NinjaTrader Version 7

DataSeries
DataSeries can be used as input for indicators.

// Instantiating a new DataSeries object and passing


it in as input to calculate
// a simple moving average
DataSeries myDataSeries = new DataSeries(this);
double value = SMA(myDataSeries, 20)[0];

Bars Object
A Bars object (holds a series of bar object that contain OHLC data) can be used as input for
indicators.

// Passing in the second Bars object held in a multi-


instrument and timeframe strategy
// The default value used for the SMA calculation is
the close price
double value = SMA(BarsArray[1], 20)[0];
Print("The current SMA value is " + value.ToString
());

Tips
1. The input series of an indicator cannot be the hosting indicator as it will cause recursive
loops.

// Using the hosting indicator like below will cause


errors with recursive loops
double value = SMA(this, 20)[0];
10.4.6.2 Accumulation/Distribution (ADL)

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)

Returns default value

© 2011 NinjaTrader, LLC


NinjaScript 821

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)

Returns upper band value


APZ(double barPct, int period).Upper[int barsAgo]
APZ(IDataSeries input, double barPct, int period).Upper[int barsAgo
]

Returns lower band value


APZ(double barPct, int period).Lower[int barsAgo]
APZ(IDataSeries input, double barPct, int period).Lower[int barsAgo
]

© 2011 NinjaTrader, LLC


822 NinjaTrader Version 7

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]

Returns down value

© 2011 NinjaTrader, LLC


NinjaScript 823

Aroon(int period).Down[int barsAgo]


Aroon(IDataSeries input, int period).Down[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.

... Courtesy of Investopedia

Syntax
AroonOscillator(int period)
AroonOscillator(IDataSeries input, int period)

Returns default value


AroonOscillator(int period)[int barsAgo]
AroonOscillator(IDataSeries input, int period)[int barsAgo]

© 2011 NinjaTrader, LLC


824 NinjaTrader Version 7

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());

// Prints the current values of a 20 period


AroonOscillator using high price type
double upValue = AroonOscillator(High, 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.

... Courtesy of Investopedia

Syntax
ADX(int period)
ADX(IDataSeries input, int period)

Returns default value


ADX(int period)[int barsAgo]
ADX(IDataSeries input, int period)[int barsAgo]

Return Value

© 2011 NinjaTrader, LLC


NinjaScript 825

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
());

// Prints the current value of a 20 period ADX using


high price type
double value = ADX(High, 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)

Returns default value


ADXR(int interval, int period)[int barsAgo]
ADXR(IDataSeries input, int interval, 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 (?)

© 2011 NinjaTrader, LLC


826 NinjaTrader Version 7

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 True Range indicator is the greatest of the following:


-current high less the current low.
-the absolute value of the current high less the previous close.
-the absolute value of the current low less the previous close.

The Average True Range is a moving average (generally 14-days) of the True Ranges.

... Courtesy of Investopedia

Syntax
ATR(int period)
ATR(IDataSeries input, int period)

Returns default value


ATR(int period)[int barsAgo]
ATR(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 (?)

© 2011 NinjaTrader, LLC


NinjaScript 827

period Number of bars used in the calculation

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)

Returns default value


BOP(int smooth)[int barsAgo]
BOP(IDataSeries input, int smooth)[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 (?)
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
());

© 2011 NinjaTrader, LLC


828 NinjaTrader Version 7

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.

1. A simple moving average in the middle


2. An upper band (SMA plus 2 standard deviations)
3. A lower band (SMA minus 2 standard deviations)

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.

... Courtesy of StockCharts

Syntax
Bollinger(double numStdDev, int period)
Bollinger(IDataSeries input, double numStdDev, int period)

Returns upper band value


Bollinger(double numStdDev, int period).Upper[int barsAgo]
Bollinger(IDataSeries input, double numStdDev, int period).Upper[
int barsAgo]

Returns lower band value


Bollinger(double numStdDev, int period).Lower[int barsAgo]
Bollinger(IDataSeries input, double numStdDev, int period).Lower[
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

© 2011 NinjaTrader, LLC


NinjaScript 829

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());

// Prints the current upper band value of a 20 period


Bollinger using low price type
double upperValue = Bollinger(Low, 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)

Returns buy pressure value


BuySellPressure().BuyPressure[int barsAgo]
BuySellPressure(IDataSeries input).BuyPressure[int barsAgo]

Returns sell pressure value


BuySellPressure().SellPressure[int barsAgo]
BuySellPressure(IDataSeries input).SellPressure[int barsAgo]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.

Parameters

© 2011 NinjaTrader, LLC


830 NinjaTrader Version 7

input Indicator source data (?)

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();
}
}

// !! Since this indicator operates in a real-time


environment, you must take special
// care in coding your strategy so that it is only
evaluated in in real-time and not
// in a backtest on historical data. In the above
example, we check for our breakout
// long signal but we also want to make sure that the
breakout bar saw 70% or more
// of its trades hit the ask or higher. Our statement
checks if the data is being
// calculated on historical data first, if true, we
enter long, if not true (live), the
// the statement then checks for the BuyPressure
condition.

Source Code
You can view this indicator method source code by selecting the menu Tools > Edit
NinjaScript > Indicator within the NinjaTrader Control Center window.

© 2011 NinjaTrader, LLC


NinjaScript 831

10.4.6.12 BuySell Volume

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)

© 2011 NinjaTrader, LLC


832 NinjaTrader Version 7

Returns a value indicating if the specified pattern was detected


CandleStickPattern(ChartPattern pattern, int trendStrength)[int
barsAgo]
CandleStickPattern(IDataSeries input, ChartPattern pattern, int
trendStrength)[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 (?)
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

© 2011 NinjaTrader, LLC


NinjaScript 833

// Go long if the current bar is a bullish engulfing


pattern
if (CandelStickPattern(ChartPattern.BullishEngulfing,
4)[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.
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.

... Courtesy of StockCharts

Syntax
ChaikinMoneyFlow(int period)
ChaikinMoneyFlow(IDataSeries input, int period)

Returns default value


ChaikinMoneyFlow(int period)[int barsAgo]
ChaikinMoneyFlow(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 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

© 2011 NinjaTrader, LLC


834 NinjaTrader Version 7

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.

... Courtesy of StockCharts

Syntax
ChaikinOscillator(int fast, int slow)
ChaikinOscillator(IDataSeries input, int fast, int slow)

Returns default value


ChaikinOscillator(int fast, int slow)[int barsAgo]
ChaikinOscillator(IDataSeries input, int fast, int slow)[int
barsAgo]

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.

© 2011 NinjaTrader, LLC


NinjaScript 835

10.4.6.16 Chaikin Volatility

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.

... Courtesy of Prophet

Syntax
ChaikinVolatility(int period)
ChaikinVolatility(IDataSeries input, int period)

Returns default value


ChaikinVolatility(int period)[int barsAgo]
ChaikinVolatility(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 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

© 2011 NinjaTrader, LLC


836 NinjaTrader Version 7

- 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)

Returns default value


CMO(int period)[int barsAgo]
CMO(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 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
());

// Prints the current value of a 20 period CMO using


high price type
double value = CMO(High, 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.

... Courtesy of StockCharts

© 2011 NinjaTrader, LLC


NinjaScript 837

Syntax
CCI(int period)
CCI(IDataSeries input, int period)

Returns default value


CCI(int period)[int barsAgo]
CCI(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 value of a 20 period CCI using
default price type
double value = CCI(20)[0];
Print("The current CCI value is " + value.ToString
());

// Prints the current value of a 20 period CCI using


high price type
double value = CCI(High, 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)

© 2011 NinjaTrader, LLC


838 NinjaTrader Version 7

Returns current session open value


CurrentDayOHL().CurrentOpen[int barsAgo]
CurrentDayOHL(IDataSeries input).CurrentOpen[int barsAgo]

Returns current session high value


CurrentDayOHL().CurrentHigh[int barsAgo]
CurrentDayOHL(IDataSeries input).CurrentHigh[int barsAgo]

Returns current session low value


CurrentDayOHL().CurrentLow[int barsAgo]
CurrentDayOHL(IDataSeries input).CurrentLow[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 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.

... Courtesy of Investopedia

Syntax
Darvas()
Darvas(IDataSeries input)

Returns the upper value

© 2011 NinjaTrader, LLC


NinjaScript 839

Darvas().Upper[int barsAgo]
Darvas(IDataSeries input).Upper[int barsAgo]

Returns the lower value


Darvas().Lower[int barsAgo]
Darvas(IDataSeries input).Lower[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)

Returns default ADX value


DM(int period)[int barsAgo]
DM(IDataSeries input, int period)[int barsAgo]

Returns +DI value


DM(int period).DiPlus[int barsAgo]
DM(IDataSeries input, int period).DiPlus[int barsAgo]

Returns -DI value


DM(int period).DiMinus[int barsAgo]
DM(IDataSeries input, int period).DiMinus[int barsAgo]

© 2011 NinjaTrader, LLC


840 NinjaTrader Version 7

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.

... Courtesy of Investopedia

Syntax
DMI(int period)
DMI(IDataSeries input, int period)

Returns default value


DMI(int period)[int barsAgo]
DMI(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 (?)

© 2011 NinjaTrader, LLC


NinjaScript 841

period Number of bars used in the calculation

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)

Returns mean value (middle band)


DonchianChannel(int period)[int barsAgo]
DonchianChannel(IDataSeries input, int period)[int barsAgo]

Returns upper band value


DonchianChannel(int period).Upper[int barsAgo]
DonchianChannel(IDataSeries input, int period).Upper[int barsAgo]

Returns lower band value


DonchianChannel(int period).Lower[int barsAgo]
DonchianChannel(IDataSeries input, int period).Lower[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

© 2011 NinjaTrader, LLC


842 NinjaTrader Version 7

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());

// Prints the current lower value of a 20 period


DonchianChannel using high price type
double value = DonchianChannel(High, 20).Lower[0];
Print("The current DonchianChannel lower 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 default value


DoubleStochastics(int period)[int barsAgo]
DoubleStochastics(IDataSeries input, int period)[int barsAgo]

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

© 2011 NinjaTrader, LLC


NinjaScript 843

double value = DoubleStochastics(10)[0];


Print("The current Double Stochastics value is " +
value.ToString());

// Prints the current %K value


double value = DoubleStochastics(10).K[0];
Print("The current Double Stochastics %K 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.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.

... Courtesy of Investopedia

Syntax
DMIndex(int smooth)
DMIndex(IDataSeries input, int smooth)

Returns default value


DMIndex(int period)[int barsAgo]
DMIndex(IDataSeries input, int smooth)[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 (?)
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.

© 2011 NinjaTrader, LLC


844 NinjaTrader Version 7

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)

Returns default value


EaseOfMovement(int smoothing, int volumeDivisor)[int barsAgo]
EaseOfMovement(IDataSeries input, int smoothing, int volumeDivisor)
[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 (?)
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());

© 2011 NinjaTrader, LLC


NinjaScript 845

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.

... Courtesy of Prophet

Syntax
FisherTransform(int period)
FisherTransform(IDataSeries input, int period)

Returns default value


FisherTransform(int period)[int barsAgo]
FisherTransform(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 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.

© 2011 NinjaTrader, LLC


846 NinjaTrader Version 7

10.4.6.28 Forecast Oscillator (FOSC)

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.

... Courtesy of FM Labs

Syntax
FOSC(int period)
FOSC(IDataSeries input, int period)

Returns default value


FOSC(int period)[int barsAgo]
FOSC(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
// 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.

© 2011 NinjaTrader, LLC


NinjaScript 847

10.4.6.29 Heiken Ashi

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)

Returns Heiken-Ashi open value


HeikenAshi().HAOpen[int barsAgo]
HeikenAshi(IDataSeries input)[int barsAgo]

Returns Heiken-Ashi high value


HeikenAshi().HAHigh[int barsAgo]
HeikenAshi(IDataSeries input)[int barsAgo]

Returns Heiken-Ashi low value


HeikenAshi().HALow[int barsAgo]
HeikenAshi(IDataSeries input)[int barsAgo]

Returns Heiken-Ashi close value


HeikenAshi().HAClose[int barsAgo]
HeikenAshi(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
// Prints the current HA open value
double value = HeikenAshi().HAOpen[0];
Print("The current Heiken-Ashi open value is " +
value.ToString());

// Prints the current HA close value


double value = HeikenAshi().HAClose[0];
Print("The current Heiken-Ashi close value is " +
value.ToString());

© 2011 NinjaTrader, LLC


848 NinjaTrader Version 7

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)

Returns midline value


KeltnerChannel(double offsetMutiplier, int period)[int barsAgo]
KeltnerChannel(IDataSeries input, double offsetMutiplier, int
period)[int barsAgo]

Returns upper band value


KeltnerChannel(double offsetMutiplier, int period).Upper[int
barsAgo]
KeltnerChannel(IDataSeries input, double offsetMutiplier, int
period).Upper[int barsAgo]

Returns lower band value


KeltnerChannel(double offsetMutiplier, int period).Lower[int
barsAgo]
KeltnerChannel(IDataSeries input, double offsetMutiplier, int
period).Lower[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
KeltnerChannel using default price type

© 2011 NinjaTrader, LLC


NinjaScript 849

double value = KeltnerChannel(1.5, 20).Upper[0];


Print("The current KeltnerChannel upper value is " +
value.ToString());

// Prints the current lower value of a 20 period


DonchianChannel using high price type
double value = KeltnerChannel(High, 1.5, 20).Lower
[0];
Print("The current KeltnerChannel lower 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.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)

Returns default value


KeyReversalDown(int period)[int barsAgo]
KeyReversalDown(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
protected override void OnBarUpdate()
{
// If we get a reversal over the past 10 bars go
short
if (KeyReversalDown(10)[0] == 1)
EnterShort();

© 2011 NinjaTrader, LLC


850 NinjaTrader Version 7

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)

Returns default value


KeyReversalUp(int period)[int barsAgo]
KeyReversalUp(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
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.

© 2011 NinjaTrader, LLC


NinjaScript 851

10.4.6.33 Linear Regression

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.

... Courtesy of Prophet

Syntax
LinReg(int period)
LinReg(IDataSeries input, int period)

Returns default value


LinReg(int period)[int barsAgo]
LinReg(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 value of a 20 period LinReg
using default price type
double value = LinReg(20)[0];
Print("The current LinReg value is " + value.ToString
());

// Prints the current value of a 20 period LinReg


using high price type
double value = LinReg(High, 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.

© 2011 NinjaTrader, LLC


852 NinjaTrader Version 7

10.4.6.34 Linear Regression Intercept

Description
The Linear Regression Intercept provides the intercept value of the Linear Regression
trendline.

Syntax
LinRegIntercept(int period)
LinRegIntercept(IDataSeries input, int period)

Returns default value


LinRegIntercept(int period)[int barsAgo]
LinRegIntercept(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 intercept value of a 20 period
LinReg using default price type
double value = LinRegIntercept(20)[0];
Print("The current intercept value is " + value.
ToString());

// Prints the current intercept value of a 20 period


LinReg using high price type
double value = LinRegIntercept(High, 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.

© 2011 NinjaTrader, LLC


NinjaScript 853

Syntax
LinRegSlope(int period)
LinRegSlope(IDataSeries input, int period)

Returns default value


LinRegSlope(int period)[int barsAgo]
LinRegSlope(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 slope value of a 20 period
LinReg using default price type
double value = LinRegSlope(20)[0];
Print("The current slope value is " + value.ToString
());

// Prints the current slope value of a 20 period


LinReg using high price type
double value = LinRegSlope(High, 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.

... Courtesy of Prophet

Syntax
MAEnvelopes(double envelopePercentage, int mAType, int period)

© 2011 NinjaTrader, LLC


854 NinjaTrader Version 7

MAEnvelopes(IDataSeries input, double envelopePercentage, int


mAType, int period)

Returns upper band levels


MAEnvelopes(double envelopePercentage, int mAType, int period).
Upper[int barsAgo]
MAEnvelopes(IDataSeries input, double envelopePercentage, int
mAType, int period).Upper[int barsAgo]

Returns moving average value


MAEnvelopes(double envelopePercentage, int mAType, int period).
Middle[int barsAgo]
MAEnvelopes(IDataSeries input, double envelopePercentage, int
mAType, int period).Middle[int barsAgo]

Returns lower band levels


MAEnvelopes(double envelopePercentage, int mAType, int period).
Lower[int barsAgo]
MAEnvelopes(IDataSeries input, double envelopePercentage, int
mAType, int period).Lower[int barsAgo]

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());

// Prints the current lower band value of a 20 period

© 2011 NinjaTrader, LLC


NinjaScript 855

SMA envelope using low price type


double lowerValue = MAEnvelopes(Low, 0.2, 3, 20).
Lower[0];
Print("The current SMA envelope lower value is " +
lowerValue.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)

Returns default value


MAX(int period)[int barsAgo]
MAX(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 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.

© 2011 NinjaTrader, LLC


856 NinjaTrader Version 7

10.4.6.38 Minimum (MIN)

Description
Returns the lowest value over the specified period.

Syntax
MIN(int period)
MIN(IDataSeries input, int period)

Returns default value


MIN(int period)[int barsAgo]
MIN(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 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.

... Courtesy of Prophet

Syntax

© 2011 NinjaTrader, LLC


NinjaScript 857

Momentum(int period)
Momentum(IDataSeries input, int period)

Returns default value


Momentum(int period)[int barsAgo]
Momentum(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 value of a 20 period Momentum
using default price type
double value = Momentum(20)[0];
Print("The current Momentum value is " + value.
ToString());

// Prints the current value of a 20 period Momentum


using high price type
double value = Momentum(High, 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.

... Courtesy of StockCharts

Syntax
MFI(int period)

© 2011 NinjaTrader, LLC


858 NinjaTrader Version 7

MFI(IDataSeries input, int period)

Returns default value


MFI(int period)[int barsAgo]
MFI(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 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.

... Courtesy of Prophet

Syntax
DEMA(int period)
DEMA(IDataSeries input, int period)

Returns default value


DEMA(int period)[int barsAgo]
DEMA(IDataSeries input, int period)[int barsAgo]

Return Value

© 2011 NinjaTrader, LLC


NinjaScript 859

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
());

// Prints the current value of a 20 period DEMA using


high price type
double value = DEMA(High, 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.

... Courtesy of Prophet

Syntax
EMA(int period)
EMA(IDataSeries input, int period)

Returns default value


EMA(int period)[int barsAgo]
EMA(IDataSeries input, int period)[int barsAgo]

Return Value

© 2011 NinjaTrader, LLC


860 NinjaTrader Version 7

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
());

// Prints the current value of a 20 period EMA using


high price type
double value = EMA(High, 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)

Returns default value


HMA(int period)[int barsAgo]
HMA(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.

© 2011 NinjaTrader, LLC


NinjaScript 861

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
());

// Prints the current value of a 20 period HMA using


high price type
double value = HMA(High, 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)

Returns default value


KAMA(int fast, int period, int slow)[int barsAgo]
KAMA(IDataSeries input, int fast, int period, int slow)[int barsAgo
]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.

Parameters
fast Fast length

© 2011 NinjaTrader, LLC


862 NinjaTrader Version 7

input Indicator source data (?)


period Number of bars used in the calculation
slow Slow 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
());

// Prints the current value of a 20 period KAMA using


high price type
double value = HMA(High, 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)

Returns MAMA value


MAMA(double fastLimit, double slowLimit)[int barsAgo]
MAMA(IDataSeries input, double fastLimit, double slowLimit)[int
barsAgo]

Returns Fama (Following Adaptive Moving Average) value


MAMA(double fastLimit, double slowLimit).Fama[int barsAgo]
MAMA(IDataSeries input, double fastLimit, double slowLimit).Fama[
int barsAgo]

Return Value

© 2011 NinjaTrader, LLC


NinjaScript 863

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
());

// Prints the current value of a 20 period Fama using


high price type
double value = MAMA(High, 0.5, 0.05).Fama[0];
Print("The current Fama 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.

... Courtesy of Prophet

Syntax
SMA(int period)
SMA(IDataSeries input, int period)

Returns default value


SMA(int period)[int barsAgo]
SMA(IDataSeries input, int period)[int barsAgo]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator

© 2011 NinjaTrader, LLC


864 NinjaTrader Version 7

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 SMA using
default price type
double value = SMA(20)[0];
Print("The current SMA value is " + value.ToString
());

// Prints the current value of a 20 period SMA using


high price type
double value = SMA(High, 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.

... Courtesy of FMLabs

Syntax
T3(int period, int tCount, double vFactor)
T3(IDataSeries input, int period, int tCount, double vFactor)

Returns default value


T3(int period, int tCount, double vFactor)[int barsAgo]
T3(IDataSeries input, int period, int tCount, double vFactor)[int
barsAgo]

Return Value

© 2011 NinjaTrader, LLC


NinjaScript 865

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());

// Prints the current value of a 20 period T3 using


high price type
double value = T3(High, 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)

Returns default value


TMA(int period)[int barsAgo]
TMA(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.

© 2011 NinjaTrader, LLC


866 NinjaTrader Version 7

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
());

// Prints the current value of a 20 period TMA using


high price type
double value = TMA(High, 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)

Returns default value


TEMA(int period)[int barsAgo]
TEMA(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

© 2011 NinjaTrader, LLC


NinjaScript 867

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
());

// Prints the current value of a 20 period TEMA using


high price type
double value = TEMA(High, 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.

... Courtesy of Investopedia

Syntax
TRIX(int period, int signalPeriod)
TRIX(IDataSeries input, int period, int signalPeriod)

Returns trix value


TRIX(int period, int signalPeriod)[int barsAgo]
TRIX(IDataSeries input, int period, int signalPeriod)[int barsAgo]

Returns signal value


TRIX(int period, int signalPeriod).Signal[int barsAgo]
TRIX(IDataSeries input, int period, int signalPeriod).Signal[int
barsAgo]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.

Parameters

© 2011 NinjaTrader, LLC


868 NinjaTrader Version 7

input Indicator source data (?)


period Number of bars used in the calculation
signalPeriod Period for signal line

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
());

// Prints the current signal value of a 20 period


TRIX using high price type
double value = TRIX(High, 20, 3).Signal[0];
Print("The current TRIX signal 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)

Returns default value


VMA(int period, int volatilityPeriod)[int barsAgo]
VMA(IDataSeries input, int period, int volatilityPeriod)[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

© 2011 NinjaTrader, LLC


NinjaScript 869

volatilityPeriod The number of bars used to calculate the CMO


based volatility index

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());

// Go long if price closes above the current VMA


value
if (Close[0] > VMA(9, 9)[0])
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.
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)

Returns default value


VWMA(int period)[int barsAgo]
VWMA(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

© 2011 NinjaTrader, LLC


870 NinjaTrader Version 7

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");

// Prints the current 14 period VWMA of high


prices to the output window
double value = VWMA(High, 14)[0];
Print("The current VWMA value of high prices 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.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)

Returns default value


WMA(int period)[int barsAgo]
WMA(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

© 2011 NinjaTrader, LLC


NinjaScript 871

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
());

// Prints the current value of a 20 period WMA using


high price type
double value = WMA(High, 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.

... Courtesy of FMLabs

Syntax
ZLEMA(int period)
ZLEMA(IDataSeries input, int period)

Returns default value


ZLEMA(int period)[int barsAgo]
ZLEMA(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 value of a 20 period ZLEMA

© 2011 NinjaTrader, LLC


872 NinjaTrader Version 7

using default price type


double value = ZLEMA(20)[0];
Print("The current SMA value is " + value.ToString
());

// Prints the current value of a 20 period ZLEMA


using high price type
double value = ZLEMA(High, 20)[0];
Print("The current ZLEMA 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.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.

... Courtesy of StockCharts

Syntax
MACD(int fast, int slow, int smooth)
MACD(IDataSeries input, int fast, int slow, int smooth)

Returns MACD value


MACD(int fast, int slow, int smooth)[int barsAgo]
MACD(IDataSeries input, int fast, int slow, int smooth)[int barsAgo
]

Returns average value


MACD(int fast, int slow, int smooth).Avg[int barsAgo]
MACD(IDataSeries input, int fast, int slow, int smooth).Avg[int
barsAgo]

Returns difference value


MACD(int fast, int slow, int smooth).Diff[int barsAgo]
MACD(IDataSeries input, int fast, int slow, int smooth).Diff[int
barsAgo]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.

© 2011 NinjaTrader, LLC


NinjaScript 873

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
());

// Prints the current MACD average value


double value = MACD(12, 26, 9).Avg[0];
Print("The current MACD average value is " + value.
ToString());

// Prints the current MACD difference value


double value = MACD(12, 26, 9).Diff[0];
Print("The current MACD difference 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)

Returns default value


NBarsDown(int barCount, bool BarDown, bool lowerHigh, bool lowerLow
)[int barsAgo]
NBarsDown(IDataSeries input, bool barCount, int BarDown, bool
lowerHigh, bool lowerLow)[int barsAgo]

© 2011 NinjaTrader, LLC


874 NinjaTrader Version 7

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)

Returns default value


NBarsUp(int barCount, int barCount, bool BarUp, bool higherHigh,
bool higherLow)[int barsAgo]
NBarsUp(IDataSeries input, int barCount, bool BarUp, bool
higherHigh, bool higherLow)[int barsAgo]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator

© 2011 NinjaTrader, LLC


NinjaScript 875

value of the referenced bar.

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.

... Courtesy of StockCharts

Syntax
OBV()
OBV(IDataSeries input)

Returns default value


OBV()[int barsAgo]
OBV(IDataSeries input)[int barsAgo]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.

© 2011 NinjaTrader, LLC


876 NinjaTrader Version 7

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.

... Courtesy of Investopedia

Syntax
ParabolicSAR(double acceleration, double accelerationStep, double
accelerationMax)
ParabolicSAR(IDataSeries input, double acceleration, double
accelerationStep, double accelerationMax)

Returns default value


ParabolicSAR(double acceleration, double accelerationStep, double
accelerationMax)[int barsAgo]
ParabolicSAR(IDataSeries input, double acceleration, double
accelerationStep, double accelerationMax)[int barsAgo]

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

© 2011 NinjaTrader, LLC


NinjaScript 877

input Indicator source data (?)

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)

Returns default value


PPO(int fast, int slow, int smooth)[int barsAgo]
PPO(IDataSeries input, int fast, int slow, int smooth)[int barsAgo]

Returns smoothed value


PPO(int fast, int slow, int smooth).Smoothed[int barsAgo]
PPO(IDataSeries input, int fast, int slow, int smooth).Smoothed[int
barsAgo]

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

© 2011 NinjaTrader, LLC


878 NinjaTrader Version 7

// Prints the current value of a 20 period Percentage


Price Oscillator
double value = PPO(12, 26, 9)[0];
Print("The current Percentage Price 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.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.

... Courtesy of Investopedia

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 pivot point value


Pivots(PivotRange pivotRangeType, HLCCalculationMode priorDayHLC,
double userDefinedClose, double userDefinedHigh, double
userDefinedLow, int width).PP[int barsAgo]
Pivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, double userDefinedClose, double
userDefinedHigh, double userDefinedLow, int width).PP[int barsAgo]

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]

© 2011 NinjaTrader, LLC


NinjaScript 879

Pivots(IDataSeries input, 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

© 2011 NinjaTrader, LLC


880 NinjaTrader Version 7

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());

// Prints the current S2 pivot value


double value = Pivots(PivotRange.Daily,
HLCCalculationMode.CalcFromIntradayData, 0, 0, 0,
20).S2[0];
Print("The current Pivots' S2 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:

// Checks that this is a valid pivot point value


if (Pivots(PivotRange.Daily, HLCCalculationMode.
DailyBars, 0, 0, 0, 20).PP.ContainsValue(0))
{
// Prints the current pivot point value

© 2011 NinjaTrader, LLC


NinjaScript 881

double value = Pivots(PivotRange.Daily,


HLCCalculationMode.DailyBars, 0, 0, 0, 20).PP[0];
Print("The current Pivots' pivot value is " +
value.ToString());
}
10.4.6.62 Polarized Fractal Efficiency (PFE)

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.

... Courtesy of FMLabs

Syntax
PFE(int period)
PFE(IDataSeries input, int period)

Returns default value


PFE(int period)[int barsAgo]
PFE(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 value of a 20 period PFE using
default price type
double value = PFE(20)[0];
Print("The current PFE value is " + value.ToString
());

// Prints the current value of a 20 period PFE using


high price type
double value = PFE(High, 20)[0];
Print("The current PFE value is " + value.ToString
());

© 2011 NinjaTrader, LLC


882 NinjaTrader Version 7

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.

... Courtesy of StockCharts

Syntax
PriceOscillator(int fast, int slow, int smooth)
PriceOscillator(IDataSeries input, int fast, int slow, int smooth)

Returns default value


PriceOscillator(int fast, int slow, int smooth)[int barsAgo]
PriceOscillator(IDataSeries input, int fast, int slow, int smooth)[
int barsAgo]

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.

© 2011 NinjaTrader, LLC


NinjaScript 883

10.4.6.64 Prior Day OHLC

Description
The prior day (session) open, high, low and close values.

Syntax
PriorDayOHLC()
PriorDayOHLC(IDataSeries input)

Returns prior session open value


PriorDayOHLC().PriorOpen[int barsAgo]
PriorDayOHLC(IDataSeries input).PriorOpen[int barsAgo]

Returns prior session high value


PriorDayOHLC().PriorHigh[int barsAgo]
PriorDayOHLC(IDataSeries input).PriorHigh[int barsAgo]

Returns prior session low value


PriorDayOHLC().PriorLow[int barsAgo]
PriorDayOHLC(IDataSeries input).PriorLow[int barsAgo]

Returns prior session close value


PriorDayOHLC().PriorClose[int barsAgo]
PriorDayOHLC(IDataSeries input).PriorClose[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 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.

© 2011 NinjaTrader, LLC


884 NinjaTrader Version 7

10.4.6.65 Range

Description
Returns the range of a bar.

Syntax
Range()
Range(IDataSeries input)

Returns default value


Range()[int barsAgo]
Range(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 (?)
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
());

// Prints the 20 period simple moving average of


range
double value = SMA(Range(), 20)[0];
Print("The 20 period average of 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

© 2011 NinjaTrader, LLC


NinjaScript 885

Indicator is at a low level, a new trend is about to start.

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)

Returns default value


RIND(int periodQ, int smooth)[int barsAgo]
RIND(IDataSeries input, int periodQ, int smooth)[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 (?)
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.

© 2011 NinjaTrader, LLC


886 NinjaTrader Version 7

... Courtesy of StockCharts

Syntax
ROC(int period)
ROC(IDataSeries input, int period)

Returns default value


ROC(int period)[int barsAgo]
ROC(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 value of a 20 period ROC using
default price type
double value = ROC(20)[0];
Print("The current ROC value is " + value.ToString
());

// Prints the current value of a 20 period ROC using


high price type
double value = ROC(High, 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

© 2011 NinjaTrader, LLC


NinjaScript 887

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)

Returns default midline value


RegressionChannel(int period, int width)[int barsAgo]
RegressionChannel(IDataSeries input, int period, int width)[int
barsAgo]

Returns upper channel value


RegressionChannel(int period, int width).Upper[int barsAgo]
RegressionChannel(IDataSeries input, int period, int width).Upper[
int barsAgo]

Returns lower channel value


RegressionChannel(int period, int width).Lower[int barsAgo]
RegressionChannel(IDataSeries input, int period, int width).Lower[
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
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

© 2011 NinjaTrader, LLC


888 NinjaTrader Version 7

// Prints the current value of a 20 period channel


using default price type
double value = RegressionChannel(20, 2).Upper[0];
Print("The current upper channel 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.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)

Returns default value


RSS(int eMA1, int eMA2, int length)[int barsAgo]
RSS(IDataSeries input, int eMA1, int eMA2, int length)[int barsAgo]

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
());

// Prints the current value of the RSS using high


price type
double value = RSS(High, 10, 40, 5)[0];

© 2011 NinjaTrader, LLC


NinjaScript 889

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.

... Courtesy of StockCharts

Syntax
RSI(int period, int smooth)
RSI(IDataSeries input, int period, int smooth)

Returns default value


RSI(int period, int smooth)[int barsAgo]
RSI(IDataSeries input, int period, int smooth)[int barsAgo]

Returns avg value


RSI(int period, int smooth).Avg[int barsAgo]
RSI(IDataSeries input, int period, int smooth).Avg[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
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

© 2011 NinjaTrader, LLC


890 NinjaTrader Version 7

());

// Prints the current value of a 20 period RSI using


high price type
double value = RSI(High, 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)

Returns default value


RVI(int period)[int barsAgo]
RVI(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
// OnBarUpdate method of a stratgegy
protected override void OnBarUpdate()
{
// Check for buy condition
if (RVI(14)[0] > 50 && CrossAbove(SMA(9), SMA
(14), 1))

© 2011 NinjaTrader, LLC


NinjaScript 891

{
// 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.

... Courtesy of FMLabs

Syntax
RSquared(int period)
RSquared(IDataSeries input, int period)

Returns default value


RSquared(int period)[int barsAgo]
RSquared(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 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());

// Prints the current value of a 20 period R-squared


using high price type

© 2011 NinjaTrader, LLC


892 NinjaTrader Version 7

double value = RSquared(High, 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.

... Courtesy of Wikipedia

Syntax
StdDev(int period)
StdDev(IDataSeries input, int period)

Returns default value


StdDev(int period)[int barsAgo]
StdDev(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 value of a 20 period StdDev
using default price type
double value = StdDev(20)[0];
Print("The current StdDev value is " + value.ToString
());

// Prints the current value of a 20 period StdDev


using high price type
double value = StdDev(High, 20)[0];

© 2011 NinjaTrader, LLC


NinjaScript 893

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.

... Courtesy of Wikipedia

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]

Returns upper value


StdError(int period).Upper[int barsAgo]
StdError(IDataSeries input, int period).Upper[int barsAgo]

Returns lower value


StdError(int period).Lower[int barsAgo]
StdError(IDataSeries input, int period).Lower[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

© 2011 NinjaTrader, LLC


894 NinjaTrader Version 7

StdError using default price type


double value = StdError(20).Upper[0];
Print("The current upper Standard Error 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.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).

... Courtesy of StockCharts

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

© 2011 NinjaTrader, LLC


NinjaScript 895

Examples
// Prints the current %D value
double value = Stochastics(3, 14, 7).D[0];
Print("The current Stochastics %D value is " + value.
ToString());

// Prints the current %K value


double value = Stochastics(3, 14, 7).K[0];
Print("The current Stochastics %K 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).

... Courtesy of StockCharts

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.

© 2011 NinjaTrader, LLC


896 NinjaTrader Version 7

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());

// Prints the current %K value


double value = StochasticsFast(3, 14).K[0];
Print("The current StochasticsFast %K 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)

Returns default value


StochRSI(int period)[int barsAgo]
StochRSI(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

© 2011 NinjaTrader, LLC


NinjaScript 897

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)

Returns default value


SUM(int period)[int barsAgo]
SUM(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 value of a 20 period SUM using
default price type
double value = SUM(20)[0];
Print("The current SUM value is " + value.ToString
());

// Prints the current value of a 20 period SUM using


high price type

© 2011 NinjaTrader, LLC


898 NinjaTrader Version 7

double value = SUM(High, 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.

Syntax - Bars Ago


High Bar
Swing(int strength).SwingHighBar(int barsAgo, int instance, int
lookBackPeriod)
Swing(IDataSeries input, int strength).SwingHighBar(int barsAgo,
int instance, int lookBackPeriod)

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

© 2011 NinjaTrader, LLC


NinjaScript 899

"strength" value or a swing pivot has not yet been found.

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."

... Courtesy of Prophet

Syntax
TSF(int forecast, int period)
TSF(IDataSeries input, int forecast, int period)

Returns default value


TSF(int forecast, int period)[int barsAgo]
TSF(IDataSeries input, int forecast, int period)[int barsAgo]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator

© 2011 NinjaTrader, LLC


900 NinjaTrader Version 7

value of the referenced bar.

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.

... Courtesy of Prophet

Syntax
TSI(int fast, int slow)
TSI(IDataSeries input, int fast, int slow)

Returns default value


TSI(int fast, int slow)[int barsAgo]
TSI(IDataSeries input, int fast, int slow)[int barsAgo]

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

© 2011 NinjaTrader, LLC


NinjaScript 901

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
());

// Prints the current value of a 20 period TSI using


high price type
double value = TSI(High, 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)

Returns default value


UltimateOscillator(int fast, int intermediate, int slow)[int
barsAgo]
UltimateOscillator(IDataSeries input, int fast, int intermediate,
int slow)[int barsAgo]

Return Value
double; Accessing this method via an index value [int barsAgo] returns the indicator
value of the referenced bar.

Parameters

© 2011 NinjaTrader, LLC


902 NinjaTrader Version 7

fast The number of bars to include in the short term


period
input Indicator source data (?)
intermediate The number of bars to include in the intermediate
term period
slow The number of bars to include in the long term
period

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.

... Courtesy of MarketScreen

Syntax
VOL()
VOL(IDataSeries input)

Returns default value


VOL()[int barsAgo]
VOL(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 (?)

© 2011 NinjaTrader, LLC


NinjaScript 903

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)

Returns default value


VOLMA(int period)[int barsAgo]
VOLMA(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
// 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");
}

© 2011 NinjaTrader, LLC


904 NinjaTrader Version 7

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)

Returns default value


VolumeOscillator(int fast, int slow)[int barsAgo]
VolumeOscillator(IDataSeries input, int fast, int slow)[int barsAgo
]

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.

© 2011 NinjaTrader, LLC


NinjaScript 905

10.4.6.86 Volume Rate of Change (VROC)

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)

Returns default value


VROC(int period, int smooth)[int barsAgo]
VROC(IDataSeries input, int period, int smooth)[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
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)

© 2011 NinjaTrader, LLC


906 NinjaTrader Version 7

Returns default value


VolumeUpDown()[int barsAgo]
VolumeUpDown(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
// 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.

... Courtesy of StockCharts

Syntax
WilliamsR(int period)
WilliamsR(IDataSeries input, int period)

Returns default value


WilliamsR(int period)[int barsAgo]
WilliamsR(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.

© 2011 NinjaTrader, LLC


NinjaScript 907

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());

// Prints the current value of a 20 period WilliamsR


using high price type
double value = WilliamsR(High, 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)

Returns default value


WoodiesCCI()[int barsAgo]
WoodiesCCI(IDataSeries input)[int barsAgo]

Returns turbo value


WoodiesCCI().Turbo[int barsAgo]
WoodiesCCI(IDataSeries input).Turbo[int barsAgo]

Returns histogram bar color


WoodiesCCI().ZoneBars[int barsAgo]
WoodiesCCI(IDataSeries input).ZoneBars[int barsAgo]

Return values representing the chopzone plot color are as follows:


0 = Negative (default color is red)
1 = Positive (default color is blue)

© 2011 NinjaTrader, LLC


908 NinjaTrader Version 7

2 = Neutral (default color is gray)


3 = Last neutral bar (default color is yellow)

Returns chopzone value


WoodiesCCI().ChopZone[int barsAgo]
WoodiesCCI(IDataSeries input).ChopZone[int barsAgo]

Return values representing the chopzone plot color are as follows:

-4 = DarkRed
-3 = LightRed
-2 = DarkOrange
-1 = LightOrange
0 = Yellow
1 = Lime
2 = LightGreen
3 = DarkGreen
4 = Cyan

Returns sidewinder value


WoodiesCCI().Sidewinder[int barsAgo]
WoodiesCCI(IDataSeries input).Sidewinder[int barsAgo]

Return values representing the sidewinder plot value are as


follows:

-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());

// Prints the current turbo value of a 20 period


WoodiesCCI using default price type

© 2011 NinjaTrader, LLC


NinjaScript 909

double value = WoodiesCCI(20).Turbo[0];


Print("The current WoodiesCCI turbo value is " +
value.ToString());
10.4.6.90 Woodies Pivots

Description
Woodies CCI Club pivots indicator.

Syntax
WoodiesPivots(PivotRange pivotRangeType, HLCCalculationMode
priorDayHLC, int width)
WoodiesPivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, int width)

Returns pivot point value


WoodiesPivots(PivotRange pivotRangeType, HLCCalculationMode
priorDayHLC, int width).PP[int barsAgo]
WoodiesPivots(IDataSeries input, PivotRange pivotRangeType,
HLCCalculationMode priorDayHLC, int width).PP[int barsAgo]

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

© 2011 NinjaTrader, LLC


910 NinjaTrader Version 7

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());

// Prints the current S2 pivot value


double value = WoodiesPivots(PivotRange.Daily,
HLCCalculationMode.CalcFromIntradayData, 20).S2[0];
Print("The current Woodies Pivots' S2 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:

// Checks that this is a valid Woodies Pivots value


if (WoodiesPivots(PivotRange.Daily,
HLCCalculationMode.DailyBars, 20).PP.ContainsValue
(0))
{
// Prints the current pivot point value
double value = WoodiesPivots(PivotRange.Daily,
HLCCalculationMode.DailyBars, 20).PP[0];
Print("The current Woodies Pivots' pivot value
is " + value.ToString());

© 2011 NinjaTrader, LLC


NinjaScript 911

}
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.

Syntax - Bars Ago


High Bar
ZigZag(DeviationType deviationType, double deviationValue, bool
useHighLow).HighBar(int barsAgo, int instance, int lookBackPeriod)
ZigZag(IDataSeries input, DeviationType deviationType, double
deviationValue, bool useHighLow).HighBar(int barsAgo, int instance,
int lookBackPeriod)

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.

© 2011 NinjaTrader, LLC


912 NinjaTrader Version 7

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

Advanced event-driven strategy programming is reserved for EXPERIENCED programmers.

NinjaTrader is unlike traditional strategy development platforms in that it is not limited to


processing your strategy logic on a bar by bar basis. NinjaTrader is a true real-time trading
platform and thus can be driven by real-time events.

In addition to the OnBarUpdate() and Initialize() methods, NinjaScript exposes the following
advanced event-driven methods:

OnConnectionStatus() - Called when a connection state changes


OnExecution() - Called when a strategy generated order is filled
OnFundamentalData() - Called on any change in fundamental data
OnMarketData() - Called on any change in a level 1 market data stream
OnMarketDepth() - Called on any change in a level 2 market data stream

© 2011 NinjaTrader, LLC


NinjaScript 913

OnOrderUpdate() - Called when a strategy generated order changes state


OnPositionUpdate() - Called when a strategy generated position changes
OnStartUp() - Called once when a script first starts up
OnTermination() - Called once when a script is terminated

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)

NOTE: To add Bars objects to your strategy see this article.

Parameters
indicator An indicator object

© 2011 NinjaTrader, LLC


914 NinjaTrader Version 7

Examples
protected override void Initialize()
{
// Charts a 20 period simple moving average to
the chart
Add(SMA(20));
}

10.4.7.4 ATM Strategy Methods

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.

ATM Strategy Management ATM Strategy Monitoring


AtmStrategyCancelEntryOrder() GetAtmStrategyEntryOrderStatus()
AtmStrategyChangeEntryOrder() GetAtmStrategyMarketPosition()
AtmStrategyChangeStopTarget() GetAtmStrategyPositionAveragePrice
AtmStrategyClose() ()
AtmStrategyCreate() GetAtmStrategyPositionQuantity()
GetAtmStrategyRealizedProfitLoss()
GetAtmStrategyStopTargetOrderStatu
s()
GetAtmStrategyUniqueId()
GetAtmStrategyUnrealizedProfitLoss()

10.4.7.4.1 AtmStrategyCancelEntryOrder()

Definition
Cancels the specified entry order.

Method Return Value


Returns true if the specified order was found; otherwise false.

Syntax
AtmStrategyCancelEntryOrder(string orderId)

Parameters
orderId The unique identifier for the entry order

Examples
protected override void OnBarUpdate()
{

© 2011 NinjaTrader, LLC


NinjaScript 915

AtmStrategyCancelEntryOrder("orderIdValue");
}
10.4.7.4.2 AtmStrategyChangeEntryOrder()

Definition
Changes the price of the specified entry order.

Method Return Value


Returns true if the specified order was found; otherwise false.

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.

Method Return Value


Returns true if the specified order was found; otherwise false.

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()

© 2011 NinjaTrader, LLC


916 NinjaTrader Version 7

{
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.

Method Return Value


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
AtmStrategyClose(string AtmStrategyId)

Parameters
AtmStrategyId The unique identifier for the ATM strategy

Examples
protected override void OnBarUpdate()
{
if (Historical)
return;

// Check for valid condition and create an ATM


Strategy
if (GetAtmStrategyUnrealizedProfitLoss
("idValue") > 500)
AtmStrategyClose("idValue");
}
10.4.7.4.5 AtmStrategyCreate()

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.

Please review the section on using ATM Strategies


This method is not backtestable and will not execute on historical data
Executions resulting from the ATM Strategy will not be plotted on the chart
See the AtmStrategyCancelEntryOrder() to cancel an entry order
See the AtmStrategyChangeEntryOrder() to change the price of the entry order

Method Return Value

© 2011 NinjaTrader, LLC


NinjaScript 917

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;

// Check for valid condition and create an ATM


Strategy
if (Close[0] > SMA(20)[0])
AtmStrategyCreate(OrderAction.Buy,
OrderType.Market, 0, 0,
TimeInForce.Day, GetAtmStrategyUniqueId
(), "MyTemplate",
GetAtmStrategyUniqueId());

© 2011 NinjaTrader, LLC


918 NinjaTrader Version 7

*** LINK TO USING ATM STRATEGIES ***


10.4.7.4.6 GetAtmStrategyEntryOrderStatus()

Definition
Gets the current state of the specified entry order. If the method can't find the specified order,
an empty array is returned.

Method Return Value


A string[] array holding three elements that represent average fill price, filled amount and
order state.

Syntax
GetAtmStrategyEntryOrderStatus(string orderId)

Parameters
orderId The unique identifier for the entry order

Examples
protected override void OnBarUpdate()
{
string[] entryOrder =
GetAtmStrategyEntryOrderStatus("orderId");

// Check length to ensure that returned array


holds order information
if (entryOrder.Length > 0)
{
Print("Average fill price is " + entryOrder
[0].ToString());
Print("Filled amount is " + entryOrder[1].
ToString());
Print("Current state is " + entryOrder[2].
ToString());
}
}
10.4.7.4.7 GetAtmStrategyMarketPosition()

Definition
Gets the current market position of the specified ATM Strategy.

Method Return Value


MarketPosition.Flat
MarketPosition.Long
MarketPosition.Short

© 2011 NinjaTrader, LLC


NinjaScript 919

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.

Method Return Value


A double value representing the average price.

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.

Method Return Value

© 2011 NinjaTrader, LLC


920 NinjaTrader Version 7

An int value representing the quantity.

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.

Method Return Value


A double value representing the realized profit and loss.

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

© 2011 NinjaTrader, LLC


NinjaScript 921

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.

Method Return Value


A string[,] multi-dimensional array holding three dimensions that represent average fill
price, filled amount and order state. The length (number of elements) represents the number
of orders that represent the specified name.

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");

// Check length to ensure that returned array


holds order information
if (orders.Length > 0)
{
for (int i = 0; i < orders.GetLength(0); i+
+)
{
Print("Average fill price is " +
orders[i, 0].ToString());
Print("Filled amount is " + orders[i,
1].ToString());
Print("Current state is " + orders[i,
2].ToString());
}
}
}
10.4.7.4.12 GetAtmStrategyUniqueId()

Definition
Generates a unique id value.

Method Return Value


A string value representing a unique id value.

© 2011 NinjaTrader, LLC


922 NinjaTrader Version 7

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.

Method Return Value


A double value representing the unrealized profit and loss.

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

© 2011 NinjaTrader, LLC


NinjaScript 923

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.

Method Return Value


An int value that represents a number of bars.

Syntax
BarsSinceEntry()
BarsSinceEntry(string signalName)

The following method signature should be used when working with multi-time frame and
instrument strategies:

BarsSinceEntry(int barsInProgressIndex, string signalName, int


entriesAgo)

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)

© 2011 NinjaTrader, LLC


924 NinjaTrader Version 7

return;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterLong();
}
10.4.7.7 BarsSinceExit()

Definition
Returns the number of bars that have elapsed since the last specified exit.

Method Return Value


An int value that represents a number of bars. A value of -1 will be returned if a previous exit
does not exist.

Syntax
BarsSinceExit()
BarsSinceExit(string signalName)

The following method signature should be used when working with multi-time frame and
instrument strategies:

BarsSinceExit(int barsInProgressIndex, string signalName, int


exitsAgo)

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;

© 2011 NinjaTrader, LLC


NinjaScript 925

// Only enter if at least 10 bars has passed


since our last exit
if (BarsSinceExit() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterLong();
}
10.4.7.8 ConnectionLossHandling

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.

Recalculate: Strategies will attempt to recalculate its strategy position when a


connection is reestablished and held for longer than RestartDelaySeconds (default = 10).
Recalculations will only occur if the strategy was stopped based on the conditions below.
Should the connection be reestablished before the strategy was stopped, the strategy will
continue running without recalculating as if no disconnect occurred.
If data feed disconnects for longer than the time specified in DisconnectDelaySeconds,
the strategy is stopped and a disconnect email alert will be sent.
If the order feed disconnects and the strategy places an order action while
disconnected, the strategy is stopped and a disconnect email alert will be sent.
If both the data and order feeds disconnect for longer than the time specified in
DisconnectDelaySeconds, the strategy is stopped and a disconnect email alert will be
sent.

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;
}

© 2011 NinjaTrader, LLC


926 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 927

protected override void OnBarUpdate()


{
// Disable strategy at 2PM
if (ToTime(Time[0]) == 140000)
Disable();
}
10.4.7.12 DisconnectDelaySeconds

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;
}

© 2011 NinjaTrader, LLC


928 NinjaTrader Version 7

protected override void OnBarUpdate()


{
if (CrossAbove(SMA(10), SMA(20), 1)
EnterLong("SMA Cross Entry");

if (CrossAbove(RSI(14, 3), 30, 1)


EnterLong("RSI Cross Entry);
}

// Example #2
// EnterLong() will be processed once for each
uniquely named entry.
protected override void Initialize()
{
EntriesPerDirection = 1;
EntryHandling = EntryHandling.UniqueEntries;
}

protected override void OnBarUpdate()


{
if (CrossAbove(SMA(10), SMA(20), 1)
EnterLong("SMA Cross Entry");

if (CrossAbove(RSI(14, 3), 30, 1)


EnterLong("RSI Cross Entry);
}
10.4.7.14 EntryHandling

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

© 2011 NinjaTrader, LLC


NinjaScript 929

protected override void Initialize()


{
EntriesPerDirection = 2;
EntryHandling = EntryHandling.AllEntries;
}

protected override void OnBarUpdate()


{
if (CrossAbove(SMA(10), SMA(20), 1)
EnterLong("SMA Cross Entry");
}

// Example #2
// EnterLong() will be processed once for each
uniquely named entry.
protected override void Initialize()
{
EntriesPerDirection = 1;
EntryHandling = EntryHandling.UniqueEntries;
}

protected override void OnBarUpdate()


{
if (CrossAbove(SMA(10), SMA(20), 1)
EnterLong("SMA Cross Entry");

if (CrossAbove(RSI(14, 3), 30, 1)


EnterLong("RSI Cross Entry);
}

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

© 2011 NinjaTrader, LLC


930 NinjaTrader Version 7

protected override void Initialize()


{
// Excludes trade history for memory savings in
a backtest
ExcludeTradeHistoryInBacktest = true;
}
10.4.7.16 ExitOnClose

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.

Note: This property is a real-time only property.

Property Value
An int value representing the number of seconds.

Syntax
ExitOnCloseSeconds

Examples
protected override void Initialize()
{

© 2011 NinjaTrader, LLC


NinjaScript 931

// Triggers the exit on close function 30


seconds prior to session end
ExitOnClose = true;
ExitOnCloseSeconds = 30;
}
10.4.7.18 ForceMaximumBarsLookBack256

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.

Method Return Value


A double value that represents the specified account item. A value of 0 will be returned on
historical bars.

Syntax
GetAccountValue(AccountItem accountItem)

Parameters
accountItem Possible values:
AccountItem.BuyingPower
AccountItem.CashValue
AccountItem.RealizedProfitLoss

Examples
protected override void OnBarUpdate()

© 2011 NinjaTrader, LLC


932 NinjaTrader Version 7

{
// 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().

Methods and Properties


Commission A double value representing the commission of an
execution
ExecutionId A string value representing the exchange
generated execution id
Instrument An Instrument value representing the instrument of
an order
MarketPosition Possible values are:
MarketPosition.Long
MarketPosition.Short
Name A string representing the name of an order which
can be provided by the entry or exit signal name
Order An IOrder value representing an order associated to
the execution. Note: Not all executions will have
associated IOrder objects (e.g.ExitOnClose
executions)
Price A double value representing the price of an
execution
Quantity An int value representing quantity of an execution
Time A DateTime structure representing the time the
execution occurred
Token A string representing the unique id of an
execution
ToString() A string representation of an execution

Examples
private IOrder entryOrder = null;

© 2011 NinjaTrader, LLC


NinjaScript 933

protected override void OnBarUpdate()


{
if (entryOrder == null && Close[0] > Open[0])
entryOrder = EnterLong();
}

protected override void OnExecution(IExecution


execution)
{
if (entryOrder != null && entryOrder ==
execution.Order)
Print(execution.ToString());
}
10.4.7.21 IncludeCommission

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

Methods and Properties

© 2011 NinjaTrader, LLC


934 NinjaTrader Version 7

OrderAction Possible values are:

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

© 2011 NinjaTrader, LLC


NinjaScript 935

Quantity An int value representing the quantity of an order


StopPrice A double value representing the stop price of an
order
Time A DateTime structure representing the last time the
order changed state
TimeInForce Possible values are:

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();
}

protected override void OnOrderUpdate(IOrder order)


{
if (entryOrder != null && entryOrder == order)
{
Print(order.ToString());
if (order.OrderState == OrderState.Filled)

© 2011 NinjaTrader, LLC


936 NinjaTrader Version 7

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.

Methods and Properties


AvgPrice A double value representing the average price of a
position
Instrument An Instrument value representing the instrument of
an order
MarketPosition Possible values are:

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

© 2011 NinjaTrader, LLC


NinjaScript 937

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.

Programming to this method is considered advanced programming and exposed for


experienced programmers
You can not start a strategy without a "Connected" connection
The connection event is for the connection where the traded account resides

© 2011 NinjaTrader, LLC


938 NinjaTrader Version 7

Method Return Value


This method does not return a value.

Method Parameters
ConnectionStatus orderStatus and priceStatus

Possible values are:

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.

orderStatus - Status of the broker's order server


priceStatus - Status of the price server

Syntax
You must override the method in your strategy with the following syntax.

protected override void OnConnectionStatus(ConnectionStatus orderStatus,


ConnectionStatus priceStatus)
{

Examples
private ConnectionStatus dataFeed = ConnectionStatus.
Connected;
protected override void OnOrderUpdate(IOrder order)
{
if (dataFeed != ConnectionStatus.Connected)
{
// Do something
}
}

protected override void OnConnectionStatus


(ConnectionStatus orderStatus, ConnectionStatus
priceStatus)
{
dataFeed = priceStatus;
}

Additional Reference Samples

© 2011 NinjaTrader, LLC


NinjaScript 939

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.

Programming to this method is considered advanced programming and exposed for


experienced programmers
An order can generate multiple executions (partial fills)
OnExecution is always called after OnOrderUpdate() is called

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 Return Value


This method does not return a value.

Method Parameters
IExecution execution

Syntax
You must override the method in your strategy with the following syntax.

protected override void OnExecution(IExecution execution)


{

Examples
private IOrder entryOrder = null;

protected override void OnBarUpdate()


{
if (entryOrder == null && Close[0] > Open[0])
entryOrder = EnterLong();
}

protected override void OnExecution(IExecution


execution)
{
if (entryOrder != null && entryOrder ==
execution.Order)
Print(execution.ToString());
}

© 2011 NinjaTrader, LLC


940 NinjaTrader Version 7

Additional Reference Samples


Additional reference code samples are available the NinjaScript Educational Resources
section of our support forum.
10.4.7.28 OnFundamentalData()

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.

Programming to this method is considered advanced programming and exposed for


experienced programmers
You can program your own order rejection handling

NinjaTrader is a multi-threaded application and therefore it is extremely important to


understand

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

© 2011 NinjaTrader, LLC


NinjaScript 941

high speed market replays.

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 Return Value


This method does not return a value.

Method Parameters
IOrder order

Syntax
You must override the method in your strategy with the following syntax.

protected override void OnOrderUpdate(IOrder order)


{

Examples
private IOrder entryOrder = null;

protected override void OnBarUpdate()


{
if (entryOrder == null && Close[0] > Open[0])
entryOrder = EnterLong();
}

protected override void OnOrderUpdate(IOrder order)


{
if (entryOrder != null && entryOrder == order)
{
Print(order.ToString());
if (order.OrderState == OrderState.
Cancelled)
{
// Do something here
entryOrder = null;
}
}
}

Additional Reference Samples


Additional reference code samples are available the NinjaScript Educational Resources
section of our support forum.

© 2011 NinjaTrader, LLC


942 NinjaTrader Version 7

10.4.7.32 OnPositionUpdate()

Definition
The OnPositionUpdate() method is called everytime a position managed by a strategy
changes state.

Programming to this method is considered advanced programming and exposed for


experienced programmers

Method Return Value


This method does not return a value.

Method Parameters
IPosition position

Syntax
You must override the method in your strategy with the following syntax.

protected override void OnPositionUpdate(IPosition position)


{

Examples
protected override void OnPositionUpdate(IPosition
position)
{
if (position.MarketPosition == MarketPosition.
Flat)
{
// Do something like reset some variables
here
}
}

Additional Reference Samples


Additional reference code samples are available the NinjaScript Educational Resources
section of our support forum.
10.4.7.33 OnStartUp()

See OnStartUp()
10.4.7.34 OnTermination()

See OnTermination()

© 2011 NinjaTrader, LLC


NinjaScript 943

10.4.7.35 Order Methods

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()

© 2011 NinjaTrader, LLC


944 NinjaTrader Version 7

10.4.7.35.1 Managed Approach

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.

A few key points:

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

* Via the SetProfitTarget(), SetStopLoss() and SetTrailStop() methods

Order Submission for Entry and Exit Methods - Basic Operation


Orders are primarily submitted from within the OnBarUpdate() method when a specific
order method is called. By default, orders are kept alive provided that they are re-
submitted on each call of the OnBarUpdate() method. If the order is not re-submitted,
the order is then cancelled. If the order is re-submitted with changed parameters (new
limit price for example) the order is modified.

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.

protected override void OnBarUpdate()


{
// Entry condition
if (Close[0] > SMA(20)[0])
EnterLongLimit(GetCurrentBid());
}

This technique allows you the quickest and easiest order submission method suitable

© 2011 NinjaTrader, LLC


NinjaScript 945

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();

Signal Names on Entry Methods


You can optionally tag an entry order with a signal name. Signal names are used to
identify executions resulting from the order on a chart and in performance reports.
Market positions created from a tagged entry method are marked with the signal name
which serves two purposes:

Used to tie an exit method to a specific position


Used to identify unique entries in a strategy

An example of an entry method that submitted a sell short market order with a tagged
signal name would look like the following:

EnterShort("My Signal Name");

Defining how Entry Methods are Processed in a Strategy


You can limit how many entry methods are processed by determining the maximum
number of entries in a single direction across all entry methods, or across unique entry
methods, defined by providing signal names. The following properties can be set in the
Strategy Dialog window when adding a strategy to a chart or to the Strategies tab of the
Control Center window.

EntriesPerDirection property - Sets the maximum number of entries in a single


direction
EntryHandling property - Limits EntriesPerDirection property across all entries on per
unique entries (tagged with a signal name)

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.

protected override void OnBarUpdate()


{
// Entry condition 1
if (CrossAbove(SMA(10), SMA(20), 1))

© 2011 NinjaTrader, LLC


946 NinjaTrader Version 7

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.

Entry Methods on Multi-Instrument Strategies


When running strategies that submit orders to multiple instruments, entry methods will
submit orders to the instrument referenced by the BarsInProgress. The following
example assumes that the strategy is running on a 1 minute ES chart. It adds an ER2
data series and enters a position on both the ES and ER2.

protected override void Initialize()


{
Add("ER2 12-06", PeriodType.Minute, 1);
}

protected override void OnBarUpdate()


{
if (BarsInProgress == 0)
EnterLong("ES Trade");
else if (BarsInProgress == 1)
EnterLong("ER2 Trade");
}

Quantity Type and TIF


You can also set the entry order quantity and order type which is generally set via the UI
at run time.
QuantityType property - Sets if the order quantity is taken from the entry method
quantity property or the default strategy quantity size
TimeInForce propery - Sets the time in force of the order

How to close a position

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()

© 2011 NinjaTrader, LLC


NinjaScript 947

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.

Closing a Position using an Exit Method


Exit methods submit orders to close out a position in whole or in part. An example of an
exit method that submitted a sell market order to close the entire strategy position would
look like the following:

ExitLong();

Closing a Partial Position using an Exit Method


You can close out a partial position by specifying the exit quantity. The following example
goes long 3 contracts. Each subsequent bar update will submit a market order to exit
one contract until the position is completely closed. ExitLong(1) will be ignored if a long
market position does not exist.

protected override void OnBarUpdate()


{
if (CrossAbove(SMA(10), SMA(20), 1))
EnterLong(3);

ExitLong(1);
}

Tying an Exit to an Entry: How to Close a Position Tagged with a Signal


Name

© 2011 NinjaTrader, LLC


948 NinjaTrader Version 7

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.

protected override void OnBarUpdate()


{
// Entry condition 1
if (CrossAbove(SMA(10), SMA(20), 1))
EnterLong("Condition 1 Entry");

// Entry condition 2
if (CrossAbove(RSI(14, 3), 30, 1))
EnterLong("Condition 2 Entry");

// Closes the position created by entry


condition 1
if (CrossBelow(SMA(10), SMA(20), 1)
ExitLong("Condition 1 Entry");

// Closes the position created by entry


condition 2
if (CrossBelow(RSI(14, 3), 70, 1))
ExitLong("Condition 2 Entry");
}

Internal Order Handling Rules that Reduce Unwanted Positions


NinjaTrader is a real-time live trading platform and thus we need to ensure that we
prevent situations in real-time where you may have multiple orders working
accomplishing the same task. An example of this would be if your strategy had a target
limit order for 1 contract working and then your strategy issued a market order to close
the position. This is dangerous since it could result in both orders getting filled and
instead of having a flat position you are now short! To prevent these types of situations,
there are some "under the hood" rules that a NinjaScript strategy follows when order
methods are called.

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.

The following rules are true per unique signal name:

Methods that generate orders to enter a position will be ignored if:


A position is open and an order submitted by an exit method (ExitLongLimit() for
example) is active and the order is used to open a position in the opposite direction

© 2011 NinjaTrader, LLC


NinjaScript 949

A position is open and an order submitted by a set method (SetStopLoss() for


example) is active and the order is used to open a position in the opposite direction
The strategy position is flat 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
The entry signal name is not unique

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 a set method (SetStopLoss() for
example) is active

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

Advanced order handling is reserved for EXPERIENCED programmers. Through advanced


order handling you can submit, change and cancel orders at your discretion through any
event-driven method within a strategy. Each order method within the "Managed Approach"
section has a method overload designed for advanced handling.

Live Until Cancelled Orders


Orders can be submitted that are live until you call the CancelOrder() method or the
order's time in force has expired, which ever comes first. This flexibility allows you to
control exactly when an order should be cancelled instead of relying on the close of a
bar. Each order method such as EnterLongLimit() has a method variation (overload)
designed to submit a live until cancelled order. When using this overload please be sure
to hold onto the IOrder object for the order to be able to call CancelOrder() on it at a later
point in time.

The IOrder Class


All order methods return an IOrder object. Several things you need to be aware of:

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

© 2011 NinjaTrader, LLC


950 NinjaTrader Version 7

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.

private IOrder entryOrder = null;


protected override void OnBarUpdate()
{
if (entryOrder == null && Close[0] > Open[0])
entryOrder = EnterLong();
}

protected override void OnOrderUpdate(IOrder


order)
{
if (entryOrder != null && entryOrder ==
order)
{
Print(order.ToString());
if (order.OrderState == OrderState.
Filled)
entryOrder = null;
}
}

Working with a Multi-Instrument Strategy


With advanced order handling you can submit an orders in the context of any bars object
by designating the "BarsInProgress" index. What this means is that if your primary bar
series is "MSFT" and your secondary series added to the strategy through the Add()
method is "AAPL", you can submit an order for either "MSFT" or "AAPL" anywhere from
within the strategy. There is detailed information on working with multi-time frame and
instrument strategies however, this sub-section strictly deals with the concept of order
submission.

Let's take as an example the EnterLongLimit() method and one of its method variations
(below) designed for advanced order handling:

EnterLongLimit(int barsInProgressIndex, bool


liveUntilCancelled, int quantity, double limitPrice, string
signalName)

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:

Add("AAPL", PeriodType.Minute, 1);

In NinjaScript, "MSFT" has a bars index value of "0" and "AAPL" would have bars index

© 2011 NinjaTrader, LLC


NinjaScript 951

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".

private IOrder entryOrder = null;


protected override void OnBarUpdate()
{
// Check if the MSFT series triggered an bar
update event
if (BarsInProgress == 0)
{

// Submit an order for AAPL in the


context of MSFT bar update event
if (entryOrder == null)
entryOrder = EnterLongLimit(1, true
, 1, Lows[1][0], "AAPL Order");
}
}
10.4.7.35.1.2 CancelOrder()

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

© 2011 NinjaTrader, LLC


952 NinjaTrader Version 7

private IOrder myEntryOrder = null;


private int barNumberOfOrder = 0;

protected override void OnBarUpdate()


{
// Submit an entry order at the low of a bar
if (myEntryOrder == null)
{
myEntryOrder = EnterLongLimit(0, true, 1,
Low[0], "Long Entry");
barNumberOfOrder = CurrentBar;
}

// If more than 5 bars has elapsed, cancel the


entry order
if (CurrentBar > barNumberOfOrder + 5)
CancelOrder(myEntryOrder);
}
10.4.7.35.1.3 EnterLong()

Definition
Generates a buy market order to enter a long position.

Method Return Value


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
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.

EnterLong(int barsInProgressIndex, int quantity, string signalName)

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.

© 2011 NinjaTrader, LLC


NinjaScript 953

Examples
protected override void OnBarUpdate()
{
if (CurrentBar < 20)
return;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterLong("SMA Cross Entry");
}

Tips (also see Overview)


If using a method signature that does not have the parameter quantity, the order quantity
will be taken from the quantity value set in the strategy dialog window when running or
backtesting a strategy
10.4.7.35.1.4 EnterLongLimit()

Definition
Generates a buy limit order to enter a long position.

Method Return Value


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
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.

EnterLongLimit(int barsInProgressIndex, bool liveUntilCancelled,


int quantity, double limitPrice, string signalName)

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

© 2011 NinjaTrader, LLC


954 NinjaTrader Version 7

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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterLongLimit(GetCurrentBid(), "SMA Cross
Entry");
}

Tips (also see Overview)


If using a method signature that does not have the parameter quantity, the order quantity
will be taken from the quantity value set in the strategy dialog window when running or
backtesting a strategy
10.4.7.35.1.5 EnterLongStop()

Definition
Generates a buy stop order to enter a long position.

Method Return Value


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
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.

EnterLongStop(int barsInProgressIndex, bool liveUntilCancelled, int


quantity, double stopPrice, string signalName)

© 2011 NinjaTrader, LLC


NinjaScript 955

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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterLongStop(GetCurrentAsk() + TickSize,
"SMA Cross Entry");
}

Tips (also see Overview)


If using a method signature that does not have the parameter quantity, the order quantity
will be taken from the quantity value set in the strategy dialog window when running or
backtesting a strategy
10.4.7.35.1.6 EnterLongStopLimit()

Definition
Generates a buy stop limit order to enter a long position.

Method Return Value


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
EnterLongStopLimit(double limitPrice, double stopPrice)
EnterLongStopLimit(double limitPrice, double stopPrice, string
signalName)
EnterLongStopLimit(int quantity, double limitPrice, double

© 2011 NinjaTrader, LLC


956 NinjaTrader Version 7

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.

EnterLongStopLimit(int barsInProgressIndex, bool liveUntilCancelled


, int quantity, double limitPrice, double stopPrice, string
signalName)

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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterLongStopLimit(High[0] + 2 * TickSize,
High[0], "SMA Cross Entry");
}

Tips (also see Overview)


If using a method signature that does not have the parameter quantity, the order quantity
will be taken from the quantity value set in the strategy dialog window when running or
backtesting a strategy

© 2011 NinjaTrader, LLC


NinjaScript 957

10.4.7.35.1.7 EnterShort()

Definition
Generates a sell short market order to enter a short position.

Method Return Value


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
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.

EnterShort(int barsInProgressIndex, int quantity, string signalName


)

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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterShort("SMA Cross Entry");
}

Tips (also see Overview)


If using a method signature that does not have the parameter quantity, the order quantity
will be taken from the quantity value set in the strategy dialog window when running or

© 2011 NinjaTrader, LLC


958 NinjaTrader Version 7

backtesting a strategy
10.4.7.35.1.8 EnterShortLimit()

Definition
Generates a sell short limit order to enter a short position.

Method Return Value


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
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.

EnterShortLimit(int barsInProgressIndex, bool liveUntilCancelled,


int quantity, double limitPrice, string signalName)

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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterShortLimit(GetCurrentAsk(), "SMA Cross

© 2011 NinjaTrader, LLC


NinjaScript 959

Entry");
}

Tips (also see Overview)


If using a method signature that does not have the parameter quantity, the order quantity
will be taken from the quantity value set in the strategy dialog window when running or
backtesting a strategy
10.4.7.35.1.9 EnterShortStop()

Definition
Generates a sell short stop order to enter a short position.

Method Return Value


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
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.

EnterShortStop(int barsInProgressIndex, bool liveUntilCancelled,


int quantity, double stopPrice, string signalName)

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)

© 2011 NinjaTrader, LLC


960 NinjaTrader Version 7

return;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterShortStop(GetCurrentBid() + TickSize,
"SMA Cross Entry");
}

Tips (also see Overview)


If using a method signature that does not have the parameter quantity, the order quantity
will be taken from the quantity value set in the strategy dialog window when running or
backtesting a strategy
10.4.7.35.1.10 EnterShortStopLimit()

Definition
Generates a sell short stop limit order to enter a short position.

Method Return Value


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
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.

EnterShortStopLimit(int barsInProgressIndex, bool


liveUntilCancelled, int quantity, double limitPrice, double
stopPrice, string signalName)

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

© 2011 NinjaTrader, LLC


NinjaScript 961

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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterShortStopLimit(Low[0] + 2 * TickSize,
Low[0], "SMA Cross Entry");
}

Tips (also see Overview)


If using a method signature that does not have the parameter quantity, the order quantity
will be taken from the quantity value set in the strategy dialog window when running or
backtesting a strategy
10.4.7.35.1.11 ExitLong()

Definition
Generates a sell market order to exit a long position.

Method Return Value


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
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.

ExitLong(int barsInProgressIndex, int quantity, string signalName,

© 2011 NinjaTrader, LLC


962 NinjaTrader Version 7

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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterLong("SMA Cross Entry");

// Exits position
if (CrossBelow(SMA(10), SMA(20), 1))
ExitLong();
}

Tips (also see Overview)


This method is ignored if a long position does not exist
It is helpful to provide a signal name if your strategy has multiple exit points to help identify
your exits on a chart
You can tie an exit to an entry by providing the entry signal name in the parameter
"fromEntrySignal"
If you do not specify a quantity the entire position is exited rendering your strategy flat
If you do not specify a "fromEntrySignal" parameter the entire position is exited rendering
your strategy flat
10.4.7.35.1.12 ExitLongLimit()

Definition
Generates a sell limit order to exit a long position.

Method Return Value

© 2011 NinjaTrader, LLC


NinjaScript 963

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.

ExitLongLimit(int barsInProgressIndex, bool liveUntilCancelled, int


quantity, double limitPrice, string signalName, 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.
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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterLong("SMA Cross Entry");

© 2011 NinjaTrader, LLC


964 NinjaTrader Version 7

// Exits position
if (CrossBelow(SMA(10), SMA(20), 1))
ExitLongLimit(GetCurrentBid());
}

Tips (also see Overview)


This method is ignored if a long position does not exist
It is helpful to provide a signal name if your strategy has multiple exit points to help identify
your exits on a chart
You can tie an exit to an entry by providing the entry signal name in the parameter
"fromEntrySignal"
If you do not specify a quantity the entire position is exited rendering your strategy flat
If you do not specify a "fromEntrySignal" parameter the entire position is exited rendering
your strategy flat
10.4.7.35.1.13 ExitLongStop()

Definition
Generates a sell stop order to exit a long position.

Method Return Value


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
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.

ExitLongStop(int barsInProgressIndex, bool liveUntilCancelled, int


quantity, double stopPrice, string signalName, 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.

© 2011 NinjaTrader, LLC


NinjaScript 965

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;

protected override void OnBarUpdate()


{
if (CurrentBar < 20)
return;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
{
EnterLong("SMA Cross Entry");
stopPrice = Low[0];
}

// Exits position
ExitLongStop(stopPrice);
}

Tips (also see Overview)


This method is ignored if a long position does not exist
It is helpful to provide a signal name if your strategy has multiple exit points to help identify
your exits on a chart
You can tie an exit to an entry by providing the entry signal name in the parameter
"fromEntrySignal"
If you do not specify a quantity the entire position is exited rendering your strategy flat
If you do not specify a "fromEntrySignal" parameter the entire position is exited rendering
your strategy flat
10.4.7.35.1.14 ExitLongStopLimit()

Definition
Generates a sell stop limit order to exit a long position.

Method Return Value

© 2011 NinjaTrader, LLC


966 NinjaTrader Version 7

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.

ExitLongStopLimit(int barsInProgressIndex, bool liveUntilCancelled,


int quantity, double limitPrice, double stopPrice, string
signalName, 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.
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;

protected override void OnBarUpdate()


{
if (CurrentBar < 20)
return;

© 2011 NinjaTrader, LLC


NinjaScript 967

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
{
EnterLong("SMA Cross Entry");
stopPrice = Low[0];
}

// Exits position
ExitLongStopLimit(stopPrice - (10 * TickSize),
stopPrice);
}

Tips (also see Overview)


This method is ignored if a long position does not exist
It is helpful to provide a signal name if your strategy has multiple exit points to help identify
your exits on a chart
You can tie an exit to an entry by providing the entry signal name in the parameter
"fromEntrySignal"
If you do not specify a quantity the entire position is exited rendering your strategy flat
If you do not specify a "fromEntrySignal" parameter the entire position is exited rendering
your strategy flat
10.4.7.35.1.15 ExitShort()

Definition
Generates a buy to cover market order to exit a short position.

Method Return Value


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
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.

ExitShort(int barsInProgressIndex, int quantity, string signalName,


string fromEntrySignal)

Parameters

© 2011 NinjaTrader, LLC


968 NinjaTrader Version 7

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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterShort("SMA Cross Entry");

// Exits position
if (CrossBelow(SMA(10), SMA(20), 1))
ExitShort();
}

Tips (also see Overview)


This method is ignored if a short position does not exist
It is helpful to provide a signal name if your strategy has multiple exit points to help identify
your exits on a chart
You can tie an exit to an entry by providing the entry signal name in the parameter
"fromEntrySignal"
If you do not specify a quantity the entire position is exited rendering your strategy flat
If you do not specify a "fromEntrySignal" parameter the entire position is exited rendering
your strategy flat
10.4.7.35.1.16 ExitShortLimit()

Definition
Generates a buy to cover limit order to exit a short position.

Method Return Value


An IOrder read-only object that represents the order. Reserved for experienced
programmers, additional information can be found within the Advanced Order Handling
section.

© 2011 NinjaTrader, LLC


NinjaScript 969

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.

ExitShortLimit(int barsInProgressIndex, bool liveUntilCancelled,


int quantity, double limitPrice, string signalName, 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.
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;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
EnterShort("SMA Cross Entry");

// Exits position
if (CrossAbove(SMA(10), SMA(20), 1))

© 2011 NinjaTrader, LLC


970 NinjaTrader Version 7

ExitShortLimit(GetCurrentAsk());
}

Tips (also see Overview)


This method is ignored if a short position does not exist
It is helpful to provide a signal name if your strategy has multiple exit points to help identify
your exits on a chart
You can tie an exit to an entry by providing the entry signal name in the parameter
"fromEntrySignal"
If you do not specify a quantity the entire position is exited rendering your strategy flat
If you do not specify a "fromEntrySignal" parameter the entire position is exited rendering
your strategy flat
10.4.7.35.1.17 ExitShortStop()

Definition
Generates a buy to cover stop order to exit a short position.

Method Return Value


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
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.

ExitShortStop(int barsInProgressIndex, bool liveUntilCancelled, int


quantity, double stopPrice, string signalName, 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.
stopPrice The stop price of the order.
quantity Entry order quantity.
liveUntilCancelled The order will NOT expire at the end of a bar but

© 2011 NinjaTrader, LLC


NinjaScript 971

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;

protected override void OnBarUpdate()


{
if (CurrentBar < 20)
return;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),
SMA(20), 1))
{
EnterShort("SMA Cross Entry");
stopPrice = Low[0];
}

// Exits position
ExitShortStop(stopPrice);
}

Tips (also see Overview)


This method is ignored if a short position does not exist
It is helpful to provide a signal name if your strategy has multiple exit points to help identify
your exits on a chart
You can tie an exit to an entry by providing the entry signal name in the parameter
"fromEntrySignal"
If you do not specify a quantity the entire position is exited rendering your strategy flat
If you do not specify a "fromEntrySignal" parameter the entire position is exited rendering
your strategy flat
10.4.7.35.1.18 ExitShortStopLimit()

Definition
Generates a buy to cover stop limit order to exit a short position.

Method Return Value


An IOrder read-only object that represents the order. Reserved for experienced
programmers, additional information can be found within the Advanced Order Handling
section.

© 2011 NinjaTrader, LLC


972 NinjaTrader Version 7

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.

ExitShortStopLimit(int barsInProgressIndex, bool liveUntilCancelled


, int quantity, double limitPrice, double stopPrice, string
signalName, 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.
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;

protected override void OnBarUpdate()


{
if (CurrentBar < 20)
return;

// Only enter if at least 10 bars has passed


since our last entry
if (BarsSinceEntry() > 10 && CrossAbove(SMA(10),

© 2011 NinjaTrader, LLC


NinjaScript 973

SMA(20), 1))
{
EnterShort("SMA Cross Entry");
stopPrice = Low[0];
}

// Exits position
ExitShortStopLimit(stopPrice + (10 * TickSize),
stopPrice);
}

Tips (also see Overview)


This method is ignored if a short position does not exist
It is helpful to provide a signal name if your strategy has multiple exit points to help identify
your exits on a chart
You can tie an exit to an entry by providing the entry signal name in the parameter
"fromEntrySignal"
If you do not specify a quantity the entire position is exited rendering your strategy flat
If you do not specify a "fromEntrySignal" parameter the entire position is exited rendering
your strategy flat
10.4.7.35.1.19 SetProfitTarget()

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

© 2011 NinjaTrader, LLC


974 NinjaTrader Version 7

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);
}

Tips (also see Overview)


Profit target orders are submitted in real-time on incoming executions from entry orders
A strategy will either generate a target order for each partial fill of an entry order or one
order for all fills. See additional information under the Strategies tab of the Options dialog
window.
If a stop loss or trail stop order is generated in addition to a profit target order, they are
submitted as OCO (one cancels other)
A profit target order is automatically cancelled if the managing position is closed by another
strategy generated exit order
10.4.7.35.1.20 SetStopLoss()

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

© 2011 NinjaTrader, LLC


NinjaScript 975

value, bool simulated)

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);
}

Tips (also see Overview)


The SetStopLoss() method can NOT be used concurrently with the SetTrailStop() method
for the same position, if both methods are called for the same position (fromEntrySignal)
the SetStopLoss() will always take precedence. You can however, use both methods in the
same strategy if they reference different signal names.
Stop loss orders are submitted in real-time on incoming executions from entry orders
A strategy will either generate a stop loss order for each partial fill of an entry order or one
order for all fills. See additional information under the Strategies tab of the Options dialog
window.
If a profit target order is generated in addition to a stop loss order, they are submitted as
OCO (one cancels other)
Stop loss orders are submitted as stop market orders
A stop loss order is automatically cancelled if the managing position is closed by another
strategy generated exit order
10.4.7.35.1.21 SetTrailStop()

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.

© 2011 NinjaTrader, LLC


976 NinjaTrader Version 7

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

Note: CalculationMode.Price is irrelevant for trail


stops
simulated If true, will simulate the stop order and submit as
market once triggered
value The value the trail stop 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 trail stop exit to
the entry and exits the position quantity represented
by the actual entry.

Examples
protected override void Initialize()
{
// Sets a trail stop of 12 ticks
SetTrailStop(CalculationMode.Ticks, 12);
}

Tips (also see Overview)


The SetTrailStop() method can NOT be used concurrently with the SetStopLoss() method
for the same position, if both methods are called for the same position (fromEntrySignal)
the SetStopLoss() will always take precedence. You can however, use both methods in the

© 2011 NinjaTrader, LLC


NinjaScript 977

same strategy if they reference different signal names.


Trail stop orders are submitted in real-time on incoming executions from entry orders
A strategy will either generate a trail stop order for each partial fill of an entry order or one
order for all fills. See additional information under the Strategies tab of the Options dialog
window.
If a profit target order is generated in addition to a trail stop order, they are submitted as
OCO (one cancels other)
Trail stop orders are submitted as stop market orders
A trail stop order is automatically cancelled if the managing position is closed by another
strategy generated exit order
10.4.7.35.2 Unmanaged Approach

The Unmanaged approach is reserved for VERY EXPERIENCED programmers. In place of


the convenience layer that the Managed approach offered, the Unmanaged approach instead
offers ultimate flexibility in terms of order submission and management. This section will
discuss some of the basics of working with Unmanaged order methods.

Getting started with Unmanaged order methods


To be able to offer you the flexibility required to achieve more complex order submission
techniques, NinjaTrader needs to be able to know if you are going to be using the
Unmanaged approach beforehand.

In the Initialize() method designating the Unmanaged property as true signifies to


NinjaTrader that you will be using the Unmanaged approach. Setting this will effectively
prevent any of the signal tracking and internal order handling rules that were present in
the Managed approach.

protected override void Initialize()


{
Unmanaged = true;
}

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.

Working with Unmanaged order methods

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

© 2011 NinjaTrader, LLC


978 NinjaTrader Version 7

provided that the close price of the current bar is greater than the current value of the 20
period simple moving average.

protected override void OnBarUpdate()


{
// Entry condition
if (Close[0] > SMA(20)[0] && entryOrder ==
null)
entryOrder = SubmitOrder(0, OrderAction.
Buy, OrderType.Limit, 1, GetCurrentBid(), 0, "",
"Long Limit");
}

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.

protected override void OnBarUpdate()


{
// Raise stop loss to breakeven when you are
at least 4 ticks in profit
if (stopOrder != null && stopOrder.StopPrice
< Position.AvgPrice && Close[0] >= Position.
AvgPrice + 4 * TickSize)
ChangeOrder(stopOrder, stopOrder.
Quantity, stopOrder.LimitPrice, Position.
AvgPrice);
}

Order Cancellation
Similar to the live until cancelled technique from the Managed approach, cancelling

© 2011 NinjaTrader, LLC


NinjaScript 979

orders can be done through the CancelOrder() method.

protected override void OnBarUpdate()


{
// Cancel entry order if price is moving away
from our limit price
if (entryOrder != null && Close[0] <
entryOrder.LimitPrice - 4 * TickSize)
{
CancelOrder(entryOrder);

// If the entryOrder IOrder object is no


longer needed I should reset it to null in the
OnOrderUpdate() method
}
}

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.

Critical considerations when using Unmanaged order methods


When using the Unmanaged approach it is imperative to understand that NinjaTrader
has many safety mechanisms that were present in the Managed approach turned off.
There are critical issues that must be considered and your strategy must be
programmed in a manner that addresses these concerns. Failure to do so may result in
a serious adverse affect on your trading account.

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.

© 2011 NinjaTrader, LLC


980 NinjaTrader Version 7

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()

Please see the "CancelOrder()" section under the "Managed Approach".


10.4.7.35.2.2 ChangeOrder()

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;

protected override void OnBarUpdate()


{
// Raise stop loss to breakeven when you are at
least 4 ticks in profit
if (stopOrder != null && stopOrder.StopPrice <
Position.AvgPrice && Close[0] >= Position.AvgPrice +
4 * TickSize)
ChangeOrder(stopOrder, stopOrder.Quantity,
stopOrder.LimitPrice, Position.AvgPrice);
}

© 2011 NinjaTrader, LLC


NinjaScript 981

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.

Method Return Value


An IOrder read-only object that represents the order. Reserved for experienced
programmers, additional information can be found within the Unmanaged Approach section.

Syntax
SubmitOrder(int barsInProgressIndex, OrderAction orderAction,
OrderType orderType, int quantity, double limitPrice, double
stopPrice, string ocoId, string signalName)

Parameters

© 2011 NinjaTrader, LLC


982 NinjaTrader Version 7

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.
orderAction Possible values:

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;

protected override void OnBarUpdate()


{
// Entry condition
if (Close[0] > SMA(20)[0] && entryOrder == null)
entryOrder = SubmitOrder(0, OrderAction.
Buy, OrderType.Market, 1, 0, 0, "", "Enter Long");
}
10.4.7.35.2.5 Unmanaged

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

© 2011 NinjaTrader, LLC


NinjaScript 983

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.

Methods and Properties


AllTrades Gets a TradeCollection object of all trades
generated by the strategy
LongTrades Gets a TradeCollection object of long trades
generated by the strategy
RealtiimeTrades Gets a TradeCollection object of real-time trades
generated by the strategy
ShortTrades Gets a TradeCollection object of short trades
generated by 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()

© 2011 NinjaTrader, LLC


984 NinjaTrader Version 7

{
// 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()

© 2011 NinjaTrader, LLC


NinjaScript 985

{
// 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.

Methods and Properties


AvgPrice Gets the average entry price of the strategy position
GetProfitLoss() Gets the unrealized PnL
MarketPosition Gets the current market position
Quantity Gets the current position size

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);
}

© 2011 NinjaTrader, LLC


986 NinjaTrader Version 7

10.4.7.37.2 GetProfitLoss()

Definition
Calculates the unrealized PnL for the position.

Method Return Value


A double value representing the unrealized PnL.

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

© 2011 NinjaTrader, LLC


NinjaScript 987

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:

Primary Bars is ES 1 Minute


Secondary Bars is ES 3 Minute
Third Bars is ER2 1 Minute

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

© 2011 NinjaTrader, LLC


988 NinjaTrader Version 7

Custom Strategy

Examples
protected override void Initialize()
{
Add(Instrument, PeriodType.Minute, 5);
Add("ER2 06-07, PeriodType.Minute, 5);
}

protected override void OnBarUpdate()


{
Print("Primary position is " + Positions[0].
MarketPosition);
Print("ER2 positions is " + Positions[2].
MarketPosition);

// Alternative approach. By checking what Bars


object is calling the OnBarUpdate()
// method, we can just use the Position property
since its pointing to the correct
// position.
if (BarsInProgress == 0)
Print("Primary position is " + Position.
MarketPosition);
else if (BarsInProgress = 2)
Print("Er2 position is " + Position.
MarketPosition);
}
10.4.7.39 RealtimeErrorHandling

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

© 2011 NinjaTrader, LLC


NinjaScript 989

Examples
protected override void Initialize()
{
RealtimeErrorHandling = RealtimeErrorHandling.
TakeNoAction;
}

private IOrder stopLossOrder = null;

protected override void OnBarUpdate()


{
if (entryOrder == null && Close[0] > Open[0])
EnterLong();

if (stopLossOrder == null)
stopLossOrder = ExitLongStop(Position.
AvgPrice - 10 * TickSize);
}

protected override void OnOrderUpdate(IOrder order)


{
if (stopLossOrder != null && stopLossOrder.Token
== order.Token)
{
// Rejection handling
if (order.OrderState == OrderState.
Rejected)
{
// Stop loss order was rejected !!!!
// Do something about it here
}
}
}

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

© 2011 NinjaTrader, LLC


990 NinjaTrader Version 7

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;
}

© 2011 NinjaTrader, LLC


NinjaScript 991

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.

Methods and Properties


Commission A double value representing the commission of
the trade
Entry Gets an IExecution object representing the entry
Exit Gets an IExecution object representing the exit
ProfitCurrency A double value representing profit in currency for
one traded unit. Multiply this value by the trade

© 2011 NinjaTrader, LLC


992 NinjaTrader Version 7

Quantity to get the total profit in currency for the


trade.
ProfitPercent A double value representing profit as a percentage
ProfitPoints A double value representing profit in points for one
traded unit. Multiply this value by the trade Quantity
to get the total profit in points for the trade.
Quantity An int value representing the quantity of the trade
ToString() A string representation of the Trade object

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];

// Calculate the PnL for the last completed


real-time trade
double lastProfit = lastTrade.
ProfitCurrency * lastTrade.Quantity;

// Pring the PnL to the Output window


Print("The last trade's profit is " +
lastProfit);
}
}
10.4.7.45 TradeCollection

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.

Methods and Properties


Count An int value representing the number of trades in
the collection
GetTrades() Gets a TradeCollection object representing a
specified position
LosingTrades Gets a TradeCollection object of losing trades
TradesPerformance Gets a TradesPerformance object
WinningTrades Gets a TradeCollection object of winning trades

© 2011 NinjaTrader, LLC


NinjaScript 993

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];

Print("The last trade profit is " +


lastTrade.ProfitPercent);
Print("The first trade profit is " +
firstTrade.ProfitPercent);
}
}

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);
}
}
}

© 2011 NinjaTrader, LLC


994 NinjaTrader Version 7

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.

Method Return Value


An TradeCollection object.

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

© 2011 NinjaTrader, LLC


NinjaScript 995

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.

Methods and Properties


Count An int value representing the number of trades in
the collection
GetTrades() Gets a TradeCollection object representing a
specified position
TradesPerformance Gets a TradesPerformance object

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];

Print("The last losing trade's profit was "


+ lastTrade.ProfitPercent);
Print("The first losing trade's profit was
" + firstTrade.ProfitPercent);
}
}
10.4.7.45.4 TradesPerformance

Definition
Performance profile of a collection of Trade objects.

Methods and Properties


AvgBarsInTrade A double value representing the avg number of bars per trade
AvgTradeDuration A TimeSpan value representing quantity-weighted avg duration
of a trade
Commission A double value representing the total commission
Currency Gets a TradesPerformanceValues object in currency
GetSharpeRatio() Calculates the Sharpe ratio using a defined risk free return
GrossLoss A double value representing the gross loss

© 2011 NinjaTrader, LLC


996 NinjaTrader Version 7

GrossProfit A double value representing the gross profit


MaxConsecLoser An int value representing the maximum number of
consecutive losses seen
MaxConsecWinner An int value representing the maximum number of
consecutive winners seen
MaxTime2Recover A TimeSpan value representing maximum time to recover
from a draw down
Percent Gets a TradesPerformanceValues object in percent
Points Gets a TradesPerformanceValues object in points
ProfitFactor A double value representing the profit factor
SharpeRatio A double value representing Sharpe ratio using a zero risk
free return
TradesPerDay An int value representing the avg trades per day

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);
}

© 2011 NinjaTrader, LLC


NinjaScript 997

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.

© 2011 NinjaTrader, LLC


998 NinjaTrader Version 7

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.

Method Return Value


A double value that represents the Sharpe ratio.

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()

© 2011 NinjaTrader, LLC


NinjaScript 999

{
// 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);
}

© 2011 NinjaTrader, LLC


1000 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 1001

A TradesPerformanceValues object that is represented in percent.

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()

© 2011 NinjaTrader, LLC


1002 NinjaTrader Version 7

{
// 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);
}

© 2011 NinjaTrader, LLC


NinjaScript 1003

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.

Methods and Properties


Count An int value representing the number of trades in
the collection
GetTrades() Gets a TradeCollection object representing a
specified position
TradesPerformance Gets a TradesPerformance object

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];

Print("The last winning trade's profit was


" + lastTrade.ProfitPercent);
Print("The first winning trade's profit was
" + firstTrade.ProfitPercent);
}
}
10.4.7.46 TradesPerformanceValues

Definition
Performance values of a collection of Trade objects.

Currency and Point based calculations are per trade


Percent based calculations are per traded unit

© 2011 NinjaTrader, LLC


1004 NinjaTrader Version 7

Methods and Properties


AvgEtd A double value representing avg end trade draw
down
AvgMae A double value representing avg maximum
adverse excursion
AvgMfe A double value representing avg maximum
favorable excursion
AvgProfit A double value representing avg profit
CumProfit A double value representing cumulative profit
(percent is compounded)
DrawDown A double value representing draw down
LargestLoser A double value representing largest loss
LargestWinner A double value representing largest gain
ProfitPerMonth A double value representing profit per month
always as a percent
StdDev A double value representing standard deviation on
a per unit basis

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: " +

© 2011 NinjaTrader, LLC


NinjaScript 1005

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);
}

© 2011 NinjaTrader, LLC


1006 NinjaTrader Version 7

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.

© 2011 NinjaTrader, LLC


NinjaScript 1007

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.

© 2011 NinjaTrader, LLC


1008 NinjaTrader Version 7

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

© 2011 NinjaTrader, LLC


NinjaScript 1009

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.

Current affected brokers:

TD AMERITRADE

* For any other broker, this property has no affect.

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;
}

© 2011 NinjaTrader, LLC

You might also like