TradeStation – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Thu, 26 Jun 2025 11:28:02 +0000 en-US hourly 1 https://wordpress.org/?v=7.0 https://easylanguagemastery.com/wp-content/uploads/2019/02/cropped-logo_size_icon_invert.jpg TradeStation – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 How To Build Profitable Trading Systems https://easylanguagemastery.com/building-strategies/how-to-build-profitable-trading-systems/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-build-profitable-trading-systems https://easylanguagemastery.com/building-strategies/how-to-build-profitable-trading-systems/#comments Mon, 12 Aug 2024 10:00:00 +0000 http://easylanguagemastery.com/?p=21231

Building a profitable trading system takes a lot of work. It's a challenging project where only some of your ideas will work. To make matters worse, you're bombarded with misleading advertising, confusing claims, and wrong information. Learning a computer language to build a system is excellent, but more is needed for a successful trading system.

Combining a few technical indicators with a buy order and adding trailing stops will not make you a profitable trading system. You are going to need an organized approach and perform specific steps to create a successful trading system.

Developing trading systems is not a science like physics. It's really a mix of both art and science. Your creativity comes into play when attempting to uncover market edges that may lead to a great trading system.

The scientific side of the process comes into play with careful observation, note-taking, and rigorous testing of your trading model. Unlike science, however, no hard-set rules will produce consistent results or winning systems every single time.

In physics, the law of gravity affects all objects on Earth the same way, all the time, everywhere. It's a law that is universally known and understood. The theory of gravity can make excellent predictions about the future. For example, it can predict when the moon will rise and estimate the flight time of an international flight. The market follows no such law. You can't predict where the market will be with 100% accuracy 10 minutes into the future or next year.

This article describes my overall process in building and testing automated trading systems that I follow. I call it the Profit Lab Method. It's a step-by-step process that helps me build a profitable trading system. Does it always work? Of course not. But I follow it religiously because I've seen it work many times. It's my blueprint for building winning trading systems. Much like before building a home, you need a blueprint.

10 Steps To Build Profitable Trading Systems

Profit Lab Method Infographic

Step 1: Finding Great Trading Ideas

The first step in developing a trading system is the key idea. A key idea is the core of your trading system. It's an observation of the market that can be used as a starting point for creating a system. It can be a straightforward observation, such as how price behaves around the 50-period moving average during a strong trend. Or it could be the observation that opening day gaps on high volume often lead to price climbing most of the day.

From a scientific point of view, your key idea is your hypothesis on how the market behaves. With this key idea, we hope to discover and exploit a potential market edge with our trading system.

This key idea should be simple and easy to program into an automated system. For example, a key idea might be to purchase a 20-day high. The hypothesis behind such a key idea is the belief that all new trends start with a 20-day high. This is an example of a trend following trading concept.

However, not all markets have trending characteristics. For instance, many examples on EasyLanguage Mastery show the S&P E-mini futures market exhibiting strong mean reversion behavior. In this case, fading or going short upon 20-day highs may be better.

The point here is you need to know your market. You need to know its characteristics and come up with a key idea.

Step 2: Focus On Best Ideas First

It's easy to collet Key Ideas from YouTube videos, book, magazines, personal observations, and blogs. I record them all in a notebook. I'll often have a dozens of Key Ideas awaiting for me in a notebook. I can't always get to them right away, so I set them aside for later. Because I have so many ideas to work on, how do I know which one to work on first?

The Stress Test

A stress test is subjective but plays a vital role in helping ensure that a given input parameter is not curve fitted to the historical data.

Stress testing involves changing the input values to see how the system performs. To do this, we will need the ability to vary an input value. Sometimes a key idea will only have one or two variables, and others will be more complex.

We want to vary the input parameter to see how our key idea holds up. For example, one of our input values in a lookback period is used within an RSI calculation. The default value is 10. We should change the lookback period from our default value of 10 to 9. In that case, I don't want to see the system's equity curve change dramatically.

Neighboring values should still show positive results. Likewise, if we increase the lookback period from 10 to 11, I don't want to see a drastic change in results. The critical point is the neighboring values around the default value of 10 should still produce positive results. In fact, it would be great to see the system remain profitable over a wide range of values.

Use TradeStation's optimizer to test values around the default value and generate a bar graph like the one below. Then you can quickly see if the value is likely over-optimized or not.

A system that holds up over a wide range of parameters demonstrates robustness and passes our stress test. See the optimization below.  If you see dramatic changes in performance, the input values may be too optimized. Be warned!

Example of robustness - a wide range of successful input values.

Ranking Key Ideas

We need a way to rank our Key Ideas and eliminate unproductive ideas. Doing this lets us focus our time and energy on the most promising prospects. This will help us get the results we want more quickly and effectively.

A simple sanity check is to rank your key idea based on an objective score. This score can be as simple as the net profit, the profit factor, or the annual rate of return. I like to use TradeStation Index or Net Profit vs. Drawdown (NPDD). But you could use whatever you wish.

Once we have the expectancy score, we can rank each of our Key Ideas by this value. I keep a spreadsheet containing a list of the Key Ideas that need review. One of the columns on this spreadsheet includes the Profit Factor. I then can quickly sort my Key Ideas based on this score, thus revealing the top-performing Key Ideas. I can then start testing my best ideas first.

Having a master list of Key Ideas lets you keep a log of what ideas you considered, rejected, or have yet to explore. Very helpful!

Step 3: Define Testing Environment

The pre-work phase for developing a system is to nail down the development environment in which you will build your trading system. This is where you decide what market to trade in and define some important parameters that will impact your development and testing. You'll want to write these down, so you remember them. This also provides the ability to re-create your development environment in the future.

Here are some things I like to record.

  • Platform & Version Numbers
  • Market to trade
  • Time frame to trade
  • Slippage & Commissions
  • Estimated starting equity
  • In-sample period
  • Out-of-sample period
  • Maximum Bar Lookback

Step 4: Define The Baseline

We're close to testing different filters, targets, and exits to our baseline strategy to see if it improves the performance. When we try these filters, how will we know if it's working well? Easy, we'll compare the performance metrics to our baseline.

In short, our baseline will act as a bench market for future comparison.

So, our baseline strategy must be working correctly. Thus, we want to review our code to ensure everything is working as expected.

Things to look for are trades closing when expected.

  • Are trades opening and closing on the same bar
  • Are trades mysteriously opening on the first bar of a new day
  • Are you using the reserved word setexitonclose, and will that be an issue
  • Are your price calculations rounding to a realistic price?

Adding Stops?

Another important aspect of our baseline is introducing a stop value. Most people only trade with stops. Thus, we should add a stop value to make our baseline more realistic, given our individual risk tolerance.

Most of my Key Ideas will don't have a stop value. At this point, I decided whether to add a stop value. Sometimes I do, while other times I don't. If I don't add one here, I will wait until the end of the development process to add a stop.

Remember that even though we pick a stop value for our baseline, we can change it later. In fact, we will be testing other stops deeper within our development process.

Integrating RSDT Templates

Next, I integrate my Key Idea into my Rapid Strategy Development Templates. I use these custom build EasyLanguage templates during development to help me quickly test different filters, stops, and exits. If you want to see a demo of these templates, you can watch this video demo. These templates are available only to students of the Builder Edition of my System Development Master Class.

Step 5: Market Environmental Filters

When designing a system, it's essential to remember the big picture. What is the overall market doing?

Market environmental filters are a term I use to describe the overall market conditions for the instrument you're trading. These large macro-level pictures appear on the daily or weekly charts.

This large macro picture can be applied to any market. For example, when looking at a daily chart, the market can be either in a bull, bear, or range-bound market. To keep things simple, we can use the binary technique to divide a market: bullish or bearish.

A bull or bear market regime filter divides the market into modes: bullish or bearish. Often this is done so you can trade with the major market trend. 

Example of a 200-day simple moving average (yellow line) acting as bull/bear filter.

For example, only take long trades during a bull market and step aside or short during a bear market. That is, only take long trades during a bull market and take short trades during a bear market. It's a simple concept, and many discretionary traders consider the market's overall trend before opening a new position. Not fighting the major market trend could improve your system drastically.

Only taking trades in the direction of the major trend as defined by a 200-day simple moving average.

Of course, you do not have to stop by dividing the market into two regimes (bull or bear market). You could divide the market into three regimes. Bull, Bear, and range bound. This complicates your system more, but it might be worth looking into.

Another common market characteristic for all markets is the strength of a trend. A market may be in a bull regime, but how strong is the trend? Is the demand rising fast, or is it a weak trend? We can further divide the market by measuring the trend's strength to make our trading system more adaptive. By introducing trend strength, we now create four distinct market environments that can be used to determine how an automated system trades.

Step 6: Independent Testing

This step aims to explore other trade filters, exit methods, and entry methods so we may incorporate these rules into our final trading system. During this step, we are interested in not only if we can improve our system but does the new rule demonstrate robustness. As shown in the previous step above, we'll stress test our filters by following the same principles.

Generally, the more trading rules you optimize together, the more likely your system will need to be optimized. It's essential to keep your trading system as simple as possible. If you only take one concept from this article, make it this one because over-optimizing is an area where many people need help. To help avoid curve fitting, the independent testing of each rule is vital.

What does Independent Testing mean? Let's say you have a simple moving average crossover system. You then wish to test a trailing stop and a trend-strength indicator to filter trades. So we have the following items to test:

  • Look-back period of the moving average crossover
  • The threshold value used on the trend filter
  • Trailing stop distance

How do you pick values for each of these indicators? How do you optimize your system? Each new rule we test must be made independently of the other rules. While it's not always possible to ultimately do it, it should be done whenever possible.

Let's say we would like to test a trailing stop. After adding the trailing stop to our baseline system, we determine such a rule is robust across a wide range of values and decide $500 is reasonable.

Let's say we next choose to test a profit target. We must revert to the baseline system to verify our profit target rule. We do not add our profit target rule to the system with the trailing stop rule. Our profit target rule must be applied to the baseline system (which has no stop loss).

Each new rule we test must be made independent of the other rules. This is done to avoid over-optimization and will help maintain a robust system.

Step 7: Intelligent Construction

After we have completed our independent testing, you will have a collection of entry methods, exit methods, and filters, along with their associated non-optimized parameter values. These rules can now be combined into a single system.

Obviously, we are going to use only some things. Instead, we will start with our baseline system, add rules one at a time as needed, and measure their effect on the system's performance.

Sometimes when adding a rule, you see substantial improvement in the performance results. In this case, you can keep it. Other times adding a rule does little to help the system's performance. In this case, it's best to keep things simple and eliminate the least productive rule. Be selective and only include a rule if it clearly helps. I use the general guideline that if a newly added rule does not improve an important performance metric (such as NPDD) by 50% or more, I don't keep it. Remember, we want to keep our strategy as simple as possible.

Step 8: Validate Strategy Robustness

Once you have combined your rules into a final trading system, you can perform Out-Of-Sample (OOS) Testing. This involves taking your final trading system and testing it on data not used during the development of the system. We do this to see how the system performs on this "unseen" data and to answer some critical questions.

  • Does the equity curve break down?
  • Does the equity curve produce wild swings?
  • Do we make new equity highs, or does the equity curve remain flat? 
  • Are the strategy parameters still reasonable/tradable?

