Category Archives: EasyLanguage equivalent to cool code

Prune Your Trend Following Algorithm

Multiple trading decisions based on “logic” may not add to the bottom line

In this post, I will present a trend following system that uses four exit techniques.  These techniques are based on experience and also logic.  The problem with using multiple exit techniques is that it is difficult to see the synergy that is generated from all the moving parts.  Pruning your algorithm may help cut down on invisible redundancy and opportunities to over curve fit.  The trading strategy I will be presenting will use a very popular entry technique overlaid with trade risk compression.

Entry logic

Long:

Criteria #1:  Penetration of the closing price above an 85 day (closing prices) and 1.5X standard deviation-based Bollinger Band.

Criteria #2:  The mid-band or moving average must be increasing for the past three consecutive days.

Criteria #3: The trade risk (1.5X standard deviation) must be less than 3 X average true range for the past twenty days and also must be less than $4,500.

Risk is initially defined by the standard deviation of the market but is then compared to $4,500. If the trade risk is less than $4,500, then a trade is entered. I am allowing the market movement to define risk, but I am putting a ceiling on it if necessary.

Short:

Criteria #1:  Penetration of the closing price below an 85 day (closing prices) and 1.5X standard deviation-based Bollinger Band.

Criteria #2:  The mid-band or moving average must be decreasing for the past three consecutive days.

Criteria #3:  Same as criteria #3 on the long side

Exit Logic

Exit #1:  Like any Bollinger Band strategy, the mid band or moving average is the initial exit point.  This exit must be included in this particular strategy, because it allows exits at profitable levels and works synergistically with the entry technique.

Exit #2:  Fixed $ stop loss ($3,000)

Exit #3:  The mid-band must be decreasing for three consecutive days and today’s close must be below the entry price.

Exit #4:  Todays true range must be greater than 3X average true range for the past twenty days, and today’s close is below yesterday’s, and yesterday’s close must be below the prior days.

Here is the logic of exits #2 through exit #4.  With longer term trend following system, risk can increase quickly during a trade and capping the maximum loss to $3,000 can help in extreme situations.  If the mid-band starts to move down for three consecutive days and the trade is underwater, then the trade probably should be aborted.  If you have a very wide bar and the market has closed twice against the trade, there is a good chance the trade should be aborted.

Short exits use the same logic but in reverse.  The close must close below the midband, or a $3,000 maximum loss, or three bars where each moving average is greater than the one before, or a wide bar and two consecutive up closes.

Here is the logic in PowerLanguage/EasyLanguage that includes the which exit seletor.

[LegacyColorValue = true]; 
Inputs: maxEntryRisk$(4500),maxNATRLossMult(3),maxTradeLoss$(3000),
indicLen(85),numStdDevs(1.5),highVolMult(3),whichExit(7);

Vars: upperBand(0), lowerBand(0),slopeUp(False),slopeDn(False),
largeAtr(0),sma(0),
initialRisk(0),tradeRisk(0),
longLoss(0),shortLoss(0),permString("");

upperBand = bollingerBand(close,indicLen,numStdDevs);
lowerBand = bollingerBand(close,indicLen,-numStdDevs);
largeATR = highVolMult*(AvgTrueRange(20));

sma = average(close,indicLen);

slopeUp = sma>sma[1] and sma[1]>sma[2] and sma[2]>sma[3];
slopeDn = sma<sma[1] and sma[1]<sma[2] and sma[2]<sma[3];

initialRisk = AvgTrueRange(20);
largeATR = highVolMult * initialRisk;
tradeRisk = (upperBand - sma);
// 3 objects in our permutations
// exit 1, exit 2, exit 3
// perm # exit #
// 1 1
// 2 1,2
// 3 1,3
// 4 2
// 5 2,3
// 6 3
// 7 1,2,3

if whichExit = 1 then permString = "1";
if whichExit = 2 then permString = "1,2";
if whichExit = 3 then permString = "1,3";
if whichExit = 4 then permString = "2";
if whichExit = 5 then permString = "2,3";
if whichExit = 6 then permString = "3";
if whichExit = 7 then permString = "1,2,3";



{Long Entry:}
If (MarketPosition = 0) and
Close crosses above upperBand and slopeUp and
(tradeRisk < initialRisk*maxNATRLossMult and tradeRisk<maxEntryRisk$/bigPointValue) then
begin
Buy ("LE") Next Bar at Market;
End;


{Short Entry:}

If (MarketPosition = 0) and slopeDn and
Close crosses below lowerBand and
(tradeRisk < initialRisk*maxNATRLossMult and tradeRisk<maxEntryRisk$/bigPointValue) then
begin
Sell Short ("SE") Next Bar at Market;
End;


{Long Exits:}

if marketPosition = 1 Then
Begin
longLoss = initialRisk * maxNATRLossMult;
longLoss = minList(longLoss,maxTradeLoss$/bigPointValue);

If Close < sma then
Sell ("LX Stop") Next Bar at Market;;

if inStr(permString,"1") > 0 then
sell("LX MaxL") next bar at entryPrice - longLoss stop;

