Free Trend Following System with Indicator Tracker

Free Trend Following System

Here is a free Trend Following System that I read about on Andreas Clenow’s www.followthetrend.com website and from his book.  This is my interpretation of the rules as they were explained.  However the main impetus behind this post wasn’t to provide a free trading system, but to show how you can program a simple system with a complete input interface and program a tracking indicator.   You might be asking what is a “tracking indicator?”  We use a tracking indicator to help provide insight to what the strategy is doing and what it might do in the near future.  The indicator can let you know that a new signal is imminent and also what the risk is in a graphical form.  The indicator can also plot the indicators that are used in the strategy itself.

Step 1:  Program the Strategy

This system is very simple.  Trade on a 50 day Donchian in the direction of the trend and use a 3 X ATR trailing stop.  So the trend is defined as bullish when the 50-day exponential moving average is greater than the 100-day exponential moving average.  A bearish trend is defined when the 50-day is below the 100-day.  Long positions are initiated on the following day when a new 50 day high has been established and the trend is bullish.  Selling short occurs when the trend is bearish and a new 50 day low is establish.  The initial stop  is set to 3 X ATR below the high of the day of entry.  I tested using a 3 X ATR stop initially from the entryPrice for protection on the day of entry, but it made very little difference.  As the trade moves more into your favor, the trailing stop ratchets up and tracks the higher intra-trade extremes.  Eventually once the market reverses you get stopped out of a long position 3 X ATR from the highest high since you entered the long trade.  Hopefully, with a big winner.   The Clenow model also uses a position sizing equation that uses ATR to determine market risk and $2000 for the allocated amount to risk.  Size= 2000 / ATR – this equation will normalize size across a portfolio of markets.

Here is the code.

//Based on Andreas Clenow's description from www.followingthetrend.com
//This is my interpretation and may or may not be what Andreas intended
//Check his books out at amazon.com
//
inputs: xAvgShortLen(50),xAvgLongLen(100),hhllLen(50),buyTrigPrice(h),shortTrigPrice(l),risk$Alloc(2000);
inputs: atrLen(30),trailATRMult(3);
vars: avg1(0),avg2(0),lXit(0),sXit(0),posSize(0),atr(0);

avg1  = xaverage(c,xAvgShortLen);
avg2  = xaverage(c,xAvgLongLen);

atr = avgTrueRange(atrLen);
posSize = maxList(1,intPortion(risk$Alloc/(atr*bigPointValue)));

If marketPosition <> 1 and avg1 > avg2 and buyTrigPrice = highest(buyTrigPrice,hhllLen) then buy posSize contracts next bar at open;
If marketPosition <> -1 and avg1 < avg2 and shortTrigPrice = lowest(shortTrigPrice,hhllLen) then sellshort posSize contracts next bar at open;

If marketPosition = 0 then
Begin
	lXit = o - trailATRMult * atr ;
	sXit = o + trailATRMult * atr; 
//	if c < lXit then Sell currentcontracts contracts next bar at open;
//	If c > sXit then buyToCover currentcontracts contracts next bar at open;
end;

If marketPosition = 1 then 
begin
	lXit = maxList(lXit,h - trailATRMult * atr);
	If c < lXit then sell currentContracts contracts next bar at open;
end;

If marketPosition = -1 then 
begin
	sXit = minList(sXit,l + trailATRMult * atr);
	If c > sXit then buyToCover currentContracts contracts next bar at open;
end;
Cleanow Simple Trend Following System

What I like about this code is how you can use it as a template for any trend following approach.  All the variables that could be optimized are included as inputs.  Many may not know that you can actually change the data series that you want to use as your signal generator right in the input.  Here I have provided two inputs : buyTrigPrice(H), shortTrigPrice(L).  If you want to use the closing price, then all you need to do is change the H and L to C.  The next lines of code performs the calculations needed to calculate the trend.  PosSize is then calculated next.  Here I am dividing the variable risk$Alloc by atr*bigPointValue.  Basically I am taking $2000 and dividing the average true range over the past 30 days multiplied by the point value of the market being tested.  Always remember when doing calculations with $s you have to convert whatever else you are using into dollars as well.  The ATR is expressed in the form of a price difference.  You can’t divide dollars by a price component, hence the multiplication by bigPointValue.  So now we have the trend calcuation and the position sizing taken care of and all we need now is the trend direction and the entry levels.  If avg1 > avg2 then the market is in a bullish posture, and if today’s High = highest(High,50) days back then initiate a long position with posSize contracts at the next bar’s openNotice how I used the keyword contracts after posSize.  This let’s TS know that I want to trade more than one contract.  If the current position is flat I set the lXit and sXit price levels to the open -/+ 3 X ATR.  Once a position (long or short) is initiated then I start ratcheting the trailing stop up or down.  Assuming a long position, I compare the current lXit and the current bar’s HIGH- 3 X ATR and take the larger of the two valuesSo lXit always moves up and never down.  Notice if the close is less than lXit I used the keyword currentContracts and contracts in the directive to exit a long trade.  CurrentContracts contains the current number of contracts currently long and contracts informs TS that more than one contract is being liquidated.  Getting out of a short position is exactly the same but in a different direction.

Step 2: Program the System Tracking Indicator

Now you can take the exact code and eliminate all the order directives and use it to create a tracking indicator.  Take a look at this code:

//Based on Andreas Clenow's description from www.followingthetrend.com
//This is my interpretation and may or may not be what Andreas intended
//Check his books out at amazon.com
//
inputs: xAvgShortLen(50),xAvgLongLen(100),hhllLen(50),buyTrigPrice(h),shortTrigPrice(l);
inputs: atrLen(30),trailATRMult(3);
vars: avg1(0),avg2(0),lXit(0),sXit(0),posSize(0),atr(0),mp(0);

avg1  = xaverage(c,xAvgShortLen);
avg2  = xaverage(c,xAvgLongLen);

atr = avgTrueRange(atrLen);

plot1(avg1,"stXavg");
plot2(avg2,"ltXavg");

If avg1[1] > avg2[1] and buyTrigPrice[1] = highest(buyTrigPrice[1],hhllLen) then mp = 1;
If avg1[1] < avg2[1] and shortTrigPrice[1] = lowest(shortTrigPrice[1],hhllLen) then mp = -1;

