Category Archives: MultiCharts

Equity Curve Feedback: The ON/OFF Switch Is Only the Beginning

There’s More Beneath the Surface.

The concept of equity curve feedback has been around for many years. I worked with Murray Ruggiero on several large projects that involved weaving trading ON/OFF switches into EasyLanguage strategies. It was arduous work, requiring considerable trial and error to keep the original strategy running in the background while automating the feedback decisions and measuring their results. But the idea offered a different avenue of research: instead of continually optimizing entry and exit parameters, we could investigate an overlay that controlled when to participate. That overlay effectively created a second version of the original system—one whose behavior depended on both the feedback model and the mechanics of stopping and restarting trading.

Only the Shadow Knows!

Equity curve feedback can be implemented using a “shadow system.” The original strategy casts a continuous shadow, following every entry and exit rule whether we are participating or sitting out. The feedback model opens and closes a viewing window onto that shadow, accepting eligible trades—or portions of trades—to build a parallel equity curve.

The challenge is keeping these two paths synchronized. The shadow must continue tracking every trade while the feedback-controlled system manages its positions and determines when to stop or resume new entries. Closing the window cannot stop the shadow: its continuing history provides the information we need to decide when to open the window again.

In my tests, I separate the feedback model from the mechanics of acting on its signals. The model determines when new entries are permitted. The Trading Settings determine when equity is sampled, what happens to existing positions when trading turns OFF, and how participation resumes when it turns ON.

Consider a longer-term trend-following strategy that may hold a position for several months. If we sample only closed-trade equity, the feedback model receives no new equity observation until that trade exits. A substantial open profit—or the loss of that profit—can develop before the model evaluates another result. Sampling at session close or every bar lets the model respond while the position is still open.

The execution choices matter just as much:

  • Finish existing trades at original exits: An OFF signal stops new entries, but an accepted position continues until the original strategy exits.
  • Liquidate at next bar close: An OFF signal schedules the accepted position to close at the following bar’s close.
  • New entries only: After an ON signal, wait for the original strategy to generate a fresh entry.
  • Adopt existing positions at next bar open: After an ON signal, join an eligible position the shadow system is already holding, using the following bar’s opening price.

For a long-term system, waiting for a fresh entry can create a lengthy pause. The shadow strategy might recover enough to turn participation ON while still holding the same trade that produced the recovery. With New entries only, we cannot join that trade. We must wait for it to end and for another entry to occur—potentially weeks or months later.

Adopting the existing position allows earlier participation, but we enter at the adoption price, not the shadow system’s original entry price. We do not receive the profits earned while we were sitting out.

This is why I made these settings explicit. The same feedback model and thresholds can produce substantially different results depending on when we observe equity and how we leave and rejoin the strategy.

Real World Examples

Here is an example of a trading system that one of my clients has used over the years.

Turning off and turn on – trading with feedback

 

Because this strategy trades every day, closed-trade equity provides frequent observations for the feedback model. TS-EquityCurve_FB offers three sampling options:

  • Closed Trades: Evaluate realized equity when trades exit.
  • Session Close: Evaluate equity, including open-position profit and loss, at each session’s close.
  • Every Bar: Evaluate equity, including open-position profit and loss, at every source bar’s close.

For this example, I selected Closed Trades, let accepted trades finish at their original exits, and resumed with fresh entries when trading turned back ON. The four execution combinations are:

  • Finish existing trades; resume with fresh entries.
  • Finish existing trades; resume by adopting an existing shadow position.
  • Liquidate at the next bar’s close; resume with fresh entries.
  • Liquidate at the next bar’s close; resume by adopting an existing shadow position.

Because positions turn over quickly, these execution choices may have less impact than in a longer-term strategy. Their actual effect must still be tested; daily trading alone does not guarantee similar results.

How Trading Settings Change the Results

For this test, I applied the Drawdown / Retracement model to a daily E-mini S&P 500 strategy using 10% drawdown, 50% recovery, and $100,000 starting account equity. The model monitors the original strategy and stops new entries after a 10% decline from peak account equity. It resumes after recovering 50% of the eventual peak-to-trough loss.  Here are examples of where bad equity curves can be improved and worsened by feedback.

The table shows how changing equity sampling and the exit/restart settings affects the results over April 2007 through November 2026.

Equity sampling When trading turns OFF When trading resumes Net profit Maximum drawdown Closed trades
Original system — — −$27K $86,212.50 228
Closed trades Finish existing trades New entries only −$5K $53,362.50 103
Closed trades Finish existing trades Adopt existing position −$4K $59,587.50 105
Closed trades Liquidate next bar close New entries only −$4K $53,362.50 103
Closed trades Liquidate next bar close Adopt existing position −$3K $59,587.50 105
Session close Finish existing trades New entries only −$17K $66,650 102
Session close Finish existing trades Adopt existing position −$76K $110,387.50 121
Session close Liquidate next bar close New entries only −$28K $86,000 102
Session close Liquidate next bar close Adopt existing position −$96K $139,875 128

Every Bar is omitted because this file contains daily bars and produces the same results as Session Close. Closed-trade sampling uses realized equity, while session-close sampling includes open-position profit and loss.

None of these configurations made money. However, all four closed-trade configurations reduced both the original strategy’s $27,150 loss and its $86,212.50 maximum drawdown. Session-close results were mixed, with some settings substantially increasing losses and drawdown.

Even with closed-trade sampling, execution settings can matter. A trade can exit and another enter during the same daily bar, before the drawdown model evaluates equity at bar close. An open position may therefore remain available to finish, liquidate, or adopt.

Equity curve feedback does not automatically improve a strategy. Its effect depends on the model, when equity is sampled, and how trading stops and restarts.

In this daily-bar example, liquidation takes place at the following bar’s close and adoption at the following bar’s open. Results include the recorded commission and slippage costs.

Equity curve feedback is easy to describe: stop trading when a rule says conditions have deteriorated, and resume when they improve. Putting that idea into practice requires more decisions than the simple ON/OFF switch suggests. When do we measure equity? What happens to an open position? When permission returns, do we wait for a fresh entry or join a trade already underway?

These examples show why those details deserve attention. Feedback can reduce drawdown, but it can also skip important winners, increase losses, or weaken a strategy’s contribution to a portfolio. The timing of winning trades matters just as much as the timing of losing trades.

I created software to make these questions easier to investigate. We can compare models and execution settings, then examine the audit trail to understand exactly how the results were produced. A better historical curve is a starting point for further testing—not proof that we have found a better trading system.

Bridge TradeStation’s Lumber Contracts

A fix for the lumber futures contracts

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.

Unlocking a Gann-Based Pivot System with My “Intelligent Stack” Design

A Wheel Within a Wheel: Recording Market Events Beyond the Daily Bar

Dust flew as I opened my trading system vault. With more than 1,000 systems tucked away, why pull out Gann Pivot? Two reasons: its entry rules make an excellent coding example, and they give me a practical way to introduce my Intelligent Stack library.

In my opinion, Bruce Babcock’s choice of the Gann name served two purposes: recognition among the many “Gannsters” studying his work, and a connection to Gann’s interest in swings and market turning points. That is my interpretation, rather than a documented statement of Babcock’s intent. Despite the name, this system does not require astrology, biblical interpretation, or elaborate geometric calculations. Its rules focus on price pivots, the trading days between them, and risk management. I would describe it as Gann-inspired swing trading, rather than an attempt to reproduce his more esoteric methods. There is an irony here: Bruce Babcock criticized Gann in his own writing, yet attached Gann’s name to this system. Perhaps the distinction was between Gann’s more esoteric explanations and the practical value of swing-based trading rules. Whatever his reasoning, the system gives us something concrete to define, code, and test.

The “wheel within a wheel” idea resurfaced during a recent session with a client. We were using a two-dimensional EasyLanguage array to store information whenever certain market events occurred. Explaining how to move and retrieve those values required more array gymnastics than I wanted. My client is exceptionally sharp and caught on quickly, but I kept thinking: the interface should make the trading logic easier to understand, without making the array bookkeeping part of the lesson.

Years ago, I built structures in Fortran to handle similar bookkeeping. For this example, I wanted to bring that approach into EasyLanguage through a simple stack interface.

A conventional stack is a last-in, first-out collection: you push new items onto the top and pop them off. My Intelligent Stack borrows the newest-at-the-top organization but serves a different purpose. We do not need to pop our pivot history. Instead, we push new observations, inspect older entries with seek, and let the library handle the underlying array bookkeeping. When the stack reaches its capacity, the oldest observation drops out of the bottom.

Gann has also been on my mind lately. My friend and colleague, Mike Chalek, explores Gann’s cycle analysis and price geometry through his work at AstroTimeCycles.com. Although some of these ideas fall outside my usual approach, nearly 40 years of research have taught me not to dismiss a trading method simply because it sounds esoteric. If its rules can be defined, coded, and tested, I am willing to give it a fair examination.

Bruce Babcock published the basis of this system over 30 years ago. He was part of the first generation of system vendors. He published a pioneering book on trading system design – Babcock, B., & Williams, L. R. (1989). The Dow Jones-Irwin guide to trading systems. Dow Jones-Irwin. Foreword by Larry Williams.

The rules from the outside seem simple and reasonable:

Long Entry Rules

Evaluate the following conditions after each trading day’s close:

  1. Identify a new high pivot. Yesterday’s high must be strictly higher than both the preceding day’s high and today’s high:
    High[1] > High[2] and High[1] > High[0]

    Yesterday is the pivot day; today’s completed bar confirms it.

  2. Find the most recent earlier, higher high pivot. Search backward through the stored high pivots until you find one whose price exceeds the newly confirmed pivot high. If none is found within the stored history, there is no new long setup.
  3. Find the lowest intervening low pivot. Between these two high pivots, locate the low pivot with the lowest price. A low pivot is a day whose low is strictly lower than the lows of the preceding and following days.
  4. Measure the time from that low to the recent high. Count trading bars beginning with the day immediately before the recent high pivot and ending with the intervening low pivot day. The count must be at least 20 bars.
  5. Place the entry order. If the setup qualifies, place a buy stop for the next trading day one tick above the recent high pivot.