if inStr(permString,"2") > 0 then
If sma < sma[1] and sma[1] < sma[2] and sma[2] < sma[3] and close < entryPrice then
Sell ("LX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeATR and close < close[1] and close[1] < close[2] then
Sell ("LX ATR") Next Bar at Market;
end;

{Short Exit:}

If (MarketPosition = -1) Then
Begin

shortLoss = initialRisk * maxNATRLossMult;
shortLoss = minList(shortLoss,maxTradeLoss$/bigPointValue);
if Close > sma then
Buy to Cover ("SX Stop") Next Bar at Market;

if inStr(permString,"1") > 0 then
buyToCover("SX MaxL") next bar at entryPrice + shortLoss stop;

if inStr(permString,"2") > 0 then
If sma > sma[1] and sma[1] > sma[2] and sma[2] > sma[3] and close > entryPrice then
Buy to Cover ("SX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeAtr and close > close[1] and close[1] > close[2] then
Buy to Cover ("SX ATR") Next Bar at Market;
end;
Trend following with exit selector

Please note that I modified the code from my original by forcing the close to cross above or below the Bollinger Bands.  There is a slight chance that one of the exits could get you out of a trade outside of the bands, and this could potentially cause and automatic re-entry in the same direction at the same price.  Forcing a crossing, makes sure the market is currently within the bands’ boundaries.

This code has an input that will allow the user to select which combination of exits to use.

Since we have three exits, and we want to evaluate all the combinations of each exit separately, taken two of the exits and finally all the exits, we will need to rely on a combinatorial table.    In long form, here are the combinations:

3 objects in our combinations of exit 1, exit 2, exit 3

  • one  – 1
  • two  – 1,2
  • three  –  1,3
  • four –  2
  • five  – 2,3
  • six –  3
  • seven  –  1,2,3

There are a total of seven different combinations. Given the small set, we can effectively hard-code this using string manipulation to create a combinatorial table. For larger sets, you may find my post on the Pattern Smasher beneficial. A robust programming language like Easy/PowerLanguage offers extensive libraries for string manipulation. The inStr string function, for instance, identifies the starting position of a substring within a larger string. When keyed to the whichExit input, I can dynamically recreate the various combinations using string values.

  1. if whichExit = 1 then permString = “1”
  2. if whichExit = 2 then permString= “1,2”
  3. if whichExit = 3 then permString = “1,2,3”
  4.  etc…

As I optimize from one to seven, permString will dynamically change its value, representing different rows in the table. For my exit logic, I simply check if the enumerated string value corresponding to each exit is present within the string.

	if inStr(permString,"1") > 0 then
sell("LX MaxL") next bar at entryPrice - longLoss stop;
if inStr(permString,"2") > 0 then
If sma < sma[1] and sma[1] < sma[2] and sma[2] < sma[3] and close < entryPrice then
Sell ("LX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeATR and close < close[1] and close[1] < close[2] then
Sell ("LX ATR") Next Bar at Market;
Using inStr to see if the current whichExit input applies

When permString = “1,2,3” then all exits are used.  If permString = “1,2”, then only the first two exits are utilized.  Now all we need to do is optimize whichExit from 1 to 7.  Let’s see what happens:

Combination of all three exits

The best combination of exits was “3”.  Remember 3 is the permString  that = “1,3” – this combination includes the money management loss exit, and the wide bar against position exit.  It only slightly improved overall profitability instead of using all the exits – combo #7.  In reality, just using the max loss stop wouldn’t be a bad way to go either.  Occam uses his razor to shave away unnecessary complexities again!

If you like this code, you should check out the Summer Special at my digital store. I showcase over ten more trend-following algorithms with different entry and exit logic constructs.  These other algorithms are derived from the best Trend Following “Masters” of the twentieth century.  IMHO!

Here is a video you can watch that goes over the core of this trading strategy.

 

How to Fix the Fixed Fractional Position Size

The Fixed Fractional position sizing scheme is the most popular, so why does it need fixed?

Problems solved with Fixed Fractional:

  1. Efficient usage of trading capital
  2. Trade size normalization between different futures contracts
  3. Trade size normalization across different market environments

These are very good reasons why you should use positions sizing.  Problem #2 doesn’t apply if you are only trading one market.  This sounds idyllic, right?  It solves these two problems, but it introduces a rather bothersome side effect – huge draw down.  Well, huge draw down in absolute terms.  Draw downs when using a fixed fractional approach are proportional to the prior run up.  If you make a ton of money on a prior trade, then your position sizing reflects that big blip in the equity curve.  So, if you have a large loser following a large winner, the draw down will be a function of the run up.  In most cases, a winning trading system using fixed fractional position sizing will scale profit up as well as draw down.  A professional money manager will look at the profit to draw down ratio instead of the absolute draw down value.  The efficient use of capital will reflect a smaller position size after a draw down, so that is good right?  It is unless you believe in a Martingale betting algorithm – double up on losses and halve winners.  Are we just stuck with large “absolute” draw downs when using this size scheme?

Possible solutions to fixing Fixed Fractional (FF)

The first thing you can do is risk less than the industry standard 2% per trade.  Using 1% will cause equity to grow at a slower rate and also reduce the inevitable draw down.  But this doesn’t really solve the problem as we are giving up the upside.  And that might be okay with you.  Profit will increase and you are using an algorithm for size normalization.  In this blog I am going to propose a trading equity adjustment feature while using FF.  What if we act like money managers, and you should even if you are trading your own personal money, and at the end of the year or month we take a little off the table (theoretically – we are not removing funds from the account just from the position sizing calculation) that is if there is any extra on the table.  This way we are getting the benefit of FF while removing a portion of the compounding effect, which reduces our allocation for the next time interval.  How do you program such a thing?  Well first off let’s code up the FF scheme.

positionSize = round((tradingCapital * riskPerTrade) / (avgTrueRange(30)*bigPointValue),0);

Nothing new here.  Simply multiply tradingCapital by the riskPerTrade (1 or 2%) and then divide by a formula that defines current and inherent market risk.  This is where you can become very creative.  You could risk the distance between entry and exit if you know those values ahead of time or you can use a value in terms of the current market.  Here I have chosen the 30-day average true range.  This value gives a value that predicts the market movement into the future.  However, this value only gives the expected market movement for a short period of time into the future.  You could us a multiplier since you will probably remain in a trade for more than a few days – that is if you are trying to capture the trend.  In my experiment I just use one as my multiplier.

Capture and store the prior year/month NetProfit

When I come up with a trading idea I usually just jump in and program it.  I don’t usually take time to see if Easy Language already provides a solution for my problem.   Many hours have been used to reinvent the wheel, which isn’t always a bad thing.  So, I try to take time and search the functions to see if the wheel already exists.  This time it looks like I need to create the wheel.  I will show the code first and then explain afterward.

inputs: useAllocateYearly(True),useAllocateMonthly(False),initCapital(100000),removePerProfit(0.50),riskPerTrade(0.01);
vars: tradingCapital(0),prevNetProfit(0),tradingCapitalAdjustment(0);
vars: oLRSlope(0),oLRAngle(0),oLRIntercept(0), oLRValueRaw(0),mp(0);
arrays: yearProfit[250](0),snapShotNetProfit[250](0);vars: ypIndex(0);


once
begin
tradingCapital = initCapital;
end;

if useAllocateYearly then
begin
value1 = year(d);
value2 = year(d[1]);
end;

if useAllocateMonthly then //remember make sure your array is 12XNumYears
begin
value1 = month(d);
value2 = month(d[1]);
end;

if useAllocateYearly or useAllocateMonthly then
begin
if value1 <> value2 then
begin
if ypIndex > 0 then
yearProfit[ypIndex] = prevNetProfit - snapShotNetProfit[ypIndex-1]
else
yearProfit[ypIndex] = prevNetProfit;

snapShotNetProfit[ypIndex] = prevNetProfit;
tradingCapitalAdjustment = yearProfit[ypIndex];
if yearProfit[ypIndex] > 0 then
tradingCapitalAdjustment = yearProfit[ypIndex] * (1-removePerProfit);
tradingCapital = tradingCapital + tradingCapitalAdjustment;
print(d,",",netProfit,",",yearProfit[ypIndex],",",tradingCapitalAdjustment,",",tradingCapital);
ypIndex +=1;
end;
end
else
tradingCapital = initCapital + netProfit;
Capture either the prior years or months net profit

I wanted to test the idea of profit retention on a monthly and yearly basis to see if it made a difference.  I also wanted to just use the vanilla version of FF.  The use of Arrays may not be necessary, but I didn’t know ahead of time.  When you program on the fly, which is also called “ad hoc” programming you create first and then refine later.  Many times, the “ad hoc” version turns out to be the best approach but may not be the most efficient.  Like writing a book, many times your code needs revisions.  When applying a study or strategy that uses dates to a chart, you don’t know exactly when the data starts so you always need to assume you are starting in the middle of a year.   If you are storing yearly data into an array, make sure you dimension you array sufficiently.  You will need 12X the number of years as the size you need to dimension your array if you want to store monthly data.

 


//250 element array will contain more than 20 years of monthly data
//You could increase these if you like just to be safe
arrays: yearProfit[250](0),snapShotNetProfit[250](0);
//Remember you dimension you arrray variable first and then
//Pass it a value that you want to initiate all the values
//in the array to equal
vars: ypIndex(0);
Dimension and Initiate Your Arrays

The first thing we need to do is capture the beginning of the year or month.  We can do this by using the year and month function.  If the current month or year value is not the same as the prior day’s month or year value, then we know we crossed the respective timeline boundary.  We are using two arrays, snapShotNetProfit and yearProfit (to save time I use this array to store monthlty values as well, when that option is chosen) and a single array index ypIndex.  If we have crossed the time boundary, the first thing we need to do is capture the EasyLanguage function NetProfit’s value.  NetProfit keeps track of the cumulative closed out trade profits and losses. Going forward in this description I am going to refer to a yearly reallocation.  If it’s the first year, the ypIndex will be zero, and in turn the first year’s profit will be the same as netProfit.  We store netProfit in the yearProfit array at the ypIndex location.  Since we are in a new year, we take a snapshot of netProfit and store it in the snapShotNetProfit array at the same ypIndex location.  You will notice I use the variable prevNetProfit in the code for netProfit.  Here is where the devil is in the details.  Since we are comparing today’s year value with yesterday’s year value and when they are different, we are already inside the new year, so we need to know yesterday’s netProfit.   Before you say it, you can’t pass netProfit a variable for prior values; you know like netProfit(1) or netProfit[1] – this is a function that has no historic values, but you can record the prior day’s value by using our own prevNetProfit  variable.  Now we need to calculate the tradingCapitalAdjustment.  The first thing we do is assign the variable the value held in  yearProfit[ypIndex].  We then test the yearProfit[ypIndex] value to see if it is positive.  If it is, then we multiply it by (1-removePerProfit).  If you want to take 75% of the prior year’s profit off the table, then you would multiply the prior year’s profit by 25%.  Let’s say you make $10,000 and you want to remove $7,500, then all you do is multiply $10,000 by 25%.  If the prior year’s netProfit is a loss, then this value flows directly through the code to the position sizing calculation (auto deallocation on a losing year).   If not, the adjusted profit portion of funds are deallocated in the position sizing equation.

The next time we encounter a new year, then we know this is the second year in our data stream, so we need to subtract last year’s snapshot of netProfit (or prevNetProfit) from the current netProfit.  This will give us the change in the yearly net profit.  We stuff this information into the yearProfit array.  The snapShotNetProfit is stuffed with the current prevNetProfit.  ypIndex is incremented every time we encounter a new yearNotice how I increment the ypIndex – it is incremented after all the calculations in the new year.  The tradingCapitalAdjustment is then calculated with the latest information.

Here is a table of how the tradingCapital and profit retention adjustment are calculated.  A yearly profit adjustment only takes place after a profitable year.  A losing year passes without adjustment.

All tests were carried out on the trend friendly crude oil futures with no execution costs from 2006 thru 2/28/2204.

See how money is removed from the allocation model after winning years.

Here are some optimization tests with 75% profit retention on yearly and monthly intervals.

Yearly First-

Yearly retention with no stop loss or break-even levels.

Now Monthly-

Monthly retention with no stop loss or break-even levels.

What if we didn’t reallocate on any specific interval?

Huge drawdowns with very little change in total profit.

Add some trade management into the mix.

Here we optimize a protective stop and a break-even level to see if we can juice the results.  All the trade management is on a position basis.

200K with No Reallocating with $14k and $8.5 stop/break-even levels [ranked by Profit Factor]
No position sizing and no reallocation with $5K and $10K stop/break-even levels

200K and monthly reallocating with $7K and $5.5K stop/break-even levels [BEST PROFIT FACTOR]
200K and monthly reallocating with $7K and $8.5K stop/break-even levels [2ND BEST PROFIT FACTOR]

Are we really using our capital in the most efficient manner?

If we retain profit, should we remove some of the loss form the position sizing engine as well.  All the tests I performed retained profit from the position size calculations.  I let the loss go full bore into the calculation.  This is a very risk averse approach.  Why don’t I retain 25% of losses and deduct that amount from the yearly loss and feed that into the position sizing engine.  This will be less risk averse – let’s see what it does.

Not as good.  But I could spend a week working different permutations and optimization sessions.

Are you wondering what Trend Following System I was using as the foundation of this strategy?  I used EasyLanguage’s Linear Regression function to create buy and short levels.  Here is the very simple code.

Value1 = LinearReg (Close, 60, 1, oLRSlope, oLRAngle, oLRIntercept, oLRValueRaw);

Value2 = oLRSlope;

Value3 = oLRAngle;

Value4 = oLRIntercept;

Value5 = oLRValueRaw;


//Basically I am buying/shorting on the change of the linear regression slope
//Also I have a volatility filter but it really isn't used
If value2 >=0 and value2[1] < 0 and avgTrueRange(30)*bigPointValue < 10000 then
buy positionSize contracts next bar at market;
If value2 <=0 and value2[1] > 0 and avgTrueRange(30)*bigPointValue < 10000 then
sellShort positionSize contracts next bar at market;

mp = marketPosition;

//I also have incorporated a 3XATR(30) disaster stop
if mp = 1 and c <= entryPrice - 3 * avgTrueRange(30) then sell next bar at market;
if mp = -1 and c >= entryPrice + 3 * avgTrueRange(30) then buyToCover next bar at market

If you want to see some more Trend Following models and their codes in EasyLanguage and TS-18 Python check out my TrendFollowing Guide and Kit.

How To Test and Optimize Turn of the Month Seasonality

Historical evidence suggests a potential seasonal pattern around the end of the month in the markets.

If you have been involved with the markets for even a short period of time, you have heard about this trade.  Buy N days prior to the end of the month and then exit M days after the end of the month.  This is a simple test to perform if you have a way to determine the N and the M in the algorithm.  You could always buy on the 24th of the month, but the 24th of the month may not equal N days prior to the end of the month. 

Simple approach that doesn’t always work – buy the 24th of the month and exit the 5th of the following month.

if dayOfMonth(d) = 24 then buy next bar at open;

if marketPosition = 1 and dayOfMonth(d) = 5 then sell next bar at open;

Before we get into a little better coding of this algorithm, let’s see the numbers.  The first graph is trading one contract of the ES futures once a month – no execution fees were applied.  The same goes for the US bond futures chart that follows.  Before reading further please read this.

CFTC-required risk disclosure for hypothetical results:

Hypothetical performance results have many inherent limitations, some of which are described below. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown. in fact, there are frequently sharp differences between hypothetical performance results and the actual results subsequently achieved by any particular trading program.

One of the limitations of hypothetical performance results is that they are generally prepared with the benefit of hindsight. In addition, hypothetical trading does not involve financial risk, and no hypothetical trading record can completely account for the impact of financial risk in actual trading. For example, the ability to withstand losses or to adhere to a particular trading program in spite of trading losses are material points which can also adversely affect actual trading results. There are numerous other factors related to the markets in general or to the implementation of any specific trading program which cannot be fully accounted for in the preparation of hypothetical performance results and all of which can adversely affect actual trading results.
Buying N days before EOM and Selling M days after EOM
Ditto!

No Pain No Gain

Looking into the maw of draw down and seeing the jagged and long teeth.

Draw down as a percentage of account value.
Ditto2

The bonds had more frequent draw down but not so deep.  These teeth can cause a lot of pain.

Well, George what is the N and M?

I should have done M days before and N days after to maintain alphabetic order, but here you go.

ES: N = 6 AND M = 6

US: N =10 AND M = 1

How did you do this?

Some testing platforms have built-in seasonality tools, but, and I could be wrong I didn’t find what I needed in the TradeStation function library.  So, I built my own.

A TradingDaysLeftInMonth function had to be created.  This function is a broad swipe at attempting to determining this value.  It’s not very smart because it doesn’t take HOLIDAYS into consideration.  But for a quick analysis it is fine.  How does one design such a function?  First off, what do we know to help provide information that might be useful?  We know how many days are in each month (again this function isn’t smart enough to take into consideration leap years) and we know what day of the week each trading day belongs to.  We have this function DayOfWeek(Date) already in EasyLanguage.  And we know the DayOfMonth(Date) (built-in too!) With these three tidbits of information, we should be able to come up with a useful function.   Not to mention a little programming knowledge.  I was working on a Python project when I was thinking of this function, so I decided to prototype it there.  No worries, the algorithm can be easily translated to EasyLanguage. And yes, I could have used my concept of a Sandbox to prototype in EasyLanguage as wellRemember a sandbox is a playground where you can quickly test a snippet of code.  Using the ONCE keyword, you can quickly throw some generic EasyLanguage together sans trade directives and mate it to a chart and get to the nuts and bolts quickly.  I personally like having an indicator and a strategy sandbox.  Here is a generic snippet of code where we assume the day of month is the 16th and it is a Monday ( 2 – 1 for Sunday thru 7 for Saturday) and there are 31 days in whatever month.

currentDayOfWeek = 2;
currentDayOfMonth = 16;
loopDOW = currentDayOfWeek;
daysInMonth = 31
#create the calender for the remaining month
tdToEOM=0; #total days to EOM
for j in range(currentDayOfMonth,daysInMonth+1):
if loopDOW != 1 and loopDOW != 7:
tdToEOM +=1;
print(j," ",loopDOW," ",tdToEOM)
loopDOW +=1;
if loopDOW > 7: loopDOW = 1; #start back on Monday
Create a synthetic calendar from the current day of month

I just absolutely love the simplicity of Python.  When I am prototyping for EasyLanguage, I put a semicolon at the end of each line.  Python doesn’t care.  Here is the output from this snippet of code.

Cur>Day    DOWDay  DaysLeftAccum.
-----------------------------------
16 2 1 Monday
17 3 2 Tuesday
18 4 3 Wednesday
19 5 4 Thursday
20 6 5 Friday
21 7 5 Saturday
22 1 5 Sunday
23 2 6 Monday
24 3 7 Tuesday
25 4 8 Wednesday
26 5 9 Thursday
27 6 10 Friday
28 7 10 Saturday
28 1 10 Sunday
30 2 11 Monday
31 3 12 Tuesday

On Monday 16th there were 12 Trading Days Left In Month Inclusive
Output of Python Snippet - use in EZLang.

I start out with the current day of the month, 16 and loop through the rest of the days of the month.  Whenever I encounter a Sunday (1) or a Saturday (7) I do not increment tdToEOM, else I do increment.  

Here is how the function works on a chart.  Remember in TradeStation I am placing a market order for the NEXT BAR.

Counting the days until the EOM

This snippet of code is the heart of the function, but you must make in generic for any day of any month.  Here it is in EasyLanguage – you will see the similarity between the Python snippet and its corresponding EasyLanguage.

array: monthDays[12](0);

monthDays[1] = 31;
monthDays[2] = 28;
monthDays[3] = 31;
monthDays[4] = 30;
monthDays[5] = 31;
monthDays[6] = 30;
monthDays[7] = 31;
monthDays[8] = 31;
monthDays[9] = 30;
monthDays[10] = 31;
monthDays[11] = 30;
monthDays[12] = 31;

vars: curDayOfMonth(0),curDayOfWeek(0),loopDOW(0),tdToEOM(0),j(0);

curDayOfWeek = dayOfWeek(d);
curDayOfMonth = dayOfMonth(d);

{Python prototype
tdToEOM=0;
for j in range(currentDayOfMonth,daysInMonth+1):
if loopDOW != 1 and loopDOW != 7:
tdToEOM +=1;
print(j," ",loopDOW," ",tdToEOM)
loopDOW +=1;
if loopDOW > 7: loopDOW = 1;
}

loopDOW = curDayOfWeek+1;
tdToEOM=0;

for j = curDayOfMonth to monthDays[month(d)]
begin
if loopDOW <> 1 and loopDOW <> 7 then
tdToEOM +=1; // tdToEOM = tdToEOM + 1;
loopDOW +=1;
if loopDOW > 7 then loopDOW = 1;
end;
TradingDaysLeftInMonth = tdToEOM;
EasyLanguage Function : TradingDaysLeftInMonth

I used arrays to store the number of days in each month.  You might find a better method.  Once I get the day of the month and the day of the week I get to work.  EasyLanguage uses a 0 for Sunday so to be compliant with the Python function I add a 1 to it.  I then loop from the current day of month through monthDays[month(d)].  Remember month(d) returns the month number [1…12].  A perfect index into my array.  That is all there is to it.  The code is simple, but the concept requires a little thinking.  Okay, now that we have the tools for data mining, let’s do some.  I did this by creating the following strategy (the same strategy that create the original equity curves.)

inputs: numDaysBeforeEOM(8),numDaysAfterEOM(10),movingAvgLen(100);
inputs: stopLossAmount(1500),profitTargetAmount(4000);

vars: TDLM(0),TDIM(0);

TDLM = tradingDaysLeftInMonth;
TDIM = tradingDayOfMonth;

if c >= average(c,movingAvgLen) and TDLM = numDaysBeforeEOM then
begin
buy("Buy B4 EOM") next bar at open;
end;

if marketPosition = 1 and barsSinceEntry > 3 then
begin
if TDIM = numDaysAfterEOM then
begin
sell("Sell TDOM") next bar at open;
end;
end;
setStopLoss(stopLossAmount);
setProfitTarget(profitTargetAmount);
EasyLanguage function driver in form of Strategy

A complete strategy has trade management and an entry and an exit.  In this case, I added an additional feature – a trend detector in the form of a longer-term moving average.  Let’s see if we can improve the trading system.  Thank goodness for Genetic Optimization.  Here is the @ES market.

Get your Pick ready to mine!

Smoothed the equity curve – took the big draw down out.

Genetically MODIFIED – Data Mining at its best!

Here are the parameters:

Did not like the moving average. Wide stop and wide profit objective. Days to EOM and after EOM stayed the same.

Bond System:

Bond market results.

If you like this type of programming check out my books at Amazon.com.  I have books on Python and of course EasyLanguage.  I quickly assembled a YouTube video discussing this post here.

Conclusion – there is something here, no doubt.  But it can be a risky proposition.  It definitely could provide fodder for the basis of a more complete trading system.

George’s Amazon Page

 

Happy New Year and some code tidbits

Dollar Cost Averaging Algorithm – Buy X amount every other Monday!

I am not going to get into this controversial approach to trading.  But in many cases, you have to do this because of the limitations of your retirement plan.  Hey if you get free matching dough, then what can you say.

Check this out!

Buy $1000 worth of shares every other Monday. INTC
if dayOfWeek(d of tomorrow)< dayOfWeek(d) Then
begin
toggle = not(toggle);
if toggle then buy dollarInvestment/close shares next bar at open;
end;
Toggle every other Monday ON

Here I use a Boolean typed variable – toggle.   Whenever it is the first day of the week, turn the toggle on or off.  Its new state becomes the opposite if its old state.  On-Off-On-Off – buy whenever the toggle is On or True.  See how I determined if it was the first day of the week; whenever tomorrow’s day of the week is less than today’s day of the week, we must be in a new week.  Monday = 1 and Friday = 5.

Allow partial liquidation on certain days of the year.

Here I use arrays to set up a few days to liquidate a fractional part of the entire holdings.

arrays: sellDates[20](0),sellAmounts[20](0);
//make sure you use valid dates
sellDates[0] = 20220103;sellAmounts[0] = 5000;
sellDates[1] = 20220601;sellAmounts[1] = 5000;
sellDates[2] = 20230104;sellAmounts[2] = 8000;
sellDates[3] = 20230601;sellAmounts[3] = 8000;

value1 = d + 19000000;
if sellDates[cnt] = value1 then
begin
sell sellAmounts[cnt]/close shares total next bar at open;
cnt = cnt + 1;
end;
Notice the word TOTAL in the order directive.

You can use this as reference on how to declare an array and assign the elements an initial value.  Initially, sellDates is an array that contains 20 zeros, and sellAmounts is an array that contains 20 zeros as well.  Load these arrays with the dates and the dollar amounts that want to execute a partial liquidation.  Be careful with using Easylanguage’s Date.  It is in the form YYYMMDD – todays date December 28, 2023, would be represented by 1231228.  All you need to do is add 19000000 to Date to get YYYYMMDD format.  You could use a function to help out here, but why.  When the d + 19000000 equals the first date in the sellDates[1] array, then a market sell order to sell sellAmounts[1]/close shares total is issued.  The array index cnt is incremented.  Notice the order directive.

sell X shares total next bar at market;

If you don’t use the keyword total, then all the shares will be liquidated.

To create a complete equity curve, you will want to liquidate all the shares at some date near the end of the chart.  This is used as input as well as the amount of dollars to invest each time.

//Demonstation of Dollar Cost Averaging
//Buy $1000 shares every two weeks
//Then liquidate a specific $amount on certain days
//of the year

vars: toggle(False),cnt(0);
inputs: settleDate(20231205),dollarInvestment(1000);
arrays: sellDates[20](0),sellAmounts[20](0);
//make sure you use valid dates
sellDates[0] = 20220103;sellAmounts[0] = 5000;
sellDates[1] = 20220601;sellAmounts[1] = 5000;
sellDates[2] = 20230104;sellAmounts[2] = 8000;
sellDates[3] = 20230601;sellAmounts[3] = 8000;

value1 = d + 19000000;
if sellDates[cnt] = value1 then
begin
sell sellAmounts[cnt]/close shares total next bar at open;
cnt = cnt + 1;
end;

if dayOfWeek(d of tomorrow)< dayOfWeek(d) Then
begin
toggle = not(toggle);
if toggle then buy dollarInvestment/close shares next bar at open;
end;

if d + 19000000 = settleDate Then
sell next bar at open;

A cool looking chart.

A chart with all the entries and exits.

Allow Pyramiding

Turn Pyramding On. You will want to allow up to X entries in the same direction regardless of the order directive.

Working with Data2

I work with many charts that have a minute bar chart as Data1 and a daily bar as Data2.  And always forget the difference between:

Close of Data2 and Close[1] of Data2

24 hour regular session used here
1231214 1705 first bar of day - close of data2 4774.00 close[1] of data2 4760.75
1231214 1710 second bar of day - close of data2 4774.00 close[1] of data2 4760.75
1231215 1555 next to last bar of day - close of data2 4774.00 close[1] of data2 4760.75
1231215 1600 last bar of day - close of data2 4768.00 close[1] of data2 4774.00

Up to the last bar of the current trading day the open, high, low, close of data2 will reflect the prior day’s values.  On the last bar of the trading day – these values will be updated with today’s values.

Hope these tidbits help you out.  Happy New Years!

Warmest regards,

George

A Timely Function in EasyLanguage

Learn how to constrain trading between a Start and End Time – not so “easy-peasy”

Why waste time on this?

Is Time > StartTime and Time <= EndTime then…  Right?

This is definitely valid when EndTime > StartTime.  But what happens when EndTime < StartTime.  Meaning that you start trading yesterday, prior to midnight, and end trading after midnight (today.)  Many readers of my blog know I have addressed this issue before and created some simple equations to help facilitate trading around midnight.  The lines of code I have presented work most of the time.  Remember when the ES used to close at 4:15 and re-open at 4:30 eastern?   As of late June 2021, this gap in time has been removed.  The ES now trades between 4:15 and 4:30 continuously.   I discovered a little bug in my code for this small gap when I was optimizing a “get out time.”   I wanted to create a user function that uses the latest session start and end times and build a small database of valid times for the 24-hour markets.  Close to 24 hours – most markets will close for an hour.  With this small database you can test your time to see if it is a valid time.  The construction of this database will require a little TIME math and require the use of arrays and loops.  It is a good tutorial.  However, it is not perfect.  If you optimize time and you want to get out at 4:20 in 2020 on the ES, then you still run into the problem of this time not being valid.  This requires a small workaround.  Going forward with automated trading, this function might be useful.  Most markets trade around the midnight hour – I think meats might be the exception.

Time Based Math

How many 5-minute bars are between 18:00 (prior day) and 17:00 (today)?  We can do this in our heads 23 hours X (60 minutes / 5 minutes) or 23 X 12 = 276 bars.  But we need to tell the computer how to do this and we also should allow users to use times that include minutes such as 18:55 to 14:25. Here’s the math – btw you may have a simpler approach.

Using startTime of 18:55 and endTime of 14:25.

  1. Calculate the difference in hours and minutes from startTime to midnight and then in terms of minutes only.
    1. timeDiffInHrsMins = 2360 – 1855 = 505 or 5 hours and 5 minutes.  We use a little short cut hear.  23 hours and 60 minutes is the same as 2400 or midnight.
    2. timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100).  This looks much more complicated than it really is because we are using two helper functions – intPortion and mod:
      1. ) intPortion – returns the whole number from a fraction.  If we divide 505/100 we get 5.05 and if we truncate the decimal we get 5 hours.
      2. ) mod – returns the modulus or remainder from a division operation.  I use this function a lot.  Mod(505/100) gives 5 minutes.
      3. ) Five hours * 60 minutes + Five minutes = 305 minutes.
  2. Calculate the difference in hours and minutes from midnight to endTime and then in terms of minutes only.
    1. timeDiffInHrsMins = endTime – 0 = 1425 or 14 hours and 25 minutes.  We don’t need to use our little, short cut here since we are simply subtracting zero.  I left the zero in the calculation to denote midnight.
    2. timeDiffInMinutes = timeDiffInMinutes + intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100).  This is the same calculation as before, but we are adding the result to the number of minutes derived from the startTime to midnight.  
      1. ) intPortion – returns the whole number from a fraction.  If we divide 1425/100, we get 14.05 and if we truncate the decimal, we get 14.
      2. ) mod – returns the modulus or remainder from a division operation.  I use this function a lot.  Mod(1425/100) gives 25.
      3. ) 14* 60 + 25 = 865 minutes.
      4. ) Now add 305 minutes to 865.  This gives us a total of 1165 minutes between the start and end times.
    3. Now divide the timeDiffInMinutes by the barInterval.  This gives 1165 minutes/5 minutes or 233 five-minute bars.

