Sunteți pe pagina 1din 63

Copyright © 2019 by Kevin J Davey. All Rights Reserved.

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

Visit my website at KJTradingsystems.com

Printed in the United States of America

First Printing: January 2019


Contents
DISCLAIMER................................................................................................................................................... 6
Introduction .................................................................................................................................................. 7
How This Book Is Structured ......................................................................................................................... 8
Don’t Forget About the ELD and Tradestation Workspace......................................................................... 10
Entry #1 – Trade The Pullback..................................................................................................................... 11
Entry #1 - General Concept ..................................................................................................................... 11
Entry #1 - Sample Trades ........................................................................................................................ 11
Entry #1 - Tradestation Code .................................................................................................................. 11
Entry #1 – Sample Equity Curve Results ................................................................................................. 12
Entry #1 – Modifications to Try............................................................................................................... 12
Entry #2 – With Trend Pullback .................................................................................................................. 13
Entry #2 - General Concept ..................................................................................................................... 13
Entry #2 - Tradestation Code .................................................................................................................. 13
Entry #2 – Modifications to Try............................................................................................................... 13
Entry #3 – Jump Off..................................................................................................................................... 14
Entry #3 - General Concept ..................................................................................................................... 14
Entry #3 - Sample Trades ........................................................................................................................ 14
Entry #3 - Tradestation Code .................................................................................................................. 14
Entry #3 – Sample Equity Curve Results ................................................................................................. 15
Entry #3 – Modifications to Try............................................................................................................... 15
Entry #4 – Super Simple Breakout .............................................................................................................. 16
Entry #4 - General Concept ..................................................................................................................... 16
Entry #4 - Sample Trades ........................................................................................................................ 16
Entry #4 - Tradestation Code .................................................................................................................. 16
Entry #4 – Sample Equity Curve Results ................................................................................................. 17
Entry #4 – Modifications to Try............................................................................................................... 17
Entry #5 – Second Chance Trend ................................................................................................................ 18
Entry # 5 - General Concept .................................................................................................................... 18
Entry #5 - Sample Trades ........................................................................................................................ 18
Entry #5 - Tradestation Code .................................................................................................................. 18
Entry #5 – Sample Equity Curve Results ................................................................................................. 19
Entry #5 – Modifications to Try............................................................................................................... 19
Entry #6 – Big Range, Big Mo ...................................................................................................................... 20
Entry # 6 - General Concept .................................................................................................................... 20
Entry #6 - Sample Trades ........................................................................................................................ 20
Entry #6 - Tradestation Code .................................................................................................................. 21
Entry #6 – Sample Equity Curve Results ................................................................................................. 21
Entry #6 – Modifications to Try............................................................................................................... 21
Entry #7 – The Report Play.......................................................................................................................... 22
Entry # 7 - General Concept .................................................................................................................... 22
Entry #7 - Sample Trades ........................................................................................................................ 22
Entry #7 - Tradestation Code .................................................................................................................. 23
Entry #7 – Sample Equity Curve Results ................................................................................................. 23
Entry #7 – Modifications to Try............................................................................................................... 24
Entry #8 – Low Vol Reversals ...................................................................................................................... 25
Entry # 8 - General Concept .................................................................................................................... 25
Entry #8 - Sample Trades ........................................................................................................................ 25
Entry #8 - Tradestation Code .................................................................................................................. 25
Entry #8 – Sample Equity Curve Results ................................................................................................. 26
Entry #8 – Modifications to Try............................................................................................................... 26
Entry #9 – Simple Pattern ........................................................................................................................... 27
Entry # 9 - General Concept .................................................................................................................... 27
Entry #9 - Sample Trades ........................................................................................................................ 27
Entry #9 - Tradestation Code .................................................................................................................. 27
Entry #9 – Sample Equity Curve Results ................................................................................................. 28
Entry #9 – Modifications to Try............................................................................................................... 28
Exit #1 – Simple and Sweet ......................................................................................................................... 29
Exit #1 Code ............................................................................................................................................ 29
Exit #2 – Hit That Target! ............................................................................................................................ 30
Exit #2 Code ............................................................................................................................................ 30
Exit #3 – At Least Breakeven ....................................................................................................................... 31
Exit #3 Code ............................................................................................................................................ 31
Exit #4 – Trailblazer ..................................................................................................................................... 32
Exit #4 Code ............................................................................................................................................ 32
Exit #5 – John Henry Exit ............................................................................................................................. 33
Exit #5 Code ............................................................................................................................................ 33
Exit #6 – Stop! (and Reverse) ...................................................................................................................... 34
Exit #6 Code ............................................................................................................................................ 34
Exit #7 – Entries as Exits? ............................................................................................................................ 35
Exit #7 Code ............................................................................................................................................ 35
Exit #8 – BONUS – Exit on Close.................................................................................................................. 36
Exit #8 Code ............................................................................................................................................ 36
Big Combo Exit ............................................................................................................................................ 37
Big Combo Exit Code ............................................................................................................................... 37
Where Do I Go From Here?......................................................................................................................... 38
How Far Can I Take This Information? ........................................................................................................ 40
Conclusion ................................................................................................................................................... 42
ABOUT THE AUTHOR – KEVIN J. DAVEY ...................................................................................................... 43
OTHER BOOKS BY KEVIN J. DAVEY .............................................................................................................. 44
BONUS – CODE IN NINJASCRIPT NT7 AND NT8 .......................................................................................... 45
DISCLAIMER

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.