Timing clarification: The 20-bar requirement applies to the distance between the intervening low pivot and the recent high pivot—not between the two high pivots

Short Entry Rules: 

  1. Just reverse the long entry rules.

Exit Rules:

These are the rules that were published way back in the early 1990s.  So, the dollar values would need to be adjusted.  However, you will get the general idea.

A simple $1000 fixed stop from entry.  Imagine trying to trade gold or crude with this tight of a stop.

A Ratcheting Percent Trailing Stop protects a growing share of a trade’s profit. It activates once closing profit or maximum position profit exceeds $1,600 per contract. Each additional $1,500 reduces the permitted giveback by five percentage points.

Highest Closing Profit Giveback Allowed Profit Protected
$1,600* 70% $480
$3,100 65% $1,085
$4,600 60% $1,840

The first row illustrates the starting level; activation occurs just above $1,600.

The stop tightens as the trade profit increases and never loosens when profit declines. I’ll explain the calculations and implementation in a later post.

 

Doesn’t EasyLanguage OOEL already include a Stack object?

Yes. TradeStation’s object-oriented EasyLanguage library includes a conventional stack with Push, Pop, and Peek operations. TradeStation documentation

My Intelligent Stack serves a different purpose. Built with ordinary EasyLanguage arrays and functions, it stores a fixed number of observations with the newest in slot zero. When it fills, the oldest observation drops out of the bottom.

For pivot analysis, we need to inspect earlier entries without removing them. My seek function provides that access, while other library functions calculate averages, standard deviations, and more. There is no pop operation because this application needs a searchable history rather than a collection we consume one item at a time.

Think of it as a bounded, newest-first history collection with the array bookkeeping tucked behind a simple interface.

Why My Intelligent Stack Design?

First off, you don’t need to enter the world of objects to use my

libraries.  I teach EasyLanguage to traders, so I try to keep things as simple as possible.  Introducing a two-dimensional array can quickly cause confusion.  My stack structure is based on synchronized single dimension-ed arrays.  And I use the word stack in all my functions.

Stack declaration

Arrays:
HPvt_stack[200](0),
LPvt_stack[200](0),
HPvtBN_stack[200](0),
LPvtBN_stack[200](0);

Here I create 4 stacks using Array declaration.  I dimension them to 200 and set the initial elements to zero.  Remember arrays are just lists that can be indexed.  The HPvt stacks are to be synchronized when using them.  In the same manner so is the LPvt stacks.

Pushing data onto a stack

    Value1 = Stack.Push(H[1],HPvt_stack,200);
Value1 = Stack.Push(barNumber-1,HPvtBN_stack,200);

When I discover a pivot high I push the price and the barNumber-1 onto their respective stacks:  HPvt_stack and HPvtBN_stack .

After pushing all four pivots:

Array Index HPvt_stack HPvtBN_stack Meaning
[0] 4 4 Number of stored pivots
[1] 110.00 138 Newest pivot
[2] 106.75 125 Previous pivot
[3] 108.50 112 Older pivot
[4] 105.25 100 Oldest pivot

Each new push places the pivot’s price and bar number at index [1], shifts older entries down, and updates the count at [0]. Matching indexes in the two stacks always describe the same pivot.

The library handles the shifting and count updates, so users can focus on the trading logic. They only need to declare the arrays with enough capacity; the stack functions manage the contents.

EasyLanguage arrays are zero-based. My implementation reserves that first element, [0], for the count and stores observations beginning at [1].

Why Do I Call Them Intelligent Stacks?

I built a collection of functions that do more than store and retrieve values. They can calculate averages, standard deviations, and other statistics over an entire stack or a selected portion. For example:

value1 = Stack.Average(chanWidthStack,20);

This calculates the average of the 20 most recent stored observations. All library functions use the Stack. prefix.

Some functions come in two forms:

value1 = Stack.Highest(HPvt_stack);
value2 = Stack.HighestIndex(HPvt_stack);

value1 contains the highest price in the stack. value2 contains its location, or index.

Why return the location? Because our price and bar-number stacks hold related information at matching indexes. If the highest price occupies slot [3] in HPvt_stack, its bar number occupies slot [3] in HPvtBN_stack. We retrieve it with:

highestPivotBar = Stack.Seek(HPvtBN_stack,value2);

The index connects the two stacks, telling us both what the highest pivot price was and when it occurred.

Now let’s put these functions to work. Each time a new pivot high is confirmed, we search the stored pivots for the most recent higher pivot high. Its bar number defines our search boundary. We then locate the lowest intervening pivot low and check whether it occurred at least 20 bars before the new pivot high. Notice how the index-returning functions connect prices with their corresponding bar numbers.

if HighPivotFormed(1,0) <> -999999 then
begin
currentHPvtBN = BarNumber - 1;
priorHPvtIndex = -1;
endIndex = 0;
interLowIndex = -1;

{ Find the most recent higher pivot high. }
if Stack.Size(HPvt_stack) > 0 then
priorHPvtIndex = Stack.GreaterIndex(HPvt_stack,H[1],1);