Build Database of all potential time stamps between start and end time

We now have all the ingredients to build are simple array-based database.  Don’t let the word array scare you away.  Follow the logic and you will see how easy it is to use them.   First, we will create the database of all the time stamps between the regular session start and end times of the data on the chart.  We will use the same time-based math (and a little more) to create this benchmark database.  Check out the following code.

// You could use static arrays
// reserve enough room for 24 hours of minute bars
// 24 * 60 = 1440
// arrays: theoTimes[1440](0),validTimes[1440](0);
// syntax - arrayName[size](0) - the zero sets all elements to zero
// this seems like over kill because we don't know what
// bar interval or time span the user will be using

// these arrays are dynamic
// we dimension or reserve space for just what we need
arrays: theoTimes[](0),validTimes[](0);

// Create a database of all times stamps that potentiall could
// occur

numBarsInCompleteSession = timeDiffInMinutes/barInterval;

// Now set the dimension of the array by using the following
// function and the number of bars we calculated for the entire
// regular session
Array_setmaxindex(theoTimes,numBarsInCompleteSession);
// Load the array from start time to end time
// We know the start time and we know the number of X-min bars
// loop from 1 to numBarsInCompleteSession and
// use timeSum as the each and every time stamp
// To get to the end of our journey we must use Time Based Math again.
timeSum = startTime;
for arrayIndex = 1 to numBarsInCompleteSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100; // 1860 - becomes 1900
if timeSum = 2400 Then
timeSum = 0; // 2400 becomes 0000
theoTimes[arrayIndex] = timeSum;