We want to see an equity curve with characteristics similar to what we see during the testing period. In other words, drawdowns and new equity highs should look similar. If they do, you have created a system that might be a winner. However, suppose the equity curve deviates from what you see in our historical data, such as dramatically falling below the zero line. In that case, it's time to return to the drawing board.

Sometimes you will have a system that goes flat on the OOS data. Does this mean it's a failure? Well, only sometimes. Suppose your historical test period, the in-sample data, had similar flat periods. In that case, the current flat period may be expected. I would be more suspicious if you had a steadily rising equity curve on the in-sample data and saw a flat OOS data period. This is likely not a good sign, and you may want to fail this system.

However, a flat period or a drawdown on the OOS data does not automatically disqualify the system. As long as it's within the parameters of what was observed during the in-sample period.

I recommend you have at least 30 trades on your out-of-sample. If you have less than 30, you'll need to stop evaluating your strategy. Save your work and revisit your trading system when you have 30+ trades on the out-of-sample. Then you can decide if it's working as expected on the out-of-sample.

The subject of testing trading systems is a vast and growing topic that can get very complex. I perform several other tests that include:

  • Data Augmentation
  • Walk Forward Analysis

Covering these will make this article far too long. To expand your testing knowledge, I recommend looking into these techniques further. I teach a course on Walk Forward Analysis called, Walk Forward Analysis for Algorithmic Traders.

The out-of-sample testing is one of the more critical tests and one of the easiest to perform, and thus I covered it in this article.

Step 9: The Bullet Proof Portfolio

So what most traders do is look for the single best trading system. I've talked to you out there, and I've done it myself. I'll spend weeks or months tailoring testing, tweaking a trading system, and attempting to find the best rules that will work. But the idea that you will build one trading system to make enough money to live on is a fallacy.

Nobody focuses on a single system if you want to be a successful trader. Instead, successful traders focus on a portfolio.

The holy grail is not a system, an indicator, or a trading style, and it's not EasyLanguage or python. Instead, it's building a bulletproof portfolio of trading systems. Again, a portfolio is probably as close as the holy grail of trading.

We want to rely on more than just one system. We want to have several systems, dozens of systems. That way, we are diversifying our risk across multiple systems. That's going to help us bring in that consistent money. This will help you become a much better and consistently profitable trader. I cannot emphasize that enough.

Check out this video of Ray Dalio on YouTube as he breaks down the holy grail concept. Ray does an excellent job showing you this graph and the magic of having a portfolio. Once you understand it, you'll see how this is the key to bringing in consistent money as a trader. It's a short video, and I urge you to watch it.

When building a portfolio, I focus on getting the correlation of daily returns as low as possible between my trading systems. I also aim to select strategies that work well together to maximize NPDD. How do I do that? I use Portfolio Analyst.

I love Portfolio Analyst so much I created a course on exactly how I use it to build a portfolio of trading systems. It's called, The Bulletproof Portfolio Method.

A portfolio of low-correlated strategies helps reduce drawdown and bring in more consistent returns. This is an important asset you'll want to focus on building.

Step 10: Trading Live!

There are many things to be aware of when trading on the live market, including how you handle...

  • Power outages
  • Dropped internet connections
  • When your live accounts become out of sync with your brokerage account
  • What do you do when you go on vacation?

These topics are beyond this article's scope, which is focused entirely on the development process, not on platform-specific issues or live trade execution. But you will want to research this.

Many of the above issues can be solved or significantly reduced by using remote hosting services to power their trading computers. 

Traders who use remote hosting services can trade from anywhere with an internet connection without having to worry about the whereabouts of their physical trading computer. This is especially useful for traders who travel frequently or want to avoid dealing with the hassles of running trading computers. But even if you never or rarely leave your home trading computer, there can be considerable advantages to hosting your trading platform on a remote site.

I'm currently using ChartVPS and have also used Speed Trading Servers.

That's it! That is my develop process in a nutshell.

My Advice...

My advice, start building systems - lots of systems! It does not matter if they do not work well or if you build systems on markets and timeframes, you don't trade. Just start practicing building systems. Get your hands dirty and put to use what you have learned. You will soon find what works for you in the system development process and what will need to be changed. 

If you want my help with building and validating trading system, join me in my in-depth training, System Development Master Class.

]]>
https://easylanguagemastery.com/building-strategies/how-to-build-profitable-trading-systems/feed/ 4
A Timely Function in Easylanguage https://easylanguagemastery.com/building-strategies/a-timely-function-in-easylanguage/?utm_source=rss&utm_medium=rss&utm_campaign=a-timely-function-in-easylanguage https://easylanguagemastery.com/building-strategies/a-timely-function-in-easylanguage/#comments Mon, 29 Jan 2024 11:00:00 +0000 https://easylanguagemastery.com/?p=533439

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.

a. 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. 

b. 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:

I) 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.

II) mod – returns the modulus or remainder from a division operation.  I use this function a lot.  Mod(505/100) gives 5 minutes.

III) 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.

a. 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.

b. 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.  

I) 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.

II) mod – returns the modulus or remainder from a division operation.  I use this function a lot.  Mod(1425/100) gives 25.

III) 14* 60 + 25 = 865 minutes.

iv) 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.

>>By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/building-strategies/a-timely-function-in-easylanguage/feed/ 4
Forgetting This Backtesting Setting Will Cost You! https://easylanguagemastery.com/building-strategies/forgetting-this-backtesting-setting-will-cost-you/?utm_source=rss&utm_medium=rss&utm_campaign=forgetting-this-backtesting-setting-will-cost-you https://easylanguagemastery.com/building-strategies/forgetting-this-backtesting-setting-will-cost-you/#comments Mon, 23 Oct 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=533092

Ever get fooled by a backtest when testing a trailing stop?

You backtest your trailing stop, and everything looks excellent. Still, you lose money on the live market because the trailing stop is not working correctly?

Well, that happens all the time, and in this article, I will tell you why it happens and how to fix it.

Algorithmic traders often grapple with the nuances of trailing stops, especially when discrepancies arise between backtested and live trading results. This article aims to dissect the mechanics behind these differences, offering insights into the complexities of both environments.

The Backtesting Conundrum

In backtesting, trailing stops are typically evaluated using historical data points, including the Open, High, Low, and Close (OHLC) of bars—whether they be minute, hourly, or daily bars. The backtesting engine, be it TradeStation's EasyLanguage or MultiCharts, has to make certain assumptions.

For instance, it needs to decide the sequence in which the high and low of a bar occurred. Did the low form before the high, or vice versa? This sequencing is crucial because it directly impacts how your trailing stop is triggered.

However, it's essential to recognize that backtesting is a simplified representation of the market. One of its most significant limitations is the inability to account for intra-bar price action. This means the engine can't simulate the real-time fluctuations within a single bar. Watch a 10-minute bar form in real-time. After the opening tick, the market moves up, then down, before going back up again. This second-by-second movement is unknown to the backtesting engine. So, the backtesting engine assumes how the bar was formed, making your backtest results an approximation at best.

My Backtests Don't Match Live Trading!

The divergence in behavior between backtesting and live trading can result in substantial discrepancies in your trading results. Suppose you have noticed a difference between your backtest and live results. In that case, the culprit is likely the live trading environment's sensitivity to intra-bar price action, something your backtesting engine couldn't simulate.

The other possibility is curve fitting (overfitting) your strategy to the historical data. This is also a common problem. While it's not the topic of this article, you can read more about curve fitting and how to avoid it here.

Best Practices When Backtesting With Trailing Stops

So, how do you mitigate this discrepancy? One practical approach is enabling the "Look Inside Bar Backtesting" (LIBBT) feature in platforms like TradeStation and MultiCharts. LIBBT allows the backtesting engine to dissect each bar into smaller segments, providing a more granular view of price action.

The Look Inside Bar Backtesting (LIBBT) feature is designed to resolve a common issue in backtesting with intraday data, where a strategy might execute orders based on the open, high, low, or close of a bar without considering the sequence of prices within the bar. 

LIBBT Setting

Access by right-clicking on your chart then slecting
Edit Strategies->Properties For All.

By enabling LIBBT, you can instruct TradeStation to "look inside" each bar better to estimate the sequence prices within the bar.

For example, if you have a 15-minute bar, enabling the LIBBT feature can give you a one-minute resolution for each bar. Put another way, the backtesting engine will evaluate your trailing stop on a minute-by-minute basis within a single bar. This results in a more accurate simulation of your trailing stop's behavior in a live trading environment, reducing the gap between backtested and actual results.

Set this feature if your strategy relies on order types that could be influenced by the sequence of prices within a bar. Trailing stops are the obvious choice. Also, if your strategy uses profit targets and a hard stop. The backtesting engine must estimate which one might be hit first; thus, using LIBBT becomes critical.

You don't have to use the LIBBT setting if your strategy only uses "next bar at open" to enter and exit trades. Likewise, the LIBBT setting is unnecessary if your strategy uses "next bar at open" with a single hard stop loss.

By understanding these nuances and employing features like LIBBT, you can significantly improve the reliability of your trading strategies, ensuring that your backtested results are more aligned with live trading outcomes.

]]>
https://easylanguagemastery.com/building-strategies/forgetting-this-backtesting-setting-will-cost-you/feed/ 2
Enhancing the 2-Period RSI2 on Indexes Using the VIX Futures Market – an RSI trading strategy https://easylanguagemastery.com/strategies/enhancing-the-2-period-rsi2-on-indexes-using-the-vix-futures-market-an-rsi-trading-strategy/?utm_source=rss&utm_medium=rss&utm_campaign=enhancing-the-2-period-rsi2-on-indexes-using-the-vix-futures-market-an-rsi-trading-strategy https://easylanguagemastery.com/strategies/enhancing-the-2-period-rsi2-on-indexes-using-the-vix-futures-market-an-rsi-trading-strategy/#respond Mon, 11 Sep 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532869

Table of Contents

Introduction

In the book “Short Term Trading Strategies That Work” by Larry Connors and Cesar Alvarez, a widely used entry strategy for Index markets is discussed, which takes advantage of the index mean reversion edge through the 2-period RSI. This RSI trading strategy involves going long only when the 2-period RSI falls below an oversold limit. In this article, we will explore whether the RSI works in different timeframes and index markets, and we will use the Volatility Index (VIX) as a filter to enhance the strategy.

To establish a reference point, let’s consider a random pick from the ES market:

Market: @ES
Timeframe: 120 mins.
Entry RSI2 crosses below 20. (Long only).
Stop loss: $1500.
Profit target: $1500.
Slippage: $12.5 per contract.
Commission: $2.5 per trade.

Based on the above parameters, the results are as follows:

Net Profit:$87.977
Avg Trade:$69.7
Trades:1.262
Profit Factor:1,10
Max DD:$37.282

We could say there is an edge, but it can be further improved to increase its effectiveness by reducing the number of trades. In order to achieve this, I want to use the VIX as a filter.

Why VIX?

Let’s explore its definition:

 “The Cboe Volatility Index (VIX) is a real-time index that represents the market’s expectations for the relative strength of near-term price changes of the S&P 500 Index (SPX). Because it is derived from the prices of SPX index options with near-term expiration dates, it generates a 30-day forward projection of volatility. Volatility, or how fast prices change, is often seen as a way to gauge market sentiment, and in particular the degree of fear among market participants.