If mp = 0 then
Begin
	lXit = o - trailATRMult * atr ;
	sXit = o + trailATRMult * atr;
end;

If mp = 1 then 
begin
	lXit = maxList(lXit,h - trailATRMult * atr);
	plot3(lXit,"LongTrail");
	If c < lXit then mp = 0;
end;

If mp = -1 then 
begin
	sXit = minList(sXit,l + trailATRMult * atr);
	plot4(sXit,"ShortTrail");
	If c > sXit then mp = 0;
end;

However, you do need to keep track if the underlying strategy is long or short and you can do this by pretending you are the computer and using the mp variable.  You know if yesterdays avg1 > avg2 and HIGH[1] = highestHigh(HIGH[1],50), then a long position should have been initiated.  If this happens just set mp to 1You set mp to -1 by checking the trend and lowestLow(LOW[1],50).  Once you know the mp or implied market position then you can calculate the lXit and sXit.  You will always plot the moving averages to help determine trend direction, but you only plot the lXit and sXit when a position is on.  So plot3 and plot4 should only be plotted when a position is long or short.

Here is a screenshot of the strategy and tracking indicator.

Notice how the Yellow and Cyan plots follow the correct market position.  You will need to tell TS not to connect these plot lines when they are not designed to be plotted.

Turn-Off Auto Plot Line Connection

Do this for Plot3 and Plot4 and you will be good to go.

I hope you found this post useful.  Also don’t forget to check out my new book at Amazon.com.  If you really want to learn programming that will help across different platforms I think it would be a great learning experience.

 

A Christmas Project for TradeStation Day-Traders

Here is a neat little day trader system that takes advantage of what some technicians call a “CLEAR OUT” trade.  Basically traders push the market through yesterday’s high and then when everybody jumps on board they pull the rug out from beneath you.  This strategy tries to take advantage of this.  As is its OK, but it could be made into a complete system with some filtering.  Its a neat base to start your day-trading schemes from.

But first have you ever encountered this one when you only want to go long once during the day.

I have logic that examines marketPosition, and if it changes from a non 1 value to 1 then I increment buysToday.  Since there isn’t an intervening bar to establish a change in marketPosition, then buysToday does not get incremented and another buy order is issued.  I don’t want this.  Remember to plot on the @ES.D.

Here’s how I fixed it and also the source of the CLEAR-OUT day-trade in its entirety.  I have a $500 stop and a $350 take profit, but it simply trades way too often.  Have fun with this one – let me now if you come up with something.

inputs: clearOutAmtPer(0.1),prot$Stop(325),prof$Obj(500),lastTradeTime(1530);

vars: coBuy(false),coSell(false),buysToday(0),sellsToday(0),mp(0),totNumTrades(0);

If d <> d[1] then
Begin
	coBuy = false;
	coSell = false;
	buysToday = 0;
	sellsToday = 0;
	totNumTrades = totalTrades;
end;

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

If h > highD(1) + clearOutAmtPer * (highD(1) - lowD(1)) then coSell = true;
If l < lowD(1) - clearOutAmtPer * (highD(1) - lowD(1)) then coBuy = true;

If totNumTrades <> totalTrades and mp = 0 and mp[1] = 0 and positionProfit(1) < 0 and entryPrice(1) > exitPrice(1) then buysToday = buysToday + 1;
If totNumTrades <> totalTrades and mp = 0 and mp[1] = 0 and positionProfit(1) < 0 and entryPrice(1) < exitPrice(1) then sellsToday =sellsToday + 1;

totNumTrades = totalTrades;

If buysToday = 0 and t < lastTradeTime and coBuy = true then buy ("COBuy") next bar at lowD(1) + minMove/priceScale stop;
If sellsToday = 0 and t < lastTradeTime and coSell = true then sellShort ("COSell") next bar at highD(1) - minMove/priceScale stop;

setStopLoss(prot$stop);
Setprofittarget(prof$Obj);
setExitOnClose;
Look at lines 22 and 23 - the entry/exit same bar fix

Get My Latest Book-TrendFollowing Systems: A DIY Project – Batteries Included

Just wanted to let you know that my latest book has just been published.

Trend Following Systems: A DIY Project – Batteries Included: Can You Reboot and Fix Yesterday’s Algorithms to Work with Today’s Markets? 

Trend Following Systems: A DIY Project – Batteries Included

This book introduces my new Python back-tester, TradingSimula-18.  It is completely and I mean completely self contained.  All you need is the latest version of Python and you will be up and running trading systems in less than 5 minutes.  Fifteen years of data on 30 futures is included (data from Quandl).  I have included more than 20 scripts that you can test and build on.   This back-tester is different than the one I published in the Ultimate Algorithmic Trading System Toolbox.  It utilizes what I call the horizontal portfolio spanning paradigm.  Instead of sequentially testing different markets in a portfoio:

It process data in the following manner:

This form of testing allows for decisions to be made on a portfolio basis at the end of any historic bar.   Things like inputting portfolio performance into an allocation formula is super simple.  However, this paradigm opens up a lot of different “what-if” scenarios.

  1. What If I Limit 2 Markets Per Sector
  2. What If I Turn Off A Certain Sector
  3. What If I Liquidate The Largest OTE loser
  4. What If I Liquidate The Largest OTE winner
  5. What If I Only Trade The Ten Markets With The Highest ADX Values

All the data and market performance and portfolio performance is right at your fingertips.  Your testing is only limited by your creativity.

The best part is you get to learn raw Python without having to install complicated libraries like SciKit, Numpy or Pandas.  You don’t even need to install distributions of commercial products – like Anaconda.  Don’t get me wrong I think Anaconda is awesome but many times it is overkill.  If you want to do machine learning then that is the way to go.  If you want to test simple Trend Following algorithms and make portfolio level decisions you don’t need a data science application.

There isn’t a complicated interface to learn.  Its all command line driven from Python’s IDLE.  90% of the source code is revealed for the back-testing software.  Its like one of those see-thru calculators.  You see all the circuits and semiconductors, but in Python.  So you will need to flow through the code to get to the sections that pertain to your test.  Here is a small sample of how you set up the testing parameters for a Donchian Script.

 

