All posts by George Pruitt

George Pruitt - Author - Blogger - Programmer - Technician Bachelor of Science in Computer Science from UNC-Asheville Levo Oculos Meos In Montes

How to Keep Track of BuysToday and SellsToday

The Useful MP

We all know how to use the reserved word/function MarketPosition – right?  Brief summary if not – use MarketPosition to see what your current position is: -1 for short, +1 for long and 0 for flat.  MarketPosition acts like a function because you can index it to see what you position was prior to the current position – all you need to do is pass a parameter for the number of positions ago.  If you pass it a one (MarketPosition(1)) then it will return the your prior position.  If you define a variable such as MP you can store each bars MarketPosition and this can come in handy.

mp = marketPosition;

If mp[1] <> 1 and mp = 1 then buysToday = buysToday + 1;
If mp[1] <> -1 and mp = -1 then sellsToday = sellsToday + 1;
Keeping Track of Buy and Sell Entries on Daily Basis

The code compares prior bar’s MP value with the current bar’s.   If there is a change in the value, then the current market position has changed.   Going from not 1 to 1 indicates a new long position.  Going from not -1 to -1 implies a new short.  If the criteria is met, then the buysToday or sellsToday counters are incremented.  If you want to keep the number of buys or sells to a certain level, let’s say once or twice,  you can incorporate this into your code.

If  time >= startTradeTime and t < endTradeTime and 
buysToday < 1 and
rsi(c,rsiLen) crosses above rsiBuyVal then buy this bar on close;
If time >= startTradeTime and t < endTradeTime and
sellsToday < 1 and
rsi(c,rsiLen) crosses below rsiShortVal then sellShort this bar on close;
Using MP to Keep Track of BuysToday and SellsToday

This logic will work most of the time, but it depends on the robustness of the builtin MarketPosition function Look how this logic fails in the following chart:

I didn't want entries in the same direction per day!
I only wanted 1 short entry per day!

MarketPosition Failure

Failure in the sense that the algorithm shorted twice in the same day.  Notice on the first trade how the profit objective was hit on the very next bar.  The problem with MarketPosition is that it only updates at the end of the bar one bar after the entry.  So MarketPosition stays 0 during the duration of this trade.  If MarketPosition doesn’t change then my counter won’t work.  TradeStation should update MarketPosition at the end of the entry bar.  Alas it doesn’t work this way.  I figured a way around it though.  I will push the code out and explain it later in more detail.

Input: rsiLen(14),rsiBuyVal(30),rsiShortVal(70),profitObj$(250),protStop$(300),startTradeTime(940),endTradeTime(1430);

Vars: mp(0),buysToday(0),sellsToday(0),startOfDayNetProfit(0);

If d <> d[1] then
Begin
buysToday = 0;
sellsToday = 0;
startOfDayNetProfit = netProfit;
end;