The index is more commonly known by its ticker symbol and is often referred to simply as “the VIX.” It was created by the Cboe Options Exchange (Cboe) and is maintained by Cboe Global Markets. It is an important index in the world of trading and investment because it provides a quantifiable measure of market risk and investors’ sentiments.”

Source: https://www.investopedia.com/terms/v/vix.asp

As we can see from the definition, incorporating the VIX in our strategy allows us to leverage market sentiment as a filtering mechanism. To achieve this, we will consider the following cases:

  • Case 1: High of the VIX is higher than X bars ago.
  • Case 2: High of the VIX is lower than X bars ago.
  • Case 3: VIX RSI of X number bars ago is greater than 50.
  • Case 4: VIX RSI of X number bars ago is lower than 50.
  • Case 5: VIX RSI of X number bars ago is greater than 80.
  • Case 6: VIX RSI of X number bars ago is lower than 20.

Considerations

Charting Software: TradeStation 10.0.

Code development language: Easylanguage 10.0.

Code Considerations:

  • Entries type: 
    • Long only.
  • Entries Direction: 
    • Mean Reversion.
  • Exits:
    • Stop Loss
    • Profit Target: Stop Loss 
  • Trigger:
    • Long when Close crosses below Oversold.
    • VIX Filter on data 2

First approach

OK, now that the code is ready, let’s add Data2 to our reference strategy:

And look for the following cases and parameters:

Results

 RSI2RSI2 + VIX filters
Net Profit:$87.977$77.862
Avg Trade:$69.7$140.29
Trades:1.262555
Profit Factor:1,101.21
Max DD:$37.282$17.862

The more effective filter case is number 4: where the RSI of the VIX with 7 bars back is above 50, even if the net profit is reduced, the strategy is more effective in reducing more than half of the trades, duplicating the average per trade and reducing the drawdown by $20.000. 

After seeing the improvement of the strategy, some questions arise:

  • Will it work in another timeframe?
  • Will it work on other Index futures markets?
  • What will happen if the VIX has a different timeframe from the primary Market?

This research will take me a considerable big amount of time to do it manually, so what better tool than Tradesq to help me out.

Applying Tradesq

Tradesq has been chosen as a Futures trading system research tool.

On Tradesq, I will enter the code, and on Data1, select the four main Index futures markets: 

@ES: E-MINI S&P 500.

@NQ: E-MINI NASDAQ 100.

@RTY: E-MINI RUSSELL 2000.

@YM: E-MINI DOW 30.

11 timeframes, from 15 minutes to daily.

For Data 2, the market will be @VX, and timeframes from 15 minutes to daily.

Results

After a few hours, we obtained results based on the following criteria:

Nasdaq 60min

Data1: Nasdaq (@NQ) 60min

Data2: VIX (@VX) 180min

ES 120min

Data1: S&P (@ES) 120min

Data2: VIX (@VX) Daily

YM 60min

Data1: DOW (@YM) 60min

Data2: VIX (@VX) 60min

YM 120min

Data1: RTY (@YM) 120min

Data2: VIX (@VX) 1440min

Note: All results include trading costs, Slippage, and Commission.

Conclusion

Incorporating the VIX as a filter has significantly improved the RSI trading strategy’s performance across different timeframes and Index futures markets. The results show promising potential and further research and testing can be conducted to refine and optimize the strategy.

>> By Juan Fernando Gómez from blog blog.tradesq.net

]]>
https://easylanguagemastery.com/strategies/enhancing-the-2-period-rsi2-on-indexes-using-the-vix-futures-market-an-rsi-trading-strategy/feed/ 0
How To Trade With A Full Time Job https://easylanguagemastery.com/getting-started/how-to-trade-with-a-full-time-job/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-trade-with-a-full-time-job https://easylanguagemastery.com/getting-started/how-to-trade-with-a-full-time-job/#respond Mon, 28 Aug 2023 12:21:04 +0000 https://easylanguagemastery.com/?p=532792

Over 15 years ago, I had the great idea of becoming a day trader. The dream of financial freedom was a distant mirage, tantalizing yet elusive. The world of trading beckoned, promising a path to independence and control. With a heart full of hope, I opened an Etrade account, ready to embark on a journey I thought would be easy. Well, the market has something else in store for me. 

The early days of trading were filled with excitement and anticipation. Each morning, I would study trade setups, attempting to seize opportunities at the market open before rushing off to work. But the path was not as smooth as I had imagined. Monitoring trades between meetings and work commitments became a battle against time. But the biggest issue was something I did not anticipate. My emotions. I was not in control. I took invalid trades, moved stops, and exited trades too early. I would take revenge trades because I was so mad at the market for taking my hard-earned cash. Other times I would be too frighted to open a new trade. I'm sure you can relate.

The dance with the market became a delicate and exhausting balancing act, leaving me lost and frustrated. My trading journey had taken a wrong turn, and I lost money, feeling defeated by the endeavor I had embraced with such enthusiasm.

The Algorithmic Trading Revelation

I was experiencing the "valley of despair." This term is often used in psychology to describe a low point in an individual's journey, particularly during a process of learning, growth, or transformation. It's not a formal psychological concept but a metaphorical description that can be applied in various contexts. In short, the valley of despair is the low point where the challenges feel overwhelming, and the initial optimism has turned into disillusionment and despair. The individual may feel stuck, overwhelmed, and unsure of how to proceed. It's a critical stage where some may give up while others find ways to persevere. 

Yep, that sounds like me. 

But from the valley of despair, a beacon of hope emerged: algorithmic trading. 

As I emerged from the valley of despair in my trading journey took an innovative approach that offered a way to trade without being chained to the screen, without the emotional biases, and without the relentless pressure of manual decision-making. It was not just a tool but a revelation, a strategic solution that opened doors to a new horizon. 

Algo trading is the process of using computer algorithms to place and manage trades according to a predefined set of rules (strategies). Imagine a seasoned trader who never sleeps, never succumbs to emotions, and executes your trading plan with machine-like precision. That's algo trading.

Here's why algo trading became my trading superpower:

1. Consistency: Algo trading follows the rules to the letter, ensuring consistent execution of your trading strategy. It doesn't get tired, distracted, or fearful. It trades the plan, every time.

2. Discipline: Emotional decisions were my downfall as a discretionary trader. Algo trading removed that weakness, executing trades without hesitation or doubt, free from the psychological traps that ensnare human traders.

3. Trading While at Work: With algo trading, my trading didn't stop when my day job began. The algorithms worked in the background, scanning the markets, placing trades, and managing positions. At the same time, I focused on my full-time job.

Backtesting and Optimization: Algo trading allowed me to test my strategies on historical data, fine-tuning them for optimal performance. This evidence-based approach gave me the confidence to trade my strategies in the live market.

Efficiency: Time was always against me in my early trading days. Algo trading changed that, automating complex tasks and freeing up my time for research, strategy development, and, most importantly, living my life.

Trading While Working Full-Time: The Power of Automation

In the world of trading, time is a precious commodity. For those juggling a full-time job, the traditional approach to trading can feel like a never-ending battle with the clock. Discretionary trading demands constant attention, quick decisions, and a relentless pursuit of market opportunities. 

As I found out, and as you may already know, the life of a discretionary trader balancing a full-time job is hectic. Mornings are spent scanning the markets, analyzing trends, and making quick decisions before heading to work. Lunch breaks become trading breaks, and evenings are consumed by research, planning, and more trading. Weekends? They're for catching up on what you missed and preparing for the week ahead.

The hustle is real, and the pressure is intense. Every moment away from the market feels like a missed opportunity. When sneaking in time on the market, I would sometimes neglect my work. I did not like this. I felt horrible. On top of that, the trading emotional toll is heavy, and the work-life balance is skewed. It's a path that can lead to burnout, frustration, and financial uncertainty.

Now, contrast this with the world of algo trading. The hustle gives way to harmony, the pressure to precision, and the chaos to control. Here's how:

Building and Testing on Your Time: With algo trading, you use your off-times, such as weekends or after work, to build and test your trading systems. It's a thoughtful, deliberate process, free from the frantic pace of the live market.

Automated Execution: Once your strategies are ready, you set them loose. The algorithms place and manage trades according to your predefined rules. They work while you work, trading in the background and executing your plan without needing your constant attention. That means at work you can do your work and not have to constantly watch the markets! This is huge. 

Consistent and Emotion-Free: Unlike discretionary trading, algo trading doesn't waver, hesitate, or second-guess. It doesn't get tired or emotional. It's a machine executing your strategy with unerring consistency, day in and day out.

Work-Life Balance: Algo trading aligns with your life, not against it. It allows you to pursue your trading goals without sacrificing your career, family, or well-being. It's trading on your terms, a path to financial freedom that fits seamlessly with your full-time job.

A Sustainable Journey: By automating the trading process, you create a sustainable, long-term approach to trading. It's not a sprint; it's a marathon, a journey that you can navigate at your pace, with control, confidence, and clarity.

The beauty of algo trading is in its empowerment. It's not just about automating trades; it's about automating your life, aligning your passion for trading with your career, and creating a balanced, fulfilling, and financially rewarding life. It's the path I chose, and it's a path that's open to you, a gateway to a life unshackled from the constraints of time and the ticking clock

Getting Started as an Algo Trader

Becoming an algo trader is an exciting adventure filled with opportunities and challenges. It requires a unique blend of skills and the right equipment to successfully navigate the world of automated trading. Here's what you'll need.

1. Understanding of Trading Principles

A journey into algo trading begins with a solid understanding of trading principles. While many traders may have a decent grasp of these concepts, delving deeper into the nuances is essential. 

Trading Strategies: Understanding various trading strategies, from trend-following to mean-reversion, is crucial. These strategies form the backbone of your algorithms, guiding their decision-making process.

Risk Management: Knowing how to manage risk is paramount. This includes setting stop-loss and take-profit levels, managing leverage, and diversifying your portfolio. In algo trading, risk management rules must be coded into the algorithms, ensuring that they operate within predefined risk parameters.

Market Analysis: Analyzing market conditions, understanding indicators, and interpreting economic data are vital skills. These insights inform your trading algorithms, enabling them to respond to changing market conditions.

Translating Principles into Algorithms: The unique challenge in algo trading is translating these principles into code. Your understanding of trading must be precise and nuanced, allowing you to create algorithms that accurately reflect your trading philosophy and approach.

2. Proficiency in EasyLanguage

Learning EasyLanguage was a transformative step in my journey into algo trading. Here's why it should be your #1 priority: it's the language of computers! Knowing how to code allows you to convert the ideas into your head into computer code so a computer can understanding it. Trying to be an algo trading without knowing how to code is like moving to a foreign country and not speaking the native language! 

Designed for Trading: EasyLanguage is explicitly designed for trading, unlike general-purpose programming languages. Its syntax and functions are tailored to the needs of traders, making it more accessible and relevant.

Building and Testing Algorithms: EasyLanguage allows you to build and test trading algorithms within the TradeStation platform. You can code your strategies, backtest them on historical data, and optimize them for live trading.

Endless Possibilities: Mastery of EasyLanguage opens the doors to endless possibilities. From simple moving average crossovers to complex multi-asset strategies, you can bring your trading ideas to life, limited only by your imagination and understanding of the markets.

3. Technical Skills

Technical skills go beyond coding. They encompass a broader understanding of the tools, platforms, and technologies that power algo trading:

TradeStation's Tools and Features: Familiarity with TradeStation's suite of tools is essential. This includes understanding how to set up charts, indicators, and automated strategies and monitor and manage live trades.

Troubleshooting: Technical skills also include troubleshooting computer issues and debugging your code.

Strategy Building: Even though you can program a strategy, you still need to build it correctly. Building trading systems is a unique skill set. You must learn how to avoid curve fitting when creating your strategy. This is often done by properly testing your design. You must learn how to optimize correctly to avoid introducing curve fitting. There is a lot of nuance here, and it can take years of practice to nail down.

4. Continuous Learning Mindset

The world of algo trading is dynamic, complex, and ever-changing. A continuous learning mindset is not just an asset; it's a necessity:

Adapting and Growing: Markets evolve, technologies advance, and trading strategies adapt. Staying current with these changes requires ongoing education, research, and development. A willingness to learn, adapt, and grow is key to long-term success. This includes refining your strategies, exploring new markets, and embracing new tools and technologies. In short, you're constantly testing new ideas and you have to put in the work. So, do you like writing code, testing new ideas? 

Learning from Experience: Algo trading is a journey filled with successes and failures, insights and surprises. Embracing a continuous learning mindset means learning from every trade, every outcome, and every experience, turning them into opportunities for growth and improvement.

These four skills form the cornerstone of a successful algo trading career. They encompass the knowledge, expertise, mindset, and technical acumen needed to navigate the world of automated trading. Together, they provide a roadmap for aspiring algo traders, guiding them from the foundational principles of trading to the specialized skills of algorithm development and execution.

Essential Equipment for Algo Trading

Embarking on the path of algo trading requires not only the right skills but also the right equipment. Here's a closer look at the essential tools and resources you'll need to become a successful algo trader, particularly if you're using TradeStation and EasyLanguage:

A Reliable Computer

Two important conciderations:

Processing Power: Algo trading demands a computer with a robust processor to handle the backtesting of algorithms efficiently.

Sufficient RAM: Adequate memory ensures smooth multitasking, allowing you to run multiple strategies, analyze data, and monitor trades without slowdowns.

In short, you want to get the best computer you can afford. Now, when just starting out this is not as important. You're learning and you're not even sure if this endeavor will be right for you. So don't go crazy with buying a $3,000 computer. You can do a lot with a sub $1,000 dollar computer. You can always upgrade in the future.

TradeStation Platform or MultiCharts

TradeStation offers a wide array of tools for building, testing, and executing algorithms. It's a one-stop-shop for algo traders, with features tailored to the needs of automated trading. TradeStation's seamless integration with EasyLanguage allows you to code, backtest,  otimize and even trade your strategies live within the platform, providing a cohesive and efficient workflow.

Another viable option for aspiring algo traders is MultiCharts, a robust trading platform that offers many of the same benefits as TradeStation. MultiCharts utilizes PowerLanguage, a programming language that shares many similarities with EasyLanguage. Like EasyLanguage, PowerLanguage is designed with traders in mind, offering a user-friendly syntax that makes coding trading strategies accessible and efficient.

The compatibility between PowerLanguage and EasyLanguage means that transitioning between the two platforms is relatively seamless. Whether you're backtesting strategies, optimizing algorithms, or executing trades, MultiCharts provides a comprehensive suite of tools that align with the needs of automated trading. It's an alternative that offers flexibility and power, catering to both novice and experienced algo traders.

Data Subscriptions

This will be a monthly reoccurring expense. Price data for the markets you want to trade. You'll need access to this data and you can buy it for a monthly fee. There are two types of data feeds you will need.

1. Historical Data: Access to historical market data is essential for backtesting your strategies, allowing you to simulate how they would have performed in the past. This is a must! TradeStation allows you to access this data easily when you have their platform. It's another great reason to use TradeStation.

2. Real-Time Data: Real-time data feeds provide the information your algorithms need to make live trading decisions, ensuring that they respond to current market conditions. Yep, this is a different feed you'll need to trade live. You won't need live data until you're trading live. When just starting our algo journey, you just need Historical Data. This will save you some money. You only need to move to real-time data when you're trading live. Once again, TradeStation make this very easy to acquire. 

Backup Systems

First, having an Uninterruptible Power Supplies (UPS) ensures that your trading continues even during power outages, providing a temporary power source that can keep your computer and internet running. It can also help protect your equipment from power surges.

The other issue is backing up your work. Imagine the agony of losing months or even years of meticulous research, coding, and optimization due to a system failure or accidental deletion. The pain is not just emotional; it's financial, disrupting your trading operations and potentially costing you valuable opportunities.  

That's where TradeStation's backup feature becomes an indispensable ally. By regularly backing up your TradeStation files, you safeguard your hard-earned work, ensuring that your trading systems, custom indicators, and personalized settings are preserved and protected. 

Regularly save copies of your EasyLanguage files, workspace settings, and strategy configurations, either on an external drive or a secure cloud service. Consider scheduling automated backups and maintaining multiple versions to ensure that you always have access to your essential files. In the fast-paced world of trading, where every moment counts, the assurance of knowing that your work is secure is priceless.

It's not just a best practice; it's a fundamental aspect of responsible trading, a commitment to your craft, and a testament to the value you place on your trading journey.

Virtual Private Server (VPS): The Freedom of Remote Hosting

One of the best things I did to improve my algo trading experience was utilizing a Virtual Private Server (VPS). It's a game-changer in the world of algo trading. It's a solution that offers unparalleled freedom, flexibility, and reliability. Here's why a VPS is an essential tool for modern algo traders:

24/7 Operation: A VPS allows your trading platform to run continuously, even when your local computer is turned off. It ensures that your algorithms are always working, scanning the markets, and executing trades. Whether it's during power outages or system maintenance, your trading never stops.

Access Your Trading Anywhere: With a VPS, you can access your trading platform from anywhere in the world with an internet connection. Whether you're traveling, at work, or simply away from your home computer, your trading operations are always within reach.

Quick Disaster Recovery: A VPS offers robust disaster recovery solutions. If something goes wrong, whether it's a hardware failure or a software glitch, recovery is quick and efficient, minimizing downtime and potential loss.

Enhanced Security: Hosting your trading platform on a VPS provides an additional layer of security. With professional hosting services, you benefit from advanced security protocols that protect your data and trading operations.

Rock Solid InternetA stable and robust internet connection ensures seamless communication with your trading computer. When trading from my home computer, my internet connection could have been better. It would occasionally drop or slow down. This can lead to a host of issues that every trader dreads:

  • Delayed execution
  • Slippage
  • Loss of control over live trades
  • Even disconnection from the market at critical moments

These disruptions not only erode profits but can undermine confidence and strategy effectiveness.

In a world where the market waits for no one, a rock-solid internet connection is your gateway to consistency, control, and confidence. It's the unseen yet vital infrastructure that empowers you to trade without boundaries, ensuring that you're always in sync with the market, no matter where you are. It's not just about speed; it's about stability, reliability, and the assurance that your trading journey continues uninterrupted.

As I said before, using a VPS was one of the best ways I improved my trading experience. But do you need to rent a VPS now? Probably not. You only need to use a VPS if you're trading live. When you're just learning, you don't need it. But, when the time comes to start trading live, it's a must.

Conclusion

For the aspiring trader balancing a full-time job, the traditional path can be a relentless race against time, fraught with emotional turmoil and unyielding demands. But there's a different path, one that aligns with the rhythm of your life, not against it.

Algo trading is more than a technological marvel; it's a paradigm shift, a transformation from chaos to control, from hustle to harmony. It's about trading on your terms, with precision, consistency, and balance. It's about building a sustainable journey towards financial freedom without sacrificing your career, your well-being, or your dreams.

Whether you're a seasoned trader seeking a new horizon or a beginner yearning for a way to trade while working full-time, algo trading is your gateway to a world unshackled from the constraints of time. It's not just a method; it's a mindset, a philosophy, a way of life. Embrace the power of automation, master the art of EasyLanguage, and embark on a journey that's uniquely yours. The market is calling, and the path is clear. The question is, are you ready to trade your way?

If the journey into the world of algo trading resonates with you, if the promise of precision, control, and balance speaks to your trading aspirations, then you're not alone. Many have walked this path, and many have sought guidance to navigate the complexities and nuances of algorithmic trading.

That's where the System Development Master Class comes into play. Designed with the aspiring algo trader in mind, this comprehensive course offers a step-by-step guide to mastering the art of EasyLanguage, building robust trading systems, and embarking on a successful trading journey.

Whether you're taking your first steps or seeking to elevate your trading to new heights, the System Development Master Class is your companion, your mentor, your roadmap to success. Ready to trade your way? Ready to embrace a new horizon? The path is open, and the opportunity awaits. Learn more and begin your journey today.

Visit the System Development Master Class

]]>
https://easylanguagemastery.com/getting-started/how-to-trade-with-a-full-time-job/feed/ 0
Extend Data Mining To Actual Trading System https://easylanguagemastery.com/building-strategies/extend-data-mining-to-actual-trading-system/?utm_source=rss&utm_medium=rss&utm_campaign=extend-data-mining-to-actual-trading-system https://easylanguagemastery.com/building-strategies/extend-data-mining-to-actual-trading-system/#respond Mon, 14 Aug 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532714

Data Mining May or May Not Link Causality

A study between ice cream sales and crime rate demonstrated a high level of correlation.  However, it would be illogical to assume that buying more ice cream leads to more crime.  There are just too many other factors and variables involved to draw a conclusion.  So, data mining with EasyLanguage may or may not lead to anything beneficial.  One thing is you cannot hang your hat completely on this type of research.  A reader of my books asked if there was evidence that pointed to the best time to enter and exit a day trade.  Is it better to enter in the morning or in the afternoon or are there multiple trading windows throughout the day?  I thought I would try to answer the question using TradeStation’s optimization capabilities.

Get Your Copy Now!

Create a Search Space of Different Window Opening Times and Open Duration

My approach is just one of a few that can be used to help answer this question.  To cut down on time and the size of this blog we will only look at day trading the @ES.D from the long side.  The search space boundaries can be defined by when we open the trading window and how long we leave it open.  These two variables will be defined by inputs so we can access the optimization engine.  Here is how I did it with EasyLanguage code.

inputs: openWindowTime(930),openWindowOffset(5),windowDuration(60);
inputs: canBuy(True),canShort(True);
if t >= calcTime(openWindowTime,openWindowOffset) and t < calcTime(openWindowTime,openWindowOffset+windowDuration) Then
Begin
if entriesToday(d) = 0 and canBuy Then
buy next bar at market;
if entriesToday(d) = 0 and canShort Then
sellshort next bar at market ;
end;

if t = calcTime(openWindowTime,openWindowOffset+windowDuration) Then
Begin
if marketPosition = 1 then sell next bar at open;
if marketPosition =-1 then buyToCover next bar at open;
end;
setExitOnClose;

Optimize when to open and how long to leave open

The openWindowTime input is the basis from where we open the trading window.  We are working with the @ES.D with an open time of 9:30 AM eastern.  The openWindowOffset will be incremented in minutes equivalent to the data resolution of the chart, five minutes.  We will start by opening the window at 9:35 and leave it open for 60 minutes.  The next iteration in the optimization loop will open the window at 9:40 and keep it open for 60 minutes as well.  Here are the boundaries that I used to define our search space.

  • window opening times offset: 5 to 240 by 5 minutes
  • window opening duration: 60 to 240 by 5 minutes