print(d," theo time",arrayIndex," ",theoTimes[arrayIndex]);
end;
Create a dynamic array with all possible time stamps

This is a simple looping mechanism that continually adds the barInterval to timeSum until numBarsInCompleteSession are exhausted.  Reade about the difference between static and dynamic arrays in the code, please.  Here’s how it works with a session start time of 1800:

theoTimes[01] = 1800 + 5 = 1805
theoTimes[02] = 1805 + 5 = 1810
theoTimes[04] = 1810 + 5 = 1815
theoTimes[05] = 1815 + 5 = 1820
theoTimes[06] = 1820 + 5 = 1830
...
//whoops - need more time based math 1860 is not valid
theoTimes[12] = 1855 + 5 = 1860
Insert bar stamps into our theoTimes array

More time-based math

Our loop hit a snag when we came up with 1860 as a valid time.  We all know that 1860 is really 1900.  We need to intervene when this occurs.  All we need to do is use our modulus function again to extract the minutes from our time.

If mod(timeSum,100) = 60 then timeSum = timeSum – 60 + 100.  Her we remove the sixty minutes from the time and add an hour to it.

1860 – 60 + 100 = 1900 // a valid time stamp

That should fix everything right?  What about this:

theoTimes[69] = 2340 + 5 = 2345
theoTimes[70] = 2345 + 5 = 2350
theoTimes[71] = 2350 + 5 = 2355
theoTimes[72] = 2355 + 5 = 2400 // whoops
2400 is okay in Military Time but not in TradeStation