{mp = marketPosition;

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

If entriesToday(date) > buysToday + sellsToday then
Begin
If marketPosition = 1 then buysToday = buysToday + 1;
If marketPosition =-1 then sellsToday = sellsToday + 1;
If marketPosition = 0 then
Begin
if netProfit > startOfDayNetProfit then
begin
if exitPrice(1) > entryPrice(1) then buysToday = buysToday + 1;
If exitPrice(1) < entryPrice(1) then sellsToday = sellsToday + 1;
end;;
if netProfit < startOfDayNetProfit then
Begin
if exitPrice(1) < entryPrice(1) then buysToday = buysToday + 1;
If exitPrice(1) > entryPrice(1) then sellsToday = sellsToday + 1;
end;
end;
print(d," ",t," ",buysToday," ",sellsToday);
end;

If time >= startTradeTime and t < endTradeTime and
buysToday < 1 and
rsi(c,rsiLen) crosses above rsiBuyVal then buy this bar on close;
If time >= startTradeTime and t < endTradeTime and
sellsToday < 1 and
rsi(c,rsiLen) crosses below rsiShortVal then sellShort this bar on close;

SetProfittarget(profitObj$);
SetStopLoss(protStop$);

SetExitOnClose;
A Better Buy and Short Entries Counter

TradeStation does update EntriesToday at the end of the bar so you can use this keyword/function to help keep count of the different type of entries.  If MP is 0 and EntriesToday increments then you know an entry and an exit has occurred (takes care of the MarketPosition snafu) – all you need to do is determine if the entry was a buy or a sell.  NetProfit is also updated when a trade is closed.   I establish the StartOfDayNetProfit on the first bar of the day (line 9 in the code) and then examine EntriesToday and if NetProfit increased or decreased.  EntryPrice and ExitPrice are also updated at the end of the bar so I can also use them to extract the information I need.   Since MarketPosition is 0  I have to pass 1 to the EntryPrice and ExitPrice functions – prior position’s prices.  From there I can determine if a Long/Short entry occurred.  This seems like a lot of work for what you get out of it, but if you are controlling risk by limiting the number of trades (exposure) then an accurate count is so very important.

An alternative is to test on a higher resolution of data – say 1 minute bars.  In doing this you give a buffer to the MarketPosition function – more bars to catch up.

 

Pyramiding and then Scaling Out at Different Price Levels – EasyLanguage

TOTAL, TOTAL, TOTAL – an important keyword

I just learned something new!  I guess I never programmed a strategy that pyramided at different price levels and scaled out at different price levels.

Initially I thought no problem.  But I couldn’t get it to work – I tried everything and then I came across the keyword Total and then I remembered.  If you don’t specify Total in you exit directives then the entire position is liquidated.  Unless you are putting all your positions on at one time – like I did in my last post.   So remember if you are scaling out of a pyramid position use Total in your logic.

vars: maxPosSize(2);

If currentContracts < maxPosSize - 1 and c > average(c,50) and c = lowest(c,3) then buy("L3Close") 1 contract this bar on close;
If currentContracts < maxPosSize and c > average(c,50) and c = lowest(c,4) then buy("L4Close") 1 contract this bar on close;


If currentContracts = 2 and c = highest(c,5) then sell 1 contract total this bar on close;
If currentContracts = 1 and c = highest(c,10) then sell 1 contract total this bar on close;
Scaling Out Of Pyramid

Why you have to use the Total I don’t know.  You specify the number of contracts in the directive and that is sufficient if you aren’t pyramiding.  The pyramiding throws a “monkey wrench” in to the works.

Scaling Out of Position with EasyLanguage

First Put Multiple Contracts On:

If c > average(c,200) and c = lowest(c,3) then buy("5Large") 5 contracts this bar on close;
Using keyword contracts to put on multiple positions

Here you specify the number of contracts prior to the keyword contracts.

Easylanguage requires you to create a separate order for each exit.  Let’s say you want to get out of the 5 positions at different times and possibly prices.  Here’s how you do it:

If currentContracts = 5 and c > c[1] then sell 1 contracts this bar on close;
If currentContracts = 4 and c > c[1] then sell 1 contracts this bar on close;
If currentContracts = 3 and c > c[1] then sell 1 contracts this bar on close;
If currentContracts = 2 and c > c[1] then sell 1 contracts this bar on close;
If currentContracts = 1 and c > c[1] then sell 1 contracts this bar on close;
One order for each independent exit

The reserved word currentContracts hold the current position size.  Intuitively this should work but it doesn’t.

{If currentContracts > 0 then sell 1 contract this bar on close;}

You also can’t put order directives in loops.  You can scale out using percentages if you like.

Value1 = 5;

If currentContracts = 5 and c > c[1] then sell 0.2 * Value1 contracts this bar on close;
If currentContracts = 4 and c > c[1] then sell 1 contracts this bar on close;
If currentContracts = 3 and c > c[1] then sell 1 contracts this bar on close;
If currentContracts = 2 and c > c[1] then sell 1 contracts this bar on close;
If currentContracts = 1 and c > c[1] then sell 1 contracts this bar on close;
Using a percentage of original order size

 

That’s all there is to scaling out.  Just remember to have an independent exit order for each position you are liquidating.  You could have just two orders:  scale out of 3 and then just 2.

 

Setting Stop Loss and Profit Target Utilizing EntryPrice with EasyLanguage

One Problem with the “Next Bar” Paradigm – market position nor entryPrice are adjusted by the end of the bar

Whenever I develop a strategy I like to program all of my entries and exits without utilizing TradeStations built-in execution functions.  I just got use to doing this when I started programming in Fortran many years ago.  However, there a few scenarios where this isn’t possible.  If you enter a trade and use the following logic to get you out with a loss or a profit when referencing your entryPrice, you will be surprised with your results.  This is because you are telling the computer to use entryPrice before you know what it is.

This logic is absolutely correct in its intention.  However, TradeStation doesn’t realize you are in a position at the end of the bar and can’t properly reference entryPrice.  Okay so we force TradeStation to only issue orders once it has a valid entryPrice.TradeStation only realizes the correct marketPosition the following day and then issues an order for the next bar.  So we get the one bar delay.  It would be helpful if TradeStation would set the marketPosition at the close of the bar on the bar of entry.   However, you can overcome this with TradeStation’s built-in execution functions.  For some reason these functions know exactly when you get in – you can also get the same results by inserting the respective strategies on the chart.

An Easy Fix Though

But this little bug can creep into other areas of your programming.  Keep an eye on this.

Multiple Ouput function in EasyLanguage

In the Pascal programming language you have Procedures and Functions.  Procedures are used when you want to modify multiple variables within a sub-program.  A function is a sub-program that returns a single value after it has been modified by say a formula.  EasyLanguage combines procedures and functions into one sub-program called a function.  Functions and procedures both have a formal parameter definition –  a list that describes the type of parameters that are being received by the calling program.  In Pascal procedures, you pass the address of the value that you want changed.  By modifying the contents of the address you can pass the value back and forth or in and out of the procedure.  In functions you pass by value.   Remember the parameter in a normal function call is used to instruct something within the body of the function and is not altered (e.g. the number 19 in value1 = average(c,19)).  This value doesn’t need to be modified it’s just used.  Look at the following code:

Here I am modifying mav1, mav2 and mav3 within the function and then passing the values back to the calling strategy/indicator/paintbar.  All functions must return a value so I simply assign the value 1 to the function name.  The key here is the keyword numericRef, once I change the values located in the addresses of mav1, mav2 and mav3 (address are provided by the keyword numericRef), they will be made available to the calling program.  This code allows the function to return more than just one value.

Using TradeStation’s Development Environment Projects

I have started using the TDE’s projects more and more.  Before, when I was working on multiple related files I would lose track of them in the editor tabs, or discover, when working over time on different projects, I would have twenty or thirty files open – this of course would slow the editor down.  Using projects can clean up your workspace and speed up productivity.  Projects have been around forever and most professional IDEs  incorporate them to aid in the organization and productivity of the programmer.

Here is simple Project with three components:  indicator, function, and strategy.

 

 

Notice how you can focus just on the components of the project.

I also like to split the editor window and populate the bottom pane with code I might need to refer.

Check out the multiple output function – geoTriMavIndic.

 

Pyramiding with Python

A reader of the “UATSTB” asked for an example of how to pyramid in the Python System BackTester (PSB).  I had original bug where you couldn’t peel off all of the positions at once.  If you tried then the PSB would crash.  I have now fixed that problem and here are the necessary lines to add on another position after the initial positions is put on.   I am using a simple moving average crossover to initiate the first position and then if the longer term moving average is positive for 4 days in a row I add on another position.  That’s it.  A max of two position only.  The system either gets reversed to the other side, stopped out or takes profits.  Attached in this post is the module that fixes the pyramiding problem and the code for this system in its entirety.   I will also put the fix in the version 2.0 download.

        upCnt = 0
dnCnt = 0
for j in range(4):
if sAverage(myClose,39,i,j) > sAverage(myClose,39,i,j+1):
upCnt += 1
if sAverage(myClose,39,i,j) < sAverage(myClose,39,i,j+1):
dnCnt += 1


#Long Entry Logic
if (mp != 1) and avg1 > avg2 and prevAvg1 < prevAvg2:
profit = 0
price = myClose[i]
tradeName = "DMA Buy"

#Long Pyramid Logic
if (mp == 1) and upCnt == 4:
profit = 0
price = myClose[i]
tradeName = "LongPyra"
Pyramiding the Long Side of a Dual Moving Average

I only put in the summary of code that will create the initial position and then add 1 more.  Notice the highlighted code from line 3 to 7.  Here I am using a simple loop to determine if the the 39-day moving average is increasing/decreasing consecutively over the past four days.  If the upCnt == 4 then I add a long position.  Notice how I test in the Long Pyramid Logic the values of mp and upCnt.  I only go long another position if I am already long 1 and upCnt == 4.  

Here is a print out of some of the trades:

20040923      DMA Buy  1 127.79000       0.00       0.00
20040923 LongPyra 1 127.79000 0.00 0.00
20041006 L-Prof 2 130.79000 5800.00 14560.00
20041116 DMA Short 1 126.14000 0.00 0.00
20041119 ShortPyra 1 128.64000 0.00 0.00
20041201 S-Prof 2 125.64000 3300.00 17860.00
20050121 DMA Buy 1 127.85000 0.00 0.00
20050202 LongPyra 1 126.01000 0.00 0.00
20050222 L-Prof 2 129.01000 3960.00 21820.00
20050418 DMA Short 1 128.18000 0.00 0.00
20050419 S-MMLoss 1 130.28000 -2200.00 19620.00
20050616 DMA Buy 1 131.41000 0.00 0.00
20050621 LongPyra 1 133.02000 0.00 0.00
20050630 L-MMLoss 2 130.48000 -3670.00 15950.00
20050809 DMA Short 1 135.95000 0.00 0.00
20050810 RevShrtLiq 1 137.78000 -1930.00 14020.00
20050810 DMA Buy 1 137.78000 0.00 0.00
20050810 LongPyra 1 137.78000 0.00 0.00
20050829 L-Prof 2 140.98000 6200.00 20220.00
Trade Listing Of DMA with Pyramiding

While I was posting the trades I found something that struck my funny – look at line 5 (highlighted).  The short pyramid trade occurs at a higher price than the initial short – at first I thought I had made a programming error.  So I thought I would double check the code and then do some debugging.  Instead of invoking the debugger which is really cool and easy to use I decided to just print out the results to the console.

        for j in range(4):
if sAverage(myClose,39,i,j) > sAverage(myClose,39,i,j+1):
upCnt += 1
if sAverage(myClose,39,i,j) < sAverage(myClose,39,i,j+1):
dnCnt += 1
if tempDate == 20041119:
print(myDate[i]," ",j," ",sAverage(myClose,39,i,j))

'''Output of debugging using a print statement
20041119 0 130.68692307692308
20041119 1 130.69538461538463
20041119 2 130.74871794871794
20041119 3 130.7723076923077'''
Debugging using Print Statements

As you can see the longer term moving average is moving down event though price has increased.  Take a look at this chart and you can see multiple occurrences of this.

Examples of Divergence of Moving Average and Price

Remember to copy and replace the tradeClass.py in you PSB2.0 directory – this fixes the pyramid bug.  Also copy the DMAPyra.py to the same directory.  If you haven’t as of yet download the PSB from this website and buy the book for a very good description.

PostPythonCode

Re-Entry After Taking A Profit

Here is some code I have been working on.  I will go into detail on the code a little later.  But this is how you monitor re-entering at a better price after taking a profit.  The problem with taking profits on longer term trend following systems is that the logic that got you into the position is probably still true and you will notice your algorithm will re-enter in the same direction.  So you need to inform your algorithm not to re-enter until a certain condition is met.  In this example, I only re-enter at a better price if the condition that got me into the trade is still valid.

Inputs: swingHiStrength(2),swingLowStrength(2),numDaysToLookBack(30),stopAmt$(500),profitAmt$(1000),getBackInAfterProfAmt$(250);
vars: mp(0),longProfTaken(false),shortProfTaken(false);

mp = marketPosition;

if not(longProfTaken) and mp <> 1 then Buy("BreakOut-B") next bar at highest(h[1],20) on a stop;
if not(shortProfTaken) and mp <>-1 then SellShort("BreakOut-S") next bar at lowest(l[1],20) on a stop;

//If mp[0] = 0 and mp[1] = 1 then print(date," ",exitPrice(1)," ",entryPrice(1));

If longProfTaken then
Begin
If c < exitPrice(1) - getBackInAfterProfAmt$/bigPointValue then
begin
longProfTaken = false;
If mp <> -1 then buy("longRe-Entry") next bar at open;
end;
end;

If shortProfTaken then
Begin
If c > exitPrice(1) + getBackInAfterProfAmt$/bigPointValue then
begin
shortProfTaken = false;
If mp <>-1 then sellShort("shortRe-Entry") next bar at open;
end;
end;


If mp = 1 and c > entryPrice + profitAmt$/bigPointValue then
begin
sell this bar on close;
longProfTaken = true;
end;

If mp =-1 and c < entryPrice - profitAmt$/bigPointValue then
begin
buyToCover this bar on close;
shortProfTaken = true;
end;

If mp = -1 then longProfTaken = false;
If mp = 1 then shortProfTaken = false;

//if mp = 1 then setStopLoss(stopAmt$);
//if mp = 1 then setProfitTarget(profitAmt$);
Re-Entering At Better Price After Profit

A Slightly More Eloquent Approach to Programming Our Pyramiding E-Mini DayTrading Algorithm.

Okay let’s see how I was able to add some eloquence to the brute force approach to this pyramiding algorithm.  The original code included multiple entry directives and a ton of hard coded numerical values.   So let me show you how I was able to refine the logic/code and in doing so make it much more flexible.  We might lose a little bit of the readability, but we can compensate by using extra commentary.

First off, let’s add flexibility by employing input variables.  In this case, we need to inform the algorithm the distance from the open to add additional positions and the max number of entries allowed for the day.

inputs : pyramidDistance(5),maxDailyEntries(3);

Now we need to set somethings up for the first bar of the day.  Comparing the date of today with the date of yesterday is a good way to do this.

if d<>d[1] then 
begin
canSell = true;
sellMult = 1;
sellStop = -999999;
entries = 0;
end;
First bar of the day housekeeping.

Here is a neat way to keep track of the number of entries as they occur throughout the trading day.  Remember the function EntriesToday(date) will not provide the information we need.

mp = marketPosition * currentShares;

if mp[1] <> mp and mp <> 0 then entries = entries + 1;
How to track the number of entries for today.

If the last bar’s mp[1] is not equal to the current bar’s mp then and mp is not equal to zero then we know we have added on another entry.  Okay now let’s think about eliminating the “brute force” approach.

Instead of placing multiple order entry directives I  only want to use one with a variable stop level.  This stop level will be guided by the variable SellMult.  We start the day with a wacky sell stop level and then calculate it based on the SellMult variable and PyramidDistance input.

if low <= sellStop  then
begin
sellMult = sellMult + 1;
end;

sellStop = openD(0) - sellMult * pyramidDistance;
Calculate and adapt sell stop level as we go along.

So on the first bar of the day the sellStop = openD(0) – sellMult * pyramidDistance or sellStop = openD(0) – 1 * 5.  Or 5 handles below the open.  Note you an change the pyramidDistance input and make it three to match the previous examples.

if entries = maxDailyEntries then canSell = false;
if time < sess1EndTime and canSell then sellShort 1 contract next bar at sellStop stop;
if mp <=-1 {and barsSinceEntry > 0} then buyToCover next bar at sellStop + 2* pyramidDistance stop;

setexitonclose;
That's it! Pretty simple isn't it?

Ok, we need to tell the computer to turn off the ability to place orders if one of two things happens:  1) we have reached the maxDailyEntries or 2) time >= sess1EndTime.    You could make the time to stop entering trades an input as well.  If neither criteria applies then place an order to sellShort at our sellStop level.   If price goes below our sell stop level then we know we have been filled and the new sellStop level needs to be recalculated.  See how we use a calculation to adapt the stop level with a single order placement directive?  This is where the eloquence comes into play.  QED.

