In TradeStation, most of the lumber history is represented by the custom continuous @LB_11INC symbol (note – you must make sure you plot enough history to surpass the April 2023 date to see any data.) The new contract is @LBR=11INC symbol. If you want to test both contracts and get realistic results, then you need the following “BRIDGE” function and strategy.
What changed: the April 2025 introduction of a Southern Yellow Pine futures contract alongside the existing lumber contract, theoretically gave the market a targeted, species‑specific price standard for the most widely used U.S. framing timber. During the pandemic the price of lumber went parabolic.
The new lumber contract is one\-quarter the size of the original contract. CME believed the smaller contract would be more accessible to traders, which in turn would improve liquidity and have a positive impact on both slippage and price volatility. While the results have been encouraging, the history of the new contract is still relatively short.
Because of this limited sample size, it makes sense to combine the old and new contracts using my “Lumber Bridge” methodology when conducting long-term backtesting. This provides a much broader historical perspective while maintaining continuity across the contract transition.
For traders building a portfolio of non\-correlated markets, lumber may be worth considering. Its unique supply\-and\-demand drivers can provide diversification benefits that are difficult to find in more traditional financial and commodity markets.
If you plot @LB=11INC going back a few years you and apply a system that has an open position at the end of the data you will get either an unrealistic profit or loss.
And if you just want to look at the newer contract you will get this in the early stages of the new contract.
If you are including lumber in your portfolio, you can use the following code to stop trading the old lumber LB=11INC and start trading the LBR=11INC on appropriate dates. I determined you should get out of LB=11INC at the open of 4/25/2023 and wait for a new signal on or after 4/25/2023 in LBR=11INC.
I exit on the open of 4/25/2023 in the old contract and start trading the new contract on the same date.
Here is a combined equity curve where there is no overlap.
LumberStrategy Code:
if symbol = "@LB=11INC" and date = 1230424 Then Begin if marketPosition = 1 then sell("OldLumber:lx") next bar at open; if marketPosition = -1 then buyToCover("OldLumber:sx") next bar at open; end;
A simple signal to get you out of the old contract
LumberBridge Function
LumberBridge = False; if symbol = "@LB=11INC" and date < 1230424 Then LumberBridge = True else if symbol = "@LBR=11INC" and date >= 1230421 Then LumberBridge = True; if symbol <> "@LB=11INC" and symbol <> "@LBR=11INC" Then LumberBridge = True;
If you will be testing lumber use this funciton
Incorporate the following code into your logic if testing lumber
includeSystem: "lumberBridgeStrategy";
if lumberBridge Then begin
buy("le:Turt20") next bar at highest(h,20) + minMove/priceScale stop; sellShort("se:Turt20") next bar at lowest(l,20) - minMove/priceScale stop; end; if marketPosition = 1 then sell("lx:Turt10") next bar at lowest(low,10) stop; if marketPosition =-1 then buyToCover("sx:Turt10") next bar at highest(high,10) stop;
Use this code to properly bridge the lumber contracts
Why do all this work
This tool is absolutely necessary when working with portfolio-based trend following systems. The lumber futures contract has demonstrated a high level of non-correlation against most other futures for years. It is a unique market.
AI can write structure, but experienced programmers still supply the craft
The more we rely on generated code, the more disciplined we must become in questioning it.
AI and modern frameworks now provide valuable insights that, just a few years ago, would have required significant time and effort to obtain. However, while they offer tremendous macro-level leverage, they can also introduce subtle assumptions that lead to impossible scenarios and misleading downstream analysis. This is especially true in environments designed for rapid idea testing, where convenience can come at the expense of deeper, microscopic introspection.
For example, in my PatternSmasher framework, I use constructs like BarsSinceEntry to control trade duration and evaluate pattern efficacy. This makes it very easy to test thousands of ideas quickly. But that convenience comes with a responsibility. If you rely on these abstractions without thinking through the details, you can end up with behavior that looks perfectly valid in code but could never occur in the real world.
I have seen this problem in other frameworks and in AI-generated code as well. This is why it is so important to continue to hone your craft and take a deep dive into the results produced by generated code. In the quant world, the first step is to study the trades and isolate problems such as what I call simultaneous same-direction exit and reentry. Once you see it, the job is to fix it without changing the intent of the algorithm.
Let me show you exactly what I mean. The logic behind this example looks perfectly fine on the surface. But when you dig into the trades, you see the problem immediately. In this chart, the system exits a long position and then turns right around and buys again at the same time and price. That is not a reversal. It is a same direction exit and reentry that simply cannot happen in the real world, and it pollutes the back test with trades that should not exist.
Example of simultaneous same-direction exit and reentry at the same time and price—an impossible trade sequence that distorts backtest results – 640 minute bar on Gold – why 640?
We entered a long position, the trade expired, immediately re-entered on the next setup, that trade expired as well, and then entered again—only to get stopped out. That’s three round turns, each incurring commission and slippage.
// Simple code that is of course mean reversion. // However, since we seem to be in this regime // let's hone our craft to make this work as intended.
if value1 = consCloses and close > average(c,movAvgLen) then buy ("lentry") next bar at open; if value2 = consCloses and close < average(c,movAvgLen) then sellShort ("sentry") next bar at open;
if barsSinceEntry > exitAfterNBars then Begin sell("lx-exp") next bar at open; buyToCover("sx-exp") next bar at open; end; setStopLoss(stopLoss);
Simple entry with expiration exit
The code that produced this looks pretty clean. You have your entry logic, a BarsSinceEntry exit, and a stop loss. On the surface, everything seems fine.
But you don’t find this kind of problem by staring at the code. You find it by looking at the trades. This is the one thing AI or a framework doesn’t examine. At first, the natural reaction is to slap a MarketPosition “gate” on the entry logic. The word “gate” may be a dead giveaway that AI has influenced the discussion. But I like it. It has been around since the early days of electrical circuits, and it is very appropriate here. I’ve noticed that many of the words AI uses have started to creep into my own vocabulary. Funny how that happens.
if marketPosition <> 1 and value1 = consCloses and close > average(c,movAvgLen) then buy ("lentry") next bar at open;
if marketPosition <> -1 and value2 = consCloses and close < average(c,movAvgLen) then sellShort ("sentry") next bar at open;
if barsSinceEntry > exitAfterNBars then Begin sell("lx-exp") next bar at open; buyToCover("sx-exp") next bar at open; end; setStopLoss(stopLoss);
Fix #1 - solves the simultaneous exit and re-entry same direction glitch
So what does that MarketPosition “gate” actually do?
It fixes the symptom. The same-bar exit and reentry disappears, and the trades look cleaner.
But it also changes the algorithm in a much deeper way.
In the original design, a new long signal while already long reaffirmed the position and should have kept the trade alive. The gate removes that behavior. Now the strategy must exit first and then wait until the next bar to reenter.
And that delay matters.
By the time the next bar arrives, the setup may be gone. What should have been one continuous trade is now split into pieces—or missed entirely.
You didn’t just clean up the trades. You changed which trades exist. The new strategy more or may not be more efficient, but just know the algorithm is now different.
Fix #2
We bought, suppressed the expiration exit due to a new buy setup—twice—and were ultimately stopped out at the level where the stop loss from the final trade that didn’t occur—but whose properties we were monitoring—would have been triggered.
Could most quants who aren’t programmers solve this riddle? Probably not. My 40 years of programming experience certainly played a role, and my familiarity with EasyLanguage—especially its limitations—helped guide me down the right path. But more importantly, I was able to recognize the nature of the problem, apply targeted fixes, and then analyze the resulting trades. I repeated this process—wash, rinse, repeat—until the issue was resolved.
Much of the knowledge I relied on has been documented by myself and others over the years. Investing time in books, videos, and webcasts specific to your programming language remains essential—it forms the foundation. But ultimately, refining your own skills and developing your craft is a time-consuming process that pays lasting dividends.
Groundwork for the Fix
Solving what initially appears to be a simple riddle requires recognizing several underlying behaviors. I was able to correct the issue because I could anticipate when a new trade was about to occur. When both the exit gate for an existing position and the entry gate for a new position in the same direction were simultaneously open, I prevented the transition by closing both gates.
However, simply blocking the transition was not enough. I had to simulate the trade that would have occurred. This meant marking the hypothetical entry price, resetting the stop-loss based on that price, and reinitializing my own bars-in-trade counter.
At this point, I could no longer rely on EasyLanguage’s built-in functions such as BarsSinceEntry or SetStopLoss. Those functions assume an actual executed trade and therefore could not reflect the internal state I needed to maintain. To solve the problem correctly, I had to take full control of trade state management and explicitly track these values myself.
canGoLong = countIF(c < c[1],consCloses) = consCloses and close > average(c,movAvgLen) ; canGoShort = countIF(c > c[1],consCloses) = consCloses and close < average(c,movAvgLen);
mp = marketPosition;
//Exit Technology
closedTrades = totalTrades; //long exit on bar after entry if mp[1] <> mp and mp = 1 or (closedTrades > closedTrades[1]) Then begin barsInTrade = 0; lStopLevel = open[0] - stopLoss/bigPointValue ; end;
//short exit on bar after entry if mp[1] <> mp and mp = -1 or (closedTrades > closedTrades[1]) Then begin barsInTrade = 0; sStopLevel = open[0] + stopLoss/bigPointValue ; end;
//long reentry stop reset if mp = 1 and canGoLong and barsInTrade > exitAfterNBars Then begin lStopLevel = open of tomorrow - stopLoss/bigPointValue ; // print(d," ",t," should exit and renter long tomorrow ",barsInTrade," ",barsSinceEntry," ",open of tomorrow); barsInTrade = -1; end;
//short reentry stop reset if mp = -1 and canGoShort and barsInTrade > exitAfterNBars Then begin sStopLevel = open of tomorrow + stopLoss/bigPointValue ; // print(d," ",t," should exit and renter short tomrorrow ",barsInTrade," ",barsSinceEntry," ",open of tomorrow); barsInTrade = -1; end;
if mp = 1 then sell("lx-stopLoss") next bar at lStopLevel stop;
if mp = -1 then buyToCover("sx-stopLoss") next bar at sStopLevel stop;
//Entry Logic if canGoLong then buy ("lentry") next bar at open; if canGoShort then sellShort ("sentry") next bar at open;
//Bars in trade expiration exit if barsInTrade > exitAfterNBars then Begin sell("lx-exp") next bar at open; buyToCover("sx-exp") next bar at open; end;
//Day of entry protection setStopLoss(stopLoss); //Increment barsInTrade - mimic TradeStation here too! if mp <> 0 then barsInTrade = barsInTrade + 1;
Fix #2 - difficult initially but reusable
This version fixes the problem by taking control of the trade state instead of relying on EasyLanguage’s built-in functions.
First, I define whether I can go long or short, independent of my current position. Then I track my own state variables—market position, bars in trade, stop levels, and trade count—so I know exactly what the system is doing at all times.
The key occurs when a same-direction signal appears after the trade has technically expired. Instead of allowing an exit and immediate reentry, I suppress both actions and simulate the renewed trade. I mark the hypothetical entry price, reset the stop based on that level, and restart my bars-in-trade counter.
Because of this, I can no longer rely on BarsSinceEntry or SetStopLoss—they depend on actual trades. I manage everything explicitly.
The result is a continuous position that preserves the original intent of the algorithm without introducing impossible trades into the backtest.
EasyLanguage also has its share of esoteric nuances. Code order can matter in some places and not in others, particularly with order execution. Even detecting position changes requires a bit of finesse. These details matter, but they are beyond the scope of this discussion.
This is where the difference between generated code and engineered code becomes clear.
A programmer who is not willing to put in the work—and instead relies on AI to solve the problem—will likely stop at the first acceptable fix. The code will run, the trades will look cleaner, and the issue will appear resolved. But the deeper problem remains: the structure has changed, trades may be missing, and the original intent of the algorithm has been compromised.
As we become more dependent on code generation through AI and frameworks, it becomes even more important to validate that the output is reasonable and reflects something that could occur in the real world. That responsibility does not go away—it increases. And it requires us to continue honing our craft.
AI can generate code and even suggest reasonable fixes, but it does not truly understand the nuances of the language, the sequencing of events, or the intent behind the strategy. It cannot look at a trade and say, “that shouldn’t have happened.” It does not debug by questioning reality—it follows patterns.
Arriving at the correct solution required recognizing the problem, iterating through possible fixes, examining the trades, and refining the logic until the behavior matched the intent. That process—wash, rinse, repeat—is the craft.
Generated code can get you started. Engineered code is what gets you to the truth. Take a look at the two following reports. Similar results, but look at the number of trades and those statistics tied to this number.
From Raw Wavelet Code to a Trading Tool with More Knobs Than Anyone Was Turning
The Indicator I Thought I Understood
A client sent me a trading indicator they had just started using. It was short. Clean. About a page of code.
I’m not entirely sure where it originated, but it had the unmistakable feel of something machine-generated — technically sound, compact, and largely undocumented.
Their usage was simple:
Plot one line
Look at its slope compared to one bar ago
Go long or short accordingly
{--------------------------------------------------------- Causal True ? trous Wavelet Indicator ---------------------------------------------------------} Inputs: UseD1(true), UseD2(false), UseD3(false), UseD4(false), UseD5(false), UseD6(false), ColorBarsByTrend(true), InvertTrendColorMap(false), // optional flip if colors look reversed TrendColor(green), // used only if ColorBarsByTrend = false DenoisedColor(white), ResidualColor(red); Vars: Price(0), c0(3.0/8.0), c1(1.0/4.0), c2(1.0/16.0),
They were using a single configuration — effectively listening to just one component of the indicator: Trend. And to be fair, it mostly worked. The trouble only appeared when the Residual (what ever that is) was plotted alongside it. Because it lived on a very different scale, it crushed the display and made the indicator look unusable. See the section at the bottom of this post for how to fix that. Other than that, nothing was actually “broken.”
That behavior was also an early clue that the code itself was likely AI-generated. If you’ve worked with John Ehlers–style indicators, you may recognize the fingerprints of Digital Signal Processing here: fixed coefficients, repeated smoothing, and the output of one calculation feeding directly into the next in a cascading fashion. Those are classic DSP techniques — powerful, but easy to mislabel or oversimplify when dropped directly into a trading context.
In hindsight, the breadcrumbs were right in the header: wavelet and à trous. Even if you’ve never heard those terms, you can paste them into an AI chat and ask, “What does this mean?” That won’t instantly tell you how to trade it — but it will give you the vocabulary and the map so you’re not reverse-engineering in the dark. From there, the real work becomes translating the math into something a trader can actually see and use.
What is a wavelet à trous?
A wavelet à trous (“with holes”) method is a signal-processing technique that breaks a data series into multiple layers, each representing a different time scale. It does this by repeatedly smoothing the data while spacing the filter farther apart at each step, without downsampling the signal.
The result is a set of detail layers (short-term to long-term) plus a final smooth baseline. By recombining selected layers, you can emphasize noise, structure, or long-term movement — depending on what you want to study.
In other words, you define the underlying structure of the market and then decompose that structure into layers of different frequencies. If you want to emphasize noise, you limit the smoothing. If you want to emphasize trend, you add more layers. Many indicators require you to constantly adjust lookback lengths to achieve smoother results, but this approach—much like an audio equalizer—only requires adding or removing layers. That alone is an extremely nice feature.
What caught my attention wasn’t that the indicator failed—it was that the code itself clearly had more depth than how it was being used. There were multiple inputs, multiple layers, and multiple outputs, yet only a single switch was being flipped. That mismatch—between the richness of the code and the simplicity of its use—is what made me start pulling on the thread.
I Knew What the Code Was Doing — But Not What It Was
I understood the mechanics. Repeated smoothing. Differences between layers. A clean reconstruction.
But the script was labeled with terms like wavelet and à trous — language most traders (myself included) don’t use day-to-day. The variable names didn’t help either. Everything technically worked, but nothing explained itself.
This wasn’t an exotic math problem. It was a communication problem.
So I did what most of us do now when we want clarity: I brought AI into the conversation.
Using AI to Understand — Not to Predict
This is important.
I didn’t ask AI to:
optimize anything
generate a strategy
predict markets
I asked it questions I’d normally ask another developer:
What is this code actually doing conceptually?
Why does the reconstruction work so cleanly?
What is changing when different layers are included or excluded?
The first pass gave me structure. The second pass gave me language. The third pass gave me something unexpected: metaphors.
Not all of them worked.
When the Right Metaphor Finally Clicked
AI proposed several ways to think about the indicator — mechanical, mathematical, spatial. Some were accurate, but none quite matched how traders experience charts.
Then we circled around sound.
Filtering. Layers. Mixing.
That’s when it clicked.
This indicator wasn’t a “trend line.” It was an equalizer.
Once I framed it that way, everything snapped into place:
The slowest layer wasn’t “trend” — it was the bass line
Faster layers weren’t noise — they were texture and rhythm
Turning components on and off wasn’t optimization — it was listening choice
The metaphor wasn’t decorative. It became a tool.
From Cryptic Code to Wavelet Analog
With that framing, I cleaned up the code:
Renamed variables so they described what they felt like, not how they were computed
Grouped logic around intention, not math
Made the behavior readable on a chart
What emerged from this process was Wavelet Analog — an indicator that separates price into layers and lets the trader decide which ones to listen to.
So why describe it as analog?
When I first saw six True/False toggles as inputs, my refactoring instincts immediately kicked in. Why six switches? Why not a single input that lets the user pick a number from one to six and choose a single layer? After all, that’s how we usually simplify interfaces. And that’s exactly how my client was using it — with only UseD1 enabled.
That kind of refactor is clean. It’s digital. It reduces complexity.
But it also misses the big picture.
The original design wasn’t meant to select one layer — it was meant to let the user combine layers. One switch, or several. Fine detail alone, coarse structure alone, or anything in between. Layers could be stacked, blended, and cascaded.
That’s where the analog idea comes in. Instead of choosing a single, precise value—a digital decision—the original script let the trader feather the signal. Think of it like adjusting bands on an audio equalizer: you’re not flipping one switch on and everything else off; you’re shaping the mix.
Once I saw it that way, the six toggles stopped looking awkward and started looking intentional. Intentional—but also redundant. Imagine having to flip six separate switches on or off, in various combinations, all while keeping in mind that you may want to optimize how those layers interact. You could encode the toggles as 0s and 1s—false and true—and that would indeed open the door to optimization. It works, but it’s still clunky. Zeros and ones everywhere.
That naturally raises the question: can this be reduced to a simple binary pattern? If you’re familiar with my Pattern Smasher work, you already know the answer is yes—binary representations are compact, expressive, and highly optimizable. It’s an excellent approach. The downside is that it requires the user (and any downstream logic) to understand base-2 numbering, which isn’t a reasonable expectation for most traders.
So instead, we sidestep the binary scaffolding while keeping its power by leaning on EasyLanguage’s string-handling capabilities. Rather than six individual toggles, we represent them as a single string of six characters, each a 0 or 1. For example:
“110000”
This string simply means UseD1 and UseD2 are active. You don’t need to know—or care—what the decimal value of “110000” is. A 1 turns on the corresponding UseDX; a 0 turns it off. When more than one 1 appears in the string, the layers are cascaded automatically.
Same analog flexibility. Cleaner interface. Far less friction.
Parsing a string with one simple function: MidStr
Having a nice library of string manipulation functions enforces my prior post on why Quant languages should use the EasyLanguage model. I can easily extract the character at each location located in the string. The first location is represented by one and the last by six.
if MidStr(Switchboard, 1, 1) = "1" then MasterOut = MasterOut Band1_Hiss; if MidStr(Switchboard, 2, 1) = "1" then MasterOut = MasterOut Band2_Treble; if MidStr(Switchboard, 3, 1) = "1" then MasterOut = MasterOut Band3_Presence; if MidStr(Switchboard, 4, 1) = "1" then MasterOut = MasterOut Band4_Mids; if MidStr(Switchboard, 5, 1) = "1" then MasterOut = MasterOut Band5_Body; if MidStr(Switchboard, 6, 1) = "1" then MasterOut = MasterOut Band6_Bass;
Using MidString to parse a String
Here the string is represented by Switchboard and is decomposed by the MidStr function. This function expects two arguments – starting postion and the number of characters to gather. As you can see by the code, we are stepping through each character in the string and extracting that particular character. Based on its value, we integrate that particular layer into the final calculation.
Same math. Same structure. Completely different understanding.
One Indicator, Multiple Trading Tempos
Here’s where the iceberg metaphor really matters.
The client had been trading the tip:
One layer
One tempo
One interpretation
But underneath that single line were multiple valid ways to trade:
Scalpers listening to fast detail
Swing traders listening to rhythm and rotation
Trend followers locking onto structure
Nothing was added. Nothing was optimized. We just stopped pretending the indicator was simpler than it really was.
The Real Lesson (and Why AI Matters Here)
AI didn’t invent anything in this process.
What it did was help surface alternative ways of thinking — some useful, some not — until the right framing emerged. The insight came from the interaction, not the output.
That’s the part of AI that excites me most for traders.
Not as a signal generator. Not as a replacement for thinking.
But as a tool for understanding what we already have.
Closing Thought and Nex Steps
Most traders inherit indicators they never fully unpack. They trade what’s visible and ignore what’s underneath.
Sometimes, the most valuable work isn’t finding something new — it’s learning how to see what’s already there.
That’s what this exercise reminded me.
In the next installment, i will unpack this intriguing indicator and turn it into a complete trading system.
Final Code and Enhancements
{------------------------------------------------------------------------------- Indicator Name: Wavelet Analog (Equalizer Naming)
Switchboard: "1 2 3 4 5 6" 1: Fine Grain Detail --- 6: Coarse Structural Detail The Anchor (SubBass) is the permanent baseline track. -------------------------------------------------------------------------------} Inputs: Switchboard("000000") [DisplayName = "Analog Switches (Bands 1-6)"], ViewMode(0) [DisplayName = "0:Signal View, 1:Difference"];
// --- Validate the switchboard ONCE --- once begin if StrLen(Switchboard) > 6 then ValidSwitches = false else begin for j = 1 to 6 begin if MidStr(Switchboard, j, 1) <> "0" and MidStr(Switchboard, j, 1) <> "1" then begin ValidSwitches = false; break; end; end; end; end;
if ValidSwitches then begin if MidStr(Switchboard, 1, 1) = "1" then MasterOut = MasterOut Band1_Hiss; if MidStr(Switchboard, 2, 1) = "1" then MasterOut = MasterOut Band2_Treble; if MidStr(Switchboard, 3, 1) = "1" then MasterOut = MasterOut Band3_Presence; if MidStr(Switchboard, 4, 1) = "1" then MasterOut = MasterOut Band4_Mids; if MidStr(Switchboard, 5, 1) = "1" then MasterOut = MasterOut Band5_Body; if MidStr(Switchboard, 6, 1) = "1" then MasterOut = MasterOut Band6_Bass;
// --- Step 4: What you CUT from the mix --- CutSignal = Close - MasterOut;
// --- Step 5: Plotting --- if CurrentBar > 130 then begin if ViewMode = 0 then begin Plot1(MasterOut, "MasterOut", White, default, 1); Plot2(Anchor, "Anchor", DarkGreen, default, 1); end else begin Plot3(CutSignal, "CutSignal", Red, default, 1); Plot4(0, "Zero", LightGray); end; end; end;
Wavelet Analog
Examples
Three charts are shown with three different presets.
Plotting 2 Scales in TradeStation
You can’t plot a single multiple output indicator with different scales in the same chart in TradesStation (well not easily). You have to plot either one or the other and this can be accomplished by using a plot toggle. Here is the toggle in EasyLanguage.
If ViewMode = 0 then begin Plot1(MasterOut, "MasterOut", White); Plot2(Anchor, "Anchor", DarkGreen); end else begin Plot3(CutSignal, "CutLine"); Plot4(0, "Zero");
The following is from the RealCode website – I have just copied and pasted this here. Here is the header information that provides credit to the original programmer.
Here is the description of the Indicator via ProRealCode. Please check out the website for further information regarding the indicator and how to use it.
The RMI Trend Sniper indicator is designed to identify market trends and trading signals with remarkable precision.
This tool combines the analysis of the Relative Strength Index (RSI) with the Money Flow Index (MFI) and a unique approach to range-weighted moving average to offer a comprehensive perspective on market dynamics.
Configuration and Indicator Parameters
The RMI Trend Sniper allows users to adjust various parameters according to their trading needs, including:
RMI Length: Defines the calculation period for the RMI.
Positive and Negative Momentum (Positive above / Negative below): Sets thresholds to determine the strength of bullish and bearish trends.
Range MA Visualization (Show Range MA): Enables users to visualize the range-weighted moving average, along with color indications to quickly identify the current market trend.
Cool Shading – right?
Many of my clients ask me to convert indicators from different languages. One of my clients came across this from ProRealCode and asked me to convert for his MulitCharts. Pro Real code is very similar to EasyLanguage with a few exceptions. If you are savvy in EL, then I think you could pick up PRC quite easily. Here it is. It is a trend following indicator. It is one of a few that I could not find the Easylanguage equivalent so I thought I would provide it. Play around with it and let me know what you think. Again, all credit goes to:
if positive = 1 then begin rwma = rwma-band; r=0; g=188; b=212; end else if negative = 1 then begin rwma = rwma+band; r=255; g=82; b=82; end else rwma = 0;
//------------------------------------------------------------// //-----Calculate MA bands-------------------------------------// vars: mitop(0),mibot(0);
mitop = rwma+band20; mibot = rwma-band20;
plot1(mitop,"TOP"); plot2((mitop+mibot)/2,"TOP-BOT"); plot3((mitop+mibot)/2,"BOT-TOP"); plot4(mibot,"BOT"); if positive = 1 then begin plot5(rwma,"Pos",GREEN); noPlot(plot4); end; if negative =1 then begin plot6(rwma,"Neg",RED); noPlot(plot3); end;
Ignore the RGB Color Codes
Getting Creative to Shade Between Points on the Chart
TradeStation doesn’t provide an easy method to do shading, so you have to get a little creative. The plot TOP is of type Bar High with the thickest line possible. The plot TOP-BOT (bottom of top) is of type Bar Low. I like to increase transparency as much as possible to see what lies beneath the shading . The BOT-TOP (top of bottom) is Bar High and BOT is Bar Low. Pos and Neg are of type Point. I have colored them to be GREEN or RED.
Multiple trading decisions based on “logic” may not add to the bottom line
In this post, I will present a trend following system that uses four exit techniques. These techniques are based on experience and also logic. The problem with using multiple exit techniques is that it is difficult to see the synergy that is generated from all the moving parts. Pruning your algorithm may help cut down on invisible redundancy and opportunities to over curve fit. The trading strategy I will be presenting will use a very popular entry technique overlaid with trade risk compression.
Entry logic
Long:
Criteria #1: Penetration of the closing price above an 85 day (closing prices) and 1.5X standard deviation-based Bollinger Band.
Criteria #2: The mid-band or moving average must be increasing for the past three consecutive days.
Criteria #3: The trade risk (1.5X standard deviation) must be less than 3 X average true range for the past twenty days and also must be less than $4,500.
Risk is initially defined by the standard deviation of the market but is then compared to $4,500. If the trade risk is less than $4,500, then a trade is entered. I am allowing the market movement to define risk, but I am putting a ceiling on it if necessary.
Short:
Criteria #1: Penetration of the closing price below an 85 day (closing prices) and 1.5X standard deviation-based Bollinger Band.
Criteria #2: The mid-band or moving average must be decreasing for the past three consecutive days.
Criteria #3: Same as criteria #3 on the long side
Exit Logic
Exit #1: Like any Bollinger Band strategy, the mid band or moving average is the initial exit point. This exit must be included in this particular strategy, because it allows exits at profitable levels and works synergistically with the entry technique.
Exit #2: Fixed $ stop loss ($3,000)
Exit #3: The mid-band must be decreasing for three consecutive days and today’s close must be below the entry price.
Exit #4: Todays true range must be greater than 3X average true range for the past twenty days, and today’s close is below yesterday’s, and yesterday’s close must be below the prior days.
Here is the logic of exits #2 through exit #4. With longer term trend following system, risk can increase quickly during a trade and capping the maximum loss to $3,000 can help in extreme situations. If the mid-band starts to move down for three consecutive days and the trade is underwater, then the trade probably should be aborted. If you have a very wide bar and the market has closed twice against the trade, there is a good chance the trade should be aborted.
Short exits use the same logic but in reverse. The close must close below the midband, or a $3,000 maximum loss, or three bars where each moving average is greater than the one before, or a wide bar and two consecutive up closes.
Here is the logic in PowerLanguage/EasyLanguage that includes the which exit seletor.
if whichExit = 1 then permString = "1"; if whichExit = 2 then permString = "1,2"; if whichExit = 3 then permString = "1,3"; if whichExit = 4 then permString = "2"; if whichExit = 5 then permString = "2,3"; if whichExit = 6 then permString = "3"; if whichExit = 7 then permString = "1,2,3";
{Long Entry:} If (MarketPosition = 0) and Close crosses above upperBand and slopeUp and (tradeRisk < initialRisk*maxNATRLossMult and tradeRisk<maxEntryRisk$/bigPointValue) then begin Buy ("LE") Next Bar at Market; End;
{Short Entry:}
If (MarketPosition = 0) and slopeDn and Close crosses below lowerBand and (tradeRisk < initialRisk*maxNATRLossMult and tradeRisk<maxEntryRisk$/bigPointValue) then begin Sell Short ("SE") Next Bar at Market; End;
{Long Exits:}
if marketPosition = 1 Then Begin longLoss = initialRisk * maxNATRLossMult; longLoss = minList(longLoss,maxTradeLoss$/bigPointValue);
If Close < sma then Sell ("LX Stop") Next Bar at Market;;
if inStr(permString,"1") > 0 then sell("LX MaxL") next bar at entryPrice - longLoss stop;
if inStr(permString,"2") > 0 then If sma < sma[1] and sma[1] < sma[2] and sma[2] < sma[3] and close < entryPrice then Sell ("LX MA") Next Bar at Market; if inStr(permString,"3") > 0 then If TrueRange > largeATR and close < close[1] and close[1] < close[2] then Sell ("LX ATR") Next Bar at Market; end;
{Short Exit:}
If (MarketPosition = -1) Then Begin
shortLoss = initialRisk * maxNATRLossMult; shortLoss = minList(shortLoss,maxTradeLoss$/bigPointValue); if Close > sma then Buy to Cover ("SX Stop") Next Bar at Market;
if inStr(permString,"1") > 0 then buyToCover("SX MaxL") next bar at entryPrice + shortLoss stop;
if inStr(permString,"2") > 0 then If sma > sma[1] and sma[1] > sma[2] and sma[2] > sma[3] and close > entryPrice then Buy to Cover ("SX MA") Next Bar at Market; if inStr(permString,"3") > 0 then If TrueRange > largeAtr and close > close[1] and close[1] > close[2] then Buy to Cover ("SX ATR") Next Bar at Market; end;
Trend following with exit selector
Please note that I modified the code from my original by forcing the close to cross above or below the Bollinger Bands. There is a slight chance that one of the exits could get you out of a trade outside of the bands, and this could potentially cause and automatic re-entry in the same direction at the same price. Forcing a crossing, makes sure the market is currently within the bands’ boundaries.
This code has an input that will allow the user to select which combination of exits to use.
Since we have three exits, and we want to evaluate all the combinations of each exit separately, taken two of the exits and finally all the exits, we will need to rely on a combinatorial table. In long form, here are the combinations:
3 objects in our combinations of exit 1, exit 2, exit 3
one – 1
two – 1,2
three – 1,3
four – 2
five – 2,3
six – 3
seven – 1,2,3
There are a total of seven different combinations. Given the small set, we can effectively hard-code this using string manipulation to create a combinatorial table. For larger sets, you may find my post on the Pattern Smasher beneficial. A robust programming language like Easy/PowerLanguage offers extensive libraries for string manipulation. The inStrstring function, for instance, identifies the starting position of a substring within a larger string. When keyed to the whichExit input, I can dynamically recreate the various combinations using string values.
if whichExit = 1 then permString = “1”
if whichExit = 2 then permString= “1,2”
if whichExit = 3 then permString = “1,2,3”
etc…
As I optimize from one to seven, permString will dynamically change its value, representing different rows in the table. For my exit logic, I simply check if the enumerated string value corresponding to each exit is present within the string.
if inStr(permString,"1") > 0 then sell("LX MaxL") next bar at entryPrice - longLoss stop; if inStr(permString,"2") > 0 then If sma < sma[1] and sma[1] < sma[2] and sma[2] < sma[3] and close < entryPrice then Sell ("LX MA") Next Bar at Market; if inStr(permString,"3") > 0 then If TrueRange > largeATR and close < close[1] and close[1] < close[2] then Sell ("LX ATR") Next Bar at Market;
Using inStr to see if the current whichExit input applies
When permString = “1,2,3” then all exits are used. If permString = “1,2”, then only the first two exits are utilized. Now all we need to do is optimize whichExit from 1 to 7. Let’s see what happens:
Combination of all three exits
The best combination of exits was “3”. Remember 3 is the permString that = “1,3” – this combination includes the money management loss exit, and the wide bar against position exit. It only slightly improved overall profitability instead of using all the exits – combo #7. In reality, just using the max loss stop wouldn’t be a bad way to go either. Occam uses his razor to shave away unnecessary complexities again!
If you like this code, you should check out the Summer Special at my digital store. I showcase over ten more trend-following algorithms with different entry and exit logic constructs. These other algorithms are derived from the best Trend Following “Masters” of the twentieth century. IMHO!
Here is a video you can watch that goes over the core of this trading strategy.
Jeff Swanson wrote a great post on multi-agent trading a few years ago.
Jeff created a simple mean reversion system and then created two derivatives that culminated in three systems (or three agents.) Using Murray Ruggiero’s Equity Curve Feedback, he was able to poll which system was doing the best, synthetically, and execute the strategy that showed the best performance. If memory serves, picking the highflyer turned out to be the way to go. Jeff had just touched the surface of Murray’s tool. but it definitely did the job. Murray contracted me to fix some problems with the ECF tool and I did, but the tool is just way too cumbersome, resource hungry and requires a somewhat higher level of EasyLanguage knowledge to be universally applicable. I was doing similar research in the area of polling multiple strategies and picking the best, just like Jeff did, and just executing that one system, when I thought about this post. Traders do this all the time. They have multiple strategies in the pipeline and monitor the performance and if one is head and shoulders better than what they are currently trading, they will switch systems. This was one of the side benefits of the ECF tool.
What is an agent
An agent is any trading system that produces a positive expectancy. Using multiple agents in a polling process allows a trader to go with the strategy that is currently performing the best. This sounds reasonable, but there are pitfalls. You could always be behind the curve – picking the best system right before it has its draw down. Agents can be similar, or they can be totally different types of systems. I am going to follow in Jeff’s footsteps and create three agents with the same DNA. Here is what I call the AgentSpawner strategy.
value1 = countIf(c < c[1],numDownDays); if c > average(c,movAvgLen) and value1 = numDownDays then buy next bar at open; if barsSinceEntry = numDaysInTrade then sell next bar at open; if marketPosition = 1 then sell next bar at entryPrice - stopLoss/bigPointValue stop;
Use this template and optimize inputs to spawn new agents
This code trades in the direction of the longer-term moving average and waits for a pull back on N consecutive down closes. I am using the neat function countIF. This function counts the number of times the conditional test occurs in the last N bars. If I want to know the number of times I have had a down close in the last 3 days, I can use this function like this.
Value1 = countIF(c<c[1],3);
// this is what the function doues // 1.) todays close < yesterdays close + 1 // 2.) yesterdays close < prior days close + 2 // 3.) day before yesterdays close < prior cays close + 3
// If value3 = 3 then I know I had three conscecutive down // closes. If value3 is less than three then I did not.
If the close is greater than the longer-term moving average and I have N consecutive down closings, then I buy the next bar at the open. I use a wide protective stop and get out after X bars since entry. Remember EasyLanguage does not count the day of entry in its barsSinceEntry calculation. I am not using the built-in setStopLoss as I don’t want to get stopped out on the day of entry. In real trading, you may want to do this, but for testing purposes my tracking algorithm was not this sophisticated. I spawned three agents with the following properties.
This is why I love copy-paste programming. This can be difficult if you don’t know your EasyLanguage or how TradeStation processes the bars of data. Get educated by checking my books out at amazon.com – that is if you have not already. This code is a very simplistic approach for keeping track of a system’s trades and its equity.
value4 = countIf(c<c[1],4); value3 = countIf(c<c[1],3); value2 = countIf(c<c[1],2); //Agent #1 tracking algorithm if sys1Signal<> 1 and c[1] > average(c[1],160) and value2[1] = 2 then begin sys1Signal = 1; sys1BarCount = -1; sys1TradePrice = open; sys1LExit = open - 7500/bigPointValue; end; if sys1Signal = 1 then begin sys1BarCount+=1; if low < sys1LExit and sys1BarCount > 0 then begin sys1TradePrice = sys1LExit; sys1Signal = 0; end; if sys1BarCount = 16 and sys1Signal = 1 then begin sys1TradePrice = open; sys1Signal = 0; end; end;
Yes, this looks a little hairy, but it really is simple stuff
I am pretending to be TradeStation here. First, I need to test to see if Agent#1 entered into a long position. If the close of yesterday is greater than the moving average, inclusive of yesterdays close, and there has been two consecutive down closes, then I know a trade should have been entered on todays open. EasyLanguage’s next bar paardigm cannot be utilized here. Remember I am not generating signals, I am just seeing if today’s (not tomorrows or the next bars) trading action triggered a signal and if so, I need to determine the entry/exit price. I am gathering this information so I can feed it into a series function. If a trade is triggered, I set four variables:
sys1Signal – 1 for long, -1 for short, and 0 for flat.
sys1BarCount – set to a -1 because I immediately increment.
sys1TradePrice – at what price did I enter or exit
sys1LExit – set this to our stop loss level
If I am theoretically long, remember we are just tracking here, then I need to test, starting with the following day, if the low of the day is below our stop loss level and if it is I need to reset two variables:
sys1TradePrice – where did I get out
sys1Signal – set to 0 for a flat position
If not stopped out, then I start counting the number of bars sys1Signal is equal to 1. If sys1BarCount = 16, then I get out at the open by resetting the following variables:
sys1TradePrice = open
sys1Signal = 0
If you look back at the properties for Agent#1 you will see I get out after 15 days, not 16. Here is where the next bar paradigm can make it confusing. The AgentSpawner strategy says to sell next bar at open when barsSinceEntry = 15. The next bar after 15 is 16, so we store the open of the 16th bar as our trade price.
Now copy and paste the code into a nice editor such as NotePad++ or NotePad and replace the string sys1 with sys2. Copy the code from NotePad++ into your EasyLanguage editor. Now back to NotePad++ and replace sys2 with sys3. Copy that code into the EL edition too. Now all you need to do is change the different properties for each agent and you will have three tracking modules.
The Power of the EasyLanguage Series Function
The vanilla version of EasyLanguage has object-oriented nuances that you may not see right off the bat. In my opinion, a series function is like a class. Before I get started, let me explain what I mean by series. All EasyLanguage function are of three types.
simple – like a Bollinger band calculation
series – like we are talking about here
auto-detect – the interpreter/compiler decides
The series function has a memory for the variables that are used within the function. Take a look at this.
input: funcID(string),seed(numericSimple);
vars: count(0); if barNumber = 1 then // on first bar seed count count = seed; count = count+1; print(d," ",funcID," ", count); SeriesFunctionTest = count;
Count is class-like member
On the first bar of the function call – remember it will be called on each bar in the chart, the function variable count is assigned seed. Seed will be ignored on subsequent bars. What makes this magical is that no matter how many times you call the function on the same bar it remembers the internal variables on somewhat of a hierarchical basis (each call remembers its own stuff.) It like a class in that it gets instantiated on the very first call. Meaning if you call it three times on the first bar of the data, you will have three distinct internal variable memories. Take a look at my sandbox function driver and its output.
result = SeriesFunctionTest("Call #1",50); result = SeriesFunctionTest("Call #2",5); result = SeriesFunctionTest("Call #3",100);
1170410.00 Call #1 52.00 // second bar it remembered count was 51 1170410.00 Call #2 7.00 // second bar it remembered count was 6 1170410.00 Call #3 102.00 // second bar it remembered count was 101
1170411.00 Call #1 53.00 // you have a unique function values that 1170411.00 Call #2 8.00 // were instantiated on the first bar 1170411.00 Call #3 103.00 // of the test.
Series functions rock - but they are resource hungry
Why is this important?
I have created a PLSimulator function that keeps track of the three agent’s performance. I need the profit or loss to stick with each function and then also add or subtract from it. This is a neat function. Remember if you like this stuff buy my books at Amazon.com.
if orderType = 1 then // stop order begin if signal = 1 or (signal = 0 and signal[1] = - 1) then modTradePrice = maxList(open,modTradePrice); if signal = -1 or (signal = 0 and signal[1] = 1) then modTradePrice = minList(open,modTradePrice); end;
if orderType = 2 then // limit order begin if signal = 1 or (signal = 0 and signal[1] = - 1) then modTradePrice = minList(open,modTradePrice); if signal = -1 or (signal = 0 and signal[1] = 1) then modTradePrice = maxList(open,modTradePrice); end; if orderType = 3 then // market order begin modTradePrice = open; end;
If Signal[0]=1 And (Signal[1]=-1 Or Signal[1]=0) Then begin LEPrice=modTradePrice; SXPrice = -999999; condition1 = false; If Signal[1]=-1 Then begin SXPrice=modTradePrice; GProfit=(SEPrice-SXPrice)+GProfit; condition1 = True; End; if not(condition1) then if printOutTrades then Print(d," L:Entry ",LEPrice) else if printOutTrades then Print(d," L:Entry ",LEPrice," ",(SEPrice-SXPrice)*bigPointValue:8:2," ",GProfit*bigPointValue:9:2); End; {('***********************************************} If Signal[0]=-1 And (Signal[1]=1 Or Signal[1]=0) Then begin SEPrice=modTradePrice; LXPrice = 999999; condition1 = false; If Signal[1]=1 Then begin condition1 = True; LXPrice=modTradePrice; GProfit=(LXPrice-LEPrice)+GProfit; End; if not(condition1) then if printOutTrades then Print(d," S:Entry ",SEPrice) else if printOutTrades then Print(d," L:Exit ",LXPrice," ",(LXPrice-LEPrice)*bigPointValue:8:2," ",GProfit*bigPointValue:9:2);
End; If Signal[0]=0 And Signal[1]=-1 Then begin SXPrice = modTradePrice; GProfit=(SEPrice-SXPrice)+GProfit; if printOutTrades then Print(d," S:Exit ",SXPrice," ",(SEPrice-SXPrice)*bigPointValue:8:2," ",GProfit*bigPointValue:9:2);
end; If Signal[0]=0 And Signal[1]=1 Then begin LXPrice = modTradePrice; GProfit=(LXPrice-LEPrice)+GProfit; if printOutTrades then Print(d," L:Exit ",LXPrice," ",(LXPrice-LEPrice)*bigPointValue:8:2," ",GProfit*bigPointValue:9:2);
end;
If Signal[1]=1 And useOte=True Then begin OpenProfit=(Close[1]-LEPrice); End; If Signal[1]=-1 and useOte=True Then begin OpenProfit=(SEPrice-Close[1]); End; If Signal[1]=0 Or useOte=False Then begin OpenProfit=0; End;
PLSimulator=(GProfit+OpenProfit)*bigpointvalue;
Simulate profit and loss and more importantly keep track of it
Feed tracker algorithm data into the function
Your information must be properly assigned to get this to work. First, I show how to get the information into the function. The function does all the work and returns the equity. I then determine the best agent by looking at the ROC over the past thirty days of equity for each agent and pick the very best. I then trade the very best. This is a very quick application of the function. I will have a more sophisticated function, something akin to Murray’s ECF but with much less overhead and more strategy templates.
if multiAgent <> multiAgent[1] then print(d," ---->multiagent trans ");
if c > average(c,movAvgLen) and value1 = numDownDays then begin if multiAgent = 1 then buy("Sys1") next bar at open; if multiAgent = 2 then buy("Sys2") next bar at open; if multiAgent = 3 then buy("Sys3") next bar at open; end; if barsSinceEntry >= numDaysInTrade then sell next bar at open; if marketPosition = 1 then sell next bar at entryPrice - stopLoss/bigPointValue stop;
Cool usage of a switch-case and agent determination
If this seems over your head…
Get one of my books are check out Jeff Swanson’s course. EasyLanguage has so many little nuggets that can help you define your algorithm into an actionable strategy. You will never know how your strategy will work until your program it (properly) and back test it. And then potentially improve it with optimization.
The Fixed Fractional position sizing scheme is the most popular, so why does it need fixed?
Problems solved with Fixed Fractional:
Efficient usage of trading capital
Trade size normalization between different futures contracts
Trade size normalization across different market environments
These are very good reasons why you should use positions sizing. Problem #2 doesn’t apply if you are only trading one market. This sounds idyllic, right? It solves these two problems, but it introduces a rather bothersome side effect – huge draw down. Well, huge draw down in absolute terms. Draw downs when using a fixed fractional approach are proportional to the prior run up. If you make a ton of money on a prior trade, then your position sizing reflects that big blip in the equity curve. So, if you have a large loser following a large winner, the draw down will be a function of the run up. In most cases, a winning trading system using fixed fractional position sizing will scale profit up as well as draw down. A professional money manager will look at the profit to draw down ratio instead of the absolute draw down value. The efficient use of capital will reflect a smaller position size after a draw down, so that is good right? It is unless you believe in a Martingale betting algorithm – double up on losses and halve winners. Are we just stuck with large “absolute” draw downs when using this size scheme?
Possible solutions to fixing Fixed Fractional (FF)
The first thing you can do is risk less than the industry standard 2% per trade. Using 1% will cause equity to grow at a slower rate and also reduce the inevitable draw down. But this doesn’t really solve the problem as we are giving up the upside. And that might be okay with you. Profit will increase and you are using an algorithm for size normalization. In this blog I am going to propose a trading equity adjustment feature while using FF. What if we act like money managers, and you should even if you are trading your own personal money, and at the end of the year or month we take a little off the table (theoretically – we are not removing funds from the account just from the position sizing calculation) that is if there is any extra on the table. This way we are getting the benefit of FF while removing a portion of the compounding effect, which reduces our allocation for the next time interval. How do you program such a thing? Well first off let’s code up the FF scheme.
Nothing new here. Simply multiply tradingCapital by the riskPerTrade (1 or 2%) and then divide by a formula that defines current and inherent market risk. This is where you can become very creative. You could risk the distance between entry and exit if you know those values ahead of time or you can use a value in terms of the current market. Here I have chosen the 30-day average true range. This value gives a value that predicts the market movement into the future. However, this value only gives the expected market movement for a short period of time into the future. You could us a multiplier since you will probably remain in a trade for more than a few days – that is if you are trying to capture the trend. In my experiment I just use one as my multiplier.
Capture and store the prior year/month NetProfit
When I come up with a trading idea I usually just jump in and program it. I don’t usually take time to see if Easy Language already provides a solution for my problem. Many hours have been used to reinvent the wheel, which isn’t always a bad thing. So, I try to take time and search the functions to see if the wheel already exists. This time it looks like I need to create the wheel. I will show the code first and then explain afterward.
if useAllocateYearly then begin value1 = year(d); value2 = year(d[1]); end;
if useAllocateMonthly then //remember make sure your array is 12XNumYears begin value1 = month(d); value2 = month(d[1]); end;
if useAllocateYearly or useAllocateMonthly then begin if value1 <> value2 then begin if ypIndex > 0 then yearProfit[ypIndex] = prevNetProfit - snapShotNetProfit[ypIndex-1] else yearProfit[ypIndex] = prevNetProfit;
Capture either the prior years or months net profit
I wanted to test the idea of profit retention on a monthly and yearly basis to see if it made a difference. I also wanted to just use the vanilla version of FF. The use of Arrays may not be necessary, but I didn’t know ahead of time. When you program on the fly, which is also called “ad hoc” programming you create first and then refine later. Many times, the “ad hoc” version turns out to be the best approach but may not be the most efficient. Like writing a book, many times your code needs revisions. When applying a study or strategy that uses dates to a chart, you don’t know exactly when the data starts so you always need to assume you are starting in the middle of a year. If you are storing yearly data into an array, make sure you dimension you array sufficiently. You will need 12X the number of years as the size you need to dimension your array if you want to store monthly data.
//250 element array will contain more than 20 years of monthly data //You could increase these if you like just to be safe arrays: yearProfit[250](0),snapShotNetProfit[250](0); //Remember you dimension you arrray variable first and then //Pass it a value that you want to initiate all the values //in the array to equal vars: ypIndex(0);
Dimension and Initiate Your Arrays
The first thing we need to do is capture the beginning of the year or month. We can do this by using the year and month function. If the current month or year value is not the same as the prior day’s month or year value, then we know we crossed the respective timeline boundary. We are using two arrays, snapShotNetProfit and yearProfit (to save time I use this array to store monthlty values as well, when that option is chosen) and a single array index ypIndex. If we have crossed the time boundary, the first thing we need to do is capture the EasyLanguage functionNetProfit’s value. NetProfit keeps track of the cumulative closed out trade profits and losses. Going forward in this description I am going to refer to a yearly reallocation. If it’s the first year, the ypIndex will be zero, and in turn the first year’s profit will be the same as netProfit. We store netProfit in the yearProfit array at the ypIndex location. Since we are in a new year, we take a snapshot of netProfit and store it in the snapShotNetProfit array at the same ypIndex location. You will notice I use the variable prevNetProfit in the code for netProfit. Here is where the devil is in the details. Since we are comparing today’s year value with yesterday’s year value and when they are different, we are already inside the new year, so we need to know yesterday’s netProfit. Before you say it, you can’t pass netProfit a variable for prior values; you know like netProfit(1) or netProfit[1] – this is a function that has no historic values, but you can record the prior day’s value by using our own prevNetProfit variable. Now we need to calculate the tradingCapitalAdjustment. The first thing we do is assign the variable the value held in yearProfit[ypIndex]. We then test the yearProfit[ypIndex] value to see if it is positive. If it is, then we multiply it by (1-removePerProfit). If you want to take 75% of the prior year’s profit off the table, then you would multiply the prior year’s profit by 25%. Let’s say you make $10,000 and you want to remove $7,500, then all you do is multiply $10,000 by 25%. If the prior year’s netProfit is a loss, then this value flows directly through the code to the position sizing calculation (auto deallocation on a losing year). If not, the adjusted profit portion of funds are deallocated in the position sizing equation.
The next time we encounter a new year, then we know this is the second year in our data stream, so we need to subtract last year’s snapshot of netProfit (or prevNetProfit) from the current netProfit. This will give us the change in the yearly net profit. We stuff this information into the yearProfit array. The snapShotNetProfit is stuffed with the current prevNetProfit. ypIndex is incremented every time we encounter a new year. Notice how I increment the ypIndex – it is incremented after all the calculations in the new year. The tradingCapitalAdjustment is then calculated with the latest information.
Here is a table of how the tradingCapital and profit retention adjustment are calculated. A yearly profit adjustment only takes place after a profitable year. A losing year passes without adjustment.
All tests were carried out on the trend friendly crude oil futures with no execution costs from 2006 thru 2/28/2204.
See how money is removed from the allocation model after winning years.
Here are some optimization tests with 75% profit retention on yearly and monthly intervals.
Yearly First-
Yearly retention with no stop loss or break-even levels.
Now Monthly-
Monthly retention with no stop loss or break-even levels.
What if we didn’t reallocate on any specific interval?
Huge drawdowns with very little change in total profit.
Add some trade management into the mix.
Here we optimize a protective stop and a break-even level to see if we can juice the results. All the trade management is on a positionbasis.
200K with No Reallocating with $14k and $8.5 stop/break-even levels [ranked by Profit Factor]
No position sizing and no reallocation with $5K and $10K stop/break-even levels
200K and monthly reallocating with $7K and $5.5K stop/break-even levels [BEST PROFIT FACTOR]200K and monthly reallocating with $7K and $8.5K stop/break-even levels [2ND BEST PROFIT FACTOR]
Are we really using our capital in the most efficient manner?
If we retain profit, should we remove some of the loss form the position sizing engine as well. All the tests I performed retained profit from the position size calculations. I let the loss go full bore into the calculation. This is a very risk averse approach. Why don’t I retain 25% of losses and deduct that amount from the yearly loss and feed that into the position sizing engine. This will be less risk averse – let’s see what it does.
Not as good. But I could spend a week working different permutations and optimization sessions.
Are you wondering what Trend Following System I was using as the foundation of this strategy? I used EasyLanguage’s Linear Regression function to create buy and short levels. Here is the very simple code.
//Basically I am buying/shorting on the change of the linear regression slope //Also I have a volatility filter but it really isn't used If value2 >=0 and value2[1] < 0 and avgTrueRange(30)*bigPointValue < 10000 then buy positionSize contracts next bar at market; If value2 <=0 and value2[1] > 0 and avgTrueRange(30)*bigPointValue < 10000 then sellShort positionSize contracts next bar at market;
mp = marketPosition;
//I also have incorporated a 3XATR(30) disaster stop if mp = 1 and c <= entryPrice - 3 * avgTrueRange(30) then sell next bar at market; if mp = -1 and c >= entryPrice + 3 * avgTrueRange(30) then buyToCover next bar at market
If you want to see some more Trend Following models and their codes in EasyLanguage and TS-18 Python check out my TrendFollowing Guide and Kit.
Historical evidence suggests a potential seasonal pattern around the end of the month in the markets.
If you have been involved with the markets for even a short period of time, you have heard about this trade. Buy N days prior to the end of the month and then exit M days after the end of the month. This is a simple test to perform if you have a way to determine the N and the M in the algorithm. You could always buy on the 24th of the month, but the 24th of the month may not equal N days prior to the end of the month.
Simple approach that doesn’t always work – buy the 24th of the month and exit the 5th of the following month.
if dayOfMonth(d) = 24 then buy next bar at open;
if marketPosition = 1 and dayOfMonth(d) = 5 then sell next bar at open;
Before we get into a little better coding of this algorithm, let’s see the numbers. The first graph is trading one contract of the ES futures once a month – no execution fees were applied. The same goes for the US bond futures chart that follows. Before reading further please read this.
CFTC-required risk disclosure for hypothetical results:
Hypothetical performance results have many inherent limitations, some of which are described below. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown. in fact, there are frequently sharp differences between hypothetical performance results and the actual results subsequently achieved by any particular trading program.
One of the limitations of hypothetical performance results is that they are generally prepared with the benefit of hindsight. In addition, hypothetical trading does not involve financial risk, and no hypothetical trading record can completely account for the impact of financial risk in actual trading. For example, the ability to withstand losses or to adhere to a particular trading program in spite of trading losses are material points which can also adversely affect actual trading results. There are numerous other factors related to the markets in general or to the implementation of any specific trading program which cannot be fully accounted for in the preparation of hypothetical performance results and all of which can adversely affect actual trading results.
Buying N days before EOM and Selling M days after EOM
Ditto!
No Pain No Gain
Looking into the maw of draw down and seeing the jagged and long teeth.
Draw down as a percentage of account value.
Ditto2
The bonds had more frequent draw down but not so deep. These teeth can cause a lot of pain.
Well, George what is the N and M?
I should have done M days before and N days after to maintain alphabetic order, but here you go.
ES: N = 6 AND M = 6
US: N =10 AND M = 1
How did you do this?
Some testing platforms have built-in seasonality tools, but, and I could be wrong I didn’t find what I needed in the TradeStation function library. So, I built my own.
A TradingDaysLeftInMonth function had to be created. This function is a broad swipe at attempting to determining this value. It’s not very smart because it doesn’t take HOLIDAYS into consideration. But for a quick analysis it is fine. How does one design such a function? First off, what do we know to help provide information that might be useful? We know how many days are in each month (again this function isn’t smart enough to take into consideration leap years) and we know what day of the week each trading day belongs to. We have this function DayOfWeek(Date) already in EasyLanguage. And we know the DayOfMonth(Date) (built-in too!) With these three tidbits of information, we should be able to come up with a useful function. Not to mention a little programming knowledge. I was working on a Python project when I was thinking of this function, so I decided to prototype it there. No worries, the algorithm can be easily translated to EasyLanguage. And yes, I could have used my concept of a Sandbox to prototype in EasyLanguage as well. Remember a sandbox is a playground where you can quickly test a snippet of code. Using the ONCE keyword, you can quickly throw some generic EasyLanguage together sans trade directives and mate it to a chart and get to the nuts and bolts quickly. I personally like having an indicator and a strategy sandbox. Here is a generic snippet of code where we assume the day of month is the 16th and it is a Monday ( 2 – 1 for Sunday thru 7 for Saturday) and there are 31 days in whatever month.
currentDayOfWeek = 2; currentDayOfMonth = 16; loopDOW = currentDayOfWeek; daysInMonth = 31 #create the calender for the remaining month tdToEOM=0; #total days to EOM for j in range(currentDayOfMonth,daysInMonth+1): if loopDOW != 1 and loopDOW != 7: tdToEOM +=1; print(j," ",loopDOW," ",tdToEOM) loopDOW +=1; if loopDOW > 7: loopDOW = 1; #start back on Monday
Create a synthetic calendar from the current day of month
I just absolutely love the simplicity of Python. When I am prototyping for EasyLanguage, I put a semicolon at the end of each line. Python doesn’t care. Here is the output from this snippet of code.
On Monday 16th there were 12 Trading Days Left In Month Inclusive
Output of Python Snippet - use in EZLang.
I start out with the current day of the month, 16 and loop through the rest of the days of the month. Whenever I encounter a Sunday (1) or a Saturday (7) I do not increment tdToEOM, else I do increment.
Here is how the function works on a chart. Remember in TradeStation I am placing a market order for the NEXT BAR.
Counting the days until the EOM
This snippet of code is the heart of the function, but you must make in generic for any day of any month. Here it is in EasyLanguage – you will see the similarity between the Python snippet and its corresponding EasyLanguage.
{Python prototype tdToEOM=0; for j in range(currentDayOfMonth,daysInMonth+1): if loopDOW != 1 and loopDOW != 7: tdToEOM +=1; print(j," ",loopDOW," ",tdToEOM) loopDOW +=1; if loopDOW > 7: loopDOW = 1; }
loopDOW = curDayOfWeek+1; tdToEOM=0;
for j = curDayOfMonth to monthDays[month(d)] begin if loopDOW <> 1 and loopDOW <> 7 then tdToEOM +=1; // tdToEOM = tdToEOM + 1; loopDOW +=1; if loopDOW > 7 then loopDOW = 1; end; TradingDaysLeftInMonth = tdToEOM;
EasyLanguage Function : TradingDaysLeftInMonth
I used arrays to store the number of days in each month. You might find a better method. Once I get the day of the month and the day of the week I get to work. EasyLanguage uses a 0 for Sunday so to be compliant with the Python function I add a 1 to it. I then loop from the current day of month through monthDays[month(d)]. Remember month(d) returns the month number [1…12]. A perfect index into my array. That is all there is to it. The code is simple, but the concept requires a little thinking. Okay, now that we have the tools for data mining, let’s do some. I did this by creating the following strategy (the same strategy that create the original equity curves.)
if c >= average(c,movingAvgLen) and TDLM = numDaysBeforeEOM then begin buy("Buy B4 EOM") next bar at open; end;
if marketPosition = 1 and barsSinceEntry > 3 then begin if TDIM = numDaysAfterEOM then begin sell("Sell TDOM") next bar at open; end; end; setStopLoss(stopLossAmount); setProfitTarget(profitTargetAmount);
EasyLanguage function driver in form of Strategy
A complete strategy has trade management and an entry and an exit. In this case, I added an additional feature – a trend detector in the form of a longer-term moving average. Let’s see if we can improve the trading system. Thank goodness for Genetic Optimization. Here is the @ES market.
Get your Pick ready to mine!
Smoothed the equity curve – took the big draw down out.
Genetically MODIFIED – Data Mining at its best!
Here are the parameters:
Did not like the moving average. Wide stop and wide profit objective. Days to EOM and after EOM stayed the same.
Bond System:
Bond market results.
If you like this type of programming check out my books at Amazon.com. I have books on Python and of course EasyLanguage. I quickly assembled a YouTube video discussing this post here.
Conclusion – there is something here, no doubt. But it can be a risky proposition. It definitely could provide fodder for the basis of a more complete trading system.
Dollar Cost Averaging Algorithm – Buy X amount every other Monday!
I am not going to get into this controversial approach to trading. But in many cases, you have to do this because of the limitations of your retirement plan. Hey if you get free matching dough, then what can you say.
Check this out!
Buy $1000 worth of shares every other Monday. INTC
if dayOfWeek(d of tomorrow)< dayOfWeek(d) Then begin toggle = not(toggle); if toggle then buy dollarInvestment/close shares next bar at open; end;
Toggle every other Monday ON
Here I use a Boolean typed variable – toggle. Whenever it is the first day of the week, turn the toggle on or off. Its new state becomes the opposite if its old state. On-Off-On-Off – buy whenever the toggle is On or True. See how I determined if it was the first day of the week; whenever tomorrow’s day of the week is less than today’s day of the week, we must be in a new week. Monday = 1 and Friday = 5.
Allow partial liquidation on certain days of the year.
Here I use arrays to set up a few days to liquidate a fractional part of the entire holdings.
value1 = d + 19000000; if sellDates[cnt] = value1 then begin sell sellAmounts[cnt]/close shares total next bar at open; cnt = cnt + 1; end;
Notice the word TOTAL in the order directive.
You can use this as reference on how to declare an array and assign the elements an initial value. Initially, sellDates is an array that contains 20 zeros, and sellAmounts is an array that contains 20 zeros as well. Load these arrays with the dates and the dollar amounts that want to execute a partial liquidation. Be careful with using Easylanguage’s Date. It is in the form YYYMMDD – todays date December 28, 2023, would be represented by 1231228. All you need to do is add 19000000 to Date to get YYYYMMDD format. You could use a function to help out here, but why. When the d + 19000000 equals the first date in the sellDates[1] array, then a market sell order to sell sellAmounts[1]/close shares total is issued. The array index cnt is incremented. Notice the order directive.
sell X sharestotal next bar at market;
If you don’t use the keyword total, then all the shares will be liquidated.
To create a complete equity curve, you will want to liquidate all the shares at some date near the end of the chart. This is used as input as well as the amount of dollars to invest each time.
//Demonstation of Dollar Cost Averaging //Buy $1000 shares every two weeks //Then liquidate a specific $amount on certain days //of the year
value1 = d + 19000000; if sellDates[cnt] = value1 then begin sell sellAmounts[cnt]/close shares total next bar at open; cnt = cnt + 1; end;
if dayOfWeek(d of tomorrow)< dayOfWeek(d) Then begin toggle = not(toggle); if toggle then buy dollarInvestment/close shares next bar at open; end;
if d + 19000000 = settleDate Then sell next bar at open;
A cool looking chart.
A chart with all the entries and exits.
Allow Pyramiding
Turn Pyramding On. You will want to allow up to X entries in the same direction regardless of the order directive.
Working with Data2
I work with many charts that have a minute bar chart as Data1 and a daily bar as Data2. And always forget the difference between:
Close of Data2 and Close[1] of Data2
24 hour regular session used here 1231214 1705 first bar of day - close of data2 4774.00 close[1] of data2 4760.75 1231214 1710 second bar of day - close of data2 4774.00 close[1] of data2 4760.75 1231215 1555 next to last bar of day - close of data2 4774.00 close[1] of data2 4760.75 1231215 1600 last bar of day - close of data2 4768.00 close[1] of data2 4774.00
Up to the last bar of the current trading day the open, high, low, close of data2 will reflect the prior day’s values. On the last bar of the trading day – these values will be updated with today’s values.
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.
Calculate the difference in hours and minutes from startTime to midnight and then in terms of minutes only.
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.
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:
) 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.
) mod – returns the modulus or remainder from a division operation. I use this function a lot. Mod(505/100) gives 5 minutes.
) Five hours * 60 minutes + Five minutes = 305 minutes.
Calculate the difference in hours and minutes from midnight to endTime and then in terms of minutes only.
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.
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.
) 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.
) mod – returns the modulus or remainder from a division operation. I use this function a lot. Mod(1425/100) gives 25.
) 14* 60 + 25 = 865 minutes.
) Now add 305 minutes to 865. This gives us a total of 1165 minutes between the start and end times.
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
// 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:
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);
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.
Backtesting with [Trade Station,Python,AmiBroker, Excel]. Intended for informational and educational purposes only!
Get All Five Books in the Easing Into EasyLanguage Series - NEW Kindle Pricing!
Announcement: Amazon has updated its pricing policy for Kindle authors, and I’ve updated the Kindle versions of the Easing into EasyLanguage series to match. Get your favorite quant the books they need! Build your knowledge and let AI enhance your work—your AI prompting and strategy architecture can only be improved by knowing the building blocks. The new price range is $9.99 to $12.99.
The Foundation Edition. The first in the series.
This series includes five editions that covers the full spectrum of the EasyLanguage programming language. Fully compliant with TradeStation and mostly compliant with MultiCharts. Start out with the Foundation Edition. It is designed for the new user of EasyLanguage or for those you would like to have a refresher course. There are 13 tutorials ranging from creating Strategies to PaintBars. Learn how to create your own functions or apply stops and profit objectives. Ever wanted to know how to find an inside day that is also a Narrow Range 7 (NR7?) Now you can, and the best part is you get over 4 HOURS OF VIDEO INSTRUCTION – one for each tutorial.
Hi-Res Edition Cover
This book is ideal for those who have completed the Foundation Edition or have some experience with EasyLanguage, especially if you’re ready to take your programming skills to the next level. The Hi-Res Edition is designed for programmers who want to build intraday trading systems, incorporating trade management techniques like profit targets and stop losses. This edition bridges the gap between daily and intraday bar programming, making it easier to handle challenges like tracking the sequence of high and low prices within the trading day. Plus, enjoy 5 hours of video instruction to guide you through each tutorial.
Advanced Topics Cover
The Advanced Topics Edition delves into essential programming concepts within EasyLanguage, offering a focused approach to complex topics. This book covers arrays and fixed-length buffers, including methods for element management, extraction, and sorting. Explore finite state machines using the switch-case construct, text graphic manipulation to retrieve precise X and Y coordinates, and gain insights into seasonality with the Ruggiero/Barna Universal Seasonal and Sheldon Knight Seasonal methods. Additionally, learn to build EasyLanguage projects, integrate fundamental data like Commitment of Traders, and create multi-timeframe indicators for comprehensive analysis.
Get Day Trading Edition Today!
The Day Trading Edition complements the other books in the series, diving into the popular approach of day trading, where overnight risk is avoided (though daytime risk still applies!). Programming on high-resolution data, such as five- or one-minute bars, can be challenging, and this book provides guidance without claiming to be a “Holy Grail.” It’s not for ultra-high-frequency trading but rather for those interested in techniques like volatility-based breakouts, pyramiding, scaling out, and zone-based trading. Ideal for readers of the Foundation and Hi-Res editions or those with EasyLanguage experience, this book offers insights into algorithms that shaped the day trading industry.
Trend Following Cover.
For thirty-one years as the Director of Research at Futures Truth Magazine, I had the privilege of collaborating with renowned experts in technical analysis, including Fitschen, Stuckey, Ruggiero, Fox, and Waite. I gained invaluable insights as I watched their trend-following methods reach impressive peaks, face sharp declines, and ultimately rebound. From late 2014 to early 2020, I witnessed a dramatic downturn across the trend-following industry. Iconic systems like Aberration, CatScan, Andromeda, and Super Turtle—once thriving on robust trends of the 1990s through early 2010s—began to falter long before the pandemic. Since 2020 we have seen the familiar trends return. Get six hours of video instruction with this edition.
Pick up your copies today – e-Book or paperback format – at Amazon.com