Optimization Ranges for Window Open and Open Duration

A total of 1739 iterations will span our search space.   The results state that waiting for twenty minutes before buying and then exiting 190 minutes later, worked best.  But also entering 90 minutes after the open and exiting 4 hours later produced good results as well (no trade execution fee were utilized.)  Initially I was going to limit entry to once per day, but then I thought it might be worthwhile to enter a fresh position, if the first one is stopped out, or pyramid if it hasn’t.  I also thought, each entry should have its own protective stop amount.  Would entering later require a small stop – isn’t most of the volatility, on average, expressed during the early part of the day.

Results of different opening and duration times.

Build a Strategy that Takes on a Secondary Trade as a New Position or One that is Pyramided.

This is not a simple strategy.  It sounds simple and it requires just a few lines of code.  But there is a trick in assigning each entry with its own exit.  As you can see there is a potential for trade overlap.  You can get long 20 minutes after the open and then add on 70 minutes  (90 from the open) later.  If the first position hasn’t been stopped out, then you will pyramid at the second trade entry.  You have to tell TradeStation to allow this to happen.

Allow TradeStation to Pyramid up to 2 positions with different signals.

System Rules

  1. Enter long 20 minutes after open
  2. Enter long 90 minutes after open
  3. Exit 1st entry 190 minutes later or at a fixed $ stop loss
  4. Exit 2nd entry 240 minutes later or at a fixed $ stop loss
  5. Make sure you are out at the end of the day

Sounds pretty simple, but if you want to use different stop values for each entry, then the water gets very muddy.

AvgEntryPrice versus EntryPrice

Assume you enter long and then you add on another long position.  If you examine EntryPrice you will discover that it reflects the initial entry price only.   The built-in variable AvgEntryPrice will be updated with the average price between the two entries.  If you want to key off of the second entry price, then you will need to do a little math.

avgEntryPrice = (entry price 1 + entry price 2) / 2

or ap = (ep1 + ep2) /2

Using this formula and simple algebra we can arrive at ep2 using this formula:  ep2 = 2*ap – ep1.  Since we already know ep1 and ap, ep2 is easy to get to.  We will need this information and also the functionality of from entry.  You tie entries and exits together with the keywords from entry.  Here are the entry and exit trade directives.