This is a simple fix with.  All we need to do is check to see if timeSum = 2400 and if so, just simply reset to zero.

Build a database on our custom time frame.

Basically, do the same thing, but use the user’s choice of start and end times.

	//calculate the number of barInterval bars in the
//user defined session
numBarsInSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(validTimes,numBarsInSession);

startTimeStamp = calcTime(startTime,barInterval);

timeSum = startTime;
for arrayIndex = 1 to numBarsInSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
validTimes[arrayIndex] = timeSum;
// print(d," valid times ",arrayIndex," ",validTimes[arrayIndex]," ",numBarsInSession);
end;
Create another database using the time frame chose by the user

Don’t allow weird times!

Good programmers don’t allow extraneous values to bomb their functions.  TRY and CATCH the erroneous input before proceeding.  If we have a database of all possible time stamps, shouldn’t we use it to validate the user entry?  Of course, we should.

//Are the users startTime and endTime valid
//bar time stamps? Loop through all the times
//and validate the times.

for arrayIndex = 1 to numBarsInCompleteSession
begin
if startTimeStamp = theoTimes[arrayIndex] then
validStartTime = True;
if endTime = theoTimes[arrayIndex] Then
validEndTime = True;
end;
Validate user's input.

Once we determine if both time inputs are valid, then we can determine if the any bar’s time stamp during a back-test is a valid time.

if validStartTime = false or validEndTime = false Then
error = True;


//Okay to check for bar time stamps against our
//database - only go through the loop until we
//validate the time - break out when time is found
//in database. CanTradeThisTime is the name of the function.
//It returns either True or False

if error = False Then
Begin
for arrayIndex = 1 to numBarsInSession
Begin
if t = validTimes[arrayIndex] Then
begin
CanTradeThisTime = True;
break;
end;
end;
end;
This portion of the code is executed on every bar of the back-test.

Once and only Once!

The code that creates the theoretical and user defined time stamp database is only done on the very first bar of the chart.  Also, the validation of the user’s input in only done once as well.  This is accomplished by encasing this code inside a Once – begin – end.

Now this code will test any time stamp against the current regular session.  If you run a test prior to June 2021, you will get a theoretical database that includes a 4:20, 4:25, and 4:30 on the ES futures.  However, in actuality these bar stamps did not exist in the data.  This might cause a problem when working with a start or end time prior to June 2021, that falls in this range.

Function Name:  CanTradeThisTime

Complete code:

//  Function to determine if time is in acceptable
// set of times
inputs: startTime(numericSimple),endTime(numericSimple);

vars: sessStartTime(0),sessEndTime(0),
startTimeStamp(0),timeSum(0),timeDiffInHrsMins(0),timeDiffInMinutes(0),
validStartTime(False), validEndTime(False);

vars: error(False),arrayIndex(0),
numBarsInSession(0),numBarsInCompleteSession(0);

arrays: theoTimes[](0),validTimes[](0);
vars: arrCnt(0),seed(0);

canTradeThisTime = false;

once
Begin

sessStartTime = sessionStartTime(0,1);
sessEndTime = sessionEndTime(0,1);

if sessStartTime > sessEndTime Then
Begin
timeDiffInHrsMins = 2360 - sessStartTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);

timeDiffInHrsMins = sessEndTime - 0;
timeDiffInMinutes += intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

if sessStartTime <= sessEndTime Then
Begin
timeDiffInHrsMins = (intPortion(sessEndTime/100) - 1)*100 + mod(sessEndTime,100) + 60 - sessEndTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

numBarsInCompleteSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(theoTimes,numBarsInCompleteSession);

timeSum = startTime;
for arrayIndex = 1 to numBarsInCompleteSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
theoTimes[arrayIndex] = timeSum;

print(d," theo time",arrayIndex," ",theoTimes[arrayIndex]);
end;

if startTime > endTime Then
Begin
timeDiffInHrsMins = 2360 - startTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
timeDiffInHrsMins = endTime - 0;
timeDiffInMinutes += intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

if startTime <= endTime Then
Begin
timeDiffInHrsMins = (intPortion(endTime/100) - 1)*100 + mod(endTime,100) + 60 - startTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

numBarsInSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(validTimes,numBarsInSession);

startTimeStamp = calcTime(startTime,barInterval);

timeSum = startTime;
for arrayIndex = 1 to numBarsInSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
validTimes[arrayIndex] = timeSum;
print(d," valid times ",arrayIndex," ",validTimes[arrayIndex]," ",numBarsInSession);
end;
for arrayIndex = 1 to numBarsInCompleteSession
begin
if startTimeStamp = theoTimes[arrayIndex] then
validStartTime = True;
if endTime = theoTimes[arrayIndex] Then
validEndTime = True;
end;
end;

if validStartTime = False or validEndTime = false Then
error = True;

if error = False Then
Begin
for arrayIndex = 1 to numBarsInSession
Begin
if t = validTimes[arrayIndex] Then
begin
CanTradeThisTime = True;
break;
end;
end;
end;
Complete CanTradeThisTime function code

Sandbox Strategy function driver

inputs: startTime(1800),endTime(1500);

if canTradeThisTime(startTime,endTime) Then
if d = 1231206 or d = 1231207 then
print(d," ",t," can trade this time");

I hope you find this useful.  Remember to purchase by Easing into EasyLanguage books at amazon.com.  The DayTrade edition is still on sale.  Email me with any question or suggestions or bugs or anything else.

 

 

Pyramania Levels with 24-Hour Session – Free Code

Easing Into EasyLanguage-DayTrade Edition [On SALE Now thru November]

Get Your Copy Now!  On sale now for thru the end of November!

EZ-DT Pyramania is a strategy I introduced in the Day Trade Edition.  The logic is rather simple – pyramid as the market moves through multiple levels during the trading day. – buy, buy, buy, dump or buy, dump, short, short, short, dump.  The distance between the levels is constant.  In the book, I showed an algorithm with a total of 6 levels with 7 edges.

Pyramania of @ES.D

Here the market opens @ 9:30 and the levels are instantly plotted and trades are executed as the market moves through the levels located above the open tick.  Over the weekend, I had a reader ask how he could modify the code to plot the levels on the 24-hour @ES session.  In the day session, I used the change in the date as the trigger for the calculation and plotting of the levels.  Here is the day session version.

inputs:numSegments(6),numPlots(6);

arrays: segmentBounds[](0);

variables: j(0),loopCnt(0),segmentSize(0),avgRng(0);
once
Begin
Array_SetMaxIndex(segmentBounds, numSegments);
end;