Now you code the opposite side and then see if you can make money  (hypothetically speaking of course) with it.  If you think about it, why does this not work.  And the not so obvious reason is that it trades too much.  Other than trading too much it makes perfect sense – buy or sell by taking a nibbles at the market.  If the market takes off then take a big bite.  The execution costs of the nibbles are just way too great.  So we need to think of a filtering process to determine when it is either better to buy or sell or when to trade at all.  Good Luck with this ES [emini S&P ]day trading algorithm!

inputs : pyramidDistance(5),maxDailyEntries(3);
vars: mp(0),icnt(0),sellStop(0),sellMult(0),canSell(true),entries(0);

if d<>d[1] then
begin
canSell = true;
sellMult = 1;
sellStop = -999999;
entries = 0;
end;

mp = marketPosition * currentShares;

if mp[1] <> mp and mp <> 0 then entries = entries + 1;
if mp[1] = -1 and mp[0] = 0 then canSell = false;
if time > 1430 then canSell = false;

if low <= sellStop then
begin
sellMult = sellMult + 1;
end;

sellStop = openD(0) - sellMult * pyramidDistance;
if entries = maxDailyEntries then canSell = false;
if time < sess1EndTime and canSell then sellShort 1 contract next bar at sellStop stop;
if mp <=-1 {and barsSinceEntry > 0} then buyToCover next bar at sellStop + 2* pyramidDistance stop;

setexitonclose;
Much More Flexible Code