{ Bound the low-pivot search using that pivot's bar number. }
if priorHPvtIndex <> -1 then
begin
priorHPvtBN = Stack.Seek(HPvtBN_stack,priorHPvtIndex);
endIndex = Stack.LesserIndex(LPvtBN_stack,priorHPvtBN,1) - 1;
end;

{ Find the lowest pivot low within the search range. }
if endIndex >= 1 then
interLowIndex = Stack.LowestRangeIndex(LPvt_stack,1,endIndex);

{ A qualifying low establishes or replaces the pending buy order. }
if interLowIndex <> -1 then
begin
interLowPivotBN = Stack.Seek(LPvtBN_stack,interLowIndex);
interLowCount = currentHPvtBN - interLowPivotBN;
if interLowCount >= interveningPvtTrigger then
begin
buyPrice = H[1] + tickOffset * MinMove / PriceScale;
buyOrderBN = BarNumber;
end;
end;
Finding an intervening lowest pivot low between pivot high boundaries

Are you Bewildered?

I know this code looks a little bit on the gross side.  I can tell you that it is better than the loopy version and we now have a nice library of functions that we can use with our stacks.  Let’s break it down.

    { Find the most recent higher pivot high. }
if Stack.Size(HPvt_stack) > 0 then
priorHPvtIndex = Stack.GreaterIndex(HPvt_stack,H[1],1);

{ Bound the low-pivot search using that pivot's bar number. }
if priorHPvtIndex <> -1 then
begin
priorHPvtBN = Stack.Seek(HPvtBN_stack,priorHPvtIndex);
endIndex = Stack.LesserIndex(LPvtBN_stack,priorHPvtBN,1) - 1;
end;
First two steps explained

Once a new pivot high is confirmed at H[1], the first if checks whether HPvt_stack contains any earlier pivot-high prices. If it does, Stack.GreaterIndex(HPvt_stack,H[1],1) searches for the first price greater than H[1]. Since the newest entry is stored at [1], this finds the most recent qualifying pivot high. The function returns its location in the stack, or -1 if none is found.

The second if proceeds only when a match exists. We use its index with Stack.Seek to read the corresponding bar number from HPvtBN_stack. Remember, the price and bar-number stacks are paired: matching indexes describe the same pivot.

That bar number establishes the older boundary for our next search. LPvtBN_stack contains the bar numbers of stored pivot lows, also ordered newest first. Stack.LesserIndex finds the first low pivot that occurred before our qualifying high pivot. Subtracting one from that index excludes this older low and everything below it. The resulting endIndex bounds the portion of LPvt_stack we will search for the lowest intervening pivot low.

In other words, we have located the bar number of the prior qualifying pivot high and use it as the boundary for our backward search. We now need to find the lowest pivot low between that boundary and the newly confirmed pivot high, along with its bar number. The stack functions handle the searching internally, so our strategy code does not need its own search loops.

   { Find the lowest pivot low within the search range. }
if endIndex >= 1 then
interLowIndex = Stack.LowestRangeIndex(LPvt_stack,1,endIndex);

{ A qualifying low establishes or replaces the pending buy order. }
if interLowIndex <> -1 then
begin
interLowPivotBN = Stack.Seek(LPvtBN_stack,interLowIndex);
interLowCount = currentHPvtBN - interLowPivotBN;
if interLowCount >= interveningPvtTrigger then
begin
buyPrice = H[1] + tickOffset * MinMove / PriceScale;
buyOrderBN = BarNumber;
end;
end;
Find the intervening lowest low pivot and validate the current pivot high

Working within our stack environment, we use Stack.LowestRangeIndex to locate the lowest pivot low within the search range in LPvt_stack. We then use that index to retrieve its corresponding bar number from LPvtBN_stack. If the newly confirmed pivot high occurred at least 20 bars after that low, we have a qualifying setup. We establish a fresh buyPrice one tick above the new pivot high.

The trickiest part of this example is using an index to connect a pivot’s price in one stack with its bar number in another. Most single-stack tasks are simpler: call a function to retrieve a value, find an extreme, or calculate an average. Here, the paired stacks let us answer both what happened and when it happened.

A Wheel within a Wheel

Our Intelligent Stack separates the storage of observations from EasyLanguage’s bar-by-bar history. Instead of recording a value on every bar, we push a value only when an event occurs, such as a newly confirmed pivot. We retrieve earlier events through stack functions rather than ordinary series indexing. This creates a second history inside the daily chart: one measured in market events instead of bars. That is our “wheel within a wheel.”

Original Results over the past 20 Years – no execution fees charged

This material is for educational purposes only and does not constitute investment advice. Futures and options trading involves substantial risk of loss and is not suitable for every investor. Any performance data shown is hypothetical and may not reflect actual results. You may lose more than your initial investment, and losses can occur quickly. Do not trade with money you cannot afford to lose. The information provided is not a solicitation or offer to buy or sell any financial instrument, and no representation is made that any account will achieve similar results. Past performance is not indicative of future results. You are responsible for your own trading decisions and should seek independent financial advice before trading

These results show why 30-year-old dollar values do not keep up with the times.

Updated Dollar Values and Intervening Bar Count:

Email me for full source code and access to the limited Intelligent Stack functions discussed in this post.

Patience, Grasshopper—the prompt is not yet the Master.

AI will not replace the seasoned programmer, well not yet.

Can AI solve 10 lines of EasyLanguage code and fix the subtle order-execution flaws hiding inside? EasyLanguage’s small footprint makes it a known weak spot for LLMs, which rely on sheer volume to learn edge cases. That weakness shows up clearly when entry and exit criteria are triggered at the same time. The strategy exits and re-enters at the exact same price and time. While trade management stays intact on paper, this simultaneous exit and re-entry cannot be truly realized in real-world trading, leaving you paying extra execution costs and commissions for phantom backtest trades.

Exit after N bars

Many predictive models utilize an “exit after N bars” rule to determine objective function fitness.

The problem with testing a “no matter what happens, you exit after N bars” strategy in TradeStation is that the engine will immediately re-enter the same trade at the exact same exit price and bar if the entry criteria remain true.

Above we had four occurrences of this problem.  In reality this is just one trade.

inputs:exitBars(7),stoploss$(2000),profitTarg$(3500);
if close > close[1] and close > average(close,20) Then
buy("simple buy") next bar at open;
if barsSinceEntry >= exitBars then
begin
if close > close[1] then sell("xitBars") next bar at market;
sell("xitBars-ll") next bar at lowest(l,2) stop;
end;
setStopLoss(stoploss$);
setProfitTarget(profitTarg$);
Simple system that allows entry and exit conditions to exist simulteneously!

The AI Response

I fed all of this into an LLM. Before going completely down the rabbit hole of a seemingly infinite prompt, test, feedback loop, I programmed the fix myself.

Then, I showed the LLM my code and asked a simple question: If we had stayed in that loop, would you have ever derived this solution?

Its answer was a clear “no.”

Here is why the AI got stuck, and why real trading and programming experience still matters.

The EasyLanguage Challenge

EasyLanguage is a specialized, niche script. Mainstream languages like Python or JavaScript have massive amounts of code online for LLMs to train on, but EasyLanguage has a much smaller footprint.

Because of that limited training data, AI models rely on broad programming rules. They simply do not understand how TradeStation’s state machine processes order fills, bar updates, and variable evaluation line-by-line during an execution pass.

How I Solved It with a PreLaunch Paradigm

Instead of trying to force built-in engine stops that kept breaking, I stepped back and built a custom execution flow using three practical techniques:

  • The Hybrid Stop Switch (setStopLoss(-1)): Standard AI models treat native engine tools and custom order logic as an either-or choice. By passing -1 into setStopLoss, I actively suppressed the native stop engine the moment my custom price targets took over, stopping order conflicts in their tracks.
  • State Priming (barsInTrade = -1): An LLM looks at setting a counter to -1 as a mistake and tries to “correct” it to 0. But because TradeStation increments variables at the very bottom of the script pass, priming barsInTrade to -1 ensured the trade clock started at exactly 0 when the next bar opened.
  • Forward-Looking Execution (open of next bar): By evaluating open of next bar inside the end-of-pass calculation, the code figures out theoretical fill prices (theoEntryPrice) and re-establishes profit targets before the new bar starts printing. That handles simultaneous exit-and-reentry collisions cleanly in a single pass.

The Bottom Line

AI has a strong bias toward fixing what is already on the screen. It tries to stretch built-in functions past their limits instead of stepping back and rebuilding the architecture.

AI writes code based on how a system is supposed to work on paper. It still takes a seasoned programmer to write code based on how execution engines actually behave in the real world.

It admitted that generative models have a strong “fix what’s there” bias. They try to bend standard built-in functions to their limit rather than stepping back, discarding broken abstractions, and manually rebuilding the architecture.

It takes a seasoned programmer; someone who truly understands platform execution loops, bar-evaluation timing, and manual state overrides to see past the standard toolkit and engineer a real solution.

My code grew from ten lines to 40.  Platform nuances and misbehavior usually needs much more code

 

 

Is Your System Broken?

The Ultimate Test of Efficacy: Time

At Futures Truth, we focused on one thing: walk-forward results across hundreds of trading systems. Back then, the industry was unrecognizable compared to today—if you can even call what exists now an “industry.”

Just this morning, I was reminiscing about vendors who sold strategies for upwards of $5,000. Those packages usually consisted of a set of rules (disclosed or not) and a rudimentary DOS-based program to generate simple charts and next-day orders. This was well before the heyday of TradeStation; those days are gone forever, for better or worse.

Back then, if a system performed well in walk-forward analysis, it earned a ranking. In those days, a Futures Truth ranking meant something. Sometimes, however, that ranking felt like a curse. Critics even argued you could “fade” a top-ranked system and make more money by taking the opposite trade. The reality is that many of those legendary “Top Ten” systems—built for a different era—simply wouldn’t survive in today’s markets.

Side Bar:  There are still services such as Striker and The Collective that still monitor trading systems.  Striker only shows real execution, which is mostly a good thing – real execution costs are shown.  But so is broker error.  Heck, we are all human and we all make mistakes.  Striker is upfront with this, and they state they will do the best they can – execution can be a beast. 

Speaking of execution – The Sunday Evening Gap

A Traders Nightmare. Most likely Trend Followers were short during the huge gap here!

 Imagine, having a stop order in crude oil on a Sunday evening when the market opens thousands of dollars through your stop.  If a system derived position is short the broker’s only directive is to GET OUT – no matter what, at the first off ramp.  The above chart shows a single contract slip on crude futures at the genesis of the Iran War.

The Million-Dollar Question

The second most common question I was asked at Futures Truth was: “How do I know if the system I’m trading is broken?”

Can you guess the most common one? “If it were your money, which system would you trade?”

We never answered that one directly; there was never a simple black-and-white answer. But the second question—the one about “broken” systems—usually surfaced when a trader was deep in a drawdown.

Seasoned traders know that systems ebb and flow; drawdown is simply the “tax” we pay to play the game. Others, however, get “married” to a system and stick with it until “death do us part.” My standard response back then was always:

“Is your current performance still within the boundaries of the backtest?”

In other words, has the system exceeded its historical maximum drawdown by a meaningful margin? Does the current real-time performance look like other “rough patches” in the historical equity curve? If the answer was yes, the trader would usually give it a little more room.

Into Unexplored Waters

Those were simpler days, but the core problem remains: we cannot see the future. No forward analysis can tell you with certainty what a trading system will do next. What it can do is tell you when the system has moved into “unexplored waters.” Once you know that, the decision to stay, abandon, or pause becomes much easier.

All trading systems oscillate between success and failure. If a system has a genuine technical edge, that edge may eventually reassert itself—provided you have the time and capital to wait. But most traders don’t have unlimited resources.

Recently, the market activity surrounding the Iran conflict has pushed many systems into intense drawdowns. The same old questions have reared their heads again. This time, however, I wanted to provide a more empirically derived analysis. I’ve developed a disciplined approach to measuring risk and reward that moves beyond “gut feel.”

To illustrate, I pulled a system off my shelf that I originally designed for retail consumption back in June 2018. Here is how it’s currently holding up:

Hypothetical Results: Before and after development.

The Profit Mirage

This is a mean-reversion approach. I remember thinking back in 2018: How much longer can this bull market continue? With that in mind, I utilized a simple regime filter. After just a few weeks of trading later that year, I genuinely thought the system might be broken. The market spent a large portion of that fall and winter below its 200-day moving average, and shorting simply wasn’t working.

The system then went dormant for a long stretch, finally “waking up” at the height of the pandemic. Had you stuck with it, you would be up significantly today (though we stopped trading right at the onset of the pandemic).

But here is the catch: Profit, by itself, is not enough to determine if a system is broken. As long as they are making money, most traders never bother to peek below the surface. This system would likely be sitting near the top of the Futures Truth rankings today. But let’s dive in and see how it actually performed on its “test of time.”

Test 1 – Baseline Projection

Baseline projection based on in sample average monthly return.

Is Outperformance Always a Good Thing?

Looking at the chart above, you see a steep deviation below the baseline initially, followed by a rocket-ship move to the upside. By late 2025, the actual equity is sitting way above the red dashed expectation line.

Most traders would see this and think they’ve struck gold. “Isn’t this what we want—a strong positive deviation?” they’d ask.

In a world of simple “bottom-line” thinking, the answer is yes. But in the world of professional algorithmic trading, this chart is screaming a different story. To a seasoned developer, deviation is deviation. Whether it’s to the upside or downside, moving this far away from the “expected” path suggests that the strategy’s original statistical model is no longer in control.

When a system starts generating 190% of its expected return, it’s often because it has inadvertently stepped into a high-volatility regime it wasn’t designed to navigate. If the “upside” is this aggressive, you can bet the “downside” risk has scaled right along with it.

Test 2:  Monte Carlo Analysis on Walk Forward

Return and Drawdown sitting on the tails.

The Statistical Reality Check

To understand why I called this system “Degraded” despite the profits, we have to look at the Monte Carlo Walk Forward distributions. This is where we compare real-time performance against thousands of simulated “alternate realities” based on the system’s history.

1. The Equity Distribution (The Good News… or is it?)

In the top chart, our actual forward equity of $67,575 (the dashed red line) sits at the 97th percentile.

  • Interpretation: Out of 1,000 possible outcomes, the system performed better than 970 of them. While this looks great, being this far out on the “tail” of the distribution suggests we are no longer operating in a normal environment.

2. The Drawdown Distribution (The Warning)

The bottom chart is the real story. The actual worst drawdown reached $18,588, placing it in the 98th–99th percentile of severity.

  • The Comparison: The median expected drawdown was only $8,125.

  • The Verdict: We have blown past the 90th percentile of $13,611 and are deep into the “danger zone.”

The Bottom Line

When a system hits the 97th percentile for gains but simultaneously hits the 99th percentile for drawdown stress, the math is telling you that the character of the strategy has changed. You aren’t just trading a system in a “rough patch”—you are trading a system that has moved into a risk regime it was never built to survive. This is the “evidence-based framework” I mentioned earlier. Without these charts, you’re just guessing. With them, you have the data to justify stepping aside.

The Verdict: Test 3 – Overall Assessment

This is where the “gut feel” ends and empirical analysis begins. The following commentary is generated by my new software; a quasi-expert system designed to pair raw statistical results with descriptive, actionable interpretation.

Status: DEGRADED

Risk Assessment: CRITICAL RISK

Incubation/Trading Readiness Score: 4 / 8

Overall Assessment: Degraded
Risk Assessment: Critical Risk
Incubation/Trading Readiness Score: 4 / 8
Return delivery is running ahead of baseline: expected annual return is 18% versus actual annual return of 34% and expected annual gain of $4,477 compares with actual annual gain of $8,536. However, that stronger return delivery has come with a less stable path and/or materially heavier risk than history would suggest. Risk is materially worse than the historical profile: actual worst drawdown of $18,588 is 2.670 times the historical drawdown of $6,962. Risk conditions are now in the Critical Risk range. The realized monthly path is poorly aligned with the baseline, based on monthly equity correlation of 0.960, projection RMSE of $21,789, normalized RMSE of 4.867, and path wander ratio of 0.621. Correlation still describes directional similarity, but RMSE and path wander ratio show how far the realized path has wandered from projection over the same window. Monte Carlo context is cautionary: actual forward equity is $67,575, gain percentile is 97% (near the top of the simulated distribution), and drawdown percentile is 99% (in the worst decile for drawdown stress). Taken together, the system shows meaningful deterioration in incubation.

A readiness reading of 4 out 8 indicates this system right now has degraded to a point where caution and I mean extreme caution should be used in your decision to trade this strategy.  The major factors influencing rating are:

  • Return Attainment:   1.907 – — This indicates the system has achieved 190.7% of its historically expected return during the incubation/trading period. In practical terms, the strategy is generating returns at nearly twice the pace implied by its historical baseline.
  • Path Wander Ratio: 0.621 — This indicates that the actual equity path is deviating from the projected path by a meaningful amount relative to the total expected move over the incubation/trading period. Put simply, the system is not wildly off course, but it is no longer tracking the historical baseline tightly.
  • Drawdown Stress: 2.67 — This indicates that the actual worst drawdown has expanded to roughly 2.7 times the level suggested by the system’s historical baseline. Put simply, the strategy may still be generating return, but it is doing so while absorbing far more pain than its historical profile would justify.

Hindsight is always 20/20, and it is easy to say now that you should have stuck with the system. But with a large sample of out-of-sample trades showing this degree of deterioration, if I had to choose between staying with it, abandoning it entirely, or temporarily shutting it down, I would probably step aside and wait for conditions to settle down. Remember, not trading is an algorithm too.   Having the right tools to make this kind of decision is paramount, because they give you an evidence-based framework for explaining and defending your reasoning.

The Power of Incubation: Is Your Best System Collecting Dust?

How many systems do you have sitting on your shelf? I personally have at least a hundred, probably more. In this business, a little dust is not always a bad thing.

Figuratively speaking, the more “dust” a system has collected, the more real-time incubation it has endured. And that gives you something far more valuable than any backtest: pure, unadulterated out-of-sample evidence.

Seeds Waiting to Be Planted

Algorithmic trading development rarely produces just one system. It creates a trail of offshoots—versions that may have looked unremarkable or even mediocre during the initial build. Yet many of these forgotten systems are really just seeds waiting for the right environment.

When you revisit them months or even years later, you may find that a strategy which struggled in 2022 has bloomed into a powerhouse in 2026. Without a framework to measure that growth, you would never know.

Why You Need an Incubation Framework

Most traders revisit old systems by simply eyeballing an equity curve. An incubation framework goes much deeper by providing:

Historical Context: Does the dusty system’s recent performance still match its original DNA?

Regime Readiness: Has the market finally moved into the regime this offshoot was designed for?

The Go/No-Go Signal: A quantitative way to decide whether a seed is finally ready to be moved from the shelf to the server.

TS-SystemChecker software

TS-System Check Control Panel

A Tool Built for the Journey

I built TS-SystemChecker because, after decades at Futures Truth and years of developing my own strategies, I needed a better way to cut through the emotional fog that surrounds system evaluation.
I didn’t design TS-SystemChecker to be a black box or some kind of get-rich-quick shortcut. I built it because, after decades at Futures Truth and years of developing my own strategies, I wanted a better way to cut through the emotional fog that surrounds system evaluation.

Whether you are a retail trader focused on refining one core system, or a developer like me with a shelf full of offshoots, this framework was built for that journey.

For the specialist: If you have one system you live and die by, the deep-dive analysis helps define its boundaries of truth. You can begin to see whether a drawdown is simply part of the system’s normal character or evidence of something more structural.

For the portfolio manager: If you are tracking a library of ideas, the Batch Analysis feature helps you monitor many systems at once. Import the trade files, review the evidence, and identify which seeds may finally be ready to move from the shelf to a live account.

Looking Beneath the Surface

At the end of the day, this is why I built TS-SystemChecker. Traders need more than opinions, hope, or fear. They need a framework grounded in evidence.

That is the real purpose of this tool: not to make decisions for you, but to help you make better ones.

TS-SystemChecker Batch Mode

Reverse-Engineering a Trading Indicator with AI

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),

...
...
...
// --- Step 1: Current price ---
Price = Close;
// --- Step 2: A0 is raw price ---
A0 = Price;
// --- Step 3: Causal ? trous B3-spline filter (past bars only) ---
A1 = c0*A0 2*c1*A0[1] 2*c2*A0[2];
A2 = c0*A1 2*c1*A1[2] 2*c2*A1[4];
A3 = c0*A2 2*c1*A2[4] 2*c2*A2[8];
A4 = c0*A3 2*c1*A3[8] 2*c2*A3[16];
A5 = c0*A4 2*c1*A4[16] 2*c2*A4[32];
A6 = c0*A5 2*c1*A5[32] 2*c2*A5[64];
// --- Step 4: Details ---
D1 = A0 - A1;
D2 = A1 - A2;
D3 = A2 - A3;
D4 = A3 - A4;
D5 = A4 - A5;
D6 = A5 - A6;
// --- Step 5: Trend ---
Trend = A6;
...
...
// --- Step 7: Residual ---
Residual = Price - Reconstructed;
// --- Step 8: Plot ---
Plot1(Trend, "Trend");
Plot2(Reconstructed, "Denoised");
Plot3(Residual, "Residual");
Wavelet a trous snippet

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"];

Vars:
// "Tone Curve" Weights (fixed EQ kernel)
Tone0(0.375), Tone1(0.25), Tone2(0.0625),

// Tracks: Raw progressively stronger low-pass versions
RawTrack(0), LP1(0), LP2(0), LP3(0), LP4(0), LP5(0), SubBass(0),

// EQ Bands (detail layers)
Band1_Hiss(0), // Ultra-high: micro flicker / "hiss"
Band2_Treble(0),
Band3_Presence(0),
Band4_Mids(0),
Band5_Body(0),
Band6_Bass(0), // Low: macro structure / "bass"

// Outputs
MasterOut(0), Anchor(0), CutSignal(0);

Vars: j(0), ValidSwitches(True);

// --- Step 1: The "Analog Console" Smoothing Ladder ---
RawTrack = Close;
LP1 = Tone0*RawTrack 2*Tone1*RawTrack[1] 2*Tone2*RawTrack[2];
LP2 = Tone0*LP1 2*Tone1*LP1[2] 2*Tone2*LP1[4];
LP3 = Tone0*LP2 2*Tone1*LP2[4] 2*Tone2*LP2[8];
LP4 = Tone0*LP3 2*Tone1*LP3[8] 2*Tone2*LP3[16];
LP5 = Tone0*LP4 2*Tone1*LP4[16] 2*Tone2*LP4[32];
SubBass = Tone0*LP5 2*Tone1*LP5[32] 2*Tone2*LP5[64];

// --- Step 2: Split into EQ Bands (details between tracks) ---
Band1_Hiss = RawTrack - LP1;
Band2_Treble = LP1 - LP2;
Band3_Presence = LP2 - LP3;
Band4_Mids = LP3 - LP4;
Band5_Body = LP4 - LP5;
Band6_Bass = LP5 - SubBass;

// --- Step 3: Master bus anchor switchboard mix ---
Anchor = SubBass;
MasterOut = Anchor;

// --- 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");
Different Plot Scale Toggle

Can the Recursive Gaussian Channel Beat the Battle Tested Bollinger Band?

Bridging 19th‑century mathematics and 21st‑century trading methods

A client sent me what looked like a simple indicator written in TradingView’s Pine Script—though I didn’t realize it was Pine at first—and asked if I could port it to EasyLanguage (or PowerLanguage for MultiCharts). If you Google “Gaussian Channel Donovan Wall TradingView,” you’ll find the original code. Pine Script isn’t exactly newcomer-friendly; it’s fine once you get the feel for it, but I’m spoiled by EasyLanguage, which —at least to my eye—reads almost like plain English. (Others may beg to differ!) Below is a brief Pine snippet; to this humble EL devotee, it’s more hieroglyphics than prose.

    _m2 := _i == 9 ? 36  : _i == 8 ? 28 : _i == 7 ? 21 : _i == 6 ? 15 : _i == 5 ? 10 : _i == 4 ? 6 : _i == 3 ? 3 : _i == 2 ? 1 : 0
_m3 := _i == 9 ? 84 : _i == 8 ? 56 : _i == 7 ? 35 : _i == 6 ? 20 : _i == 5 ? 10 : _i == 4 ? 4 : _i == 3 ? 1 : 0
_m4 := _i == 9 ? 126 : _i == 8 ? 70 : _i == 7 ? 35 : _i == 6 ? 15 : _i == 5 ? 5 : _i == 4 ? 1 : 0
_m5 := _i == 9 ? 126 : _i == 8 ? 56 : _i == 7 ? 21 : _i == 6 ? 6 : _i == 5 ? 1 : 0
_m6 := _i == 9 ? 84 : _i == 8 ? 28 : _i == 7 ? 7 : _i == 6 ? 1 : 0
_m7 := _i == 9 ? 36 : _i == 8 ? 8 : _i == 7 ? 1 : 0
_m8 := _i == 9 ? 9 : _i == 8 ? 1 : 0
_m9 := _i == 9 ? 1 : 0

I could see right away that the code was doing some kind of coefficient “lookup,” so I ran it through ChatGPT to get a quick explanation. The model suggested it was building weights from Pascal’s Triangle. A bit later the client sent me the original TradingView post, which confirmed the script was using John Ehlers’s Gaussian filter to build a channel—similar in spirit to Keltner or Bollinger bands.

Once Ehlers’s name popped up, the next stop was his resource-rich site (mesasoftware.com/TechnicalArticles) for the theory behind the filter. I also searched for a ready-made EasyLanguage version but came up empty. With ChatGPT’s help I decided to roll my own; after all, knocking out support code like this is exactly what these AI tools are for.

What do Carl Friedrich Gauss, Blaise Pascal, and the markets have in common.

You’ve probably bumped into the bell curve in school—maybe in a stats class, maybe when teachers “graded on a curve.” Mathematicians call it by a few interchangeable names:

  • Normal distribution (stats class)
  • Gaussian curve (named after Carl Friedrich Gauss)
  • Binomial curve (because it pops out of Pascal’s Triangle)

No matter the label, it’s the same smooth hump that says, “most values cluster in the middle, very few at the extremes.” Gauss formalized the formula, Pascal’s Triangle supplies the ready‑made integer weights, and traders borrow both ideas to build filters that tame noisy price charts.

Big picture: Gauss gives us the shape of the curve, Pascal gives us the exact numbers to approximate it, and that combo lets us create a market indicator that reacts quickly and stays smooth.

How does this help build an indicator?

The word channel is in the name of the indicator, so it was highly likely we are dealing with a smoothed price with an upper and lower band a certain distance from the smoothed price.  If you feed this into Chat GPT and ask for it in EasyLanguage, it will create an indicator using a bunch of arrays.  See Chat GPT isn’t 100% knowledgeable of EasyLanguage like it is with python.  It didn’t understand the concept of EasyLanguage’s serialized variables.  You know where you can refer to a prior value of a variable – myValue[1] or myValue[2].  Chat tries to replicate this with the usage of arrays which gets you into a bunch of trouble right off the bat.  Let’s discuss this a little later.

The Mechanics of smoothing price with Pascal’s Triangle, or Gaussian Kernal or Binomial Coefficients.

(a + b)^2 = a^2 + 2ab + b^2 → coefficients 1  2  1

(a + b)^3 = a^3 + 3a^2b + 3ab^2 + b^3 → coefficients 1 3 3 1

(a + b)^4 = a^4 + 4a^3b + 6a^2b^2 + 4ab^3 + b^4 → coefficients 1 4 6 4 1

(a + b)^5 → coefficients 1 5 10 10 5 1

(a + b)^6 → coefficients 1 6 15 20 15 6 1

(a + b)^7 → coefficients 1 7 21 35 35 21 7 1

(a + b)^8 → coefficients 1 8 28 56 70 56 28 8 1

(a + b)^9 → coefficients 1 9 36 84 126 126 84 36 9 1
Binomial Coefficients

Stack those rows, keep going, and you build Pascal’s Triangle—each number is the sum of the two numbers just above it.

Look at the 7th row of Pascal’s Triangle:

1  6  15  20  15  6  1

Normalize those numbers (divide by their sum), and you obtain a discrete approximation of a Gaussian kernel.  Big Deal, right?  You don’t need to know the math behind this, just know that each row in Pascal’s triangle is symmetric.  Each row starts are one and ends at one.  You can use these coefficients to weight each value across a period of time.  Do you mean all this math stuff is akin to a weighted moving average.

Idea Weighted Moving Average Binomial / Gaussian weights Why they feel similar
What it does Averages recent prices, but gives newer bars bigger weights (e.g., 1-2-3-4). Averages recent prices using the numbers from Pascal’s Triangle (e.g., 1-4-6-4-1). Both are just weighted sums of past prices.
Shape of the weights Forms a triangle – rises steadily to the newest bar, then drops to zero beyond the window. Forms a bell – climbs to the centre, then falls off symmetrically. Triangles and bells are both peaked shapes: the middle matters most, the edges least.
Normalizing step Divide by the sum of the weights (e.g., 1+2+3+4 = 10) so they add to 1. Same: divide by 1+4+6+4+1 = 16 so they add to 1. After normalizing, each is just a fancy way to say “take a percentage of each bar and add them up.”
Smoothing power Good at knocking out single-bar noise, but the straight sides of the triangle let more mid-frequency wiggles through. Slightly better at suppressing both very fast and mid-speed wiggles, so the line looks cleaner. Both cut random jitter while trying not to lag too far behind real turns.
Math connection A single pass of linear weights. What you get if you apply a two-point moving average over and over again (each pass builds the next Pascal row). Re-applying a simple WMA repeatedly evolves into the binomial weights – that’s the family link.

Which comes first the indicator or the function that feeds the indicator?

If you are working with code and especially with ChatGPT or any other LLM you need a medium where you can quickly program and observe results.  The indicator analysis module will give you instant results. and this is where you should start.  However, if you look at the TradingView code of the Gaussian Channel you will notice that the smoothing function is called twice, once for the close and once for the true range on each bar.  In other words, you are using the same code twice and incorporating this without functions would be redundant.  In my first attempt, I created the smoothing function and named it Binomial, and the channels were a magnitude of 10 below the current price.  So, all the price bars were scrunched at the very top of the chart.  At first if you don’t succeed, try and try and try and try again.

At first ChatGPT kept insisting on arrays because it didn’t realize EasyLanguage can reference earlier bars just by tagging a variable with [n]. EasyLanguage conveniently hides that bookkeeping, but you have to tell the model so it stops reinventing circular buffers. Once I explained that a local variable—say filt—already remembers its prior values (filt[1], filt[2], etc.), the conversation moved forward.

The next hurdle was clarifying that Donovan’s script feeds raw data (Close and TrueRange) into every stage, not the output of the previous stage. ChatGPT was trying to build a true cascade—each pole using the prior pole’s result—whereas Donovan calculates each pole completely independently. After I pointed that out, the model rewrote the logic correctly and even walked me through the difference:

  1. Cascaded filter → Pole 2 uses Pole 1’s output, Pole 3 uses Pole 2’s, and so on.

  2. Independent poles → Every pole starts over with the raw Close and Range.

That explanation finally squared the circle and let me produce an EasyLanguage version that matches the original TradingView indicator.

“Cascade” = one stage feeding the next

Think of a cascade as a relay race:

  1. Stage 1 (“Pole 1”) takes the raw price, smooths it a little, and hands the baton to …

  2. Stage 2 (“Pole 2”), which smooths the output of stage 1 a bit more, then passes to …

  3. Stage 3, and so on.

After 4-, 6-, or 9-hand-offs the combined shape of all those little smooths matches the full Gaussian bell.


The indicator lets you pick anywhere from two to nine poles to do the heavy lifting on the data-smoothing. And no, we’re not talking about the North and South Poles—or the kind you cast a fishing line from.

So, what is a pole?

In filter speak, a pole is one little “memory stage” inside the math that reaches back to yesterday’s value (or last bar’s value) before deciding today’s output. Stack more poles and you stack more of those memory stages:

  • 1 pole → basically a quick-and-dirty exponential average.

  • 4 poles → four mini-averages chained together; much smoother, a hair more lag.

  • 9 poles → nine stages deep; super-silky curve, but you’ll feel the delay.

Think of each pole as a coffee filter. One filter catches the big grounds, two filters catch the sludge, and by the time you’ve got nine stacked up, you’re practically drinking distilled water. Same beans in, different smoothness out.

You can dial in two extra tweaks:

  • Lag compensation – Tell the code to look one step ahead by swapping in a one-bar forecast of price for the raw price. That little nudge pulls the channel forward so it doesn’t trail the market.
  • Extra smoothing – Want the line even silkier? Flip the switch and the function just averages the most-recent two filter values. It’s a tiny moving average—jitter drops a notch, lag creeps up by only half a bar.

For illustrative purposes this is how Pole 6 is calculated.  I also show a mapping scheme to store Pascal’s triangle into arrays.  I put all this code inside a function with the name BinomialFilterN.

{─────────────────────────────────────────────────────────────────────
2. Hard-code every Pascal row (n = 1 … 9)
─────────────────────────────────────────────────────────────────────}
once
begin
{ n = 1 : 1 1 }
m0Map[1] = 1; m1Map[1] = 1;

{ n = 2 : 1 2 1 }
m0Map[2] = 1; m1Map[2] = 2; m2Map[2] = 1;

{ n = 3 : 1 3 3 1 }
m0Map[3] = 1; m1Map[3] = 3; m2Map[3] = 3; m3Map[3] = 1;

{ n = 4 : 1 4 6 4 1 }
m0Map[4] = 1; m1Map[4] = 4; m2Map[4] = 6; m3Map[4] = 4;
m4Map[4] = 1;

{ n = 5 : 1 5 10 10 5 1 }
m0Map[5] = 1; m1Map[5] = 5; m2Map[5] = 10; m3Map[5] = 10;
m4Map[5] = 5; m5Map[5] = 1;

{ n = 6 : 1 6 15 20 15 6 1 }
m0Map[6] = 1; m1Map[6] = 6; m2Map[6] = 15; m3Map[6] = 20;
m4Map[6] = 15; m5Map[6] = 6; m6Map[6] = 1;

{ n = 7 : 1 7 21 35 35 21 7 1 }
m0Map[7] = 1; m1Map[7] = 7; m2Map[7] = 21; m3Map[7] = 35;
m4Map[7] = 35; m5Map[7] = 21; m6Map[7] = 7; m7Map[7] = 1;

{ n = 8 : 1 8 28 56 70 56 28 8 1 }
m0Map[8] = 1; m1Map[8] = 8; m2Map[8] = 28; m3Map[8] = 56;
m4Map[8] = 70; m5Map[8] = 56; m6Map[8] = 28; m7Map[8] = 8;
m8Map[8] = 1;

{ n = 9 : 1 9 36 84 126 126 84 36 9 1 }
m0Map[9] = 1; m1Map[9] = 9; m2Map[9] = 36; m3Map[9] = 84;
m4Map[9] = 126; m5Map[9] = 126; m6Map[9] = 84; m7Map[9] = 36;
m8Map[9] = 9; m9Map[9] = 1;
end;

{─────────────────────────────────────────────────────────────────────
3. Working variables
─────────────────────────────────────────────────────────────────────}
variables:
beta_(0), { = 1 – alpha }
f1(0), f2(0), f3(0), f4(0), f5(0),
f6(0), f7(0), f8(0), f9(0),
f(0);

beta_ = 1 - alpha;

{─────────────────────────────────────────────────────────────────────
4. Initialise memory until we have enough bars
─────────────────────────────────────────────────────────────────────}
if currentBar <= poleCount then
begin
f1 = 0; f2 = 0; f3 = 0; f4 = 0; f5 = 0;
f6 = 0; f7 = 0; f8 = 0; f9 = 0;
end
else
begin
{================== 1-pole ==================}
if poleCount = 1 then
begin
f1 = m0Map[1]*power(alpha,1)*source
+ m1Map[1]*power(beta_,1)*f1[1];
f = f1;
end;

{================== 2-pole ==================}
{================== 3-pole ==================}
{================== 4-pole ==================}
{================== 5-pole ==================}
{================== 6-pole ==================}

if poleCount = 6 then
begin
f6 = m0Map[6]*power(alpha,6)*source
+ m1Map[6]*power(beta_,1)*f6[1]
- m2Map[6]*power(beta_,2)*f6[2]
+ m3Map[6]*power(beta_,3)*f6[3]
- m4Map[6]*power(beta_,4)*f6[4]
+ m5Map[6]*power(beta_,5)*f6[5]
- m6Map[6]*power(beta_,6)*f6[6];
f = f6;
end;
Code showing Pascal's Triangle and 6 pole smoothing

There is redundant code here, but I included it to make it readable for most of my EasyLanguage/PowerLanguage programmers.   The math is very simple when you break it down.  If we choose Pole #6 all we do is:

beta_ = (1 – Cosine(360 / per)) / (Power(1.414, 2 / numPoles) – 1);
alpha = -beta_ + SquareRoot(beta_ * beta_ + 2 * beta);

  1. 1 x alpha^6 x close
  2. plus 6 x beta^1 x prior f6[1]
  3. minus 15 x beta^2 x f6[2]
  4. plus 20 x beta^3 x f6[3]
  5. minus 15 x beta^4 x f6[4]
  6. plus 6 x beta^5 x f6[5]
  7. minus 1 x beta^6 x f6[6]

EasyLanguage’s trig calls expect degrees, while most other languages want radians. That’s why the code feeds Cosine(360 / per)—the 360 converts the cycle length into degrees before taking the cosine.

I also lift the constant √2 (1.414…) by squaring it with Power(1.414, 2)and use the same Power routine for roots—for example, the cube root of x is simply Power(x, 1 / 3).

I placed BinomialFilterN inside a second routine called GaussianChannelFunc—a classic wrapper.

Why bother with the extra layer?

Reason What the wrapper does before/after calling BinomialFilterN
Housekeeping • Converts the user-friendly period (per) into the α required by the core filter.• Optional one-bar “look-ahead” to cancel lag.• Runs the filter twice (price and TrueRange).
Packaging • Builds upper, centre, and lower bands from the two filtered series.• Returns all three numbers through one array argument.
Extensibility Tomorrow you can tweak the channel logic—different volatility measure, ATR multiplier, extra smoothing—without touching the filter math. The heavy-duty code stays in BinomialFilterN; the wrapper simply preps inputs and formats outputs.

Think of it as a coffee machine:

  • BinomialFilterN is the brewing unit—hot water + grounds in, espresso out, and it never changes.
  • GaussianChannelFunc is the barista: grinds the beans, measures the water, adds milk and foam, then hands you the finished latte. If you want vanilla syrup tomorrow, you ask the barista; you don’t redesign the boiler.

By splitting the work this way, each piece stays focused, easier to test, and simple to extend later.

The wrapper has to hand back three numbers—upper band, centre line, and lower band—yet an EasyLanguage function can formally return only one. The standard workaround is to pass the additional outputs by reference:

// upper are caught by the receiving function as type numericRef
// can get unweilding quickly
value1 = GaussianChannelFunc(src, periods, numOfPoles,compLag, smooth, upper, mid, lower);
Code Snippet - Calling the function with three containers for the levels

That works, but the call quickly turns into a mile-long argument list.
Instead, I bundle those three outputs into a tiny array and pass the array’s address once:


array:GaussianChanArray[3](0); // remember we can use [0]

value1 = GaussianChannelFunc(src, periods, numOfPoles, compLag, smooth,GaussianChanArray);

upperChannel = GaussianChanArray[0];
centreLine = GaussianChanArray[1];
lowerChannel = GaussianChanArray[2];
Using a simple array as container for return values

This wasn’t that impressive, but what if your function needed to return five values?

Now onto the indicator and the strategy

From the outside this looks like a quick coding job—but getting here was a series of detours. I let ChatGPT drive and only nudged when it went off-track. Here are the dead-ends we hit before the indicator finally behaved:

  • Pine-script blind spot
    • ChatGPT didn’t recognise TradingView syntax, so its first translation attempts were gibberish.
  • “Mystery math” instead of binomial weights
    • After I mentioned Ehlers and Gaussian smoothing, the model invented a dynamic weighting scheme rather than using the fixed Pascal-triangle numbers the original script relies on.
  • Arrays everywhere
    • It kept insisting on circular buffers because it didn’t realise EasyLanguage variables already remember their own history via [1], [2], etc.
  • Wrong memory reference
    • Even after the array issue was fixed, the code updated each pole with raw price / range instead of the pole’s own prior output.
  • Unwanted filter cascade
    • ChatGPT then tried a true “cascade” (pole 2 fed by pole 1, pole 3 by pole 2). Donovan’s version calculates every pole independently—so we had to unwind that and start over.
  • Sign-flip confusion
    • It forgot the plus/minus pattern that keeps the Gaussian zero-lagged, producing a line that trailed price by several bars.

Each course-correction tightened the spec until the model finally spit out the straight, hard-coded-coefficients version you see now.

After all that was it worth the time and analysis?

  • A stop version where you buy at and sell short at the upper and lower levels worked best.  Liquidating at the midlevel on a stop was also incorporated.
  • Using a large profit objective and a relatively small stop loss seemed to work best.
  • Intermediate period length and utilizing 8 poles produced the best results.

ELD for TradeStation and Multicharts

GAUSSIANSTUDY

Text files of functions, indicator and strategies

GaussianChannelFunc Function

Head to Head with Bollinger Bands

Test results across 22 commodities for the past 25 years.

Gaussian Channel:  Optimizing the period and ATR multiplier with 8 poles:

Simple Bollinger Band: optimizing moving average length and number of standard deviations

Conclusion (fight-card style)

Decision on the first bout:
The Rolling heavy-hitter—Bollinger Bands—lands the cleaner power shots and takes the scorecards in our 22-commodity test.

But don’t call it a knockout just yet.
The Recursive counter-puncher—the Gaussian Channel—fights with an extra weapon: pole count. Adjusting those poles changes how tightly the centre line hugs price, and we’ve only sparred with one setting.

Next round:
Tune the poles, test different time-frames, and pit the fighters on equities and FX. The smarter, jabbing Gaussian might steal the rematch once its footwork is dialed in.

 

EasyLanguage Version Control and Back Up

I Can’t Believe I Just Lost All My Studies!

“How can I not restore it? I back up my files every week!” Have you found yourself in this same predicament before.  Somehow, I’ve lost my code more times than I care to admit. The TradeStation and MultiCharts paradigm of requiring us to store our precious strategies and indicators in a proprietary, non–text format has its advantages, but to me the drawbacks far outweigh any benefits.

  • Pros of a proprietary library: Seamless integration, single-click compile/run, built-in (if limited) version history, encryption, and straightforward workspace management.

  • Cons: Opaque blobs that aren’t easily diffed, harder to back up in granular increments, potential single point of failure, and extra steps when migrating to other tools.

Git is overkill for a single developer of an EasyLanguage Study.

Most programmers who work in a domain‐specific language like EasyLanguage simply don’t “get” Git. If you’re unfamiliar with Git, here’s a quick definition:

Git is the version‐control system created by Linus Torvalds—yes, the same Linus Torvalds who gave us Linux and turned down a huge payday to release it as open source. Git lets multiple developers track changes, revert to earlier versions, and collaborate seamlessly on code without stepping on each other’s toes.

Git records changes to a project by taking snapshots (commits) of its files and storing them in a distributed repository, so developers can branch and merge independently before synchronizing updates. It’s often hard to grasp because the concepts of branching, merging, and distributed workflows differ from linear, centralized versioning models and require a shift in thinking and terminology.

Fun fact: ChatGPT did a back-of-the-envelope calculation suggesting that, had Linus charged for Linux, his net worth could be as high as $50 billion. In reality, he’s a salaried employee at the Linux Foundation with a net worth closer to $10 million—proof that the open-source model can be wildly generous for everyone except the original author.

What is an EasyLanguage programmer to do?

One straightforward (but labor-intensive) method is to copy your EasyLanguage or PowerLanguage code into a plain-text editor like Notepad and save it in a well-named folder—either locally or in the cloud. That gives you a basic text-based backup. If you want to track versions, you can simply take a snapshot every time you make a change and append a version number to the filename (e.g., MyStrategy_v1.0.txt, MyStrategy_v1.1.txt, etc.). For most solo EasyLanguage developers, this ad-hoc versioning is sufficient, since you’re typically the only person editing the code. However, in the unlikelihood that you do collaborate with others, it becomes cumbersome to merge updates or see exactly what changed between versions. In this scenario, learning GIT would be worthwhile.

Because EasyLanguage developers typically work solo (to protect their proprietary code), most don’t bother with Git. And let’s face it—many of us get lazy about backups and versioning. You create a strategy that works, start tweaking it, and before you know it you can’t recall how to revert to the original. Who else has been down that road?

A few years ago, I developed a simple macro with AutoIt where I would hit <CTRL> F9 and all the code in my current editor window was select and copied and saved to a new text file.

Recently I modified the macro to add a version suffix to the filename if the filename already exits.  If you hit save and the lates version is _v002.txt, then the macro will save it as _v003.txt

Back up – Checked!  Version control – Checked!  Anything else?

I do use Git for my multi‐file projects—it’s fantastic for instantly showing me what changed between commits when something breaks. I wish I had that same “see the diff” workflow for my EasyLanguage scripts. Thanks to WinMerge, I actually can: just select two versions of my script, and it highlights every added, removed, or modified line. WinMerge is free to use (they do ask for a small donation if you find it valuable), and now I can conveniently compare any two snapshots of my code—just like I would with Git.

The differences will be highlighted in the document maps on the left side and then also directly in the code.

Take a look at this video to see my workflow.

What good are these tools if you don’t use them?

I tried to make the task of backing up and version control as simple as clicking <ctrl> F9.  Now it is up to you to do it.  I promise the more you do it, the less of hassle it will become, and I can almost guarantee you will thank me in the future.  Trust me – this is as easy as GIT.  However, setting up GIT is not a cakewalk.

Here all you need to do is download the two software and following the instructions in getting the following script compiled to an .exe.  Trust me it is much easier than it looks.  I am providing this information so that I don’t have to provide an .EXE and all of the headaches involved with downloading it.  However, if you are cool with downloading an .EXE, then shoot me an email and I will provide a link.

In few days I will publish some results of the work of my “Snap-Back” strategy.

This is the AutoIt script you will need to copy after you download AutoIt.  Don’t worry you don’t need to understand it.  After the code listing, I give step by step instructions on how to turn the script into an executable.

#include <Clipboard.au3>
#include <File.au3>
#include <MsgBoxConstants.au3>
#include <StringConstants.au3>

; Set hotkeys:
HotKeySet("^{F9}", "CaptureActiveWindow") ; F9 → capture text
HotKeySet("^{F12}", "TerminateScript") ; F12 → exit script

; Keep the script running
While 1
Sleep(100)
WEnd

Func CaptureActiveWindow()
; 1) Get full active window title
Local $activeTitle = WinGetTitle("[ACTIVE]")