#--------------------------------------------------------------------------------
#   If you want to ignore a bunch of non-eseential stuff then
#      S C R O L L   A L M O S T  H A L F   W A Y  D O W N
#--------------------------------------------------------------------------------
#TradingSimula18.py - programmed by George Pruitt
#Built on the code and ideas from "The Ultimate Algorithmic Tradins System T-Box"
#Code is broken into sections
#Most sections can and should be ignored
#Each trading algorithm must be programmed with this template
#This is the main entry into the platform
#--------------------------------------------------------------------------------
#Import Section - inlcude functions, classes, variables from external modules
#--------------------------------------------------------------------------------
# --- Do  not change below here
from getData import getData
from equityDataClass import equityClass
from tradeClass import tradeInfo
from systemMarket import systemMarketClass
from indicators import highest,lowest,rsiClass,stochClass,sAverage,bollingerBands
from indicators import highest,lowest,rsiClass,stochClass,sAverage,bollingerBands,\
    adxClass,sAverage2
from portfolio import portfolioClass
from systemAnalytics import calcSystemResults
from utilityFunctions import getDataAtribs,getDataLists,roundToNearestTick,calcTodaysOTE
from utilityFunctions import setDataLists,removeDuplicates
from portManager import portManagerClass,systemMarkTrackerClass
from positionMatrixClass import positionMatrixClass
from barCountCalc import barCountCalc

from sectorClass import sectorClass, parseSectors, numPosCurrentSector,getCurrentSector
#-------------------------------------------------------------------------------------------------
# Pay no attention to these two functions - unless you want to
#-------------------------------------------------------------------------------------------------
def exitPos(myExitPrice,myExitDate,tempName,myCurShares):
    global tradeName,entryPrice,entryQuant,exitPrice,numShares,myBPV,cumuProfit
    if mp < 0:
        trades = tradeInfo('liqShort',myExitDate,tempName,myExitPrice,myCurShares,0)
        profit = trades.calcTradeProfit('liqShort',mp,entryPrice,myExitPrice,entryQuant,myCurShares) * myBPV
        profit = profit - myCurShares *commission;trades.tradeProfit = profit;cumuProfit += profit
        trades.cumuProfit = cumuProfit
    if mp > 0:
        trades = tradeInfo('liqLong',myExitDate,tempName,myExitPrice,myCurShares,0)
        profit = trades.calcTradeProfit('liqLong',mp,entryPrice,myExitPrice,entryQuant,myCurShares) * myBPV
        profit = profit - myCurShares * commission;trades.tradeProfit = profit;cumuProfit += profit
        trades.cumuProfit = cumuProfit
    curShares = 0
    for remShares in range(0,len(entryQuant)):curShares += entryQuant[remShares]
    return (profit,trades,curShares)

def bookTrade(entryOrExit,lOrS,price,date,tradeName,shares):
    global mp,commission,totProfit,curShares,barsSinceEntry,listOfTrades
    global entryPrice,entryQuant,exitPrice,numShares,myBPV,cumuProfit
    if entryOrExit == -1:
        profit,trades,curShares = exitPos(price,date,tradeName,shares);mp = 0
    else:
        profit = 0;curShares = curShares + shares;barsSinceEntry = 1;entryPrice.append(price);entryQuant.append(shares)
        if lOrS == 1:mp += 1;trades = tradeInfo('buy',date,tradeName,entryPrice[-1],shares,1)
        if lOrS ==-1:mp -= 1;trades = tradeInfo('sell',date,tradeName,entryPrice[-1],shares,1)
    return(profit,curShares,trades)

dataClassList = list()

marketMonitorList,masterDateList,masterDateGlob,entryPrice = ([] for i in range(4))
buy = entry = 1; sell = exit = -1; ignore = 0;
entryQuant,exitQuant,trueRanges,myBPVList = ([] for i in range(4))
myComNameList,myMinMoveList,systemMarketList = ([] for i in range(3))
cond1,cond2,cond3,cond4 = ([] for i in range(4))
marketVal1,marketVal2,marketVal3,marketVal4 = ([] for i in range(4))
portManager = portManagerClass();marketList = getData();portfolio = portfolioClass()
numMarkets = len(marketList);positionMatrix = positionMatrixClass();positionMatrix.numMarkets = numMarkets
firstMarketLoop = True

#----------------------------------------------------------------------------------
# Set up algo parameters here
#----------------------------------------------------------------------------------
startTestDate = 20100101 #must be in yyyymmdd
stopTestDate = 20190228 #must be in yyyymmdd
rampUp = 100 # need this minimum of bars to calculate indicators
sysName = 'Donch-MAX2NSect' #System Name here
initCapital = 500000
commission = 100
Ignore Most Of This Code

Everything is batched processed: set up, pick market or portfolio, run.  Then examine all of the reports.  Here is an example of the sector analysis report.

          Total Profit  Max DrawDown
Currency    -------------------------------
BP           -14800      19062 
SF            -8600      53575 
AD             4670      11480 
DX            10180      10279 
EC            -9000      16775 
JY            10025      18913 
CD           -19720      21830 
-------------------------------------------
Totals:      -27245      69223
-------------------------------------------
Energies    -------------------------------
CL           -40400      55830 
HO            80197      23382 
NG           -14870      28920 
RB           -45429      61419 
-------------------------------------------
Totals:      -20502      75957
-------------------------------------------
Metals      -------------------------------
GC            27210      36610 
SI            -1848       2389 
HG            -2402       2438 
PL           -16750      25030 
PA            27230      38615 
-------------------------------------------
Totals:       33440      61472
-------------------------------------------
Grains      -------------------------------
S_            27312       9088 
W_           -25538      32600 
C_            -1838      12212 
BO            -8460       9544 
SM              390      11250 
RR            -1390      12060 
-------------------------------------------
Totals:       -9523      34135
-------------------------------------------
Financials  -------------------------------
US            29488      18375 
TY              969      12678 
TU            -2020       3397 
FV            -2616       4531 
ED            -4519       4869 
-------------------------------------------
Totals:       21302      30178
-------------------------------------------
Softs       -------------------------------
SB            -1716      19717 
KC            15475      44413 
CC              540       8090 
CT            -8705      35660 
LB            22269      16586 
OJ             4720       8262 
-------------------------------------------
Totals:       32583      57976
-------------------------------------------
Meats       -------------------------------
LC           -18910      24020 
LH           -31270      35640 
FC            14600      25737 
-------------------------------------------
Totals:      -35580      59550
-------------------------------------------
Sector Analysis