CFTC RULE 4.41 - HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN


LIMITATIONS. UNLIKE AN ACTUAL PERFORMANCE RECORD, SIMULATED RESULTS DO NOT REPRESENT
ACTUAL TRADING. ALSO, SINCE THE TRADES HAVE NOT BEEN EXECUTED, THE RESULTS MAY HAVE
UNDER-OR-OVER COMPENSATED FOR THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS
LACK OF LIQUIDITY. SIMULATED TRADING PROGRAMS IN GENERAL ARE ALSO SUBJECT TO THE FACT
THAT THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO REPRESENTATION IS BEING MADE
THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFIT OR LOSSES SIMILAR TO THOSE SHOWN.

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.

Email: kdavey at kjtradingsystems.com


Introduction

“Hi, I’m Kevin, and I’m an algorithmic trader.”

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.

So, with that, let’s get started!


How This Book Is Structured

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

Entry #1 - General Concept


In most longer trends, there are pullbacks – short term movements against that primary trend. This
could initiate from people taking profits on their existing trades, for example.

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.

Entry #1 - Sample Trades

Entry #1 - Tradestation Code

Input:entry1_sl(5),entry1_slx(20);

//entry1_sl = short term trend length

//entry1_slx = longer term trend length


if c>c[entry1_sl] and c<c[entry1_slx] then buy next bar at market;

if c<c[entry1_sl] and c>c[entry1_slx] then sellshort next bar at market;

Entry #1 – Sample Equity Curve Results

Here is a performance curve, with a simple exit:

Entry #1 – Modifications to Try

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

Entry #2 - General Concept

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.

Entry #2 - Tradestation Code

Input:entry2_sl(5), entry2_slx(20);

// entry2_sl = short term trend length

// entry2_slx = longer term trend length

if c<c[entry2_sl] and c>c[entry2_slx] then buy next bar at market;

if c>c[entry2_sl] and c<c[entry2_slx] then sellshort next bar at market;

Entry #2 – Modifications to Try

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

Entry #3 - General Concept

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.

Entry #3 - Sample Trades

Entry #3 - Tradestation Code

Input: entry3_pbasebar(10), entry3_trendbar(20), entry3_atrmult(2);

var: entry3_pbase(0);
entry3_pbase =(highest(high, entry3_pbasebar)+lowest(low, entry3_pbasebar))/2;

If close>close[entry3_trendbar] then buy next bar at entry3_pbase +


entry3_atrmult*AvgTrueRange(15) stop;

If close<close[entry3_trendbar] then sellshort next bar at entry3_pbase -


entry3_atrmult*AvgTrueRange(15) stop;

Entry #3 – Sample Equity Curve Results

Here is a performance curve, with a simple exit:

Entry #3 – Modifications to Try

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

Entry #4 - General Concept

VERY simple breakout, different than Entry #3. Same basic idea, though; hop aboard the train as it starts
moving away from the station!

Entry #4 - Sample Trades

Entry #4 - Tradestation Code

Input: entry4_x(10);

Buy next bar at highest(high, entry4_x) stop;

SellShort next bar at lowest(low, entry4_x) stop;


Entry #4 – Sample Equity Curve Results

Here is a performance curve, with a simple exit:

Entry #4 – Modifications to Try

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

Entry # 5 - General Concept

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.

Obviously, for selling short it is the exact opposite.

Entry #5 - Sample Trades

Entry #5 - Tradestation Code