; 2) Extract just the tab name (text after the last " - ")
Local $tabName = StringRegExpReplace($activeTitle, '^.* - (.+)$', '\1')
If $tabName = $activeTitle Then
; no dash found, use full title
$tabName = $activeTitle
EndIf

; 3) Remove illegal filename characters
Local $cleanTitle = StringRegExpReplace($tabName, '[\\\/:\*\?"<>\|]', "")
If $cleanTitle = "" Then $cleanTitle = "CapturedText"

; 4) Build default filename
Local $defaultFileName = $cleanTitle & ".txt"

; 5) Activate window and copy its contents
WinActivate($activeTitle)
Sleep(200)
Send("^a") ; Select all
Sleep(200)
Send("^c") ; Copy
Sleep(200)

; 6) Retrieve clipboard text
Local $text = _ClipBoard_GetData()
If @error Then
MsgBox($MB_ICONERROR, "Error", "Failed to get clipboard data.")
Return
EndIf

; 7) Ask user where to save, defaulting to our cleaned tab name
Local $savePath = FileSaveDialog( _
"Save Captured Text", _
@ScriptDir, _
"Text Files (*.txt)", _
2, _
$defaultFileName _
)
If $savePath = "" Then
MsgBox($MB_ICONINFORMATION, "Cancelled", "Save operation cancelled.")
Return
EndIf