Plus I include EasyLanguage for the majority of the scripts.  Of course without the portfolio level management.  I am working on a new website that will support the new book at TrendFollowingSystems.com.

Please take a look at my latest book – it would make an awesome Christmas present.

 

Testing Keith Fitschen’s Bar Scoring with Pattern Smasher

Keith’s Book

Thanks to MJ for planting the seed for this post.  If you were one of the lucky ones to get Keith’s “Building Reliable Trading SystemsTradable Strategies that Perform as They Backtest and Meet Your Risk-Reward Goals”  book by John Wiley 2013 at the list price of $75 count yourself lucky.  The book sells for a multiple of that on Amazon.com.  Is there anything earth shattering in the book you might ask?  I wouldn’t necessarily say that, but there are some very well thought out and researched topics that most traders would find of interest.

Bar Scoring

In his book Keith discusses the concept of bar-scoring.  In Keith’s words, “Bar-scoring is an objective way to classify an instrument’s movement potential every bar.  The two parts of the bar-scoring are the criterion and the resultant profit X days hence.”  Keith provides several bar scoring techniques, but I highlight just one.

Keith broke these patterns down into the relationship of the close to the open, and close in the upper half of the range; close greater than the open and close in the lower half of the range.  He extended the total number of types to 8 by adding the relationship of the close of the bar to yesterdays bar.

The PatternSmasher code can run through a binary representation

for each pattern and test holding the position for an optimizable number of days.  It can also check for long and short positions.  The original Pattern Smasher code used a for-loop to create patterns that were then compared to the real life facsimile.  In this code it was easier to just manually define the patterns and assign them the binary string.

if c[0]> c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2  then patternString = "----";
if c[0]> c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2  then patternString = "---+";
if c[0]> c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2  then patternString = "--+-";
if c[0]> c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2  then patternString = "--++";
if c[0]< c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2  then patternString = "-+--";
if c[0]< c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2  then patternString = "-+-+";
if c[0]< c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2  then patternString = "-++-";
if c[0]< c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2  then patternString = "-+++";
Manual Pattern Designations

Please check my code for any errors.  Here I go through the 8 different relationships and assign them to a Patter String.  “-+++”  represents pattern number (7 ) or type (7 + 1 = 8 – my strings start out at 0).  You can then optimize the test pattern and if the test pattern matches the actual pattern, then the Pattern Smasher takes the trade  on the opening of the next bar and holds it for the number of days you specify.  You an also designate long and short positions in the code.  Here I optimized the 8 patterns going long and short and holding from 1-4 days.

Here is the equity curve!  Remember these are Hypothetical Results with $0 commission/slippage and historic performance is not necessarily indicative of future results.  Educational purposes only!  This is tested on ES.D

Play around with the code and let me know if you find any errors or any improvements.

input: patternTests(8),orbAmount(0.20),LorS(1),holdDays(0),atrAvgLen(10),enterNextBarAtOpen(true);
  
var: patternTest(""),patternString(""),tempString("");
var: iCnt(0),jCnt(0);
array: patternBitChanger[4](0);
   
{written by George Pruitt -- copyright 2019 by George Pruitt
 This will test a 4 day pattern based on the open to close
 relationship.  A plus represents a close greater than its
 open, whereas a minus represents a close less than its open.
 The default pattern is set to pattern 14 +++- (1110 binary).
 You can optimize the different patterns by optimizing the
 patternTests input from 1 to 16 and the orbAmount from .01 to
 whatever you like.  Same goes for the hold days, but in this
 case you optimize start at zero.  The LorS input can be
 optimized from 1 to 2 with 1 being buy and 2 being sellshort.}
  
patternString = "";
patternTest = "";
 
patternBitChanger[0] = 0;
patternBitChanger[1] = 0;
patternBitChanger[2] = 0;
patternBitChanger[3] = 0;
 
value1 = patternTests - 1;
 
 
//example patternTests = 0 -- > 0000
//example patternTests = 1 -- > 0001
//example patternTests = 2 -- > 0010
//example patternTests = 3 -- > 0011
//example patternTests = 4 -- > 0100
//example patternTests = 5 -- > 0101
//example patternTests = 6 -- > 0110
//example patternTests = 7 -- > 0111

if(value1 >= 0) then
begin
 
    if(mod(value1,2) = 1) or value1 = 1 then patternBitChanger[0] = 1;
    value2 = value1 - patternBitChanger[0] * 1;
  
    if(value2 >= 7) then begin
        patternBitChanger[3] = 1;
        value2 = value2 - 8;
    end;
 
    if(value2 >= 4) then begin
        patternBitChanger[2] = 1;
        value2 = value2 - 4;
    end;
    if(value2 = 2) then patternBitChanger[1] = 1;
end;

for iCnt = 3 downto 0  begin
    if(patternBitChanger[iCnt] = 1) then
    begin
        patternTest = patternTest + "+";
    end
    else
    begin
        patternTest = patternTest + "-";    
    end;
end;
 
 patternString = "";
  
if c[0]> c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2  then patternString = "----";
if c[0]> c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2  then patternString = "---+";
if c[0]> c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2  then patternString = "--+-";
if c[0]> c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2  then patternString = "--++";
if c[0]< c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2  then patternString = "-+--";
if c[0]< c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2  then patternString = "-+-+";
if c[0]< c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2  then patternString = "-++-";
if c[0]< c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2  then patternString = "-+++";

 
if(barNumber = 1) then print(elDateToString(date)," pattern ",patternTest," ",patternTests-1);
if(patternString = patternTest) then
 begin
 
//   print(date," ",patternString," ",patternTest); //uncomment this and you can print out the pattern
	if (enterNextBarAtOpen) then
	begin
		if(LorS = 2) then SellShort("PatternSell") next bar on open;
		if(LorS = 1) then buy("PatternBuy") next bar at open;
	end
	else
	begin
		if(LorS = 2) then SellShort("PatternSellBO") next bar at open of tomorrow - avgTrueRange(atrAvgLen) * orbAmount stop;
    	if(LorS = 1) then buy("PatternBuyBO") next bar at open of tomorrow + avgTrueRange(atrAvgLen) * orbAmount stop;
    end;
	