if d <> d[1] Then // only works on the @ES.D or any .D session
begin
avgRng = average(range of data2,20);
segmentSize = avgRng/numSegments;
loopCnt = -1*numSegments/2;
for j = 0 to numSegments
begin
segmentBounds[j] = openD(0) + loopCnt * segmentSize;
loopCnt = loopCnt + 1;
end;
end;

//The following time constraint only works when all time stamps
//are less than the end of day time stamp
//This will not work when time = 1800 and endTime = 1700
if t < calcTime(sessionEndTime(0,1),-barInterval) Then
begin
if numPlots >= 1 then plot1(segmentBounds[0],"Level 0");
if numPlots >= 2 then plot2(segmentBounds[1],"Level 1");
if numPlots >= 3 then plot3(segmentBounds[2],"Level 2");
if numPlots >= 4 then plot4(segmentBounds[3],"Level 3");
if numPlots >= 5 then plot5(segmentBounds[4],"Level 4");
if numPlots >= 6 then plot6(segmentBounds[5],"Level 5");
if numPlots >= 7 then plot7(segmentBounds[6],"Level 6");
// plot8(segmentBounds[7],"Level 7");
// plot9(segmentBounds[8],"Level 8");
end;
Works great with @ES.D or any @**.D

I like this code because it exposes you to arrays, loops, and plotting multiple values.  You can fix this by modifying and adding some code.  I used the Trading Around Midnight blog post to get the code I needed to enable plotting around 0:00 hours.  Here is the updated code:

inputs:numSegments(6),numPlots(6);
arrays: segmentBounds[](0);
variables: j(0),loopCnt(0),segmentSize(0),avgRng(0),
startTime(0),endTime(0),endTimeOffset(0);

once
Begin
Array_SetMaxIndex(segmentBounds, numSegments);
end;

startTime = sessionStartTime(0,1);
endTime = sessionEndTime(0,1);
//let TS tell you when the market opens - remember the
//first time stamp is the open time + bar interval
if t = calcTime(sessionStartTime(0,1),barInterval) Then
begin
avgRng = average(range of data2,20);
segmentSize = avgRng/numSegments;
loopCnt = -1*numSegments/2;
for j = 0 to numSegments
begin
segmentBounds[j] = open + loopCnt * segmentSize;
loopCnt = loopCnt + 1;
end;
end;

// if startTime > endTime then you know you are dealing with
// timees that more than likely bridges midnight
// if time is greater then 1700 (end time) then you must
// subtract an offset so it makes sense - endTimeOffset
// play with the math and it will come to you
if startTime > endTime then
begin
endTimeOffset = 0;
if t >= startTime+barInterval and t<= 2359 then
endTimeOffSet = 2400-endTime;
end;
if t-endTimeOffSet < endTime Then
begin
if numPlots >= 1 then plot1(segmentBounds[0],"Level 0");
if numPlots >= 2 then plot2(segmentBounds[1],"Level 1");
if numPlots >= 3 then plot3(segmentBounds[2],"Level 2");
if numPlots >= 4 then plot4(segmentBounds[3],"Level 3");
if numPlots >= 5 then plot5(segmentBounds[4],"Level 4");
if numPlots >= 6 then plot6(segmentBounds[5],"Level 5");
if numPlots >= 7 then plot7(segmentBounds[6],"Level 6");
// plot8(segmentBounds[7],"Level 7");
// plot9(segmentBounds[8],"Level 8");
end;
Modification to plot data around midnight

Here I let TS tell me with the market opens and then use some simple math to make sure I can plot with the time is greater than and less than the end of day time.

Plots from 18:05 through midnight until 17:00 the next day.

Email me if you have the book and want to companion code to the strategy – georgeppruitt@gmail.com

 

 

 

 

Can You Turn Failure into Success?

Have You Ever Wondered If You Just Reversed the Logic?

You have been there before. What you thought was a great trading idea turns out to be a big flop. We have all developed these types of algorithms. Then it hits you, just flip the logic and in turn the equity curve. Hold your horses! First off you have to make sure it’s not just the execution costs that is hammering the equity curve into oblivion. When testing a fresh trading idea, it is best to keep execution costs to zero. This way if your idea is a good one, but is simply backward, then you have a chance of creating something good out of something bad. I was playing around with a mean reversion day trading algorithm (on the @ES.D – day session of the mini S&P 500) that created the following equity curve.  Remember to read the disclaimer concerning hypothetical performance before proceeding reading the rest of this blog.  It is located under the DISCLAIMER – REAMDE! tab.  By reading the rest of this blog post it implies that you understand the limitations of hypothetical back testing and simulated analysis.

The pandemic created a strong mean reversion environment. In the initial stage of this research, I did not set the executions costs – they defaulted to zero. My idea was to buy below the open after the market moved down from the high of the day a certain percentage of price. Since I was going to be buying as the market was moving down, I was willing to use a wide stop to see if I could hold on to the falling knife. Short entries were just the opposite -sell short above the open after the market rallied a certain percentage of price. I wanted to enter on a hiccup. Once the market moved down a certain range from the high of the day, I wanted to enter on a stop at the high of the prior bar. I figured if the price penetrated the high of the prior five-minute bar in a down move, then it would signal an eventual rotation in the market. Again, I was just throwing pasta against the wall to see what would stick. I even came up with a really neat name for the algorithm the Rubber Band system – stretch just far enough and the market is bound to slam back. Well, there wasn’t any pasta sticking. Or was there? If I flipped the equity curve 180 degrees, then I would have a darned good strategy. All it would take is to reverse the signals, sell short when I was buying and buy when I was selling short. Instead of a mean reversion scheme, this would turn into a momentum-based strategy.

Here are the original rules.

maxCloseMinusOpen = maxList(close - todaysOpen,maxCloseMinusOpen);
maxOpenMinusClose = maxList(todaysOpen - close,maxOpenMinusClose);

if c < todaysOpen and todaysOpen-c = maxOpenMinusClose and
(maxCloseMinusOpen + maxOpenMinusClose)/c >= stretchPercent Then
canBuy = True;
if c > todaysOpen and c- todaysOpen = maxCloseMinusOpen and
(maxCloseMinusOpen + maxOpenMinusClose)/c >= stretchPercent Then
canShort = True;
Guts of the complete failure.

Here I measure the maximum distance from the highest close above the open and the lowest close below the open.  The distance between the two points is the range between the highest and lowest closing price of the current day.  If the close is less than today’s open, and the range between the extremes of the highest close and lowest close of the trading day is greater than stretchPercent, then an order directive to buy the next bar at the current bar’s high is issued.  The order is alive until it is filled, or the day expires.  Selling short uses the same calculations but requires the close of the current bar to be above the open.   The stretchPercent was set to 1 percent and the protective stop was set to a wide $2,000.  As you can see from the equity curve, this plan did not work except for the time span of the pandemic.  Could you optimize the strategy and make it a winning system.  Definitely.  But the 1 percent and $2000 stop seemed very logical to me.  Since we are comparing the range of the data to a fixed price of the data, then we don’t need to worry about the continuous contract distortion.  Maybe we would have to, if the market price was straddling zero.  Anyways, here is a strategy using the same entry technique, but reversed, with some intelligent trade filtering.  I figured a profit objective might be beneficial, because the stop was hit several times during the original test.

$2K was hit often!
Using some trade filtering and stop loss and profit objective on the reversal of the original strategy.

If you like the following code, make sure you check out my books at Amazon.com.  This type of code is used the Hi-Res and Day-Trading editions of the Easing_Into_Easylanguage series.

input: stretchPercent(0.01),stopLoss(1000),takeProfit(1000),
dontTradeBefore(930),dontTradeBeforeOffset(5),
dontTradeAfter(1500),dontTradeAfterOffset(5),
rangeCompressionPercent(0.75);

vars: buysToday(0),shortsToday(0),mp(0),atr(0),canBuy(False),canShort(False),canTrade(False);
vars: todaysOpen(0),maxCloseMinusOpen(0),maxOpenMinusClose(0);
if t = sessionStartTime(0,1)+barInterval Then
Begin
todaysOpen = open;
maxCloseMinusOpen = 0;
maxOpenMinusClose = 0;
buysToday = 0;
shortsToday = 0;
canTrade = False;
atr = avgTrueRange(20) of data2;
if trueRange of data2 < atr * rangeCompressionPercent Then
canTrade = True;
canBuy = False;
canShort = False;

end;

mp = marketPosition;

if mp = 1 and mp <> mp[1] then buysToday +=1;
if mp =-1 and mp <> mp[1] then shortsToday +=1;

maxCloseMinusOpen = maxList(close - todaysOpen,maxCloseMinusOpen);
maxOpenMinusClose = maxList(todaysOpen - close,maxOpenMinusClose);

if c < todaysOpen and todaysOpen-c = maxOpenMinusClose and
(maxCloseMinusOpen + maxOpenMinusClose)/c >= stretchPercent Then
canShort = True;
if c > todaysOpen and c- todaysOpen = maxCloseMinusOpen and
(maxCloseMinusOpen + maxOpenMinusClose)/c >= stretchPercent Then
canBuy = True;