Input: entry5_X(10), entry5_Y(15);


Condition1=close>average(close, entry5_X);

Condition2=close<Percentile(.10, Close, entry5_Y);

Condition3=close<close[1] and close[1]<close[2] and close[2]<close[3];

If condition1 and (condition2 or condition3) then buy next bar at market;

Condition4=close<average(close, entry5_X);

Condition5=close>Percentile(.90, Close, entry5_Y);

Condition6=close>close[1] and close[1]>close[2] and close[2]>close[3];

If condition4 and (condition5 or condition6) then sellshort next bar at market;

Entry #5 – Sample Equity Curve Results

Here is a performance curve, with a simple exit:

Entry #5 – Modifications to Try

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

Entry # 6 - General Concept

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…

Entry #6 - Sample Trades


Entry #6 - Tradestation Code

Input: entry6_xr(5), entry6_daysback(10);

Var: entry6_rrange(0);

entry6_rrange=high-low;

if entry6_rrange>2*stddev(entry6_rrange, entry6_xr)+average(entry6_rrange, entry6_xr) and


close>close[entry6_daysback] then buy next bar at market;

if entry6_rrange>2*stddev(entry6_rrange, entry6_xr)+average(entry6_rrange, entry6_xr) and


close<close[entry6_daysback] then sellshort next bar at market;

Entry #6 – Sample Equity Curve Results

Here is a performance curve, with a simple exit:

Entry #6 – Modifications to Try

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

Entry # 7 - General Concept

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.

Entry #7 - Sample Trades


Entry #7 - Tradestation Code

Input: entry7_xxx(930);

Var: entry7_buyprice(0), entry7_sellprice(0);

If time= entry7_XXX then begin

entry7_buyprice=high+.01; //change .01 to represent 1-2 ticks in your desired market

entry7_sellprice=low-.01;

end;

If time= entry7_XXX then begin

Buy next bar at entry7_buyprice stop;

Sellshort next bar at entry7_sellprice stop;

end;

Entry #7 – Sample Equity Curve Results

Here is a performance curve, with a simple exit:


Entry #7 – Modifications to Try

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

Entry # 8 - General Concept

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.

Entry #8 - Sample Trades

Entry #8 - Tradestation Code

Input: entry8_len(5);

If v<average(v,5) then begin

If close=lowest(close, entry8_len) then buy next bar at market;

If close=highest(close, entry8_len) then sellshort next bar at market;

end;
Entry #8 – Sample Equity Curve Results

Here is a performance curve, with a simple exit:

Entry #8 – Modifications to Try

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

Entry # 9 - General Concept

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!

Entry #9 - Sample Trades

Entry #9 - Tradestation Code

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

Here is a performance curve, with a simple exit:

Entry #9 – Modifications to Try

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

Setstopcontract; //calculate the stop loss as dollars per contract

SetStopLoss(exit1_stopl); // $ exit1_stopl stop loss per contract

//SetStopLoss(3*AvgTrueRange(15)*BigPointValue); // 3 ATR stop (popular with Van Tharp fans)


Exit #2 – Hit That Target!

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

Setstopcontract; //calculate as dollars per contract

SetProfitTarget (exit2_proft); // exit2_proft profit target per contract


Exit #3 – At Least Breakeven

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

BuyToCover next bar at close+(exit4_trailamt/BigPointValue) stop; //trail the previous close by


$1000, will not be good in a slow downtrend
Exit #5 – John Henry Exit

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.

I have tried all sorts of variations:

 Exit after X bars only if profitable

 Exit after X bars only if in losing trade

 Switch to breakeven after X bars

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

If BarsSinceEntry>=exit5_X then begin

Sell next bar at market;

BuyToCover next bar at market;

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

//stop and reverse type entry/exit pairs

If close>close[5] then buy next bar at market;

If close<close[5] then Sellshort next bar at market;

****************************************************

// Option #2

//no stop and reverse (only stop loss exit)

If marketposition=0 and close>close[5] then buy next bar at market;

If marketposition=0 and close<close[5] then Sellshort next bar at market;

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

// momentum entry, moving average crossover exit

Input: exit7_X(5),exit7_XX(7);

//ENTRIES

If close>close[exit7_X] then buy next bar at market;

If close<close[exit7_X] then sellshort next bar at market;

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

1. Setexitonclose works great in backtest. It is flawless.

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.

Big Combo Exit Code

//Stop loss, profit target and breakeven stop all together