end;
 
if(holdDays = 0 ) then setExitonClose;
if(holdDays > 0) then
begin
    if(barsSinceEntry = holdDays and LorS = 2) then BuyToCover("xbarLExit") next bar at open;
    if(barsSinceEntry = holdDays and LorS = 1) then Sell("xbarSExit") next bar at open;
end;
Bar Scoring Testing Template

How To Program A Ratcheting Stop in EasyLanguage

30 Minute Break Out utilizing a Ratchet Stop [7 point profit with 6 point retention]
I have always been a big fan of trailing stops.  They serve two purposes – lock in some profit and give the market room to vacillate.  A pure trailing stop will move up as the market makes new highs, but a ratcheting stop (my version) only moves up when a certain increment or multiple of profit has been achieved.  Here is a chart of a simple 30 minute break out on the ES day session.  I plot the buy and short levels and the stop level based on whichever level is hit first.

When you program something like this you never know what is the best profit trigger or the best profit retention value.  So, you should program this as a function of these two values.  Here is the code.

inputs: ratchetAmt(6),trailAmt(6);
vars:longMult(0),shortMult(0),myBarCount(0);
vars:stb(0),sts(0),buysToday(0),shortsToday(0),mp(0);
vars:lep(0),sep(0);

If d <> d[1] then
Begin
	longMult = 0;
	shortMult = 0;
	myBarCount = 0;
	mp = 0;
	lep = 0;
	sep = 0;
	buysToday = 0;
	shortsToday = 0;
end;

myBarCount = myBarCount + 1;

If myBarCount = 6 then  // six 5 min bars = 30 minutes
Begin
	stb = highD(0);  //get the high of the day
	sts = lowD(0);   //get low of the day
end;

If myBarCount >= 6 and buysToday + shortsToday = 0 and high >= stb then 
begin
	mp = 1;  //got long - illustrative purposes only
	lep = stb;

end;
If myBarCount >=6 and buysToday + shortsToday = 0 and low <= sts then begin
	mp = -1; //got short
	sep = sts;
end;

If myBarCount >=6 then 
Begin
	plot3(stb,"buyLevel");
	plot4(sts,"shortLevel");
end;
If mp = 1 then buysToday = 1;
If mp =-1 then shortsToday = 1;


// Okay initially you want a X point stop and then pull the stop up
// or down once price exceeds a multiple of Y points
// longMult keeps track of the number of Y point multipes of profit
// always key off of lep(LONG ENTRY POINT)
// notice how I used + 1 to determine profit
// and -  1 to determine stop level
If mp = 1 then 
Begin
	If h >= lep + (longMult + 1) * ratchetAmt then	longMult = longMult + 1;
	plot1(lep + (longMult - 1) *  trailAmt,"LE-Ratchet");
end;

If mp = -1 then 
Begin
	If l <= sep - (shortMult + 1) * ratchetAmt then	shortMult = shortMult + 1;
	plot2(sep - (shortMult - 1) *  trailAmt,"SE-Ratchet");
end;
Ratcheting Stop Code

So, basically I set my multiples to zero on the first bar of the trading session.  If the multiple = 0 and you get into a long position, then your initial stop will be entryPrice + (0 – 1) * trailAmt.  In other words your stop will be trailAmt (6 in this case) below entryPrce.  Once price exceeds or meets 7 points above entry price, you increment the multiple (now 1.)  So, you stop becomes entryPrice + (1-1) * trailAmt – which equals a break even stop.  This logic will always move the first stop to break even.  Assume the market moves 2 multiples into profit (14 points), what would your stop be then?

stop = entryPrice + (2 – 1) * 6 or entryPrice + 6 points.

See how it ratchets.  Now you can optimized the profit trigger and profit retention values.  Since I am keying of entryPrice your first trailing stop move will be a break-even stop.

This isn’t a strategy but it could very easily be turned into one.

Question on Multiple Time Indicator [Discrete Bars]

A reader of this blog proffered an excellent question on this indicator.  I hope this post answers his question and I am always open to any input that might improve my coding!

Because I use BarNumber in my MODULUS calculation the different time frames that I keep track of may not align with the time frames on the chart; your 10-minute bar O, H, L, and C values may not align with the values I am storing in my 10-minute bar container.    Take a look at this snapshot of a spreadsheet.

Here I  print out a 5-minute bar of the ES.D.  Because I use BarNumber in my Modulus calculation, I don’t get to a zero remainder until  9:50 in the 10, 15, and 20 minute time frames.  At 9:50 I start building fresh 10, 15, 20 minute bars by resetting the O, H, L and C to those of the 5-minute bars.  From there I keep track of the highest highs and lowest lows by extracting the data from the 5-minute bar.  I always set the close of the different time frames to the current 5-minute bar’s close.   Once the modulus for the different time frames reaches zero I close out the bar and start fresh again.  The 25-minute bar didn’t reach zero until the 10:05 bar.

I will see if I can come up with some code that will sync with the data on the chart.

Passing a Two Dimensional Array to a Function- EasyLanguage

In this post, I want to share some code that I was surprised wasn’t really all that accessible.  I was in need of passing a 2-D array to a function and couldn’t remember the exact syntax.  The semantics of the problem is pretty straightforward.

  • Build Array
  • Pass Array as Reference
  • Unpack Array
  • Do Calculation

A 2D Array Is Just Like a Table

Any readers please correct me if I am wrong here, but you can’t use dynamic arrays on any dimension greater than 1.  A dynamic array is one where you don’t initially know the size of the array so you leave it blank and TradeStation allocates memory dynamically.  Also, there are a plethora of built-in functions that only work with dynamic arrays.  Once we step up in dimension then that all goes out the window.  I know what you are thinking, just use multiple dynamic arrays.  Sometimes you want to keep the accounting down to a minimum and a matrix or table fits this bill.  So if you do use multi-dimension arrays just remember you will need to know the total number of rows and columns in your table.  Table?  What do you mean table?  I thought we were talking about arrays.  Well, we are and a two-dimensional array can look like a table with rows as your first index and columns as your second.  Just like an Excel spreadsheet.  First, let’s create a very small and simple table in EasyLangauge:

array: testArray[2,2](0);