if canTrade and t >= calcTime(dontTradeBefore,dontTradeBeforeOffset) and
t < calcTime(dontTradeAfter,dontTradeAfterOffset) and t < sessionEndTime(0,1) Then
begin
if shortsToday = 0 and canShort = True Then
sellshort next bar at l stop;
if buysToday = 0 and canBuy = True Then
buy next bar at h stop;
end;


setExitOnClose;
setStopLoss(stopLoss);
setProfitTarget(takeProfit);
The anti Rubber Band Strategy

Trade filtering was obtained by limiting the duration during the trading day that a trade could take place.  It’s usually wise to wait a few minutes after the open and a few minutes prior to the close to issue trade directives.  Also, range compression of the prior day seems to help in many cases.  Or at least not range expansion.   I only allow one long entry or one short or both during the trading day – two entries only!  Read the code and let me know if you have any questions.  This is a good framework for other areas of research.  Limiting entries using the mp variable is a neat technique that you can use elsewhere.

And as always let me know if you see any bugs in the code.  Like Donnie Knuth says, “Beware of bugs in the above code; I have only proved it correct, not tried it!”

The Day Trading Edition of Easing Into EasyLanguage Now Available!

Learn Pyramiding, Scaling In or Out, Camarilla, Break Out and Clear Out techniques in day trading environment.

Get Your Copy Now!
  • Chapter 1 – Open Range Break Out and other Sundries
  • Chapter 2 – Improving Our ORBO with Pattern Recognition
  • Chapter 3 – Time based Breakout
  • Chapter 4 – Trading After the Lunch Break
  • Chapter 5 – Extending Our Break Out Technology With Pyramiding and Scaling Out
  • Chapter 6 – Scaling Out of Pyramided and multiple Positions
  • Chapter 7 – Pyramania
  • Chapter 8 – Introduction to Zone Trading with the Camarilla
  • Chapter 9 – Day Trading Templates Appendix
A Chart from Chapter 8 – Camarilla Equation

Take a look at this function that spans the entire search space of all the combinations of the days of the week.

inputs: optimizeNumber(numericSimple);
arrays: dowArr[31]("");
vars: currDOWStr(""),daysOfWeek("MTWRF");

//Once
//begin
print(d," ",t," assigning list ");
dowArr[1]="MTWRF";dowArr[2]="MTWR";
dowArr[3]="MTWF";dowArr[4]="MTRF";
dowArr[5]="MWRF";dowArr[6]="TWRF";
dowArr[7]="MTW";dowArr[8]="MTR";
dowArr[9]="MTF";dowArr[10]="MWR";
dowArr[11]="MWF";dowArr[12]="MRF";
dowArr[13]="TWR";dowArr[14]="TWF";
dowArr[15]="TRF";dowArr[16]="WRF";
dowArr[17]="MT";dowArr[18]="MW";
dowArr[19]="MR";dowArr[20]="MF";
dowArr[21]="TW";dowArr[22]="TR";
dowArr[23]="TF";dowArr[24]="WR";
dowArr[25]="WF";dowArr[26]="RF";
dowArr[27]="M";dowArr[28]="T";
dowArr[29]="W";dowArr[30]="R";
dowArr[31]="F";
//end;

OptimizeDaysOfWeek = False;
if optimizeNumber > 0 and optimizeNumber < 32 Then
Begin
currDOWStr = midStr(daysOfWeek,dayOfWeek(d),1);
if inStr(dowArr[optimizeNumber],currDOWStr) <> 0 Then
OptimizeDaysOfWeek = True;
end;
All The Permutations of the Days of the Week

 

Trade after the Lunch Break in Apple

Williams Awesome Oscillator Indicator and Strategy

Awesome Oscillator

This is a very simple yet telling analysis.  Here is the EasyLanguage:

[LegacyColorValue = true]; 



Vars:oscVal(0),mavDiff(0);


mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);
oscVal = mavDiff - average(mavDiff,5);

Plot3( 0, "ZeroLine" ) ;

if currentbar>=1 then
if oscVal>oscVal[1] then plot1(mavDiff,"+AO")
else plot2(mavDiff,"-AO")
Williams Awesome Oscillator Source Code

And here is what it looks like:

Williams Awesome Oscillator

The code reveals a value that oscillates around 0.  First calculate the difference between the 5-day moving average of the daily midPoint (H+ L)/2 and the 34-day moving average of the midPoint.    A positive value informs us that the market is in a bullish stance whereas a negative represents a bearish tone.  Basically, the positive value is simply stating the shorter-term moving average is above the longer term and vice versa. The second step in the indicator calculation is to subtract the 5-day moving average of the differences from the current difference.  If the second calculation is greater than the prior day’s calculation, then plot the original calculation value as green (AO+).  If it is less (A0-), then paint the first calculation red.  The color signifies the momentum between the current and the five-day smoothed value.

Awesome Indicator Strategy

mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);
oscVal = mavDiff - average(mavDiff,5);


mp = marketPosition;
mavUp = countIf(mavDiff > 0,30);
mavDn = countIf(mavDiff < 0,30);

value1 = countIf(oscVal > oscVal[1],10);

oscRatio = value1/10*100;
The beginning of an AO based Strategy

Here I am using the very handy countIf function.  This function will tell you how many times a Boolean comparison is true out of the last N days.  Her I use the function twice, but I could have replaced the second function call with mavDn = 30 – mavUp.  So, I am counting the number of occurrences of when the mavDiff is positive and negative over the past 30-days.  I also count the number of times the oscVal is greater than the prior oscVal.  In other words, I am counting the number of green bars.  I create a ratio between green bars and 10.  If there are six green bars, then the ratio equals 60% This indicates that the ratio of red bars would be 40%.  Based on these readings you can create trade entry directives.

if canShort and mavUp > numBarsAbove and mavDiff > minDiffAmt and oscRatio >= obRatio then
sellShort next bar at open;

if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= osRatio Then
buy next bar at open;
Trade Directives

If the number of readings out of the last 30 days is greater than numBarsAbove and mavDiff is of a certain magnitude and the oscillator ratio is greater than buyOSCRatio, then you can go short on the next open.  Here we are looking for the market to converge.  When these conditions are met then I think the market is overbought.  You can see how I set up the long entries.  As you can see from the chart it does a pretty good job.  Optimizing the parameters on the crude oil futures yielded this equity curve.

Too few trades!

Not bad, but not statistically significant either.  One way to generate more trades is to install some trade management such as protective stop and profit objective.

Using wide stop and profit objective.

Using a wide protective stop and large profit objective tripled the number of trades.  Don’t know if it is any better, but total performance was not derived from just a couple of trades.  When you are working with a strategy like this and overlay trade management you will often run into this situation.

Exiting while conditions to short are still turned on!

Here we either get stopped out or take a profit and immediately reenter the market.  This occurs when the conditions are still met to short when we exit a trade.  The fix for this is to determine when an exit has occurred and force the entry trigger to toggle off.  But you have to figure out how to turn the trigger back on.  I reset the triggers based on the number of days since the triggers were turned off – a simple fix for this post.  If you want to play with this strategy, you will probably need a better trigger reset.

I am using the setStopLoss and setProfitTarget functionality via their own strategies – Stop Loss and Profit Target.  These functions allow exit on the same as entry, which can be useful.  Since we are executing on the open of the bar, the market could definitely move either in the direction of the stop or the profit.  Since we are using wide values, the probability of both would be minimal.  So how do you determine when you have exited a trade.  You could look the current bar’s marketPosition and compare it with the prior bar’s value, but this doesn’t work 100% of the time.  We could be flat at yesterday’s close, enter long on today’s open and get stopped out during the day and yesterday’s marketPosition would be flat and today’s marketPosition would be flat as well.  It would be as if nothing occurred when in fact it did.

Take a look at this code and see if it makes sense to you.

if mp[1] = 1 and totalTrades > totTrades then
canBuy = False;

if mp[1] = -1 and totalTrades > totTrades then
canShort = False;

if mp[1] = 0 and totalTrades > totTrades then
Begin
if mavDiff[1] < 0 then canBuy = False;
if mavDiff[1] > 0 then canShort = False;
end;

totTrades = totalTrades;
Watch for a change in totalTrades.

If we were long yesterday and totalTrades (builtin keyword/function) increases above my own totTrades, then we know a trade was closed out – a long trade that is.  A closed out short position is handled in the same manner.  What about when yesterday’s position is flat and totalTrades increases.  This means an entry and exit occurred on the current bar.  You have to investigate whether the position was either long or short.  I know I can only go long when mavDiff is less than zero and can only go short when mavDiff is greater than zero.  So, all you need to do is investigate yesterday’s mavDiff  to help you determine what position was entered and exited on the same day.  After you determine if an exit occurred, you need to update totTrades with totalTrades.  Once you determine an exit occurred you turn canBuy or canShort off.  They can only be turned back on after N bars have transpired since they were turned off.   I use my own barsSince function to help determine this.

if  not(canBuy) Then
if barsSince(canBuy=True,100,1,0) = 6 then
canBuy = True;
if not(canShort) Then
if barsSince(canShort=True,100,1,0) = 6 then
canShort = True;

Complete strategy code:

