Major update: this project has been forked into a new one — De-Fi Automated Trading. See the update log at the bottom of this page for the full story.
01Motivation: Taking the Human Out of the Trade
Since I was a child I've been fascinated by money markets and the unseen forces that drive price movements in securities. After reading many books on the nuances of markets, social psychology, risk management, and technical analysis — and after years of manual trading with no success — I took a different route entirely.
Speculative trading carries many challenges, and one of the biggest is the inevitable set of emotions and biases that surface while trading. Humans react irrationally when faced with the fear of losing; that fear subconsciously distorts how we perceive the information in front of us and causes us to act against apparent logic. So I developed a trading system that pairs quantitative indicators and parameters with fully autonomous algorithmic scripts capable of executing, monitoring, editing, and cancelling orders. The strategy runs on pre-defined parameters with zero human interaction — leaving no room for emotion to interfere.
02The System at a Glance
To derive the data the system needs, I built an Excel model that calculates the most probabilistic prices a security may reach after an entry trigger, computed over the asset's historical price data. The algorithmic trading script pulls its entry and exit logic from the parameters this model produces. The sample data used throughout this page comes from a derivative issued on Binance's Perpetual Futures market over the course of 2.5 years.
Data collection works like this: over an asset's historical price history, hypothetical entries are recorded wherever a quantitative entry parameter (such as a support/resistance cross) would have triggered. After each entry price, I collect the maximum high and maximum low the price reaches 30 minutes, 6 hours, 12 hours, and 24 hours afterward — then calculate the percentage change from the entry price for each time interval.
03Distribution Tables
Once enough price data is collected, a frequency distribution table highlights the key areas price reaches within each time interval, with separate distributions for long and short positions. A clear pattern emerges in the sample data: as time elapses, the percentage change deviates further from the entry price — the time-varying volatility of an open trade inherently increases the longer it stays open. Lines are drawn on the tables to show the consistent slope of increasing variance across the time intervals, and the levels circled in red become the take-profit (TP) and stop-loss (SL) candidates used in the later steps.
04Probability Tables
In combination with the frequency distributions, the probability tables provide the data needed to evaluate probabilistic outcomes for each TP and SL level in every time interval. In theory, we want to maximize the probability of hitting our TP levels and minimize the probability of hitting our SL levels — while maintaining a viable risk-to-reward ratio.
For example, we could choose an SL between −6.0% and −6.5% for long positions, where the cumulative probability is only around 10% — but it takes just a handful of losers to blow an account. A low probability is still a possible outcome. In the tables, the "I" labels represent the independent probability of price reaching a specific price range, while the "C" labels represent the cumulative probability of price being at or below that range for longs (and vice versa for shorts). The red circles mark the TP and SL levels carried into the next step.
05Parameter Inputs
The TP and SL levels derived from the previous steps are entered into the input section of the model for both the long and short strategy systems (circled in red below). At the bottom of each input panel you'll also find fields for starting capital, leverage amount, funding rate (fees), spreads, commissions, and maximum position size per trade. These inputs allow the model to calculate a far more accurate round-trip trade outcome and portfolio forecast.
06The Simulation Engine
With the price data and parameter inputs entered, the simulation can determine the outcome of each "trade": P = profit/win, L = loss, D = draw (neither TP nor SL triggered). When a draw occurs, the simulation moves to the next time interval and re-checks whether the percentage change surpasses the TP or SL inputs. U = unknown, meaning both the TP and SL levels were surpassed within the same time interval — the data in the model simply can't determine which was hit first. The results section separates unknown outcomes from known ones, and can also calculate all 24-hour draws and unknowns as losses (at the 24-hour SL level) as a worst-case scenario.
Under the hood it's Boolean logic. The cells check whether the high exceeds the TP input and whether the low stays above the SL input — returning a 1 if true and a 0 if not. The same pattern, with slightly different logic and formulas, drives the P, L, D, and U fields to ensure the correct outcomes are calculated. The outcome sums must balance against the total trade count from the price input tables, which acts as a built-in check. Longer nested IF statements then determine which outcome occurred in each row (which cell equals 1) and apply the appropriate TP/SL interval calculation, using the input-section values to produce the most accurate balance change and equity curve.
07Results & Optimization
The final results reveal whether the trading system has any merit in terms of sustainability and profitability — and by testing various TP/SL levels, the parameters can be optimized against the historical data. The risk-to-reward (RR) ratio averages all TP and SL levels into a single overall figure, color-coded by the level of risk relative to potential gain: red when risking more than the potential reward, yellow when roughly balanced, and green for the ideal setup of risking less than the potential gain.
These numbers are meaningless on their own, though — they have to be read against the win/loss ratio. I won't go deep into the relationship between win/loss and RR ratios here, but I want to emphasize how important analyzing these metrics together is before committing real capital to any strategy:
Worked example — 100 sample trades. Say we win 30% of trades (30 winners, 70 losers) risking 1x on the SL to gain 2x on the TP — an RR ratio of 0.5. The winners produce 30 × 2 = 60, the losers cost 70 × 1 = 70, and the net is 60 − 70 = −10. Even with a very favorable RR ratio (0.5), the low win/loss ratio (3:7) means losers outpace winners — on average, a −10% loss over 100 trades with a 1% SL and 2% TP.
This page isn't meant to be a guide or a complete explanation of the model, the trading system, its theories, algorithms, APIs, or calculations — nor how the price data was derived. That would be far outside the scope of a project write-up. The goal here is to briefly demonstrate the model's function and capabilities. For the full picture, the cover sheet section below goes much deeper into the trading system, theories, algorithmic functions, and pipeline workflow.
08Want Access to the File?
Algorithmic Trading Model — v2.03
Click the button to access the available files for download.
Note: a password is required — please contact me if you need one.
09Active Development
Updates actively being implemented and researched:
Monte Carlo Simulation
I'm implementing a Monte Carlo (MC) simulation page that can calculate thousands of portfolio outcomes from random variables and the model's parameter inputs — verifying that the parameters have a probable chance of long-term success and a viable RR ratio. Instead of relying on the model alone, an MC simulation run in tandem helps ensure the system isn't overfitted and the data isn't skewed toward a biased representation. It can surface problems in the system before capital is committed, rather than discovering them only after a stretch of unprofitable trades.
Advanced Booleans
I'm researching more sophisticated Boolean logic to push the limits of what Excel can do. Specifically, I want to compare the current model (immediate entries on support/resistance line crosses) against entries based on retracement levels. Prices tend to retrace after crossing critical levels, and that price discovery can produce wild swings. Immediate entries risk overpaying when price retraces shortly after the trigger, and they increase the likelihood of hitting the SL rather than entering at a better retracement price. On the other hand, retracement orders risk missing fills entirely when price has enough momentum to run without returning. I'd like to simulate both entry styles and compare their performance returns directly.
Dynamic Spread %
The spread percentage is currently a fixed average, but in reality it varies greatly with order size, current liquidity, and volume. I'd like to implement a value that scales the spread with order size, since larger orders have a greater impact on the order book — and depending on the book's liquidity, the spread can significantly affect the accuracy of the forecasted balance change. Eventually, live volume and order book liquidity could feed in as additional constants for even more accurate outcomes.
Correlation Analysis
Once I've collected enough data across separate securities, I want to assess the correlations between assets within the model using various statistical techniques. Understanding those correlations gives a more accurate picture of specific sectors and helps manage portfolio risk across multiple securities — some assets act as leading indicators for other, "lagging" ones, which opens up further strategies to develop into the trading system.
Data Collection Automation
I'm researching tools and scripts capable of scanning, deriving, and entering price data from TradingView automatically — the entry price plus the 30m/6h/12h/24h max highs and lows for each entry (nine inputs in total). This process is currently manual and extremely time-consuming, which is why only a handful of securities are analyzed and traded by the algorithm today. Eventually I'd like every security on an exchange analyzed, filtered by performance return and RR ratio, and implemented into the algorithm to trade 24/7 whenever parameters trigger. I'm currently looking into Python libraries to get this down to a few clicks.
Visual Analytics
I'm building a "Final Analysis & Conclusions" page that curates the most useful data, stats, and visual analytics for all the principal factors in the system. Given Excel's limitations, I may pull data through Tableau to generate deeper visual insights and integrate them back into the model's conclusions page.
10The Trading System in Depth
What follows is the full cover sheet — a more detailed explanation of the data collection process, the theories behind the system, and how the algorithm works end to end.
Thesis
The simulated models presented here calculate the most probabilistic outcomes based on parameters collected over the historical price data of a particular security. That data is then integrated into an automated algorithmic trading program through a couple of user-friendly interfaces. By removing human bias and emotion from entries and exits, we rely solely on the quantitative data — executed automatically on our behalf through pre-defined parameters and algorithmic logic. Entries are triggered by a price cross of the support and resistance slopes formed from the highs and lows of the current trend, explained in the "Technical Setups" section below.
Extracting excess returns from price movements is largely viewed as speculative — perhaps because most trades are executed and driven by human emotion instead of facts and logic. So where's the edge? Instead of arbitrarily choosing TP/SL levels like most traders do, we derive them from back-tested historical price data and statistical probabilities through a time-series interval model. The stats the model produces are unique, useful information that most market participants simply don't have.
A fifteen-year study of TSE day-trading performance found that aggregate net performance was largely negative: across a twelve-year stretch, the fraction of profitable day traders hovered consistently around 5%, while unprofitable traders accounted for 72–80% of total trading volume (Barber et al., 2017). My approach to that challenge is to find a systematic edge through quantifiable, statistical calculations — analyzing data better than my competitors to land in the net-positive minority. Knowing the probabilistic price levels a security tends to reach within a given time interval is invaluable information a trader can exploit.
Price action on time frames under an hour is driven almost entirely by technical forces, which creates opportunities a trader can take advantage of. Market inefficiencies constantly correct themselves, but there are moments when a security becomes overbought or oversold on technical indications. Support and resistance lines form areas of confluence — high-probability zones that produce high volatility and large price moves. When price crosses those S&R lines, it enters "discovery mode": how high will it go, how long will it stay, what kind of retracements will it make? We can never answer those questions with certainty, but we can calculate the most probable levels price will reach, based on historical scenarios of the same setup.
The system trades perpetual futures, giving access to both long and short positions with substantial liquidity and leverage. Perpetual futures are inherently different from the underlying assets: the contracts are derivatives, so the aggregate result of all market participants is always zero — for every gain there's an equal and opposite loss. Everyone is playing a zero-sum game for one reason: the potential to earn a net gain on capital at risk. Zero-sum games reward the player who understands market dynamics better than the majority of the money flow — which is precisely the edge this system is built to find.
Goals & Tasks
The overall goal of the model is to derive key data values to use as parameters in a trading system whose net return outperforms common indexes like the S&P 500 and the Dow Jones. The specific tasks integral to performance, consistency, risk management, and drawdown control are:
- Collect a large historical sample of price data for the asset in question (the more, the better): the trigger/entry price based on S&R levels, and the maximum high and maximum low reached 30 minutes, 6 hours, 12 hours, and 24 hours after the trigger — with each interval using the trigger price as its reference.
- Analyze the computed statistics — mean, median, and standard deviation — from the data pages (1.A & 1.B), and use them to set the take-profit and stop-loss inputs in the simulation model (pages 2.A & 2.B).
- Tune the TP & SL levels per interval to maximize winners, minimize losers, and maintain viable win/loss and RR ratios. Net change should be reasonably profitable, final inputs should sit within one standard deviation of the median (in the case of asymmetrical distributions), and the chosen levels must be probable (per the sim pages). Small corrections per interval keep the net results consistent with minimal variance, preventing overfitting.
- Validate the whole. A reasonable net positive return, viable win/loss and RR ratios, and consistent outcomes satisfy the requirements for a long-term winning strategy with proper risk management.
Technical Setups & Data Collection
Parallel channels based on support and resistance levels are the technical indicator that triggers entries for both long and short positions. Largely based on Alan Andrews' pitchfork channels, the indicator is tailored with a trigger line buffered ±1.5% from the upper and lower parallel trendlines. The full theory of why channels are used as the entry parameter is beyond the scope of this write-up, but detailed information on trendlines and channels is easy to find online.
- In Figure 1, arrow 1 points to the bottom line of the sloped channel — the main trendline. To prevent fake-outs (price reversing shortly after triggering an entry), the 1.5% buffered trigger line sits above the trendline for long entries.
- Circle 2 shows the buffer doing its job: price crossed the trendline but never reached the trigger line, so no order fired — potentially preventing a loss.
- Arrow 3 shows a confirmed entry: price breaks through the trigger line and successfully continues upward.
Note: the same rules apply to short positions, using the lower parallel line with a −1.5% buffer.
Figure 2 shows the process of collecting the data the models need. Three elements are recorded for each trade row on the long/short data pages: the entry price, the highs of each time interval (H.1–H.4), and the lows of each interval (L.1–L.4). For example, a long entry at 4:30 PM at $8.458 might record a 30-minute high of $8.522 (+0.76%) and low of $8.326 (−1.59%), a 6-hour high of $8.755 (+3.51%) and low of $8.307 (−1.82%), a 12-hour high of $8.814 (+4.21%) and low of $8.394 (−0.76%), and a 24-hour high of $8.656 (+2.34%) and low of $8.467 (+0.11%).
The trendline and trigger lines are dynamic — they move with future price changes. In Figure 4 (left), price crosses the trendline but fails to reach the trigger line, then drops back through the trendline in the opposite direction. When that happens, the trendline and trigger line must be updated to the new S&R levels. Figure 4 (right) shows the old trendline (dashed) and the new updated trendline and trigger line touching the newly created high.
Price crossing the resistance trigger line = long entry. Price crossing the support trigger line = short entry.
Simulation Model
By inputting the highs and lows from the 30-minute candle chart across the 30m/6h/12h/24h intervals into the long (1.A) and short (1.B) data pages, the model simulates how many winners and losers occur, the max gain/loss per trade, and the net value of those outcomes (the time intervals can be edited to suit the desired candle frame). The simulation classifies each trade using Boolean logic — checking whether price surpassed the TP or SL levels entered on pages 2.A & 2.B. If the high and low cross both the TP and SL within the same interval, the result is "unknown" and can be omitted from the calculations via the "No U + D" results column.
If neither level is surpassed, the trade is a "draw" for that interval — nothing happened — and the simulator checks the next interval, and so on through the 24-hour interval. A draw at 24 hours is calculated as a loss at the 24-hour SL percentage, as a worst-case scenario. This prevents the skew that would result from counting draws as winners; the "No U + D" header omits draws from being counted as losses for comparison.
Reading the short-trade examples in Figure 5:
- A −3.17% low within the 30-minute frame surpasses the −1.58% TP input, and the high never reaches the 2.40% SL — a winner.
- A 2.69% high within the 30-minute frame surpasses the 2.40% SL, and the low never reaches the −1.58% TP — a loser.
- Neither the high nor the low surpasses either level within the frame — a draw; the simulation repeats the process at 6h, 12h, and finally 24h.
- Both the high and low surpassed the TP and SL within the same interval — an unknown. Did price hit the TP or the SL first? There isn't enough information to say.
Algorithmic Logic
Using an automated trading platform with a proprietary scripting language, trades execute based on the code carried in triggered alerts. I won't go into detail on how the platform or code works — the point is to show how the script handles the model's parameters and executes orders when conditions trigger, as in the short-position example in Figure 6.
Integration & Execution
A couple of user-friendly interfaces fully automate the algorithm's logic using parameters from the model. TradingView provides the graphical interface for drawing trendlines and firing alerts when prices cross them; each alert carries a script message to a third-party server, Alertatron. Alertatron receives the alert, scans the commands, and forwards the requests — which can enter trades, create or edit open TP & SL orders, close orders, and more — to the exchange of choice. Binance is the supported exchange used here, with API keys and the required permissions connected to the Alertatron account. Figure 7 shows the flow from a TradingView alert, through Alertatron, to Binance.
Depending on the asset, there may be numerous trading pairs across tokens. High trading volume in both USDT and BUSD stablecoin pairs is a selection requirement for the algorithm: separating long and short positions into different stablecoin pairings allows reduce-only orders and prevents hedging on the same asset (holding both a long and short open simultaneously, where one would otherwise cancel out the other). With the pairs separated, the algorithm's logic never needs to handle hedged positions. Capital is split between the two stablecoins in proportion to the leverage power available on each:
Long positions = USDT | Short positions = BUSD e.g. ETH/USDT = 10x max ; ETH/BUSD = 5x max Total capital = $10,000 USDT balance = $3,330 × 10x = $33,300 purchase power BUSD balance = $6,670 × 5x = $33,350 purchase power
The total leveraged purchase power ends up balanced at roughly $33,300 on both sides.
Sources
- Fama, Eugene (1991). "Efficient Capital Markets II", Journal of Finance, 46, pp. 1575–617.
- Coghlan Capital (n.d.). Andrews Pitchfork.
- Barber, Lee, Liu, Odean, Zhang (2017). "Do Day Traders Rationally Learn About Their Ability?", University of California, Berkeley, pp. 2, 9–11, 12–15.
11Update Log
Regulatory Restrictions
Canada implemented sweeping regulations restricting many of the services this algorithm relied on. Binance — the centralized exchange at the core of the system — pulled out of Canada completely as of September 1, 2023, along with the majority of major exchanges. The exchanges still willing to serve Canadians operate under heavy restrictions that render my trading activity impossible: a $30,000 yearly purchase limit on crypto and a complete ban on leverage trading unless you hold $5M+ in assets (which I, unfortunately, do not). I sometimes trade more than $30,000 in a single week, and I need at least 5x leverage to trade position sizes that remain profitable after spreads and fees.
There are solutions — but the new approach is more involved: more expansive scripting logic and a self-hosted server to execute API requests. The upside is that the end result is safe from any future regulation. dYdX, a decentralized exchange beyond the reach of government enforcement, offers decent liquidity and an expansive API that fits the model's requirements. This work will likely be forked into a separate project; as a result, this project is marked Completed, and the new project will carry the new algorithm.
Forked: De-Fi Automated Trading
dYdX v4 has been released, offering a new ecosystem of decentralized trading with full self-custody wallet connections. Thanks to fully permissionless access, the exchange has no KYC limitations or minimum fund requirements, and the network is distributed across thousands of independently run nodes worldwide. Initial setup is complete and in testing — revitalizing this project, but as a fork, since the entire trading pipeline has changed: a remote server hosted in a crypto-friendly country, the repositories to handle the dYdX and TradingView APIs, and the dYdX wallet connected through the API on the remote server.