Once
begin
	testArray[0,0] = 100;
	testArray[0,1] = 5;
	
	testArray[1,0] = 200;
	testArray[1,1] = 10;
	
	testArray[2,0] = 300;
	testArray[2,1] = 7.5;
	
	Value2 = getArrayHH(testArray,2,2);
	Print (value2);

end;
Create a Very Small Table in Our Sandbox

 

My EasyLanguage Sandbox

You will notice I used the keyword Once.  I use this whenever I want to play around with some code in my EasyLanguage Sandbox.  Huh?  In programmer-ese a Sandbox is a quick and dirty environment that runs very quickly and requires nearly zero overhead.  So here I apply the code to print out just one line of output when applied to any chart.   Notice how I declare the 2-D array – use the keyword Array: and the name of the array or table and allocate the total number of rows as the first argument and the total number of columns as the second argument.  Also notice the arguments are separated by a comma and enclosed in square brackets.  The following value enclosed in parentheses is the default value of every element in the array.    Remember arrays are zero-based in EasyLanguage.  So if you dimension an array with the number 2 you access the rows with 0 and 1 and 2.  Same goes for columns as well.  Did you catch that.  If you dimension an array with the number 2 shouldn’t there be just 2 rows?  Well in EasyLanguage when you dimension an array you get a free element at row 0 and column 0.  In EasyLanguage you can just ignore row 0 and column 0 if you like.  Here is the code if you ignore row 0 and column 0.

Should I Use Row 0 and Column Zero – It’s A Preference

array: testArray[2,2](0);

Once
begin
	testArray[1,1] = 100;
	testArray[1,2] = 5;
	
	testArray[2,1] = 200;
	testArray[2,2] = 10;
		
	Value2 = getArrayHH(testArray,2,2);
	Print (value2);

end;
Ignore the Elements at Row 0 and Column 0

Out Of Bounds

Even though you get one free row you still cannot go beyond the boundaries of the array size.  If I were to say something like:

testArray[3,1] = 300;

I would get an error message.  If you want to work with a zero element then all of your code must coincide with that.  If not, then your code shouldn’t try to access row 0 or column 0.    Okay here is the function that I programmed for this little test:

inputs: tempArray[x,y](numericArray),numOfRows(numericSimple),whichColumn(numericSimple);

vars: j(0),tempHi(0),cnt(0);

For j= 1 to numOfRows 
Begin
	print(j," ",tempArray[j,whichColumn]);
	If tempArray[j,whichColumn] > tempHi then tempHi = tempArray[j,whichColumn];
end;

GetArrayHH = tempHi;
Function That Utilizes a 2D Array

Notice in the inputs how I declare the tempArray with the values x and y.  You could have used a and b if you like or any other letters.  This informs the compiler to expect a 2D array.  It doesn’t know the size and that’s not important as long as you control the boundaries from the calling routine.  The second parameter is the number of rows in the table and the third parameter is the column I am interested in.  In this example, I am interested in column 2.

The Caller Function is the QuarterBack – Make Sure You Don’t Throw it Out of Bounds

Again this function assumes the caller will prevent stepping out of bounds.  I loop the number of rows in the table and examine the second column and keep track of the highest value.  I then return the highest column value.

This was a simple post, but remembering the syntax can be tough and know that EasyLangauge is zero-based when it comes to arrays is nice to know.   You can also use this format for your own Sandbox.

 

 

MULTI-TIME FRAME – KEEPING TRACK OF DISCRETE TIME FRAMES

Just a quick post here.  I was asked how to keep track of the opening price for each time frame from our original Multi-Time Frame indicator and I was answering the question when I thought about modifying the indicator.  This version keeps track of each discrete time frame.  The original simply looked back a multiple of the base chart to gather the highest highs and lowest lows and then would do a simple calculation to determine the trend.  So let’s say its 1430 on a five-minute bar and you are looking back at time frame 2.  All I did was get the highest high and lowest low two bars back and stored that information as the high and low of time frame 2.  Time frame 3 simply looked back three bars to gather that information.  However if you tried to compare these values to a 10-minute or 15-minute chart they would not match.

In this version, I use the modulus function to determine the demarcation of each time frame.  If I hit the border of the time frame I reset the open, high, low and carry that value over until I hit the next demarcation.  All the while collecting the highest highs and lowest lows.  In this model, I am working my way from left to right instead of right to left.  And in doing so each time frame is discrete.

Let me know which version you like best.

 

Inputs:tf1Mult(2),tf2Mult(3),tf3Mult(4),tf4Mult(5);



vars: mtf1h(0),mtf1l(0),mtf1o(0),mtf1c(0),mtf1pvt(0),diff1(0),
      mtf2h(0),mtf2l(0),mtf2o(0),mtf2c(0),mtf2pvt(0),diff2(0),
      mtf3h(0),mtf3l(0),mtf3o(0),mtf3c(0),mtf3pvt(0),diff3(0),
      mtf4h(0),mtf4l(0),mtf4o(0),mtf4c(0),mtf4pvt(0),diff4(0),
      mtf0pvt(0),diff0(0);

If barNumber = 1 then
Begin
	mtf1o = o;
	mtf2o = o;
	mtf3o = o;
	mtf4o = o;
end;


