# Check out the latest video on Pyramiding.

Here is the finalized tutorial on building the pyramiding ES-day-trade system that was presented in the last post.

I will admit this video should be half as long as the end result.  I get a bit long-winded.  However, I think there are some good pointers that should save you some time when programming a similar system.

### EasyLanguage Source:

Here is the final code from the video:

``````vars: mp(0),lastTradePrice(0),canSell(true);

mp = marketPosition * currentContracts;

if date <> date then
begin
canSell = true;  // canSell on every day
end;

if mp = -1 then canSell = false; // one trade on - no more
if time > 1430 then canSell = false; //no entries afte 230 central

if mp = 0 and canSell = true then sellShort next bar at OpenD(0) - 3 stop;

if mp = -1 then sellShort next bar at OpenD(0) - 6 stop; //add 1
if mp = -2 then sellShort next bar at OpenD(0) - 9 stop; //add 2

if mp = -1 then lastTradePrice = OpenD(0) - 3; //keep track of entryPrice
if mp = -2 then lastTradePrice = OpenD(0) - 6;
if mp = -3 then lastTradePrice = OpenD(0) - 9;

if mp <> 0 then buyToCover next bar at lastTradePrice + 3 stop; // 3 handle risk on last trade

// next line provides a threshold prior to engaging trailing stop
if mp = -3 and barsSinceEntry > 0 and lowD(0) < lastTradePrice - 3 then buyToCover next bar at lowD(0) + 3 stop;

setExitOnClose;``````
EasyLanguage for Pyramiding and Day-Trading ES

### What we learned here:

• can’t use entriesToday(date) to determine last entry price
• must use logic to not issue an order to execute on the first bar of the next day
• mp = marketPosition * currentContracts is powerful stuff!

In the next few days, I will publish the long side version of this code and also a more eloquent approach to the programming that will allow for future modifications and flexibility.

#### Let me know how it works out for you.

Take this code and add some filters to prevent trading every day or a filter to only allow long entries!

# Learn to Program Pyramiding Algorithm

Would you like to learn how to do this?  Check back over the next few days and I will show you to do it.  Warning:  its not straightforward as it seems – some tricks are involved.  Remember to sign up for email notifications of new posts.

UPDATE:  I have recorded an introductory webcast on how to program this pyramiding scheme.  This webcast is Part 1 and illustrates how to brainstorm and start thinking/programming about a problem.  Part 1 introduces some concepts that show how you can use and adapt some of EasyLanguage built-in reserved words and functions.  I start from the perspective of a somewhat beginning EasyLanguage programmer  – one that knows enough to maybe not get the problem solved, but at least get the ball rolling.  The final code may not look anything like the code I present in Part 1.  However it is sometimes important to go down the wrong trail so that you can learn the limitations of a programming language.  Once you know the limitations, you can go about programming workarounds and fixes.  I hope you enjoy Part 1  I should have Part 2 up soon.  Don’t be too critical, this is really the first webcast I have recorded.  You’ll notice I repeat myself and I refer  to one function input as a subscript.  Check it out:  https://youtu.be/ip-DyyKpOTo

# Don’t Fool Yourself – Limitations of Back Testing with Daily Data [EasyLanguage]

Which equity curve do you like best? (created with EasyLanguage script) This one… Or this one? Obviously the first one.  Even though it had a substantial draw down late in the test.  What if I told you that the exact same system logic generated both curves?  Here is the EasyLanguage code for this simple system.

``````Buy next bar at open of next bar + .25 *avgTrueRange(10) stop;
Sellshort next bar at open of next bar - .25*avgTrueRange(10) stop;

setStopLoss(500);
setProfitTarget(1000);``````
Open Range Break Out with Profit and Loss Objective