; 8) Simple version control: if the file exists, append _v001, _v002, ...
Local $base = StringTrimRight($savePath, 4) ; remove .txt
Local $ext = ".txt"
Local $i = 1
Local $dest = $savePath
While FileExists($dest)
$dest = $base & "_v" & StringFormat("%03d", $i) & $ext
$i += 1
WEnd

; 9) Write the text to the versioned filename
Local $fileHandle = FileOpen($dest, 2) ; write mode
If $fileHandle = -1 Then
MsgBox($MB_ICONERROR, "Error", "Failed to open file for writing.")
Return
EndIf
FileWrite($fileHandle, $text)
FileClose($fileHandle)

MsgBox($MB_ICONINFORMATION, "Success", "Text saved successfully to:" & @CRLF & $dest)
EndFunc

Func TerminateScript()
Exit 0
EndFunc
Auto It Script - Set it and Forget it

Step 1: Download and Install AutoIt (plus SciTE-Lite)

  1. Go to the AutoIt website: https://www.autoitscript.com/site/autoit/downloads/
  2. Under “AutoIt Full Installation,” click Download.
  3. Run the downloaded installer (AutoIt3.exe) and follow the prompts:
  • Accept the license agreement.
  • Leave all default components checked (this installs both AutoIt and SciTE-Lite).
  • Finish the installation.