inputs:numBarsAbove(10),numBarsBelow(10),buyOSCRatio(60),shortOSRatio(40),minDiffAmt(2),numBarsTrigReset(6);
Vars:canBuy(True),canShort(True),mp(0),totTrades(0),oscVal(0),mavDiff(0),oscRatio(0),mavUp(0),mavDn(0),stopLoss$(1000);


mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);
oscVal = mavDiff - average(mavDiff,5);


mp = marketPosition;
mavUp = countIf(mavDiff > 0,30);
mavDn = countIf(mavDiff < 0,30);

value1 = countIf(oscVal > oscVal[1],10);

oscRatio = value1/10*100;



if not(canBuy) Then
if barsSince(canBuy=True,100,1,0) = numBarsTrigReset then
canBuy = True;
if not(canShort) Then
if barsSince(canShort=True,100,1,0) = numBarsTrigReset then
canShort = True;

if mp[1] = 1 and totalTrades > totTrades then
canBuy = False;

if mp[1] = -1 and totalTrades > totTrades then
canShort = False;

if mp[1] = 0 and totalTrades > totTrades then
Begin
if mavDiff[1] < 0 then canBuy = False;
if mavDiff[1] > 0 then canShort = False;
end;


if canShort and mavUp > numBarsAbove and mavDiff > minDiffAmt and oscRatio >= buyOSCRatio then
sellShort next bar at open;

if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= shortOSRatio Then
buy next bar at open;

totTrades = totalTrades;
Inputs used to generate the equity curve.

The EasyLanguage Function: A Thing of Beauty

The concept of Scope when it comes to a programming language can get very confusing very quickly. If you are new to programming and you think Scope is a mouthwash, no worries here. I will give a full explanation of Scope in terms of programming with the help of ChatGPT. Its response is italicized.

I recently chatted with ChatGPT about Scope in terms of the Python programing language.

In Python, the scope of a variable refers to the region of the program where that variable can be accessed or referenced. There are two types of scopes in Python: global scope and local scope.

Here’s an example that demonstrates the concept of scope in Python:

# global variable
x = 10

def my_func():
# local variable
y = 5
print("x inside my_func:", x) # x is accessed from the global scope
print("y inside my_func:", y) # y is accessed from the local scope

my_func()

print("x outside my_func:", x) # x is accessed from the global scope
print("y outside my_func:") # y is not defined in the global scope, so this will raise a NameError
Example of Scope as demonstrated by Chat-GPT

In this example, we define a global variable x with a value of 10.

We then define a function my_func that has a local variable y with a value of 5. Inside the function, we print the values of x and y. The variable x is accessed from the global scope, which means it can be referenced from anywhere in the program.

The variable y, on the other hand, is only accessible within the function, which is the local scope. Outside the function, we print the value of x again, which is still accessible from the global scope. However, when we try to print the value of y, we get a NameError because y is not defined in the global scope.

Okay that was pretty formal. In simpler terms, a variable declared inside a function can only be seen inside that function, unless it is declared globally. Another thing about Scope, is that the variables have amnesia. Once you step out of the function the variable forgets what it was, and you can’t refer to its prior value upon return to the function.

Unless you are an EasyLanguage function. Scope is still constrained by an EasyLanguage function, because it is a separate piece of code held within the library of Analysis Techniques. Most of the time you can’t see what’s in the function unless you open it with the ELEditor. However, the variables that are defined inside the function do not suffer from amnesia. If you need to refer to a prior value of a locally declared variable, you can. This type of function is what EasyLanguage calls a Serial function. The only downside to this function is it slows processing down quite a bit.

Okay. To make a long story short I wanted to show the magic of EasyLanguage function that I have been working with on a project. This project includes some of Ehlers’ cycle analysis functions. The one I am going to discuss today is the HighRoof function – don’t worry I am not going to go into detail of what this function does. If you want to know just GOOGLE it or ask ChatGPT. I developed a strategy that used the function on the last 25 days of closing price data. I then turned around and fed the output of the first pass of the HighRoof function right back into the HighRoof function. Something similar to embedding functions.

doubleSmooth = average(average(c,20),20);

Sort of like a double smoothed moving average. After I did this, I started thinking does the function remember the data from its respective call? The first pass used closing price data, so its variables and their history should be in terms of price data. The second pass used the cyclical movements data that was output by the initial call to the HighRoof function. Everything turned out fine, the function remembered the correct data. Or seemed like it did. This is how you learn about any programming language – pull out your SandBox and do some testing. First off, here is my conversion of Ehlers’ HighRoof function in EasyLanguage.

//Ehlers HiRoof
Inputs: dataSeries(numericseries),cutPeriod(Numeric);

Vars: a1(0), b1(0), c1(0), c2(0), c3(0), Filt(0), Filt2(0),
alpha1(0),oneMinusAlpha1(0), highPass(0),myhp(0),degrees(0);
Vars: numTimesCalled(0);

//Highpass filter cyclic components whose periods are shorter than 48 bars

numTimesCalled = numTimesCalled + 1;

print(d," numTimesCalled ",numTimesCalled," highPass[1] ",highPass[1]," highPass[2] ",highPass[2]," highPass[3] ",highPass[3]);
degrees = .707*360 / CutPeriod;

alpha1 = (Cosine(degrees) + Sine(degrees) - 1) / Cosine(degrees);

oneMinusAlpha1 = 1-alpha1;

highPass = square(oneMinusAlpha1/2)*(dataSeries-2*dataSeries[1]+dataSeries[2]) +
2*(oneMinusAlpha1)*highPass[1]-square(oneMinusAlpha1)*highPass[2];



EhlersHighRoof=highPass;
Ehlers High Roof Function

This function requires just two inputs – the data (with a history) and a simple length or cut period. The first input is of type numericSeries and the second input is of type numericSimple. You will see the following line of code

 print(d," numTimesCalled ",numTimesCalled," highPass[1] ",highPass[1]," highPass[2] ",highPass[2]," highPass[3] ",highPass[3]);

This code prints out the last three historic values of the HighPass variable for each function call. I am calling the function twice for each bar of data in the Crude Oil futures continuous contract.

1230206.00 numTimesCalled  494.00 highPass[1]   -0.78 highPass[2]   -0.51 highPass[3]   -0.60
1230206.00 numTimesCalled 494.00 highPass[1] -0.05 highPass[2] -0.02 highPass[3] -0.06
1230207.00 numTimesCalled 495.00 highPass[1] -0.38 highPass[2] -0.78 highPass[3] -0.51
1230207.00 numTimesCalled 495.00 highPass[1] 0.04 highPass[2] -0.05 highPass[3] -0.02
1230208.00 numTimesCalled 496.00 highPass[1] 0.31 highPass[2] -0.38 highPass[3] -0.78
1230208.00 numTimesCalled 496.00 highPass[1] 0.16 highPass[2] 0.04 highPass[3] -0.05
1230209.00 numTimesCalled 497.00 highPass[1] 0.49 highPass[2] 0.31 highPass[3] -0.38
1230209.00 numTimesCalled 497.00 highPass[1] 0.15 highPass[2] 0.16 highPass[3] 0.04
1230210.00 numTimesCalled 498.00 highPass[1] 0.30 highPass[2] 0.49 highPass[3] 0.31
1230210.00 numTimesCalled 498.00 highPass[1] 0.07 highPass[2] 0.15 highPass[3] 0.16
1230213.00 numTimesCalled 499.00 highPass[1] 0.52 highPass[2] 0.30 highPass[3] 0.49
1230213.00 numTimesCalled 499.00 highPass[1] 0.08 highPass[2] 0.07 highPass[3] 0.15
1230214.00 numTimesCalled 500.00 highPass[1] 0.44 highPass[2] 0.52 highPass[3] 0.30
1230214.00 numTimesCalled 500.00 highPass[1] 0.04 highPass[2] 0.08 highPass[3] 0.07
Output of calling HighRoof twice per bar

Starting at the top of the output you will see that on 1230206 the function was called twice with two different sets of data. As you can see the output of the first two lines is of a different magnitude. The first line is approximately an order or magnitude of 10 of the second line. If you go to lines 3 and 4 you will see the highPass[1] of lines 1 and 2 moves to highPass[2] and then onto highPass[3]. I think what happens internally is for every call on per bar basis, the variables for each function call are pushed into a queue in memory. The queue continues to grow for whatever length is necessary and then either maintained or truncated at some later time.

Why Is This So Cool?

In many languages the encapsulation of data with the function requires additional programming. The EasyLanguage function could be seen as an “object” like in object-oriented programming. You just don’t know you are doing it. EasyLanguage takes care of a lot of the behind-the-scenes data management. To do the same thing in Python you would need to create a class of Ehlers Roof that maintain historic data in class members and the calculations would be accomplished by a class method. In the case of calling the function twice, you would instantiate two classes from the template and each class would act independent of each other.

Here is my SandBox for Indicator


Value1 = EhlersHighRoof(close,25);
plot1(Value1,"EhlersHiRoof");
Value2 = EhlersHighRoof(value1,25);
plot2(Value2,"EhlersHiRoof2");
Sandbox Playground for Ehlers Function

 

One last nugget of information. If you are going to be working with trigonometric functions such as Cosine, Sine or Tangent, make sure your arguments are in degrees not radians. In Python, you must use radians.