If barNumber > 1 then
Begin

	Condition1 =  mod((barNumber+1),tf1Mult) = 0;
	Condition2 =  mod((barNumber+1),tf2Mult) = 0;
	Condition3 =  mod((barNumber+1),tf3Mult) = 0;
	Condition4 =  mod((barNumber+1),tf4Mult) = 0;
	
	mtf1h = iff(not(condition1[1]),maxList(high,mtf1h[1]),high);
	mtf1l = iff(not(condition1[1]),minList(low,mtf1l[1]),low);
	mtf1o = iff(condition1[1],open,mtf1o[1]);
	mtf1c = close;

	
	mtf0pvt = (close + high + low) / 3;
	diff0 = close - mtf0pvt;
	
	mtf2h = iff(not(condition2[1]),maxList(high,mtf2h[1]),high);
	mtf2l = iff(not(condition2[1]),minList(low,mtf2l[1]),low);
	mtf2o = iff(condition2[1],open,mtf2o[1]);
	mtf2c = close;
	
	
	mtf1pvt = (mtf1h+mtf1l+mtf1c) / 3;
	diff1 = mtf1c - mtf1pvt;
		
	mtf2pvt = (mtf2h+mtf2l+mtf2c) / 3;
	diff2 = mtf2c - mtf2pvt;
		
	mtf3h = iff(not(condition3[1]),maxList(high,mtf3h[1]),high);
	mtf3l = iff(not(condition3[1]),minList(low,mtf3l[1]),low);
	mtf3o = iff(condition3[1],open,mtf3o[1]);
	mtf3c = close;
	
	mtf3pvt = (mtf3h+mtf3l+mtf3c) / 3;
	diff3 = mtf3c - mtf3pvt;
	
	mtf4h = iff(not(condition4[1]),maxList(high,mtf4h[1]),high);
	mtf4l = iff(not(condition4[1]),minList(low,mtf4l[1]),low);
	mtf4o = iff(condition4[1],open,mtf4o[1]);
	mtf4c = close;

	mtf4pvt = (mtf4h+mtf4l+mtf4c) / 3;
	diff4 = mtf4c - mtf4pvt;
	
	
	Condition10 = diff0 > 0;
	Condition11 = diff1 > 0;
	Condition12 = diff2 > 0;
	Condition13 = diff3 > 0;
	Condition14 = diff4 > 0;
	 
	If condition10 then setPlotColor(1,Green) else SetPlotColor(1,Red);
	If condition11 then setPlotColor(2,Green) else SetPlotColor(2,Red);
	If condition12 then setPlotColor(3,Green) else SetPlotColor(3,Red);
	If condition13 then setPlotColor(4,Green) else SetPlotColor(4,Red);
	If condition14 then setPlotColor(5,Green) else SetPlotColor(5,Red);
	
	condition6 = condition10 and condition11 and condition12 and condition13 and condition14;
	Condition7 = not(condition10) and not(condition11) and not(condition12) and not(condition13) and not(condition14);

	If condition6 then setPlotColor(7,Green);
	If condition7 then setPlotColor(7,Red);
	
	If condition6 or condition7 then plot7(7,"trend");

	Plot6(5,"line");	
	Plot1(4,"t1");
	Plot2(3,"t2");
	Plot3(2,"t3");
	Plot4(1,"t4");
	Plot5(0,"t5"); 

end;
Multi-Time Frame with Discrete Time Frames

Using a Dictionary to Create a Trading System

Dictionary Recap

Last month’s post on using the elcollections dictionary was a little thin so I wanted to elaborate on it and also develop a trading system around the best patterns that are stored in the dictionary.  The concept of the dictionary exists in most programming languages and almost all the time uses the (key)–>value model.  Just like a regular dictionary a word or a key has a unique definition or value.  In the last post, we stored the cumulative 3-day rate of return in keys that looked like “+ + – –” or “+ – – +“.  We will build off this and create a trading system that finds the best pattern historically based on average return.  Since its rather difficult to store serial data in a Dictionary I chose to use Wilder’s smoothing average function.

Ideally, I Would Have Liked to Use a Nested Dictionary

Initially, I played around with the idea of the pattern key pointing to another dictionary that contained not only the cumulative return but also the frequency that each pattern hit up.  A dictionary is designed to have  unique key–> to one value paradigm.  Remember the keys are strings.  I wanted to have unique key–> to multiple values. And you can do this but it’s rather complicated.  If someone wants to do this and share, that would be great.  AndroidMarvin has written an excellent manual on OOEL and it can be found on the TradeStation forums.  

Ended Up Using A Dictionary With 2*Keys Plus an Array

So I didn’t want to take the time to figure out the nested dictionary approach or a vector of dictionaries – it gets deep quick.  So following the dictionary paradigm I came up with the idea that words have synonyms and those definitions are related to the original word.  So in addition to having keys like “+ + – -” or “- – + -” I added keys like “0”, “1” or “15”.  For every  + or – key string there exists a parallel key like “0” or “15”.  Here is what it looks like:

–  –  –  –  = “0”
– – – + = “1”
– – + – = “2”

You can probably see the pattern here.  Every “+” represents a 1 and every “0” represent 0 in a binary-based numbering system.  In the + or – key I store the last value of Wilders average and in the numeric string equivalent, I store the frequency of the pattern.

Converting String Keys to Numbers [Back and Forth]

To use this pattern mapping I had to be able to convert the “++–” to a number and then to a string.  I used the numeric string representation as a dictionary key and the number as an index into an array that store the pattern frequency.  Here is the method I used for this conversion.  Remember a method is just a function local to the analysis technique it is written.

//Lets convert the string to unique number
method int convertPatternString2Num(string pattString) 
Vars: int pattLen, int idx, int pattNumber;
begin
	pattLen = strLen(pattString);
	pattNumber = 0;
	For idx = pattLen-1 downto 0 
	Begin
		If MidStr(pattString,pattLen-idx,1) = "+" then pattNumber = pattNumber + power(2,idx);
	end;
	Return (pattNumber);
end;
String Pattern to Number

This is a simple method that parses the string from left to right and if there is a “+” it is raised to the power(2,idx) where idx is the location of “+” in the string.  So “+  +  –  –  ” turns out to be 8 + 4 + 0 + 0 or 12.

Once I retrieve the number I used it to index into my array and increment the frequency count by one.  And then store the frequency count in the correct slot in the dictionary.

patternNumber = convertPatternString2Num(patternString); 
//Keep track of pattern hits
patternCountArray[patternNumber] = patternCountArray[patternNumber] + 1;
//Convert pattern number to a string do use as a Dictionary Key
patternStringNum = numToStr(patternNumber,2);
//Populate the pattern number string key with the number of hits
patternDict[patternStringNum] = patternCountArray[patternNumber] astype double;
Store Value In Array and Dictionary

Calculating Wilder’s Average Return and Storing in Dictionary

Once I have stored an instance of each pattern [16] and the frequency of each pattern[16] I calculate the average return of each pattern and store that in the dictionary as well.

//Calculate the percentage change after the displaced pattern hits
Value1 =  (c - c[2])/c[2]*100;
//Populate the dictionary with 4 ("++--") day pattern and the percent change
if patternDict.Contains(patternString) then
Begin
	patternDict[patternString] = (patternDict[patternString] astype double * 
	(patternDict[patternStringNum] astype double - 1.00) + Value1) / patternDict[patternStringNum] astype double;