Input: exit1_stopl(1000);

Input: exit2_proft(1000);

Input:exit3_beamt(1000);

Setstopcontract; //calculate the stop loss as dollars per contract

SetStopLoss(exit1_stopl); // $ exit1_stopl stop loss per contract

SetProfitTarget (exit2_proft); // exit2_proft profit target per contract

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!

Here is how I recommend you proceed:

1. Learn Your Trading Platform

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.

2. Have a Structured Approach For Testing and Development

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.

3. Select Some Markets, and Bar Sizes

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.

4. Put Together Entries and Exits

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.

Just code the strategy, verify it and you’ll be ready to test.

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)

 7 exits (even more if you combine them in different configurations)

 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!)

Multiplying it out, you have

9 x 7 x 7 x 50 x 10 = 220,500 unique tests

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

 Grains and Ags

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:

For Intermediate/Advanced Algo Traders:

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

Notes about NinjaScript 7

● 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

Notes about NinjaScript 8

● 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

Translations provided by IronBuffalo. Please mail IronBuffalo@mail.com with comments, questions, or


errata.
Entry #1 - Trade The Pullback

Minimum Bars Required to Test: 20

NT7 and NT8

//Input Variables

int entry1_sl =5, entry1_slx = 20;

//entry1_sl = short term trend length

//entry1_slx = longer term trend length

if (Close[0] > Close[entry1_sl] && Close[0] < Close[entry1_slx])

EnterLong();

if (Close[0] < Close[entry1_sl] && Close[0] > Close[entry1_slx])

EnterShort();

Entry #2 - With Trend Pullback

Minimum Bars Required to Test: 20


NT7 and NT8

//Input Variables

int entry2_sl = 5, entry2_slx = 20;

// entry2_sl = short term trend length

// entry2_slx = longer term trend length

if (Close[0] < Close[entry2_sl] && Close[0] > Close[entry2_slx])

EnterLong();

if (Close[0] > Close[entry2_sl] && Close[0] < Close[entry2_slx])

EnterShort();

Entry #3 - Jump Off

Minimum Bars Required Required to Test: 20


NT7

// Input Variables

int entry3_pbasebar = 10, entry3_trendbar = 20, entry3_atrmult = 2;

var entry3_pbase = (High[HighestBar(High, entry3_pbasebar)] + Low[LowestBar(Low, entry3_pbasebar)])


/ 2;

if (Close[0] > Close[entry3_trendbar])

EnterLongStop(entry3_pbase + entry3_atrmult * ATR(15)[0]);

if (Close[0] < Close[entry3_trendbar])

EnterShortStop(entry3_pbase - entry3_atrmult * ATR(15)[0]);


NT8

// Input Variables

int entry3_pbasebar = 10, entry3_trendbar = 20, entry3_atrmult = 2;

var entry3_pbase = (High[HighestBar(High, entry3_pbasebar)] + Low[LowestBar(Low, entry3_pbasebar)])


/ 2;

if (Close[0] > Close[entry3_trendbar])

EnterLongStopMarket(entry3_pbase + entry3_atrmult * ATR(15)[0]);

if (Close[0] < Close[entry3_trendbar])

EnterShortStopMarket(entry3_pbase - entry3_atrmult * ATR(15)[0]);


Entry #4 - Super Simple Breakout

Minimum Bars Required Required to Test: 10

NT7

// Input Variables

int entry4_x = 10;

EnterLongStop(High[HighestBar(High, entry4_x)]);

EnterShortStop(Low[LowestBar(Low, entry4_x)]);
NT8

// Input Variables

int entry4_x = 10;

EnterLongStopMarket(High[HighestBar(High, entry4_x)]);

EnterShortStopMarket(Low[LowestBar(Low, entry4_x)]);

Entry #5 - Second Chance Trend

Minimum Bars Required Required to Test: 15


NT7 and NT8

// Input Variables

int entry5_X = 10, entry5_Y = 15;

var Condition1 = Close[0] > SMA(entry5_X)[0];

var Condition2 = Close[0] < GetPercentile(.10, Close, entry5_Y);

var Condition3 = Close[0] < Close[1] && Close[1] < Close[2] && Close[2] < Close[3];

if (Condition1 && (Condition2 || Condition3)) EnterLong();

var Condition4 = Close[0] < SMA(entry5_X)[0];

var Condition5 = Close[0] > GetPercentile(.90, Close, entry5_Y);

var Condition6 = Close[0] > Close[1] && Close[1] > Close[2] && Close[2] > Close[3];