After this, you’ll have:

  • AutoIt (the compiler/interpreter) in your Program Files.
  • SciTE-Lite (a lightweight code editor preconfigured for AutoIt) installed, usually at
 C:\Program Files (x86)\AutoIt3\SciTE\

Step 2: Open SciTE-Lite and Create a New Script

  1. Launch SciTE-Lite:
  • Windows Start Menu → All Programs → AutoIt v3 → SciTE-Lite (AutoIt)
  • Or double-click the SciTE-Lite shortcut if one was placed on your desktop.
  • In SciTE-Lite, go to File → New (or press Ctrl+N). You’ll see a blank editor window.

Step 3: Copy Your Script Code from the Website

  1. Select all of the code (click inside the code block above, then press Ctrl+A) and copy (Ctrl+C).
  2. Return to the blank SciTE-Lite window and paste (Ctrl+V) the code into it.

Step 4: Save the Script as EzLangToText.au3

  1. In SciTE-Lite, choose File → Save As… (or press Ctrl+Shift+S).
  2. In the “Save As” dialog:
  • Navigate to Documents\AutoIt Scripts\ if it exists or stay in the default folder.
  • For “File name,” type:
  • EzLangToText.au3
  • Ensure “Save as type” is set to AutoIt v3 Source (*.au3).
  • Click Save.

