KJTradingSystems-Entry&Exits With Ninja
KJTradingSystems-Entry&Exits With Ninja
KJTradingSystems-Entry&Exits With Ninja
All rights reserved. No part of this book may be reproduced in any form or by any electronic or
mechanical means including information storage and retrieval systems, without permission in writing
from the author. The only exception is by a reviewer, who may quote short excerpts in a review.
Kevin J. Davey
Data, information, and material (“content”) is provided for informational and educational purposes only.
This material neither is, nor should be construed as an offer, solicitation, or recommendation to buy or
sell any securities. Any investment decisions made by the user through the use of such content is solely
based on the users independent analysis taking into consideration your financial circumstances,
investment objectives, and risk tolerance. Neither KJTradingSystems.com (KJ Trading) nor any of its
content providers shall be liable for any errors or for any actions taken in reliance thereon. By accessing
the KJ Trading site, a user agrees not to redistribute the content found therein unless specifically
authorized to do so.
Individual performance depends upon each student’s unique skills, time commitment, and effort.
Results may not be typical and individual results will vary.
U.S. Government Required Disclaimer - Commodity Futures Trading Commission states: Futures and
Options trading has large potential rewards, but also large potential risk. You must be aware of the
risks and be willing to accept them in order to invest in the futures and options markets. Don't trade
with money you can't afford to lose. This is neither a solicitation nor an offer to Buy/Sell futures,
stocks or options on the same. No representation is being made that any account will or is likely to
achieve profits or losses similar to those discussed in this document. The past performance of any
trading system or methodology is not necessarily indicative of future results.
NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL, OR IS LIKELY TO ACHIEVE PROFITS
OR LOSSES SIMILAR TO THOSE DISCUSSED WITHIN THIS SITE. IF YOU DECIDE TO INVEST REAL MONEY,
ALL TRADING DECISIONS SHOULD BE YOUR OWN.
No, this isn’t my opening line at Algorithmic Traders Anonymous, but algo trading can indeed be
addicting – in a good way!
There is a great thrill in developing a trading strategy, testing it over history to see how profitable it has
been, and then running it with real money on the line – especially if it makes money!
That is algo trading in a nutshell – you take some entries and exits, combine them into a strategy, then
test and evaluate on historical data. If it is profitable, and meets all your criteria, you then turn the algo
loose on a market or markets. If things work out right (and they don’t always work out right, trust me
on that), you should be able to earn a reasonable risk adjusted rate of return.
The process to properly develop an algo is complicated – it is not as simple as applying the strategy to a
chart and optimizing like crazy– and is advanced material not included in this short book. But any algo
has to start with the basic components: entries and exits.
That is what this book is all about, getting you started with developing some simple trading algos. In the
sections that follow, you’ll notice that I tend to keep things simple. I don’t have (or recommend) entries
with 10 or 20 conditions, rules or filters just to get a buy signal. I think that is overkill. Based on 25+
years of trading, I can tell you that the market tends to agree with me – simplest usually works best.
In this book, you will find 9 unique entries, and 7 exits. These are all used by me in at least one, and
sometimes multiple, strategies I personally trade. So, they have been battle tested, and proven to work
with real money. But don’t take my word for it – TEST THESE YOURSELF!
Not every entry works in every market, nor with every bar size. Same with exits. But the entries and
exits I give do work in quite a few situations.
NOTE: All my examples are based on futures trading, which is what I primarily trade in real life. The
entries and exits could also apply to stocks, CFDS, forex, etc. You just have to test them.
I have created a separate section for each entry, and for each exit. For the entries, you will typically see:
A short explanation of the concept. I believe the best entries should have some logical
reasoning behind it. This is where I differ from machine learning purists. A machine learning
program can say “when close of 13 bars ago is greater than the close of 47 bars ago, buy” and
maybe that strategy does well historically. But, is there any relevance behind the close of 13
and 47 bars ago, or is just a random “blind squirrel eventually finds a nut” situation? Machine
learning is great at finding profitable relationships, but many are spurious – meaning they are
just fluke situations. I favor entries (and exits) that I can reasonably explain and understand.
Some sample trades. Seeing trades on a chart can help you get a feel for what the entry is
doing. Just be careful, because people tend to nitpick or over-engineer when they see trades on
a chart, and devise filters to add, etc. It is easy to fall into the trap of “I can make this strategy a
lot better by adding this condition, or that filter.” I usually just look at some trades to make sure
the code is actually working.
The code in Tradestation (Easy Language) format. This is also provided as an ELD file in this
package. If you use Multicharts, the code should work there too. Other languages will have to
be translated, but usually with Easy Language you can read what is going on and figure things
out. Easy Language is called that for a reason! It is my trading strategy programming language
of choice, and should be yours, too.
Sample equity curve. Just to prove that these entries work, I show the results (usually with a
simple exit) for a selected instrument (I purposely leave the exact instrument and bar size
anonymous, since I want you to test it yourself!). Remember, these results are all hypothetical,
subject to the disclaimer at the beginning of the book.
Ideas for Modifications. There are lots of things you can do to modify these entries. Keep in
mind that there is NO BAD MODIFICATION, only ones you have not tested. Once you test, you
might say a modification is bad, but until then, your new modified idea is as good as any other.
For exits, I include a short explanation, and the actual Tradestation code.
NOTE: For the 9 entries and 7 exits, I do NOT claim to be the original creator of any of these ideas,
although I may have been. These ideas may have come from a book I read, a magazine article, the
Internet, or I may have just dreamed them up. I have no idea (no pun intended) where they came from.
Typically, I find ideas out there, and then immediately modify them to my liking. Chances are that is the
case with many of these entries and exits.
So, with all that out of the way, let’s first dive into the entries!
Don’t Forget About the ELD and Tradestation Workspace
To help you out, I have included a simple ELD (Tradestation code file) and Tradestation workspace
(Tradestation chart file) as part of this package. It includes all the entries and all the exits. I have
designed it so you can select 1 entry and 1 exit, and you can even iterate through each of them.
Of course, you can copy the individual entries into your own strategies. These entries and exits are free
to use. If you have success with them, just drop me an e-mail – I love hearing from other traders!
Entry #1 – Trade The Pullback
The idea with this entry is that when there is a short term pullback, many times the pullback succeeds,
and the original trend is destroyed, at least for a while. The idea is that the short term trend can be
more important than the long term trend, and therefore it can be a successful trade.
Obviously, there are a few variables here: what defines a trend, and what defines a pullback? For this
entry, I will use simple momentum to establish the short and long trend.
So the rules are simple: if the short term momentum is up, and the longer term momentum is down,
buy. Vice versa to sell short.
Input:entry1_sl(5),entry1_slx(20);
I used momentum here to define the long and short term trend. You could use moving averages
instead, although the lag inherent in moving averages might be troublesome. You could also use
trendlines (not as easy to code) to define these trends.
Simple filters like RSI, Stochastics or ADX can also be added to the primary signal, as a way to filter out
bad signals. Just be careful – too many filters usually leads to a better backtest, and WORSE real time
performance!
Entry #2 – With Trend Pullback
In entry #1, I was trading in the direction of the pullback, against the main trend. Of course, you could
do just the opposite – trade with the main trend, and against the pullback.
This entry idea is then the reverse of the Entry #1, and is something you can do to pretty much every
entry signal you can come up with. I routinely test both my original idea, and the exact opposite.
So the rules are simple: if the short term momentum is up, and the longer term momentum is down, sell
short. Vice versa to buy.
Input:entry2_sl(5), entry2_slx(20);
One downside to this pullback entry is that you are going against the short term trend, which is always
scary. So, maybe something to try is to wait until the market reverses from the pullback. In a long term
up trend, you wait for a small downtrend, then once you see signs of the uptrend resuming (maybe a
bullish candlestick pattern), you enter.
Entry #3 – Jump Off
Find a breakout, trade in the direction of it. Pretty simple. You’ll have a lot of losers due to false
breakouts, but the big winners should make up for it.
This entry establishes a base, based on the recent highs and lows, and then trades a breakout from that
base. In addition, it only does this in the direction of a momentum derived trend.
var: entry3_pbase(0);
entry3_pbase =(highest(high, entry3_pbasebar)+lowest(low, entry3_pbasebar))/2;
One possible modification here is to eliminate the momentum trend component, and just take the
breakout above or below the base, regardless of trend. It does eliminate one input to optimize, which is
nice.
Entry #4 – Super Simple Breakout
VERY simple breakout, different than Entry #3. Same basic idea, though; hop aboard the train as it starts
moving away from the station!
Input: entry4_x(10);
Since this entry is so simple, you could try all sorts of filters to eliminate poor signals (like RSI, ADX, etc).
It is a pretty much accepted fact that most breakouts fail, but the ones that succeed are typically very
good.
Entry #5 – Second Chance Trend
This entry is sort of trend following, sort of mean reversion, sort of anticipating a pullback. Really, it is a
combination of all 3 of these features.
For buys:
It first looks that the current close is greater than the average of the last X closes – a standard trend
measurement.
Then the entry looks for situations where the current close is in the bottom 10% of recent closes (over
the last Y bars), and/or there have been 3 down bars in a row.
Condition4=close<average(close, entry5_X);
I don’t have the 10th and 90th percentiles as variables, but you could certainly try that. Also, instead of 3
consecutive up/down days, maybe try 2 days, or 4 days. Or maybe try 3 of 4 days being up/down.
There are a lot of variations you can try with this entry.
Entry #6 – Big Range, Big Mo
I’ve traded this entry for a number of years, and I really like it. Others do too – some education guru
(actually, he is a fake guru, or a “furu”) created a video about it, and claimed he created it – yet he got it
from me! And I do not know where exactly I got it from, maybe from my own brain, but likely not. But
my ego is small (unlike the aforementioned guru); I can admit I don’t know if I created this or not. I do
happily trade it though.
The general idea is that after a big range bar, you enter in the direction of recent momentum. If you
haven’t figured this out already, I really like getting into trades in the direction of current momentum. It
is kind of like hopping on a train – would you rather get on a train moving in the direction you want, or
do you want to get on a train moving in the opposite direction, and HOPE it turns around? Pretty easy
answer to that in my simple mind…
Var: entry6_rrange(0);
entry6_rrange=high-low;
I use 2 times the standard deviation to help me determine what a “big” range is, but you could certainly
try other numbers. The one bad thing about a multiplier of 2 is that it does not allow many trades.
Maybe lowering it to 1.0 or 1.5 would give more quality trades. As always, you have to test it!
Entry #7 – The Report Play
Many markets have regular reports, whether it is weekly, monthly, quarterly, etc. Many times, these
reports, from the US govt, private industry, central banks and others, move the markets a great
magnitude, and usually do it quickly.
This idea simply places a buy and sell short stop order above and below the market a minute or so
before the report. Then, when the report hits, as long as there is a trend, you’ll catch it!
Note though that this can be dangerous. Many times markets whip back and forth after a report. Also,
right at report time, many players pull their orders, and your stop order may incur excessive slippage. I
used to trade this with Natural Gas, during the weekly energy report. It was profitable, but the slippage
was big. Eventually, I concluded the risk adjusted returns, mainly due to excessive slippage, were just
too great to bear.
Input: entry7_xxx(930);
entry7_sellprice=low-.01;
end;
end;
Instead of stop orders, I’d try limit orders, at a price you feel would be appropriate. The problem is limit
buy orders are below the market, so it is hard to trade a breakout upwards with that order – you might
miss it.
Another thing to try is to not trade report, but instead trade standard time bars. For instance, maybe
you have a chart with 15 minute bars, but you activate these orders only at the start of every hour
(every 4 bars). This might take advantage of the many people trading hourly bars.
Entry #8 – Low Vol Reversals
On bars with low volume, buy if the close is the lowest recent close. Vice versa for shorts. This type of
mean reversion trade tend to work good in stock indices.
Input: entry8_len(5);
end;
Entry #8 – Sample Equity Curve Results
Instead of buying when a local low is hit, sellshort instead. Or, instead of requiring a low volume bar for
the signal to occur, try a high volume bar instead. Lots of possibilities here.
Entry #9 – Simple Pattern
This entry is just an example of about a million different patterns you can try. Patterns are useful on
many timescales, and even though I did not have patterns for any other entry, I use them in many
strategies. Sometimes a simple price pattern does “tip” you off that the market is going to move in a
certain direction. Time to catch that train!
If low[3]>low[2] and low[2] > low[1] and close>high[1] then buy next bar at market;
If high[3]<high[2] and high[2] < high[1] and close<low[1] then sellshort next bar at market;
Entry #9 – Sample Equity Curve Results
Create your own patterns! Use candlestick patterns, or simple patterns based on open high low close
prices. There are so many things to try, you could really just stick with testing patterns. I like to observe
a market for a while, and look at some old charts, and see if anything jumps out. If it does, I’ll program
and test it.
Most patterns are probably zero-sum; meaning, they likely work about 50% of the time. But until you
test them, you do not know for sure.
Exit #1 – Simple and Sweet
Trading without a stop loss is like walking a tightrope without a net. If you fall, with no net you might
die. With a net, you still might get hurt, but you’ll likely live for another day. Same thing with stop
losses. They almost always decrease net profit, but many times will prevent big losses from becoming
enormous.
I show below a stop loss with a set dollar amount. This could be a variable if you want, and could be
based on any amount, or any calculation, you desire.
Exit #1 Code
Input: exit1_stopl(1000);
Although the common adage “the trend is your friend” implies no profit taking target, many times you
might want one. One example is with mean reverting strategies, where you might want to get in, get a
quick profit, and get out before the trend turns/resumes.
This can be set up just like the stop loss exit #1.
Exit #2 Code
Input: exit2_proft(1000);
I personally rarely use breakeven stops, but many people like them. The idea of watching a nice profit
disappear is emotionally tough. So, a breakeven stop might be in order. You do not want to use this exit
alone, but maybe in combination with other exits.
Exit #3 Code
Input:exit3_beamt(1000);
SetBreakeven(exit3_beamt) ;//if max profit exceeds exit3_beamt, then trail with a breakeven stop
Exit #4 – Trailblazer
An offshoot of the breakeven stop is the trailing stop. This can take many forms, but the general idea is
that if the price goes against you too much, you will get out. The code I show is for the simplest one, but
realize that if there is no dramatic single bar drop, this code will allow slow erosion of your profit. There
are ways to make this trail from a high point.
There are a couple of variations of a trailing stop worth mentioning. First, there is a parabolic stop,
which tends to more quickly lock in profit as the price accelerates. A second one is a chandelier stop,
championed by educator Chuck LeBeau. It also tends to lock in profits as price continues in your
direction.
Both of these can either be found as a standard Tradestation strategy, or on the Tradestation support
forums. For both of these, there are many parameters to set, and for this reason, I do not use either
very much, if at all. In my mind, the risk of curvefitting is just too great.
Exit #4 Code
Input:exit4_trailamt(1000);
Sell next bar at close-(exit4_trailamt/BigPointValue) stop; //trail the previous close by $1000, will not
be good in a slow downtrend
I once read an interview with legendary trader, and owner of the Boston Red Sox baseball team, John
Henry. He claimed he really like exiting after a certain number of bars, regardless of profit and loss.
I was amazed when I read that, because for many years that has been one of my favorite exits! I am
nowhere as successful as he is, but it is nice to know I am doing the same sort of thing.
None seem to work as well as just exiting, regardless of position profit, so that is what I’ll include here.
Exit #5 Code
Input:exit5_X(10);
End;
Exit #6 – Stop! (and Reverse)
Did you realize every entry can also be a stop and reverse exit? Or not? So, really, for every entry you
have, you can have new entries only taken when the current position is flat, or you can have entries
double as a reversal exit.
Just be careful, and make sure that you always have an exit if you are not employing stop and reverse
(Option #2 below)
Exit #6 Code
// Option #1
****************************************************
// Option #2
SetStopLoss(1000);
Exit #7 – Entries as Exits?
Most people, including myself, never really realized the power of this next exit. In September 2017, I
was teaching an advanced strategy class, and we started using typical entries as our exits. In most cases,
we actually improved performance, when compared to simple stop losses or profit targets. It was quite
incredible.
The neat thing about this approach is that every entry can double as an exit. Just imagine how many
combinations you can test with this approach!
Exit #7 Code
Input: exit7_X(5),exit7_XX(7);
//ENTRIES
//EXITS
If close crosses below average(close, exit7_XX) then sell next bar at market;
If close crosses above average(close, exit7_XX) then buytocover next bar at market;
Exit #8 – BONUS – Exit on Close
I’m including this exit as an extra bonus, because it is a tricky exit. It uses the Tradestation keyword
“setexitonclose.” The idea here is that the strategy will automatically close all positions at the last bar of
the day.
While that sounds pretty good – many times the closing price has a lot of significance, and many traders
would like to lock in that price at the end of the day, there are a few things you need to be aware of:
2. In real time trading, though, it is awful. It just does not work. The reason is the close order only gets
sent AFTER Tradestation is notified that the market is closed. So, in real time, the market closes,
Tradestation becomes aware that the market is closed, the order is then sent to the exchange, and then
the order is rejected – because you can’t send a market order to a closed market!!!
3. There is only one way around this that allows you to use setexitonclose in real trading. This piece of
information is alone worth paying for this book. I personally spent a lot of time struggling with this
issue, until I found the solution. The solution?: Custom sessions that end a few minutes before the
exchange closes.
Let’s say the exchange closes at 5:00 PM ET, which many markets do. Simply create a custom
session that closes at 4:58 PM, and include setexitonclose in your code. Then, when you run in real
time, when the 4:58 bar closes, your order will get sent and executed!
One important NOTE: to have a custom session on your chart, you cannot use daily bars in
Tradestation. You can only use custom sessions on XX minute bars.
So, because of the difficulties with using this exit, I am including it only as a “bonus.”
Exit #8 Code
Setexitonclose; //MUST use with custom session for real time trading
Big Combo Exit
The exits I just gave you are not “all or nothing.” You can easily combine them into one “super” exit.
Just remember to be careful not to add too many parameters that can be optimized. When you perform
optimization on many parameters, your model can get overfit very quickly.
Input: exit1_stopl(1000);
Input: exit2_proft(1000);
Input:exit3_beamt(1000);
SetBreakeven(exit3_beamt) ;//if max profit exceeds exit3_beamt, then trail with a breakeven stop
Where Do I Go From Here?
At this point, your head might be swimming, and honestly I am not surprised. There is a lot of
information here!
If you do not have a trading platform that you can test strategies with, I suggest you get one. Then,
learn how to program strategies in it. I use Tradestation, as do most traders I associate with. I even
have some special incentives with Tradestation for my students – just shoot me an e-mail for details.
So this is the first step – being able to program and run strategy performance tests.
The proper test method is critical to success here. Many people just think they can just create a
strategy, optimize everything, take the best overall result, and then trade it. If only!
The reality is proper strategy development and testing is a lot of work, and it is full of pitfalls. I
developed my approach the hard way, by losing money in the markets. Here is what I use today:
I call my approach the Strategy Factory® approach, and it is so unique I received a US Government
Trademark for it. It works for me, and has worked for many others I have worked with.
Before you embark on testing entries and exits, make sure you have a solid approach to develop and
test your strategies.
I have some strategies that work great on many markets, and some strategies that work great only on
one particular market. The problem is that I never know which is which until I test them!
So, before I start any testing, I usually lay out exactly what markets I am going to test, and what bar sizes
I am going to test. Both of these are critical, because a strategy with Euro daily bars might perform
totally different than a Japanese Yen strategy with daily bars, or even a Euro strategy with 120 minute
bars.
This step is “create a strategy!” Take an entry I gave earlier, couple it with one or more exits I gave, and
there you go – you have a strategy to test. Actually you have at least 2 strategies, since you can create a
reverse of any strategy.
5. Start Evaluating
Use your test and development process you created in step 2 (you do have a process, right?!?) to
establish what is a good strategy, and what is not. Then, get testing!
How Far Can I Take This Information?
By my calculations, with just the information in this book, you could test:
9 entries
7 reverse of entries I provided (only 7 since entry #1 and #2 are already reverse of each other)
50 markets
10 bar sizes (actually you can test any bar size from 1 minutes up to daily or weekly bars, so it is
many more than 10!)
WOW!
You could be testing just the ideas in this book for years. And, I am sure quite a few of those tests would
yield nice strategies. Of course, most will be junk, but that is life for a strategy developer.
To whittle it down a bit, you could focus on market sectors instead of individual markets. Maybe just
trade one instrument from each of the following sectors:
Interest Rates
Stock Indices
Currencies
Metals
Energies
Softs
For bar size, you could test only daily bars (I find those work best).
That still leaves you with 3,087 tests, which is still a daunting (but hopefully fun!) task.
The point is that in order to find strategies, you have to test strategies. Lots of strategies. Lots of tests.
It is grueling and frustrating sometimes. But when you uncover a good strategy, the work involved
always seems worth it.
Conclusion
Well, we’ve come to the end of this book. But, it is only the beginning of your algorithmic journey.
The entries and exits I have provided are from actual strategies I trade or have traded, so I know they
work. BUT THESE ENTRIES AND EXITS DO NOT WORK IN ALL SITUATIONS!!!
You have to test and evaluate various combinations, on markets you wish to trade. And that is the
tough part. Keep in mind that a proper test and evaluation process is critical. Properly testing a
strategy is not as easy as what is shown below, although many think it is:
The key with knowing you are testing correctly is in real trading. If your real money trading is meeting
your profit and risk goals, then you are developing and evaluating your strategies correctly.
If you are not meeting your goals, perhaps it is time to change the way you test your strategies. Only
you know which path to take.
If you are unsure about what you are doing, just drop me an e-mail at kdavey@kjtradingsystems.com. I
always enjoy speaking with other traders.
Good Luck, and please let me know of your entry and exit success!
ABOUT THE AUTHOR – KEVIN J. DAVEY
As an award winning full time trader, and best-selling and award winning author, Kevin Davey has been an expert
in the algorithmic trading world for several decades. Between 2005 and 2007, Kevin competed in the World Cup
Championship of Futures Trading, where he finished first once and second twice, achieving returns in excess of 100%
each year.
Kevin develops, analyzes, and tests trading strategies in every futures market from the e-mini S&P to crude oil to
corn to cocoa. He currently trades full time with his personal account. He also helps small groups of traders
significantly increase their trading prowess via his award winning algorithmic trading course, “Strategy Factory®.”
Kevin’s Strategy Factory Workshop was awarded 2016 “Trading Course of The Year” by a prestigious trading website.
More information is available at https://www.kjtradingsystems.com .
Kevin also helps educate the trading community via his best selling winning book, “Building Winning Algorithmic
Trading Systems: A Trader's Journey From Data Mining to Monte Carlo Simulation to Live Trading,” published by
Wiley. This book was a 2 time winner of TraderPlanet.com’s “Trading Book of The Year” in 2014 and 2016.
Kevin is a Summa Cum Laude graduate of The University of Michigan, with a B.S.E in aerospace engineering. Kevin
also has an MBA with Technology Management Concentration from Case Western Reserve University – Weatherhead
School of Management, where he received the Dean’s Academic Achievement Award with a perfect 4.0 grade point
average.
Prior to trading full time, Kevin was Vice President of Quality and Engineering for an aerospace company that
designed and manufactured flight critical components, managing over 100 engineers and support staff. For his
efforts, he was honored with the prestigious “40 Under 40” Award from Crain’s Cleveland Business Magazine.
Kevin currently lives outside of Cleveland, Ohio with his wife and three children.
OTHER BOOKS BY KEVIN J. DAVEY
For Beginning Algo Traders:
All of these highly ranked books are available at Amazon.com. Click on either book above to be directed to Amazon.
BONUS – CODE IN NINJASCRIPT NT7 AND NT8
Important
● These code snippets are not intended to be full strategies. They are the building blocks of
strategies, intended to illustrate various approaches to building strategies. If you run these
snippets as-is, you may or may not receive results; and depending on what concept is being
illustrated, some snippets may or may not result in one or more trades.
● This code is provided as informational and as-is, with no warranty of suitability for any particular
purpose.
● This code is not necessarily optimized. Basic and Substantial optimizations may be necessary
before using in live algorithms.
● When running a Strategy in Strategy Analyzer, it’s important to set the ‘Min. bars required’ or
else the strategy may produce an error. These values come from the different types of
calculations within the code; and are specified in each section for easy reference.
● Running backtests in NinjaScript 7 may require downloading and managing data for the
instruments and data periods you want to test.
● For more information on using Strategy Analyzer to run backtests, see:
https://ninjatrader.com/support/helpGuides/nt7/?strategy_analyzer.htm
● Minimum Bars Required to test is set both in the code, and in the Strategy Analyzer. The value
set in the module is used as the default value, but can be changed when running a backtest.
○ Set ‘’ to the number of bars required in the function called OnStateChange(), and ONLY
in the state handler section where (State == State.SetDefaults).
● In Version 8, NinjaTrader Input Variables are handled a bit differently. Instead of declared within
the module (file) with the rest of the variables and code, Inputs are declared in a separate
function called OnStateChange(), and ONLY in the state handler section where (State ==
State.SetDefaults).
○ Then, there are separate getters and setters for the actual values, with Attributes
allowing them to appear in the Strategy Window as Input Parameters
○ Getters/Setters and Attributes are standard in modern object oriented programming
languages (see Encapsulation; Attributes), But do require a slightly deeper level of
general programming knowledge.
○ IMPORTANT: Because of this, all Inputs have been converted to simple variables in
order to relieve the reader of having to know these implementation details.
● For more information on using Strategy Analyzer to run backtests, see:
https://ninjatrader.com/support/helpGuides/nt8/en-us/?strategy_analyzer.htm
//Input Variables
EnterLong();
EnterShort();
//Input Variables
EnterLong();
EnterShort();
// Input Variables
// Input Variables
NT7
// Input Variables
EnterLongStop(High[HighestBar(High, entry4_x)]);
EnterShortStop(Low[LowestBar(Low, entry4_x)]);
NT8
// Input Variables
EnterLongStopMarket(High[HighestBar(High, entry4_x)]);
EnterShortStopMarket(Low[LowestBar(Low, entry4_x)]);
// Input Variables
var Condition3 = Close[0] < Close[1] && Close[1] < Close[2] && Close[2] < Close[3];
var Condition6 = Close[0] > Close[1] && Close[1] > Close[2] && Close[2] > Close[3];
less++;
equal++;
}
NT8
less++;
// Input Variables
EnterLong();
EnterShort();
// Input Variables
if (Time[0].TimeOfDay == entry7_xxx)
entry7_buyprice = High[0] + .01; //change .01 to represent 1-2 ticks in your desired market
if (Time[0].TimeOfDay == entry7_xxx)
EnterLongStop(entry7_buyprice);
EnterShortStop(entry7_sellprice);
}
NT8
// Input Variables
if (Time[0].TimeOfDay == entry7_xxx)
entry7_buyprice = High[0] + .01; //change .01 to represent 1-2 ticks in your desired market
if (Time[0].TimeOfDay == entry7_xxx)
EnterLongStopMarket(entry7_buyprice);
EnterShortStopMarket(entry7_sellprice);
// Input Variables
int entry8_len = 5;
if (Low[3] > Low[2] && Low[2] > Low[1] && Close[0] > High[1]) EnterLong();
if (High[3] < High[2] && High[2] < High[1] && Close[0] < Low[1]) EnterShort();
// Input Variables
// Input Variables
// Input Variables
// Input Variables
#region Variables
#endregion
// Input Variables
//Calculate MaxPositionProfit
SetStopLoss(Position.AvgPrice);
NT8
// Input Variables
//Calculate MaxPositionProfit
maxPositionProfit = Math.Max(maxPositionProfit,
Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency));
SetStopLoss(CalculationMode.Currency, Position.AveragePrice);
Exit #4 - Trailblazer
// Input Variables
// Input Variables
ExitLong();
ExitShort();
}
NT8
// Input Variables
ExitLong();
ExitShort();
// Option #1
// Option #2
SetStopLoss(1000);
NT8
// Option #1
// Option #2
SetStopLoss(CalculationMode.Currency, 1000);
Exit #7 - Entries as Exits?
// Input Variables
//ENTRIES
//EXITS
NT7
Not necessary in NinjaTrader. Instead, NinjaTrader has two settings that can be called in Initialize().
ExitOnClose (true/false) controls whether or not the strategy should close all positions at the end of a
session. ExitOnCloseSeconds sets the number of seconds before the real-time session close to run the
exit logic.
NT8
In NinjaTrader8, the variables are named IsExitOnSessionCloseStrategy, and
ExitOnSessionCloseSeconds. The functionality is the same as NT7.