end
Else
begin
	patternDict[patternString] = value1;
//	print("Initiating: ",patternDict[patternString] astype double);
end;
(pAvg * (N-1) + return) / N

When you extract a value from a collection you must us an identifier to expresses its data type or you will get an error message : patternDict[patternString] holds a double value {a real number}  as well as patternDict[patternStringNum] – so I have to use the keyword asType.  Once I do my calculation I ram the new value right back into the dictionary in the exact same slot.  If the pattern string is not in the dictionary (first time), then the Else statement inserts the initial three-day rate of return.

Sort Through All of The Patterns and Find the Best!

The values in a dictionary are stored in alphabetic order and the string patterns are arranged in the first 16 keys.  So I loop through those first sixteen keys and extract the highest return value as the “best pattern.”

//  get the best pattern that produces the best average 3 bar return
vars: hiPattRet(0),bestPattString("");
If patternDict.Count > 29 then
Begin
	index = patternDict.Keys;
	values = patternDict.Values; 
	hiPattRet = 0;
	For iCnt = 0 to 15
	Begin
		If values[iCnt] astype double > hiPattRet then
		Begin
			hiPattRet = values[iCnt] astype double ;
			bestPattString = index[iCnt] astype string;
		end;
	end;
//	print(Date," BestPattString ",bestPattString," ",hiPattRet:8:4," CurrPattString ",currPattString);
end;
Extract Best Pattern From All History

If Today’s Pattern Matches the Best Then Take the Trade

// if the current pattern matches the best pattern then bar next bar at open
If currPattString = BestPattString then buy next bar at open;
// cover in three days
If barsSinceEntry > 2 then sell next bar at open;
Does Today Match the Best Pattern?

If today matches the best pattern then buy and cover after the second day.

Conclusion

I didn’t know if this code was worth proffering up but I decided to posit it because it contained a plethora of programming concepts: dictionary, method, string manipulation, and array.  I am sure there is a much better way to write this code but at least this gets the point across.

Contents of Dictionary at End of Run

++++    0.06
+++-   -0.08
++-+    0.12
++--   -0.18
+-++    0.08
+-+-    0.40
+--+   -0.46
+---    0.34
-+++    0.20
-++-    0.10
-+-+    0.23
-+--    0.31
--++    0.02
--+-    0.07
---+    0.22
----    0.46
0.00  103.00
1.00  128.00
10.00  167.00
11.00  182.00
12.00  146.00
13.00  168.00
14.00  163.00
15.00  212.00
2.00  157.00
3.00  133.00
4.00  143.00
5.00  181.00
6.00  151.00
7.00  163.00
8.00  128.00
9.00  161.00
Contents of Dictionary

Example of Trades

Pattern Dictionary System

 

Code in Universum

//Dictionary based trading sytem
//Store pattern return
//Store pattern frequency
// by George Pruitt
Using elsystem.collections; 

vars: string keystring("");
vars: dictionary patternDict(NULL),vector index(null), vector values(null);
array: patternCountArray[100](0);

input: patternTests(8);
  
var: patternTest(""),tempString(""),patternString(""),patternStringNum("");
var: patternNumber(0);
var: iCnt(0),jCnt(0);
//Lets convert the string to unique number
method int convertPatternString2Num(string pattString) 
Vars: int pattLen, int idx, int pattNumber;
begin
	pattLen = strLen(pattString);
	pattNumber = 0;
	For idx = pattLen-1 downto 0 
	Begin
		If MidStr(pattString,pattLen-idx,1) = "+" then pattNumber = pattNumber + power(2,idx);
	end;
	Return (pattNumber);
end;


once begin 
   clearprintlog; 
   patternDict = new dictionary; 
   index = new vector;
   values = new vector;
end;   

//Convert 4 day pattern displaced by 2 days
patternString = ""; 
for iCnt = 5 downto 2
begin
    if(close[iCnt]> close[iCnt+1]) then
    begin
        patternString = patternString + "+";
    end
    else
    begin
        patternString = patternString + "-";
    end;
end;

//What is the current 4 day pattern
vars: currPattString("");
currPattString = "";

for iCnt = 3 downto 0
begin
    if(close[iCnt]> close[iCnt+1]) then
    begin
        currPattString = currPattString + "+";
    end
    else
    begin
        currPattString = currPattString + "-";
    end;
end;

//Get displaced pattern number
patternNumber = convertPatternString2Num(patternString); 
//Keep track of pattern hits
patternCountArray[patternNumber] = patternCountArray[patternNumber] + 1;
//Convert pattern number to a string do use as a Dictionary Key
patternStringNum = numToStr(patternNumber,2);
//Populate the pattern number string key with the number of hits
patternDict[patternStringNum] = patternCountArray[patternNumber] astype double;
//Calculate the percentage change after the displaced pattern hits
Value1 =  (c - c[2])/c[2]*100;
//Populate the dictionary with 4 ("++--") day pattern and the percent change
if patternDict.Contains(patternString) then
Begin
	patternDict[patternString] = (patternDict[patternString] astype double * 
	(patternDict[patternStringNum] astype double - 1.00) + Value1) / patternDict[patternStringNum] astype double;
end
Else
begin
	patternDict[patternString] = value1;
//	print("Initiating: ",patternDict[patternString] astype double);
end;
//  get the best pattern that produces the best average 3 bar return
vars: hiPattRet(0),bestPattString("");
If patternDict.Count > 29 then
Begin
	index = patternDict.Keys;
	values = patternDict.Values; 
	hiPattRet = 0;
	For iCnt = 0 to 15
	Begin
		If values[iCnt] astype double > hiPattRet then
		Begin
			hiPattRet = values[iCnt] astype double ;
			bestPattString = index[iCnt] astype string;
		end;
	end;
//	print(Date," BestPattString ",bestPattString," ",hiPattRet:8:4," CurrPattString ",currPattString);
end;
// if the current pattern matches the best pattern then bar next bar at open
If currPattString = BestPattString then buy next bar at open;
// cover in three days
If barsSinceEntry > 2 then sell next bar at open;
Pattern Dictionary Part II

 

 

 

Backtesting with [Trade Station,Python,AmiBroker, Excel]. Intended for informational and educational purposes only!

Follow

Get every new post delivered to your Inbox

Join other followers: