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.