if (Condition4 && (Condition5 || Condition6)) EnterShort();


Notes:
GetPercentile() is not a built in function with NinjaScript. This function is required as well:
NT7

private double GetPercentile(double rank, IDataSeries series, int xbars)

// Simple math-based approach to percentile

int less = 0, equal = 0;

for (var i = 0; i < xbars; i++)

if (series[i] < rank)

less++;

else if (series[i] == rank)

equal++;

return (200 * less + 100 * equal) / (xbars * 2);

}
NT8

// Be sure BarsRequiredToTrade is more than xbars, or this may crash

private double GetPercentile(double rank, ISeries<double> series, int xbars)

// Simple math-based approach to percentile

int less = 0, equal = 0;

for (var i = 0; i < xbars; i++)

if (series[i] < rank)

less++;

else if (series[i] == rank)


equal++;

return (200 * less + 100 * equal) / (xbars * 2);

Entry #6 - Big Range, Big Mo

Minimum Bars Required to Test: 10

NT7 and NT8

// Input Variables

int entry6_xr = 5, entry6_daysback = 10;

var entry6_rrange = Range();

if ((entry6_rrange[0] > 2 * StdDev(entry6_rrange, entry6_xr)[0] + SMA(entry6_rrange, entry6_xr)[0]) &&


Close[0] > Close[entry6_daysback])

EnterLong();

if ((entry6_rrange[0] > 2 * StdDev(entry6_rrange, entry6_xr)[0] + SMA(entry6_rrange, entry6_xr)[0]) &&


Close[0] < Close[entry6_daysback])

EnterShort();

Entry #7 - The Report Play

Minimum Bars Required to Test: 1


NT7

// Input Variables

var entry7_xxx = new TimeSpan(9,30,0);

double entry7_buyprice = 0, entry7_sellprice = 0;

if (Time[0].TimeOfDay == entry7_xxx)

entry7_buyprice = High[0] + .01; //change .01 to represent 1-2 ticks in your desired market

entry7_sellprice = Low[0] - .01;

if (Time[0].TimeOfDay == entry7_xxx)

EnterLongStop(entry7_buyprice);

EnterShortStop(entry7_sellprice);

}
NT8

// Input Variables

var entry7_xxx = new TimeSpan(9,30,0);

double entry7_buyprice = 0, entry7_sellprice = 0;

if (Time[0].TimeOfDay == entry7_xxx)

entry7_buyprice = High[0] + .01; //change .01 to represent 1-2 ticks in your desired market

entry7_sellprice = Low[0] - .01;


}

if (Time[0].TimeOfDay == entry7_xxx)

EnterLongStopMarket(entry7_buyprice);

EnterShortStopMarket(entry7_sellprice);

Entry #8 - Low Vol Reversals

Minimum Bars Required to Test: 5

NT7 and NT8

// Input Variables

int entry8_len = 5;

if (Volume[0] < SMA(Volume, 5)[0])

if (Close[0] == Close[LowestBar(Close, entry8_len)]) EnterLong();

if (Close[0] == Close[HighestBar(Close, entry8_len)]) EnterShort();

Entry #9 - Simple Pattern

Minimum Bars Required to Test: 4


NT7 and NT8

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();

Exit #1 - Simple and Sweet

Minimum Bars Required to Test: 1 (15 if using ATR)


NT7

// Input Variables

double exit1_stopl = 1000;

SetStopLoss(Position.Quantity == 0 ? exit1_stopl : exit1_stopl / Position.Quantity); // $ exit1_stopl stop


loss per contract

//SetStopLoss(3 * ATR(15) * Instrument.MasterInstrument.PointValue); // 3 ATR stop (popular with Van


Tharp fans)

// NOTE: The expression 'Position.Quantity == 0 ? exit1_stopl : exit1_stopl / Position.Quantity' prevents a


divide by zero condition if we have no open positions
NT8

// Input Variables

double exit1_stopl = 1000;

SetStopLoss(CalculationMode.Currency, Position.Quantity == 0 ? exit1_stopl : exit1_stopl /


Position.Quantity); // $ exit1_stopl stop loss per contract

//SetStopLoss(3 * ATR(15)[0] * Instrument.MasterInstrument.PointValue); // 3 ATR stop (popular with


Van Tharp fans)

// NOTE: The expression 'Position.Quantity == 0 ? exit1_stopl : exit1_stopl / Position.Quantity' prevents a