Now SciTE-Lite knows this is an AutoIt script.


Step 5: Compile the Script to an .exe

  1. Make sure EzLangToText.au3 is the active tab in SciTE-Lite.

  2. Press F7 (or go to Tools → Compile).

  • SciTE-Lite runs AutoIt’s compiler (Aut2Exe) behind the scenes.
  • In the output pane at the bottom, you’ll see messages like “Compiling…” and finally “Compiled successfully.”
  • When the compile finishes, you’ll find EzLangToText.exe in the same folder as your .au3 file.

Step 6: Run the Resulting EXE

  • You can now double-click EzLangToText.exe to run it on any Windows PC (no AutoIt installation needed)


Some EasyLanguage Functions Are Really “Classy”

The Series Function is very special

When a function accesses a previously stored value of one of its own variables, it essentially becomes a “series” function. Few programming languages offer this convenience out of the box. The ability to automatically remember a function’s internal state from one bar (or time step) to the next is known as state retention. In languages like Python, achieving this typically requires using a class structure. In Module #2 of my Easing into EasyLanguage Academy, I explained why EasyLanguage isn’t as simple as its name implies—yet this feature shows how its developers aimed to simplify otherwise complex tasks.

If you’ve ever worked with functions with memory that exchange data using a numericRef input, you’ve essentially been using a pseudo-class—a form of object-oriented programming in its own right. EasyLanguage includes a robust object-oriented library (with excellent resources by Sunny Harris and Sam Tennis – buy their book on Amazon), yet you’re confined to its built-in functionality since it doesn’t yet support user-defined class structures. Nonetheless, the series functionality combined with data passing brings you remarkably close to a true object-oriented approach—and the best part is, you might not even realize it.

Example of a Series Function

I was recently working on the Trend Strength indicator/function and have been mulling this post over for some time, so I thought this would be a good time to write about it.  The following indicator to function conversion will create a function of type series (a function with a memory.)  The name series is very appropriate in that this type of function runs along with the time series of the chart.  It must do this so it can reference prior bar values.

You can ensure a function is treated as a series function in two ways:

  1. Using a Prior Value:
    When you reference a previous value within the function, EasyLanguage automatically recognizes the need to remember past data and treats the function as a series function.

  2. Setting the Series Property:
    Alternatively, you can explicitly set the function’s property to “series” via a dialog. This instructs EasyLanguage to handle the function as a series function, ensuring that state is maintained across bars.

    Manually Set the Function to type Series

Importantly, regardless of the function’s name or even if it’s called within control structures (like an if construct), a series function is evaluated on every bar. This guarantees that the historical data is consistently updated and maintained, which is essential for accurate time series analysis.

Converting an indicator to a function

You can find a wide variety of EasyLanguage indicators online, though many are available solely as indicators. This is fine if you’re only interested in plotting the values. However, if you want to incorporate an indicator into a trading strategy, you’ll need to convert it into a function. For calculation-intensive indicators, it’s best to follow a standard prototype: use inputs for interfacing, perform calculations via function calls, and apply the appropriate plotting mechanisms. By adhering to this development protocol, your indicator functions can be reused across different analysis studies, enhancing encapsulation and modularity. Fortunately, converting an indicator’s calculations into a function is a relatively straightforward process. Here is indicator that I found somewhere.

Inputs: 
ShortLength(13), // Shorter EMA length
LongLength(25), // Longer EMA length
SignalSmoothing(7); // Smoothing for signal line
Vars:
DoubleSmoothedPC(0),
DoubleSmoothedAbsPC(0),
TSIValue(0),
SignalLine(0);
// Price Change (PC)
Value1 = Close - Close[1];
// First Smoothing (EMA of PC and |PC|)
Value2 = XAverage(Value1, LongLength);
Value3 = XAverage(AbsValue(Value1), LongLength);
// Second Smoothing (EMA of First Smoothed Values)
DoubleSmoothedPC = XAverage(Value2, ShortLength);
DoubleSmoothedAbsPC = XAverage(Value3, ShortLength);
// Compute TSI
If DoubleSmoothedAbsPC <> 0 Then
TSIValue = 100 * (DoubleSmoothedPC / DoubleSmoothedAbsPC);