This algorithm relies heavily on needing to know which occurred first: the high or the low of the day.   The second chart tells the true story because it looks inside the daily bar to see what really happened.  The first chart uses an algorithm to try to determine which happened first and applies this to the trades.  In some instances,  the market looks like it opens then has a slight pull back and then goes up all day.  As a result the system buys and holds the trade through the close and onto the next day, but in reality the market opens, goes up and triggers a long entry, then retraces and you get stopped out.  What was a nice winner turns into a bad loss.  Here is an example of what might have happened during a few trades: Nice flow – sold, bought, sold, bought, sold again and finally a nice profit.  But this is what really happened: Sold, bought, reversed short on same day and stopped out on same day.  Then sold and reversed long on same day and finally sold and took profit.   TradeStation’s Look Inside Bar feature helps out when your system needs to know the exact path the market made during the day.  In many cases, simply clicking this feature to on will take care of most of your testing needs.  However, this simple algorithm needs to place or replace orders based on what happens during the course of the day.  With daily bars you are sitting on the close of the prior day spouting off orders.  So once the new day starts all of your orders are set.  You can’t see this initially on the surface, because it seems the algorithm is so simple.   Here is another consequence of day bar testing when the intra-day market movement is paramount: Here the computer is doing exactly what you told it!  Sell short and then take a profit and sell short 25% of the ATR below the open.  Well once the system exited the short it realized it was well below the sell entry point so it immediately goes short at the exact same price (remember TS doesn’t allow stop limit orders).  You told the computer that you wanted to be short if the market moves a certain amount below the open.  These were the orders that were place on yesterday’s close  This may not be exactly what you wanted, right?  You probably wanted to take the profit and then wait for the next day to enter a new trade.  Even if you did want to still be short after the profit level was obtained you wouldn’t want to exit and then reenter at the same price (practically impossible) and be levied a round-turn slip and commission.   You could fiddle around with the code and try to make it work, but I guarantee you that a system like this can only be tested properly on intra-day data.  Let’s drop down to a lower time frame, program the system and see what the real results look like: Looks very similar to the daily bar chart with Look Inside Bar turned on.  However, it is different.  If you wan’t to gauge a systems potential with a quick program, then go ahead and test on daily bars with LIB turned on.  If it shows promise, then invest the time and program the intra-day version just to validate your results.  What do you mean spend the time?  Can’t you simply turn your chart from daily bars to five minute bars and be done with it.  Unfortunately no!  You have to switch paradigms and this requires quite a bit more programming.  Here is our simple system now in EasyLanguage:

``````Vars:stb(0),sts(0),atr(0),icnt(0);

{Use highD() and XXXXD(0)  functions to capture the highs, lows, and closes for the past 10 days.
I could have just used a daily bar as data2.
I am looking at five minute bars so we know how the market flows through the day.
}

{This loop kicks out a warning message, but seems to work
Just do this once at the beginning of the day - faster}

{remember true range is either the higher of todays high
Or yesterdays close minus the lower of todays low or
yesterdays close}

{ tradeStation time stamps at the close of the bar so
we capture the opening of the open time plus the bar interval -
in this case 5 minute - so at 1800 + 5 (1805) I capture the open
of the day}

if time = sess1StartTime + barInterval then
begin
Value1 = 0.0;
for icnt = 1 to 10
begin
Value1 = value1 + maxList(closeD(icnt-1),highD(icnt)) - minList(closeD(icnt-1),lowD(icnt));
end;
atr = value1/10.0;
stb = open + .25* atr;
sts = open - .25* atr;
sellsToday = 0;
end;

mp = marketPosition; {The ole mp trick}

If mp = 1 and mp <> 1 then buysToday = buysToday + 1;
If mp =-1 and mp <> -1 then sellsToday = sellsToday + 1;

if buysToday = 0  and time < sess1EndTime and close <= stb then buy next bar at stb stop;
if sellsToday = 0 and time < sess1EndTime and close >= sts then sellshort next bar at sts stop;

setStopLoss(500);
setProfitTarget(1000);``````
Open Range Break Out Utilizing Five Minute Bars

Here is a validation that Look Inside Bar does work: This is the trade from June 1st.  Scroll back up to the second chart where LIB is turned on.

# Camarilla – A group of confidential, often scheming advisers; a cabal.

An attentive reader of this blog, Walter Baker,  found some typos in my code.  I have corrected them in the code section – if you have used this code make sure you copy and paste the code in its entirety into your EasyLanguage editor and replace your prior version.

I wanted to elaborate on the original version of Camarilla.  The one that users have been downloading from this website is pure reversion version.  The Camarilla Equation was by created by Nick Scott, a bond day trader, in 1989.  The equation uses just yesterday’s price action to project eight support/resistance price levels onto today’s trading action.  These levels, or advisers, as the name of the equation suggests provides the necessary overlay to help predict turning points as well as break outs.  Going through many charts with the Camarilla indicator overlay it is surprising how many times the market does in fact turn at one of these eight price levels.  The equations that generate the support/resistance levels are mathematically simple:

Resistance #4 = Close + Range * 1.1 / 2;

Resistance #3 = Close + Range * 1.1/4;

Resistance #2 = Close + Range * 1.1/6;

Resistance #1 = Close + Range * 1.1/12;

Support #1 = Close – Range * 1.1/12;

Support #2 = Close – Range * 1.1/6;

Support #3 = Close – Range * 1.1/4;

Support #4 = Close – Range * 1.1/2;