divide by zero condition if we have no open positions

Exit #2 - Hit That Target!

Minimum Bars Required to Test: 1


NT7

// Input Variables

double exit2_proft = 1000;

SetProfitTarget(Position.Quantity == 0 ? exit2_proft : exit2_proft / Position.Quantity); //exit2_proft profit


target per contract

// NOTE: The expression 'Position.Quantity == 0 ? exit2_proft : exit2_proft / Position.Quantity' prevents a


divide by zero condition if we have no open positions
NT8

// Input Variables

double exit2_proft = 1000;

SetProfitTarget(CalculationMode.Currency, Position.Quantity == 0 ? exit2_proft : exit2_proft /


Position.Quantity); //exit2_proft profit target per contract

// NOTE: The expression 'Position.Quantity == 0 ? exit2_proft : exit2_proft / Position.Quantity' prevents a


divide by zero condition if we have no open positions

Exit #3 - At Least Breakeven

Minimum Bars Required to Test: 1


NT7

// Module(class) level Variables

#region Variables

private double maxPositionProfit = 0; // be sure to reset to zero on new position

#endregion

// Input Variables

double xit3_beamt = 1000;

//Calculate MaxPositionProfit

maxPositionProfit = Math.Max(maxPositionProfit, Position.GetProfitLoss(PerformanceUnit.Currency));

if (maxPositionProfit > xit3_beamt)

SetStopLoss(Position.AvgPrice);
NT8

// Module(class) level Variable

private double maxPositionProfit = 0; // be sure to reset to zero on new position

// Input Variables

double xit3_beamt = 1000;

//Calculate MaxPositionProfit
maxPositionProfit = Math.Max(maxPositionProfit,
Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency));

if (maxPositionProfit > xit3_beamt)

SetStopLoss(CalculationMode.Currency, Position.AveragePrice);

Exit #4 - Trailblazer

Minimum Bars Required to Test: 1

NT7 and NT8

// Input Variables

double exit4_trailamt = 1000;

ExitLongStopMarket(Close[0] - (exit4_trailamt / Instrument.MasterInstrument.PointValue)); //trail the


previous close by $1000, will not be good in a slow downtrend

ExitShortStopMarket(Close[0] + (exit4_trailamt / Instrument.MasterInstrument.PointValue)); //trail the


previous close by $1000, will not be good in a slow downtrend

Exit #5 - John Henry Exit

Minimum Bars Required to Test: 1


NT7

// Input Variables

double exit5_X = 10;

if (BarsSinceEntry() >= exit5_X)

ExitLong();

ExitShort();

}
NT8

// Input Variables

double exit5_X = 10;

if (BarsSinceEntryExecution() >= exit5_X)

ExitLong();

ExitShort();

Exit #6 - Stop! (and Reverse)

Minimum Bars Required to Test: 6


NT7

// Option #1

//stop and reverse type entry/exit pairs

if (Close[0] > Close[5]) EnterLong();

if (Close[0] < Close[5]) EnterShort();

// Option #2

//no stop and reverse (only stop loss exit)

if (Position.MarketPosition == MarketPosition.Flat && Close[0] > Close[5]) EnterLong();

if (Position.MarketPosition == MarketPosition.Flat && Close[0] > Close[5]) EnterShort();

SetStopLoss(1000);
NT8

// Option #1

//stop and reverse type entry/exit pairs

if (Close[0] > Close[5]) EnterLong();

if (Close[0] < Close[5]) EnterShort();

// Option #2

//no stop and reverse (only stop loss exit)

if (Position.MarketPosition == MarketPosition.Flat && Close[0] > Close[5]) EnterLong();

if (Position.MarketPosition == MarketPosition.Flat && Close[0] > Close[5]) EnterShort();

SetStopLoss(CalculationMode.Currency, 1000);
Exit #7 - Entries as Exits?

Minimum Bars Required to Test: 7

NT7 and NT8

// Input Variables

// momentum entry, moving average crossover exit

int exit7_X = 5, exit7_XX = 7;

//ENTRIES

if (Close[0] > Close[exit7_X]) EnterLong();

if (Close[0] < Close[exit7_X]) EnterShort();

//EXITS

if (CrossBelow(Close[0], SMA(Close, exit7_XX), 1)) ExitLong();

if (CrossAbove(Close[0], SMA(Close, exit7_XX), 1)) ExitShort();

Exit #8 – BONUS – Exit on Close

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.

S-ar putea să vă placă și