// Compute Signal Line
SignalLine = XAverage(TSIValue, SignalSmoothing);
// Plot the TSI and Signal Line
Plot1(TSIValue, "TSI");
Plot2(SignalLine, "Signal");
TSI via Web

Now we can functionize it.

Below is an example of how you might convert an indicator into a function called TrendStrengthIndex. Notice that the first change is to replace any hard-coded numbers in the indicator’s inputs with parameters declared as numericSimple (or numericSeries where appropriate). This allows the function to accept dynamic values when called.  Not to give anything away, but you can also declare variables as numericRef, numericSeries, numericArrayRef, string, stringRef, and stringArrayRef.  Let’s not worry about these types right now.

inputs: 
ShortLength(numericSimple), // Shorter EMA length
LongLength(numericSimple), // Longer EMA length
SignalSmoothing(numericSimple); // Smoothing for signal line
Inputs must be changed to function nomenclature

Below is an example function conversion for the TrendStrengthIndex indicator.  The plot statements have been commented out since—rather than plotting—the function now passes back the calculated value to the calling program.

Vars:
DoubleSmoothedPC(0),
DoubleSmoothedAbsPC(0),
TSIValue(0),
SignalLine(0);
// Price Change (PC)
Value1 = Close - Close[1];
// First Smoothing (EMA of PC and |PC|)
Value2 = XAverage(Value1, LongLength);
Value3 = XAverage(AbsValue(Value1), LongLength);
// Second Smoothing (EMA of First Smoothed Values)
DoubleSmoothedPC = XAverage(Value2, ShortLength);
DoubleSmoothedAbsPC = XAverage(Value3, ShortLength);
// Compute TSI
If DoubleSmoothedAbsPC <> 0 Then
TSIValue = 100 * (DoubleSmoothedPC / DoubleSmoothedAbsPC);

// Compute Signal Line
SignalLine = XAverage(TSIValue, SignalSmoothing);
// Plot the TSI and Signal Line
//Plot1(TSIValue, "TSI"); commented out
//Plot2(SignalLine, "Signal"); commented out
TrendSTrengthIndex = TSIValue;
Functionalize It!

This works great if we just want the TrendStrengthIndex, but this indicator, like many others has a signal line.  The signal line for such indicators is usually a smoothed version of the main calculation.  Now you could do this smoothing outside the function, but wouldn’t it be easier if we did everything inside of the function?

Oh no!  I need to pass more than one value back!

If we just wanted to pass back TSIValue all we need to do is assign the name of the function to this value.

Passing values by reference

We can adjust the function to return multiple values by defining some of the inputs as numericRef. Essentially, when you pass a variable as a numericRef, you’re actually handing over its memory address—okay, let’s get nerdy for a moment! This means that when the function updates the value at that address, the calling routine immediately sees the change, giving the variable a kind of quasi-global behavior. Without numericRef, any modifications made inside the function stay local and never propagate back to the caller.  Not only is the function communicating with the calling strategy or indicator it is also remember its own stuff for future use.  Take a look at this code.

inputs: 
ShortLength(numericSimple), // Shorter EMA length
LongLength(numericSimple), // Longer EMA length
SignalSmoothing(numericSimple), // Smoothing for signal line

TrendStrength.index(numericRef), // Output
TrendStrength.signal(numericRef); //OutPut
Vars:
DoubleSmoothedPC(0),
DoubleSmoothedAbsPC(0),
SignalLine(0);

// Force series FUNCTION BEHAVIOR
Value4 = Value3[1];
// Price Change (PC)
Value1 = Close - Close[1];
// First Smoothing (EMA of PC and |PC|)
Value2 = XAverage(Value1, LongLength);
Value3 = XAverage(AbsValue(Value1), LongLength);

// Second Smoothing (EMA of First Smoothed Values)
DoubleSmoothedPC = XAverage(Value2, ShortLength);
DoubleSmoothedAbsPC = XAverage(Value3, ShortLength);
// Compute TSI
If DoubleSmoothedAbsPC <> 0 Then
TrendStrength.index = 100 * (DoubleSmoothedPC / DoubleSmoothedAbsPC);

// Compute Signal Line
TrendStrength.signal = XAverage(TrendStrength.index, SignalSmoothing);

TrendStrengthIndex = 1;
Is this a function or is it a class?

There is a lot going on here.  Since we are storing our calculations in the two numericRef inputs, TrendStrength.index and TrendStrength.signal the function name can simply be assigned the number 1.  You only need to do this because the function needs to be assigned something, or you will get a syntax error.  Since we are talking objects, I think it would be appropriate to introduce “dot notation.”  When programming with objects you access the class members and methods buy using a dot.  If you have an exponential moving average class in python you would access the variables and functions (methods) in the class like this.

class ExponentialMovingAverage:
# Class-level defaults serve as initial values.
alpha = 0.2 # Default smoothing factor
ema = None # EMA starts as None

def update(self, price):
"""
Update the EMA with a new price.

Parameters:
price (float): The new price to incorporate.

Returns:
float: The updated EMA value.
"""
# If ema is None, this is the first update
if self.ema is None:
self.ema = price
else:
self.ema = self.alpha * price + (1 - self.alpha) * self.ema
return self.ema

# Create an instance of the class.
ema_calculator = ExponentialMovingAverage()

# Dot notation to access the class attribute.
print("Alpha value:", ema_calculator.alpha)

# Dot notation to access the EMA attribute before any updates.
print("Initial EMA (should be None):", ema_calculator.ema)

# Dot notation to call the update method.
ema_value = ema_calculator.update(10)
print("EMA after update with 10:", ema_value)
Using dot notation to extract values from a class

Since you are using EasyLanguage and a series function, you don’t have to deal with something like this.  On the surface this looks a little gross but coming from a programming background this is quite eloquent.  I only show this to demonstrate dot notation.  In an attempt to mimic dot notation in the EasyLanguage function, I simply add a period ” , ” to the input variable names that will return the numbers we need to plot.  Take a look at the nomenclature I am using.

    TrendStrength.index(numericRef), // Output
TrendStrength.signal(numericRef); //OutPut
Function Name +

I am using the function name a ” . ” and an appropriate variable name.  This is not necessary.  Historically, input names that were modified within a function were preceded by the letter “O.”  In this example, Oindex and Osignal.  This represented “output.”  Remember these naming conventions are all up to you.  Here is the new indicator using our EasyLanguage “Classy” function and our pseudo dot notation nomenclature.

//Utilize the TrendStrengthIndex classsy function

inputs: shortLength1(9), longLength1(19), signalSmoothing1(9);
inputs: shortLength2(19), longLength2(39), signalSmoothing2(13);

vars: trendStrength1.index(0), trendStrength1.signal(0);
vars: trendStrength2.index(0), trendStrength2.signal(0);
value1 = TrendStrengthIndex(shortLength1,longLength1,signalSmoothing1,trendStrength1.index,trendStrength1.signal);
value2 = TrendStrengthIndex(shortLength2,longLength2,signalSmoothing2,trendStrength2.index,trendStrength2.signal);


plot1(trendStrength1.index,"TS-Index-1");
plot2(trendStrength1.signal,"TS-Signal-1");

plot3(trendStrength2.index,"TS-Index-2");
plot4(trendStrength2.signal,"TS-Signal-2");
Take a look at how we access the information we need from the function calls.

You might be surprised to learn that you may have been doing object-oriented programming all along without realizing it. Do you prefer the clarity of dot notation for accessing function output, or would you rather stick with a notation that uses a big “O” combined with the input name to represent functions with multiple outputs? Also, notice how each function call behaves like a new instance—the internal values remain discrete, meaning that each call remembers its own state independently.  In other words, each function call remembers its own stuff.

Two distinct function values from the same function – called twice on the same bar.

RMI Trend Sniper in EasyLanguage

RMI Trend Sniper Indicator – Described on ProRealTime in PR Code.

RMI Trend Sniper Indicator – Indicators – ProRealTime

RMI Trend Sniper: An Innovative Trading Indicator

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.

//PRC_RMI Trend Sniper
//version = 0
//26.03.24
//Iván González @ www.prorealcode.com
//Sharing ProRealTime knowledge

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:

//Iván González @ www.prorealcode.com
//Sharing ProRealTime knowledge
 


inputs:Length(14),//RMI Length
pmom(66),//Positive above
nmom(30);//Negative below

//-----RSI and MFI calculation-----------------------------//

vars: alpha(0),src1(0),src2(0),up(0),down(0),myrsi(0),seed(True);

alpha = 1/length;
//-----Up
src1 = maxList(close-close[1],0);
if seed then
up = average(src1,length)
else
up = alpha*src1 + (1-alpha)*up[1];

//-----Down
src2 = -1 * minList(close-close[1],0);
if seed then
down = average(src2,length)
else
down = alpha*src2 + (1-alpha)*down[1];

seed = False;

//-----Rsi
if down = 0 then
myrsi = 100
else if up = 0 then
myrsi = 0
else
myrsi = 100 - (100/(1+up/down));
vars: mfiVal(0),rsimfi(0),bpmom(False),bnmom(False),positive(0),negative(0),ema(0);
//-----MFI
mfiVal = moneyFlow(length);
//-----RsiMfi
rsimfi = (myrsi+mfiVal)/2;
//----------------------------------------------------------//
//-----Long Short Conditions--------------------------------//
ema = average(c,5);

bpmom = rsimfi[1] < pmom and rsimfi > pmom and rsimfi > nmom and (ema-ema[1])>0;
bnmom = rsimfi<nmom and (ema-ema[1])<0;

if bpmom then
begin
positive = 1;
negative = 0;
end
else if bnmom then
begin
positive = 0;
negative = 1;
end;

//----------------------------------------------------------//
//------Calculate RWMA--------------------------------------//
vars: band(0),band20(0),barRange(0),weight(0),sum(0),twVal(0),rwma(0);

band = minList(avgtruerange(30)*0.3,close*(0.3/100));
band20 = band[20]/2*8;
barRange = high-low;

weight = BarRange/summation(BarRange,20);
sum = summation(close*weight,20);
twVal = summation(weight,20);
rwma = sum/twVal;

vars: r(0),g(0),b(0);

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.

Indicator Settings.

Happy New Year!