if time = calcTime(openTime,entryTime1Offset) then
buy("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset) then
buy("2nd buy") next bar at open;

if time = calcTime(openTime,entryTime1Offset + exitTime1Offset) then
sell("1st exit") from entry("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset + exitTime2Offset) then
sell("2nd exit") from entry("2nd buy") next bar at open;

if mp = 1 Then
Begin
value1 = avgEntryPrice;
if currentShares = 2 then value1 = avgEntryPrice*2 - entryPrice;
sell("1st loss") from entry("1st buy") next bar at entryPrice - stopLoss1/bigPointValue stop;
sell("2nd loss") from entry("2nd buy") next bar at value1 - stopLoss2/bigPointValue stop;
end;

if mp = 1 and t = openTime + barInterval then sell("oops") next bar at open;

Entry and Exit Directives Code

The trade entry directives are rather simple, but you must use the calcTime function to arrive at the correct entry and exit times.  Here we are using the benchmark, openTime and the offsets of entryTime1Offset and entryTime2Offset.  This function adds (or subtracts if the offset is negative) the offset to the benchmark.  This takes care of when the trading windows open, but you must add the entry1TimeOffset to exit1TimeOffset to calculate the duration the trading window is to remain open.  This goes for the second entry window as well.

Now let’s look at the exit directives.  Notice how I exit the 1st buy entry with the code from entry (“1st buy”).  This ties the entry and exit directives together.  This is pretty much straightforward as well.  The tricky part arrives when we try to apply different money management stops to each entry.  Exiting from the 1st buy requires us to simply subtract the $ in terms of points from entryPrice.  We must use our new equation to derive the 2nd entry price when two contracts are concurrent.   But what if we get stopped out of the first position prior to entering the second position?  Should we continue using the formula.  No.  We need to fall back to entryPrice or avgEntryPrice:  when only one contract or unit is in play, these two variables are equal.  We initially assign the variable value1 to the avgEntryPrice and only use our formula when currentShares = 2.  This code will work a majority of the time.  But take a look at this trade:

Didn’t have an intervening bar to update the 2nd entry price. The first entry price was used as the basis to calculate the stop loss!

This is an anomaly, but anomalies can add up.  What happened is we added the second position and the market moved down very quickly – too quickly for the correct entry price to be updated.  The stop out (2nd loss) was elected by using the 1st entry price, not the second.  You can fix this with the following two solutions:

  1. Increase data resolution and hope for an intervening bar
  2. Force the second loss to occur on the subsequent trading bar after entry.  This means you will not be stopped out on the bar of entry but will have to wait five minutes or whatever bar interval you are working with.
Fixed – just told TS to place the order at the close of the bar where we were filled!

OK – Now How Do We Make this a Viable Trading System

If you refer back to the optimization results you will notice that the average trade (before execution costs) was around $31.  Keep in mind we were trading every day.  This is just the beginning of your research – did we find a technical advantage?  No.  We just found out that you can enter and exit at different times of the trading day, and you can expect a positive outcome.  Are there better times to enter and exit?  YES.  You can’t trade this approach without adding some technical analysis – a reason to enter based on observable patterns.  This process is called FILTERING.   Maybe you should only enter after range compression.  Or after the market closed up on the prior day, or if the market was an NR4 (narrow range 4.)  I have added all these filters so you can iterate across them all using the optimization engine.  Take a look:

filter1 = True;
filter2 = True;

if filtNum1 = 1 then
filter1 = close of data2 > close[1] of data2;
if filtNum1 = 2 Then
filter1 = close of data2 < close[1] of data2;
if filtNum1 = 3 Then
filter1 = close of data2 > open of data2;
if filtNum1 = 4 Then
filter1 = close of data2 < open of data2;
if filtNum1 = 5 Then
filter1 = close of data2 > (h data2 + l data2 + c data2)/3;
if filtNum1 = 6 Then
filter1 = close of data2 < (h data2 + l data2 + c data2)/3;
if filtNum1 = 7 Then
filter1 = openD(0) > close data2;
if filtNum1 = 8 Then
filter1 = openD(0) < close data2;

if filtNum2 = 1 Then
filter2 = trueRange data2 < avgTrueRange(10) data2;
if filtNum2 = 2 Then
filter2 = trueRange data2 > avgTrueRange(10) data2;
if filtNum2 = 3 Then
filter2 = range data2 = lowest(range data2,4);
if filtNum2 = 4 Then
filter2 = range data2 = highest(range data2,4);

Filter1 and Filter2 - filter1 looks for a pattern and filter2 seeks range compression/expansion.

Let’s Search – And Away We Go

I will optimize across the different patterns and range analysis and different $ stops for each entry (1st and 2nd.)

Optimize across patterns and volatility and protective stops for 1st and 2nd entries.

Best Total Profit

Trade when today’s open is greater than yesterday’s close and don’t worry about the volatility.  Use $550 for the first entry and $600 for the second.

Best W:L Ratio and Respectable Avg. Trade

This curve was created  by waiting for yesterday’s close to be below the prior day’s and yesterday being an NR4 (narrow range 4).  And using a $500 protective stop for both the 1st and 2nd entries.

Did We Find the Holy Grail?  Gosh No!

This post served two purposes.  One, how to set up a framework for data mining and two, create code that can handle things that aren’t apparently obvious – entryPrice versus avgEntryPrice!

if filter1 and filter2 Then
begin
if time = calcTime(openTime,entryTime1Offset) then
buy("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset) then
buy("2nd buy") next bar at open;
end;

Incorporating Filter1 and Filter2 in the Entry Logic

>>By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/building-strategies/extend-data-mining-to-actual-trading-system/feed/ 0
Stepping into Algorithmic Trading: A Beginner’s Guide https://easylanguagemastery.com/learn-easylanguage/stepping-into-algorithmic-trading-a-beginners-guide/?utm_source=rss&utm_medium=rss&utm_campaign=stepping-into-algorithmic-trading-a-beginners-guide https://easylanguagemastery.com/learn-easylanguage/stepping-into-algorithmic-trading-a-beginners-guide/#respond Mon, 19 Jun 2023 10:01:49 +0000 https://easylanguagemastery.com/?p=532552

Discover the world of algorithmic trading. This comprehensive guide introduces EasyLanguage, explains the benefits and challenges of algo trading, and provides a practical example. Ideal for beginners.

Introduction

The world is changing. You can see that all around you. 

From augmented reality to trading, things are changing. Fading from our world are the days when trading involved waking up early, coffee in hand, and closely watching the ticker tape roll by. Today, we're stepping into the exciting and high-paced world of algorithmic trading, where machines, not people, make decisions.

In this article, our focus will be to unravel the complex threads of algorithmic trading, explore its advantages and contrast it with traditional, human-driven discretionary trading. While the topic may seem daunting, we'll make it as accessible as possible. We aim to strip away the intimidating jargon and replace it with relatable explanations, always maintaining the gravity of our subject matter. We will also provide a tangible example to illuminate further the concepts involved.

So, if you’ve been considering algorithmic trading but are unsure what it is, I invite you to join us on this enlightening journey into the cutting-edge world of algo trading. 

What is Algorithmic Trading?

Algo Trading Is Trading With Rules You Give To A Computer.

Algo Trading Is Trading With Rules You Give To A Computer.

Trading is a vast world with different approaches to deciding when to buy or sell. At the heart of it all, we find two methods:

  1. Discretionary trading
  2. Algorithmic trading

Discretionary Trading

Not long ago, most traders were into discretionary trading. Discretionary trading is the old-school style where human intuition, experience, and judgment call the shots. Discretionary traders analyze market conditions, trends, and other factors, then make decisions based on their analysis.

Discretionary trading is like your grandma's secret cooking style—no recipe needed. It’s all about intuition, expertise, and judgment. As a discretionary trader, you analyze market conditions, trends, and other vital factors and then decide based on your findings. It’s an art requiring a refined palette honed over time. And for many, the results can be as satisfying as a well-cooked meal.

With the advent of computer technology and the ability of more and more people to utilize that technology, computers began to be used in trading. First, they were used to draw price charts of the movement of stocks. The technical indicators, like moving averages, were plotted on those charts. Ultimately, these computers evolved to make trades by simply buying and selling programs running on these computers.

Thus, we now have algorithmic trading. 

Algorithmic Trading

Imagine you have a smart kitchen appliance that knows exactly when to add the right ingredients to make your meal perfect every time—that's algorithmic cooking! When it comes to trading, you have a set of pre-programmed instructions, the system analyzes market conditions and makes trades with mathematical precision, all without human intervention.

Algorithmic Trading always hinges on rules. Think of these rules. These rules explicitly tell you when to enter and exit a trade. These rules might seem arbitrary or even chaotic at times, but they are there, steering your trades even if you don't consciously acknowledge them.

Now, let's consider some instances.

  • You hear a TV pundit passionately advocating for a stock on CNBC. You jump in and make a purchase. Voila! There's a rule in action: "TV pundit advocates, I invest."
  • A YouTube video highlights an interesting setup on gold so you place your oder? Ther rule: "YouTube pundit advocates, I invest."
  • Or, perhaps you're utilizing technical indicators? "Sell short if the price exceeds a 20-period average and the RSI value dips below 20."

The beauty of trading is that it accommodates endless permutations of rules. However, in algo trading these these rules are systematically defined, rigidly followed, and immune to whims or personal biases, they pave the way for an algorithm.

What is an Algo?

So, what exactly is an 'algo'? It's simply a set of predetermined rules dictating when to buy, sell, enter, or exit. It can also incorporate guidelines for position sizing, handling bulk orders, risk management, and more. In essence, an algorithm is a well defined trading plan. This trading plan can be given to a computer to execute. The computer will follow this algorithm 100%. No changing the rules, moving the stop or exiting early. 

An algorithm or algo for short, is nothing but a set of instructions telling the computer all the rules needed to buy and sell. That's it. No room for gut feelings or personal judgement – it's all about consistency and precision.

An algorithmic trading strategy can be as simple or complex as you make it. Fancy a straightforward example? Here's a two-line strategy:

1. Go long when the two period RSI falls below 20.
2. Sell when the two period RSI rises above 50.

This is a simple algo that will buy and sell based upon the RSI indicator.

So, what's the secret sauce to successful algorithmic trading? It boils down to two vital ingredients:

1. Testability: Most algorithms can undergo historical testing, also known as backtesting. This provides a huge advantage, which I'll delve into later. This allows the trader to assess the strategy's viability before risking real money. Think how powerful that is! You can test your trading ideas to see if they will work or not before putting money on the line.

2. Consistency: Algorithms are like well-disciplined soldiers. They follow instructions to the letter, every single time. If an algo spots a long setup today, it'll prompt you to go long. If the same setup recurs tomorrow, it'll signal you to go long again. The algorithm doesn't care about market news, Federal Reserve sentiments, or even if Jim Cramer emphatically recommended a stock on his show - unless, of course, you've programmed it to consider such factors. The algorithm remains steadfast, consistently adhering to its rules."

Do I Need To Be A Computer Scientist To Algo Trade?

Contrary to what you might think, you don't need a computer science degree to get started with algorithmic trading. There are user-friendly trading platforms and coding languages designed for this purpose. For example, TradeStation's EasyLanguage is popular due to its simplicity and power. But it's not the only option out there—various platforms cater to different needs and skill levels.

The transition from discretionary to algorithmic trading has been a game-changer in the trading world. I remember the first time I heard about algo trading. It sounded like something out of a futuristic novel. Back when I was getting into trading, I made all the decisions on when to buy and sell. But today, all my active trading is done via computer. Having a computer execute my trades is as commonplace as using my smartphone. The fact that we have this type of technology on our desktops and trust machines to handle our money shows how far we've come.

But don't worry, this doesn't signal an imminent robot uprising. Instead, it shows us a new path to efficient and strategic trading.

Advantages of Algorithmic Trading

Algo Trading Has Many Advantages

Algo Trading Has Many Advantages

Now that we've introduced algorithmic trading, let's talk about what makes it great for active traders like you and me. 

Speed and Efficiency: In the trading world, a few seconds can make a massive difference. Humans bless our hearts, we just can't compete with computers regarding speed. Algorithmic trading systems can respond instantly to market changes and execute trades at the speed of light (well, maybe not literally, but you get the picture). This allows you to seize opportunities that would be impossible to catch manually.

Reduce Psychological Factors: Algorithmic trading helps eliminate those pesky emotional and psychological factors that come with trading. Let's face it, we humans can be a bit... emotional. We panic, we get greedy, we fear missing out. Thus, we have a difficult time sticking to our trading plan. In short, we make dumb mistakes that cost us dearly. But computers? They're as cool as a cucumber. An algorithm won't buy a stock just because it has a fear of missing out. It won't panic and sell everything at the first sign of trouble. It sticks to the plan, no matter what.

Backtest Strategies: Before you run your algorithm in real-time, you can test it with historical market data to see how it would have performed. Think of it as a 'time machine' that lets you see the results of your strategy without risking any actual money. Backtesting gives you confidence in your strategy and helps you refine it before letting it loose on the live market.

Always Ready: We've all had those days when we're just not feeling 100%. Maybe we're a bit under the weather, or perhaps the latest episode of our favorite show left us up all night in suspense. Either way, our trading decisions on those days might not be the best. But an algorithm? It doesn't have days off. It doesn't get tired, sick, or distracted. It consistently follows the trading plan, day in and day out.

Trade in Multiple Markets and Strategies: Now, I don't know about you, but I find it hard enough to keep track of my keys, let alone multiple markets at the same time. But for an algorithm, this is a walk in the park. It can monitor and trade numerous markets and assets concurrently, increasing your opportunities to profit. A computer can trade 20, 40, or even more charts at the same time. Can you do that? In a way, using a computer to trade so many different charts is a way to leverage your time, tallents, and opportunity.

So there you have it, the major advantages of algorithmic trading. But before you rush off to code your first trading algorithm, it's only fair we also talk about the downsides. After all, no system is perfect, and it's better to be aware of the potential pitfalls upfront."

Disadvantages of Algorithmic Trading

Algo Trading Is Not Perfect

Algo Trading Is Not Perfect

I've waxed lyrically about the wonders of algorithmic trading, but like anything in life, it's not without its challenges. I believe in giving you the full picture, so let's explore some disadvantages.

Learning Curve: You have to learn to code to be a good algorithmic trader. At least for now. This may not be easy for some. Spending months learning a programming language may not be fun for some, while others find it a fun and rewarding experience. You also have to become familiar with computers. Most people are, but you may have to dig deeper with backups, power supplies, routers, and other less common computer issues. 

Technical Difficulties and System Failures: Computers are fantastic tools, but they're not infallible. There could be bugs in your code, server issues, or internet connection problems. Imagine your algorithm going rogue right when you've stepped out for a lunch break! Because we’re not perfect, nor is technology, it’s crucial to monitor your systems and have a backup plan in place.

Over-optimization in Backtesting: Remember the backtesting feature I was so excited about earlier? Well, it has a dark side. It's possible to tweak your algorithm so much based on historical data that it becomes too perfect, too specialized. This might sound good, but it can make your strategy ineffective when new unforeseen market conditions arise. It's like training for a marathon by only running in perfect weather on a flat surface and then finding out the race day is stormy on hilly terrain. 

Lack of Adaptive Judgment for Market Changes: Algorithms follow a preset strategy and can lack the ability to adapt to sudden changes in the market. As smart as they are, they can't yet interpret news events, political changes, or sudden market shifts as a human might. For now, they still need us humans to tweak and adjust them in response to such changes. We also have tools at our disposal to help with that, but that’s a more advanced topic for a later day.

Remember, these downsides aren't there to scare you away from algo trading, but rather to prepare you. The key to successful algo trading is creating a sound strategy, backtesting extensively, monitoring your system, and being ready to adapt when necessary. It's like sailing - you need to prepare your ship, know your route, keep an eye on the weather, and always be ready to adjust your course as needed.

Algo Trading Does Not Eliminate Emotions From Trading

Algo Trading Does Not Remove All Emotions From Trading

Algo Trading Does Not Remove All Emotions From Trading

Algorithmic trading is often the perfect antidote to the emotional roller coaster that can come with manual trading. By letting pre-set rules dictate your trading decisions, you insulate yourself from the fear, greed, and other emotions that can cloud your judgment. But let's not get too ahead of ourselves. While algorithms help steer the ship steadily through the turbulent market waters, they don't wholly banish human emotion from the equation.

How is that possible? After all, an algorithm doesn't have feelings. It doesn't second-guess its decisions or suffer from a fear of missing out. However, while the algorithm is emotionless, the person behind it isn't. Even the most seasoned algorithmic traders can fall prey to emotional pitfalls.

Firstly, there's the creation and tweaking of the algorithm itself. It requires discipline and objectivity to follow a rigorous development process, to backtest your strategy adequately, and to resist the urge to over-optimize based on past performance. The temptation to tweak the algorithm when it's going through a losing streak can be powerful—an emotional response that could lead to poor decisions.

Then, there's the trust factor. It takes tremendous confidence to trust your algorithm, especially during those inevitable periods of drawdown. Even with a tested and proven algorithm, doubt can creep in when the going gets tough. This can lead to manually overriding the algorithm, usually at the wrong time, and often leading to regrettable outcomes.

Lastly, there's the element of fear. Fear of missing out on a 'sure-win' trade that doesn't fit the algorithm's rules or fear of loss when the algorithm is underperforming. These fears can prompt rash actions, like abandoning your algorithm for manual trades or prematurely shutting down the algorithm.

Remember, while algo trading reduces the influence of human emotion in trading decisions, it doesn't eliminate it entirely. The key to successful algorithmic trading is acknowledging these emotional challenges and developing strategies to manage them effectively. After all, even the best algorithms are only as good as the trader's ability to stick with them.

Algo Trading Is Not “Set And Forget”

If you're new to the world of algorithmic trading, it might be tempting to think of it as a "set it and forget it" operation. You might imagine turning on your algo Monday morning and walking away only to check your account balance at the end of the week. However, issues can come up. Successful algo trading requires an attentive eye and an understanding of the technical issues that may arise.

Algorithmic trading, while heavily automated, is not immune to technical glitches. Machines may not experience fear or greed, but they can and do experience downtime, bugs, and data errors. It's essential to actively monitor your trades to ensure your algorithm is functioning as expected and to troubleshoot any issues that might come up.

Here are some common technical challenges you might encounter in your algo trading journey:

1. Connection Interruptions: In the digital world, steady internet connection is a trader's lifeline. A brief interruption can lead to missed trades or, worse, leaving positions open that should have been closed. Some algo traders opt for Virtual Private Servers (VPS) to maintain a steady, reliable connection.

2. Platform or Software Bugs: Even the best trading platforms are not immune to the occasional software bug. These could lead to errant trades, inaccurate data, or sudden crashes.

3. Data Feed Errors: Algos depend on real-time data feeds to make their decisions. If there's a glitch in this feed, the algorithm could make trades based on faulty data.

4. Hardware Failures: Computers, like any piece of machinery, are subject to failure. A sudden crash could leave your algo in the lurch, which could be catastrophic if it happens at a crucial trading moment.

5. Algorithm Errors: Sometimes, the problem lies within the algorithm itself. A coding error or an unforeseen scenario could lead to unexpected trading behavior.

So, while the automation in algorithmic trading alleviates much of the manual workload, it's not a hands-off approach. Just as a ship's captain keeps an eye on the horizon even in calm waters, an algo trader must monitor their systems, ready to steer through any sudden storms that might arise. After all, the market never sleeps, and while your algo might run like clockwork, it's up to you to keep the gears well-oiled.

I often check my trading algos several times a day. The vast bulk of the time, everything is running fine. But it's exceptions you want to catch!

Backtesting - A Time Machine For The Markets!

Backtesting a strategy is like a Time Machine!

Backtesting a strategy is like a Time Machine!

Imagine if you could peer into the past, armed with the knowledge you have today. Think of the power it would give you—the ability to see how a particular decision might have played out, to learn from your past mistakes before you even make them. Sounds like a dream, right? Well, in algorithmic trading, it's not a dream but a reality. We call it 'backtesting'.

Backtesting is the process of testing your algorithm's rules against historical market data. It's akin to a simulation, placing you in the thick of past market scenarios and enabling you to observe how your strategy would have performed.

The advantages of backtesting are manifold, but here are a few that really make it shine:

1. Risk Assessment: Backtesting allows you to gauge the level of risk associated with your strategy. You can see the drawdowns, the losing streaks, and the volatility, helping you set appropriate risk parameters.

2. Performance Evaluation: It provides a quantitative measure of your strategy's performance. You can evaluate key metrics like the Sharpe ratio, the win rate, and the average profit per trade.

3. Strategy Refinement: Backtesting shines a light on the strengths and weaknesses of your strategy. This insight allows you to fine-tune your rules, improving your algorithm over time.

4. Confidence Building: Knowing your strategy has weathered the storms of past market scenarios can build confidence in its future performance.

Now, to effectively backtest, you need the right tools. And that's where TradeStation comes in. It's my platform of choice, and not just because it has an impressive array of tools for algorithmic trading. Its backtesting capabilities are exceptional.

TradeStation allows you to backtest using precise historical data across numerous markets and time frames. It also offers an impressive array of performance metrics and customizable reports that let you dive deep into your strategy's performance.

The platform also boasts an intuitive interface that's friendly to beginners, yet powerful enough for seasoned traders. And let's not forget about EasyLanguage, TradeStation's proprietary coding language, which makes algorithm design accessible even to those without extensive coding experience.

In short, backtesting is an incredible tool in an algo trader's arsenal, and with a platform like TradeStation, you can leverage it to its full potential. Just remember, while backtesting offers valuable insights, it's not a guarantee of future success. Use it as one of many tools in your toolbox to navigate the thrilling journey that is algorithmic trading.

A Real-world Example of Algorithmic Trading

Now, let's bring all of this to life with a practical example of algorithmic trading in action. For this, we'll use a simple RSI indicator applied to the E-mini S&P. 

1. Buy Signal: The RSI value falls below 20, our algorithm would automatically place a buy order.

2. Sell Signal: When the RSI value rises above 80, our algorithm would then automatically place a sell order.

3. Filter: We're also going to create a filter. We only want to trade when the market is win a bull market. We'll define a bull market when price is above the 200-day simple moving average. This filter will supersede the Buy and Sell signals. That is, if we're in a bear market, no trading will take place.

4. Stop Loss: We'll also place a stop order $3,500 below our entry price. This will help protect our capital of the markets move against us.

Below is what the EasyLanguage code looks like. Don't worry if you don't understand the code. The point is, it's not a lot of code.


input:
BuyThreshold(20),
SellThreshold(80),
RegimeLookback(200),
StopLoss$(3500);

variable:
Bullmarket(false);

If ( RegimeLookback > 0 ) then
   Bullmarket = Close > average( Close, RegimeLookback )
Else
   Bullmarket = true;

If RSI(close,2) < BuyThreshold and Bullmarket then
   buy next bar at market;
If RSI(close,2) > SellThreshold then
   sell next bar at market;

if ( StopLoss$ > 0 ) then
   Setstoploss( StopLoss$ );

This simple strategy applied to E-mini S&P produces these results, below. That's a $81,750 in profit. It's not super great but it's positive. You can see how a few simple rules can produce good results.

RSI(2) Strategy Example

RSI(2) Strategy Example

Remember, the devil is in the details. Fine-tuning your strategy, backtesting it thoroughly, and continuously monitoring it is where the real work (and fun) lies!

Why EasyLanguage?

EasyLanguage Is A Great Programming Language For Algo Traders!

EasyLanguage Is A Great Programming Language For Algo Traders!

Now, I know what you're thinking. 'Okay, Jeff, this all sounds great, but how do I actually start coding my trading algorithm?' That's where EasyLanguage comes in. It's a programming language developed by TradeStation specifically for designing trading strategies, and as its name suggests, it's... well, easy!

EasyLanguage was designed with traders in mind, not computer scientists. It uses simple, English-like syntax, making it more accessible for beginners than many other programming languages. Imagine being able to tell your computer to buy when the short moving average crosses above the long moving average, and it actually understands you. That's EasyLanguage for you!

What makes EasyLanguage stand out is its simplicity and focus on trading. It's specifically built for creating and testing trading strategies, so it has many built-in functions and features that cater directly to traders. This saves you time and effort as you don't need to code everything from scratch.

For new algo traders, EasyLanguage is a great tool because it allows you to focus on your trading strategy rather than getting lost in complicated programming syntax. But don't let its simplicity fool you. EasyLanguage is powerful and flexible enough to handle complex strategies and indicators. As you become more comfortable with it, it can accommodate the growth and evolution of your trading skills.

EasyLanguage is supported by a robust community of traders and developers who share code, answer questions, and provide resources. So, if you ever feel stuck or need inspiration, there's a whole community ready to lend a hand.

In short, EasyLanguage offers the perfect balance between simplicity for beginners and power for advanced users. It's like a trusty pocket knife - easy to handle, yet capable of getting the job done. So, if you're eager to dive into the world of algo trading, EasyLanguage is a fantastic place to start your journey.

Choosing Your Algo Trading Platform

When I first started looking into algo trading in 2009, TradeStation was about the only platform available. At least the only platform that could backtest and run algos I can remember. In short, it was King.Today you'll see a marketplace buzzing with various high-quality trading platforms. It's a competitive environment driving up standards and bringing better features and lower costs for the retail trader.However, navigating through these choices can feel overwhelming. Which platform is the best? Which offers the features you need? Which one simplifies the process of building algorithms? To help you cut through the noise, let's focus on some essential features that a platform should have for effective algo trading. Here's what you should look out for:1. Charting Capabilities: During the idea creation phase, it's crucial to visualize your concepts in action. A platform with advanced charting capabilities can make this much easier.2. Broker Integration: Platforms differ in their approach to broker integration. Some, like TradeStation, are linked directly to a specific brokerage, while others, like NinjaTrader or Multicharts, offer a wider selection. Consider the trade-off between convenience and options.3. Ease of Programming: An essential feature for algo traders is the ability to easily create custom indicators and strategies. A platform that offers an easy-to-learn programming language will be an asset in the long run.4. Market Data Integration: Ensure your chosen platform connects seamlessly with your required market data.5. Standard Indicators and Studies: Look for platforms offering a broad range of pre-programmed indicators and functions.6. Optimization and Walkforward Analysis: The platform should allow for optimizing your code's parameters and numbers. Additionally, the availability of walk-forward testing can generate more realistic "out-of-sample" results.7. Monte Carlo Testing: The platform should also have Monte Carlo testing to help you plan for possible future profits and drawdowns.

8. Trading Simulator The platform allow you to trade in simulation mode. This allows you to test your trading system on live market data without placing real orders.8. Trader Community: An active trading community can offer valuable insights and solutions. It's a significant plus when choosing a platform.9 Live Trading & Automation: The platform should cater to the entire process from development and testing to live trading and automation.TradeStation emerged as the clear favorite among my traders. Still, depending on your specific needs, any powerful platform might suffice. Here are the top contenders.

Top Choice:

TradeStation - TradeStation is a great platform. It's also my data provider and broker. And with its built-in programming language (EasyLanguage), it's the fastest platform to download and get up and running as an algo trader.

Other Great Platforms:

Remember, the perfect platform aligns with your trading goals and style, making your journey into algo trading as smooth and productive as possible.

Conclusion

And there we have it, folks! We've taken a deep dive into the world of algorithmic trading, compared it with discretionary trading, and explored the potential benefits and challenges of the algo approach. 

Remember, at its core, algorithmic trading is about consistency, speed, and emotionless execution. It's like a diligent worker bee, following your trading instructions to the letter, day in and day out. While it's not without its challenges - technical hiccups, the risk of over-optimization, and a learning curve - the potential advantages are certainly compelling. Faster trades, elimination of emotional decisions, and the ability to backtest are just a few perks that make algo trading appealing to many traders.

As we've discussed, getting started with algo trading doesn't have to be daunting, especially with the help of EasyLanguage. Its user-friendly syntax and robust trading-focused functionality make it a superb entry point for budding algo traders. And remember, there's a whole community out there ready to support you on your journey.

So, I encourage you to roll up your sleeves and delve deeper into algo trading and EasyLanguage. Start simple, take it one step at a time, and don't be afraid to get your hands dirty. The world of algorithmic trading is full of opportunities for those willing to learn.

Before I sign off, here's a fun fact for you to chew on: Did you know that as of my last check, more than 75% of trades on the US stock market are executed by algorithms? Now, isn't that food for thought?

Remember, trading, whether discretionary or algorithmic, is a journey, not a destination. So buckle up, enjoy the ride, and let's master EasyLanguage together!

Next Steps

In my opinion, if you want to become a successful algo trader, your first step is to learn a programming language. I recommend using TradeStation’s EasyLanguage. You can learn more by checking out these articles.

You can also find a lot of great EasyLanguage resournces on our Learn EasyLanguage page including, EasyLanguage Resource Page, EasyLanguage Quiz and Free Mini Course.

You can also have me teach you EasyLanguage by joining the Coder Edition of my System Development Master Class. That’s the fastest way to learn EasyLanguage. And time is money!

]]>
https://easylanguagemastery.com/learn-easylanguage/stepping-into-algorithmic-trading-a-beginners-guide/feed/ 0
EasyLanguage to Determine Week of Month https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/?utm_source=rss&utm_medium=rss&utm_campaign=easylanguage-to-determine-week-of-month https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/#respond Mon, 22 May 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532499

Week Of Month
I could be wrong, but I couldn’t find this functionality in EasyLanguage. I was testing a strategy that didn’t want to trade a specific week of the month. If it’s not built-in, then it must be created. I coded this functionality in Sheldon Knight’s Seasonality indicator but wanted to create a simplified universal version. I may have run into one little snag. Before discussing the snag, here is a Series function that returns my theoretical week of the month.

vars: weekCnt(0),cnt(0);
vars: newMonth(False),functionSeed(False);

if month(d) <> month(d[1]) Then
Begin
weekCnt = 1;
end;

if dayOfWeek(d)<dayOfWeek(d[1]) and month(d) = month(d[1]) Then
begin
weekCnt = weekCnt + 1;
end;
if weekCnt = 1 and dayofMonth(d) = 2 and dayOfWeek(D) = Sunday Then
print("Saturday was first day of month"," ",d);

WeekOfMonth = weekCnt;

Series Function to Return Week Rank


This function is of type Series because it has to remember the prior output of the function call – weekCnt.  This function is simple as it will not provide the week count accurately (at the very beginning of a test) until a new month is encountered in your data.  It needs a ramp up (at least 30 days of daily or intraday data) to get to that new month.  I could have used a while loop the first time the function was called and worked my way back in time to the beginning of the month and along the way calculate the week of the month.  I decided against that, because if you are using tick data then that would be a bunch of loops and TradeStation can get caught in an infinite loop very easily.

This code is rather straightforward.  If the today’s month is not equal to yesterday’s month, then weekCnt is set to one.  Makes sense, right.  The first day of the month should be the first week of the month.  I then compare the day of week of today against the day of week of yesterday.  If today’s day of week is less than the prior day’s day of week, then it must be a Sunday (futures markets open Sunday night to start the week) or Monday (Sunday = 0 and Monday = 1 and Friday = 5.)  If this occurs and today’s month is the same as yesterday’s month, weekCnt is incremented.  Why did I check for the month?  What if the first trading day was a Sunday or Monday?  Without the month comparison I would immediately increment weekCnt and that would be wrong.  That is all there is to it?  Or is it?  Notice I put some debug code in the function code.

Is There a Snag?

April 2023 started the month on Saturday which is the last day of the week, but it falls in the first week of the month.  The sun rises on Sunday and it falls in the second week of the month.  If you think about my code, this is the first trading day of the month for futures:

month(April 2nd) = April or 4

month(March 31st) = March or 3

They do not equal so weekCnt is set to 1.  The first trading day of the month is Sunday or DOW=0 and the prior trading day is Friday or DOW=5.  WeekCnt is NOT incremented because month(D) doesn’t equal month(D[1]).  Should WeekCnt be incremented?  On a calendar basis it should, but on a trading calendar maybe not.  If you are searching for the first occurrence of a certain day of week, then my code will work for you.  On April 2nd, 2023, it is the second week of the month, but it is the first Sunday of April.

Thoughts???  Here are a couple of screenshots of interest.

Indicator in Histogram form representing the Week of Month

Some months are spread across SIX weeks.

This function is an example of where we let the data tell us what to do.  I am sure there is calendar functions, in other languages, that can extract information from just the date.  However, I like to extract from what is actually going to be traded.

Email me if you have any questions, concerns, criticism, or a better mouse trap.

>> By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/feed/ 0
Bull Flag on futures markets? https://easylanguagemastery.com/indicators/bull-flag-on-futures-markets/?utm_source=rss&utm_medium=rss&utm_campaign=bull-flag-on-futures-markets https://easylanguagemastery.com/indicators/bull-flag-on-futures-markets/#comments Mon, 08 May 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532389

Recently someone asked on an Easylanguage forum if anyone had coded a Bull flag / Bear flag pattern recognition to use on a futures index strategy. I realized that I did not know the pattern, so I went and looked for it.

Bull flag pattern

A bull flag is a technical chart pattern that is often used by traders to identify potential bullish market movements. The pattern is characterized by a strong upward move, followed by a period of consolidation, or “flag,” that is usually parallel to the trendline of the initial move.

The bull flag pattern is considered a continuation pattern, as it indicates that the current bullish trend will likely continue after the consolidation period. This can be a valuable signal for traders looking to enter long positions or add to existing ones.

The pattern typically forms after a strong upward move, which is known as the “flagpole.” This initial move can be caused by a number of factors, such as positive earnings reports, strong economic data, or other market-moving news. During the consolidation period, the price of the security will generally move sideways, forming a “flag” shape on the chart.

Traders typically look for a breakout above the resistance level of the flag to confirm the continuation of the bullish trend. Additionally, traders may use a stop-loss order below the support level of the flag to protect their position in case the trend does not continue.

Bull flag in quantitative trading

We can get as fancy as we want with Easylenguage, but I wanted to take a straightforward approach:

Flagpole: Two simple moving average (SMA).

  • Bullish flagpole SMA based on the low price, and current SMA bigger than the previous two SMA´s.
  • Bearish flagpole SMA based on the high price, and current SMA lover then the previous two SMA´s.

Breakout: RSI2 that breaks over limit on the direction on the trend.

Exits: Stop loss and profit target.

Long and Shorts: The ability to test only long, only short or both.  

Charting Software: Tradestation 10.0

Code development: Easylenguage 10

Research platform: https://tradesq.net/

Bull Flag on futures markets? –Easylanguage code

Let’s see how it works on a chart:

Long entries on Bull flag on a @CL 1440m chart

Short entries on bear flag on a @CL 1440m chart

Its not perfect “flag” shape, but the concept of entering after the breakout of the retracement works pretty well.

Now that we have the code and the strategy let’s see if it would work in future markets. For the study, Tradesq will test it for us on 43 Future markets and 11 timeframes in a matter of hours. Can you imagine how much time would take to perform the test manually?

Results

We have many edges on currencies, energies, grains, Indexes, and interest sectors.

Results filtered by (NP/DD>4, Number of trades above 200)

Let’s have a look at Some results from every sector.

30Yr Bonds(@US) 240min

Heating Oil(@HO) 360min

British Pound(@BP) 240min

Spring Wheat(@MW) 360min

Nasdaq(@NQ) 30min

Note: All results include trading costs, Slippage and Commission.

Conclusion

I don’t know if the code developed will resolve the poster question on the Bull Bear Flag pattern, but certainly did find really good edges.

The study was intended to show how we can start from a simple idea and use tools like Tradesq and Easylanguage / Powerlanguage to build strategies. As a result, we found firm edges through five (5) different future market sectors. 

It does not mean this are strategies ready to trade, additional filters and robustness tests must be applied, but is a terrific starting point.

>>By Juan Fernando Gómez From blog.tradesq.net  Email: jgomezv2@jgomezv2

]]>
https://easylanguagemastery.com/indicators/bull-flag-on-futures-markets/feed/ 5
Understanding the Relationship Between Stocks & Bonds https://easylanguagemastery.com/indicators/understanding-relationship-stocks-bonds/?utm_source=rss&utm_medium=rss&utm_campaign=understanding-relationship-stocks-bonds https://easylanguagemastery.com/indicators/understanding-relationship-stocks-bonds/#comments Mon, 24 Apr 2023 10:00:50 +0000 http://systemtradersuccess.com/?p=6825