The core theory behind the equation and levels is that prices have a tendency to revert to the mean.  Day trading the stock indices would be easy if price broke out and continued in that direction throughout the rest of the day.  We all know that “trend days” occur very infrequently on a day trade basis; most of the time the indices just chop around without any general direction.  This is where the Camarilla can be effective.  Take a look at the following chart [ ES 5-minute day session] where the indicator is overlaid. and how the strategy was able to take advantage of the market’s indecisiveness.  This particular example shows the counter-trend nature of the Camarilla.  The original Camarilla looked at where the market opened to make a trading decision.  The chart below is an adapted version of the one I send out when one registers on for the download.   I thought it would be a good idea to show the original that incorporates a break out along with the counter trend mechanism.  I will go over the code in the next post.  You can copy the code below and paste directly into you EasyLanguage editor.

## Original Camarilla rules:

• If market opens between R3 and R4 go with the break out of R4.  This is the long break out part of the strategy.
• If market opens between R3 and S3 then counter trend trade at the R3 level.  In other words, sell short at R3.  If the market moves down, then buy S3.  As you can see this is the mean reversion portion of the strategy.
• If market open between S3 and S4 go with the break out of S4 – the short break out method.
• Stops are placed in the following manner:
• If long from a R4 break-out, then place stop at R3.
• If short from a S4 break-out, then place stop at S3.
• If long from a R3 countertrend, then place stop at R4.
• If short from a S3 countertrend, then place stop at S4.
• Profit objectives can be placed at opposite resistance/support levels:
• If short from a R3 countertrend, then take profits at S1, S2, or S3.
• If long from a S3 countertrend, then take profits at R1, R2, or R3.

Profit objectives for all trades can be a dollar, percent of price of ATR multiple.

``````inputs: endTradetime(1530);
vars:	R1(0),R2(0),R3(0),R4(0),S1(0),S2(0),S3(0),S4(0),pivotPoint(0),myAvg(0);
vars: s3_s4(0),s2_s3(0),s1_s2(0),s4_s5(0);
vars: r1_r2(0),r2_r3(0),r3_r4(0),r4_r5(0);
vars: r1_s1(0),r3_s3(0),r4_s4(0),r5_s5(0);

if date <> date then
begin
sellTrig = 0;
waitBar = 0;

s3Pen = 0;
r3Pen = 0;
s4Pen = 0;
r4Pen = 0;
s2Pen = 0;
r2Pen = 0;

sellsToday = 0;

r4_r5 = 0;
r3_r4 = 0;
r2_r3 = 0;
r1_r2 = 0;

r1_s1 = 0;
r3_s3 = 0;
r4_s4 = 0;
r5_s5 = 0;

s1_s2 = 0;
s2_s3 = 0;
s3_s4 = 0;
s4_s5 = 0;

end;

waitBar = waitBar + 1;

R4 = CloseD(1)+(HighD(1)-LowD(1)) * 1.1 / 2;
R3 = CloseD(1)+(HighD(1)-LowD(1)) * 1.1/4;
R2 = CloseD(1)+(HighD(1)-LowD(1)) * 1.1/6;
R1 = CloseD(1)+(HighD(1)-LowD(1)) * 1.1/12;
S1 = CloseD(1)-(HighD(1)-LowD(1)) * 1.1/12;
S2 = CloseD(1)-(HighD(1)-LowD(1)) * 1.1/6;
S3 = CloseD(1)-(HighD(1)-LowD(1)) * 1.1/4;
S4 = CloseD(1)-(HighD(1)-LowD(1)) * 1.1/2;

if openD(0)<= s4 then s4_s5 = 1;

If openD(0)> s4 and openD(0) <= s3 then s3_s4 = 1;
If openD(0)> s3 and openD(0) <= s2 then s2_s3 = 1;
If openD(0)> s2 and openD(0) <= s1 then s1_s2 = 1;

If openD(0)> s1 and openD(0) <= r1 then r1_s1 = 1;

If openD(0)> r1 and openD(0) <= r2 then r1_r2 = 1;
If openD(0)> r2 and openD(0) <= r3 then r2_r3 = 1;
If openD(0)> r3 and openD(0) <= r4 then r3_r4 = 1;

If openD(0)> r4 then r4_r5 = 1;

if openD(0) < r3 and openD(0) > s3 then r3_s3 = 1;
If openD(0) < r4 and openD(0) > s4 then r4_s4 = 1;

if time < endTradeTime and time > 930 then
begin

if r3_r4 = 1 and entriesToday(date) < 3 and  c < r4 then buy("R4-BrkOut") next bar at r4 stop;
if s3_s4 = 1 and entriesToday(date) < 3 and  c > s4 then sellShort("S4-BrkOut") next bar at s4 stop;

if c > r2 then r2Pen = 1;
if c > r3 then r3Pen = 1;
if c > r4 then r4Pen = 1;

if r3_s3 = 1 and r3Pen = 1 and c > r3 and entriesToday(date) < 3
then sellShort("R3Sell") next bar at r3 stop;