Intermarket Analysis is the comparison of potentially related markets. For example:

  • S&P500 and 30 Year Treasury Bonds
  • 30 Year Treasury Bonds and Gold
  • S&P500 and Japanese Yen
  • Shanghai Composite Index and Aussie Dollar, etc.

The problem with using TradeStation for any Intermarket Analysis is the dreaded “You may not mix symbols with different delays in the same window” error code. That’s exactly what you’ll get if you try to add 30 Year Treasury Bond Futures (symbol US) to an Emini chart (symbol ES). The problem arises because the data comes from two different exchanges – CBOT for Bonds and CME for the Emini. TradeStation says:

Using ETFs for Intermarket Analysis

Tradestation limitation TradeStation does not allow you to plot two symbols in the same chart window when the amount of delay for the data is different. For example, one is delayed and one is real-time, or both are delayed but the exchanges providing the symbols’ data delay by different amounts of time. Otherwise, during the market session, you would see last prices on the current bar that are asynchronous (i.e. not simultaneous).
There are various ways around the problem – most of them quite complex and involving exchanging data between charts. However, I have found an easier solution. Read on for some tricks of the trade and useful equities vs. bonds indicators.

The solution to the problem is to find market symbols from the same exchange. With the explosion in the number of Exchange Traded Funds (ETFs) it is usually possible to find ones that track the underlying markets you are interested in.

For the Emini the obvious choice is the SPDR (symbol SPY) ETF traded on the AMEX exchange. For the Bond market the best choice is the iShares Lehman 20+ Year Treasury Bond ETF (symbol TLT), also traded on the AMEX exchange.

In the left panel of the chart above, daily data for the SPY and TLT symbols have been plotted quite happily on the same chart. However, in the right panel you get the dreaded “mix symbols” error code when plotting the ES and US symbols.

Are the Emini and Bond Markets Correlated?

The answer is sometimes yes and sometimes no. Correlation between the two markets can go as high as +60% (correlated) or a low as -60% (negatively correlated). You can add the in-built TradeStation correlation indicator on a chart of SPY and TLT to see this for yourself.

There are 2 opposing factors that drive the Bond and Stock markets at different times:

  • Interest rates might be falling and causing Bond prices to rise. The stock market might view the lower interest rates as encouraging for the economy and respond with higher stock prices. Alternatively, rising interest rates will cause Bond prices to fall and the stock market might view the tightening as negative for the economy and stock prices. In these cases correlation between the two markets is positive as they are moving in sync.
  • Stocks and Bonds are also alternative investment vehicles. If the stock market is rising strongly it might encourage Bond investors to cash out and put their money in the stock market and thereby cause Bond prices to fall. Alternatively, if there is a stock market panic investors might rush for the safety of Bonds and push Bond prices up. In these cases the two markets are negatively correlated as they are moving in opposite directions.

Measuring Differences Between the Emini and Bond Markets

With SPY and TLT plotted on the same chart we can compare price movements. A popular oscillator is shown in the screen grab above. In this case a ratio of SPY and TLT is calculated and this value is compared to a moving average of the ratio.

I prefer to use another measure of relative price movement. The screen grab below shows TradeStation EasyLanguage code for my Bond Oscillator. Instead of using the ratio of SPY and TLT prices it calculates the difference in percentage movement. This indicator is more like a momentum indicator.

The two indicators are comparead below. The Bond Oscillator (momentum type) is shown above and the Spread Oscillator (moving average type) is shown below. As you can see, the Bond Oscillator generates more defined turning points and is easier to trade.

The chart below shows the Bond Oscillator added to a 3 year chart of daily SPY prices. Spikes (up and down) in the oscillator show periods when the SPY is over or under-valued against Bonds. These periods can persist for some time – more so on the upside than the downside. To illustrate this a PaintBar has been added to highlight periods when the Bond Oscillator is above +5 (shown as white bars) and below -5 (shown as red bars).

Rather than use extreme readings on the Bond Oscillator to enter trades, it is safer to wait until the Oscillator crosses the zero line after an extreme reading. This prevents entering the trades too early.

Another trick I have found using this indicator is to wait for an extreme Oscillator reading and then look for a large daily move in the opposite direction in the Bond market. For example, Bonds are in a down trend, the Bond Oscillator goes above +5 and then Bonds have a one-day large up move. This pattern is signaling that professionals are taking profits at stock market highs and reaching for the safety of Bonds, hence driving Bond prices higher.

TradeStation EasyLanguage code for the PaintBar is shown in the screen grab below.

Bond Market Turning Points and the Emini

The last series of Bond Intermarket indicators are designed to highlight market turning points. I have found that there is a tendency for the Emini to lag the Bond market by approximately 20 days. To illustrate this point check out the chart below.

The SPY (Emini equivalent) is shown in the top of the chart and below it is TLT (Bond market equivalent) with closing prices shifted by 20 days. The red vertical lines show how turning points in the two markets (one delayed by 20 days) often line up. The neat thing about this analysis is that the Bond market turning points are known well in advance.

As an aside, this 20 day delay is also the reason I use 20 days as the look back period in the previous two indicators, Spread Oscillator and Bond Oscillator.

The chart below shows the state of the current Bond market (mid April 2007). A vertical line has been added showing where prices were 20 days ago. As you can see, since then the Bond market has declined steeply. If the 20 day relationship holds we may well see another turning point in the stock market. Only time will tell.

If you’re interested in following turning points in the Bond market you can use the indicator below to plot these vertical lines. The indicator allows multiple vertical lines of different frequencies to be plotted. Just vary the inputs NumLines (number of vertical lines) and Period (20 days, etc.). Make sure there’s enough back history in the chart to plot the lines though – if you ask for two 200 day lines and only have 300 days of history on the chart, the indicator won’t work!

I hope this article on Intermarket Analysis and equities versus bonds was helpful to you. You can download the indicator code used in this analysis.

— By Barry Taylor from Emini Watch

]]>
https://easylanguagemastery.com/indicators/understanding-relationship-stocks-bonds/feed/ 1