if r4Pen = 1 and c < r4 then r4Pen = 0;
if r3Pen = 1 and c < r3 then r3Pen = 0;
if r2Pen = 1 and c < r2 then r2Pen = 0;

if c < r1 then
begin
r2Pen = 0;
r3Pen = 0;
r4Pen = 0;
end;
if c > s1 then
begin
s2Pen = 0;
s3Pen = 0;
s4Pen = 0;
end;

if c < s2 then s2Pen = 1;
if c < s3 then s3Pen = 1;
if c < s4 then s4Pen = 1;

if r3_s3 = 1 and s3Pen = 1 and c < s3 and entriesToday(date) < 3 then

if s4Pen = 1 and c > s4 then s4Pen = 0;
if s3Pen = 1 and c > s3 then s3Pen = 0;
if s2Pen = 1 and c > s2 then s2Pen = 0;

if marketPosition = 1 then
begin
sell from entry("S3Buy") next bar at s4 stop;
sell from entry("R4-BrkOut") next bar at r3 stop;
end;

if marketPosition = -1 then
begin
buyToCover from entry("R3Sell") next bar at r4 stop;
buyToCover from entry("S4-BrkOut") next bar at s3 stop;
end;

end;

setExitOnClose;``````
Camarilla Strategy EasyLanguage Source

# Day Of Week Analysis using a Method In EasyLanguage

One metric that seems to be missing from TradeStation is a Day Of Week analysis.  It would be nice, but I don’t know how helpful, to know the \$P/L breakdown on a weekday basis; does your system make all of its money on Mondays and Fridays?  I created the code that will print out to the print log using an EasyLanguage method.  A method is a subroutine that can be included in the main code (strategy, indicator, etc.,.)  The global parameters to the main program can be seen inside the method.  You can localize variable scope to the method by declaring the variable within the method’s body.  A method is a great way to modularize your programming, but it is not the best way to reuse software; the method is accessible only to the main program.  This EasyLanguage also utilizes an array and shows a neat piece of code to access the array elements and align them with the day of the week.  The dayOfWeek() function returns [1..5] depending on what day of the week the trading day falls on.  Monday = 1 and Friday = 5.  The array has five elements and each element accumulates the \$P/L for each of the five days based on when the trade was initiated.

``````vars: mp(0);
array: weekArray(0);

method void dayOfWeekAnalysis()   {method definition}
begin
If mp = 1 and mp = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue;
If mp = -1 and mp = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue;
end;
Buy next bar at highest(high,9) stop;
Sellshort next bar at lowest(low,9) stop;

mp = marketPosition;

if mp <> mp then dayOfWeekAnalysis();

If lastBarOnChart then
Begin
print("Monday ",weekArray);
print("Tuesday ",weekArray);
print("Wednesday ",weekArray);
print("Thursday ",weekArray);
print("Friday ",weekArray);
end;``````
Code using METHOD and ARRAY manipulation

Here is an example of the print out created by running this simple EasyLanguage strategy.  Maybe don’t trade on Monday?  Or is that curve fitting.  This is an interesting tool and might carry more weight if applied to day trade algorithm.  Maybe!

• Monday -8612.50
• Tuesday 6350.00
• Wednesday 2612.50
• Thursday -937.50
• Friday -1987.50

# Using Strings in EL for multi-step System

This little strategy uses EasyLanguage’s string manipulation to keep track of a multi-step, mutli-criteria, multi-state trade entry. You don’t buy until the buyString is equal to “BUY”. The sell side is just the opposite. When you program a multi-step entry you also need to build a reset situation. In the case of this system you reset the string to null(“”) when the price dips back down below the 9 day moving average. After resetting the process starts over again.

``````
{Use curly brackets for mult-line

This system needs three criteria to be met
Buy Criteria 1:  C > 9 day movAvg - trend Up
Buy Criteria 2:  H = HighestHigh 10 days - break Out
Buy Criteria 3:  C < C - retracement }

if marketPosition = 0 then {If flat then reset strings}
begin
sellString = "";
end;

if c >= average(c,9) then buyString = "B";  //First criteria met
if c < average(c,9) then buyString = "";

if c > average(c,9) then sellString = "";
if c <= average(c,9) then sellString = "S";

begin
if h > highest(h,10) then buyString = buyString + "U"; //Second Criteria met
end;

begin
if c < c then buyString = buyString + "Y"; //Third criteria met
end;

if sellString = "S" then
begin
if l > lowest(l,10) then sellString = sellString + "E";
end;

if sellString = "SE" then
begin
if c > c then sellString = sellString + "LL";
end;

if sellSTring = "SELL" then sellShort ("sellString") next bar at open;
setStopLoss(1000);

SetPercentTrailing(1000, 30);  ``````
``` ```