How to automate a trading strategy: from idea to code
- Automating a strategy means writing your rules so precisely that a computer can follow them: when to enter, where the stop and target go, how big, and when to stop for the day.
- The path has five steps: idea, exact rules, code, honest testing, then running it (first on paper, then live).
- Most of the work is in the first two steps. A rule you can't write down exactly isn't a rule a computer can follow, and often isn't one you follow either.
- TradeHarbor's Strategy lab turns a written idea into rules and the Python code they become; the Backtester and forward testing check it; the automation beta runs it.
Most traders lose more to execution than to their ideas. They hesitate on the entry, move the stop, take one more trade after the daily limit, or skip the setup that would have paid for the week. Automation removes those moments. The computer takes every trade the rules allow, places the stop every time, and stops when the rules say stop.
That doesn't make a strategy profitable. A strategy with no edge loses money faster when it's automated, because it never gets tired. What automation gives you is a strategy you can actually measure, because it's traded exactly the same way every time. This guide walks through the whole process. Each step has its own deeper guide.
Step 1: start with an idea you can explain
Every strategy starts as a sentence: "I buy when price breaks out of the first 15 minutes' range." "I fade big moves back toward the average." "I trade pullbacks in the direction of the trend." That's fine as a start. The problem is that a sentence leaves out almost everything a computer needs to know.
Take the opening range breakout. Which market? Which 15 minutes: from the 9:30 New York open? Does "breaks out" mean a single tick above the high, or a 5-minute bar closing above it? What if it breaks both sides? Where's the stop, and the target? How many contracts? Can it trade again after a loss? When does it close an open trade at the end of the day?
You answer those questions every time you trade the idea by hand, but usually in the moment, and not always the same way. Automating forces you to answer them once, in advance.
Step 2: turn it into exact rules
A testable strategy has the same parts every time:
- Market and timeframe: what it trades, on what bar size (1, 5 or 15 minutes, for example).
- Session: the hours it may open trades, and whether it must be flat by a set time or may hold a trade overnight.
- Entry conditions: exact, checkable statements. "The 5-minute bar closes above the opening range high", not "price looks strong".
- Exits: a stop, a target or several, and optionally a breakeven move or a trailing stop.
- Size: how many contracts, and the most it may hold.
- Limits: trades per day, and what happens after a loss.
Turning a trading idea into strategy rules works through this for a real example, including the questions most people miss.
In TradeHarbor: the Strategy lab's Build a strategy tab is a set of blocks for exactly these parts: market and session, long and short entry conditions, stops, up to three targets, breakeven, trailing stop, flat-by time, scaling in and trading days. You can also describe your idea in plain words to the strategy assistant: it asks about anything your description leaves open, proposes the rules as these blocks, and says plainly what it can't express, so you can see the gaps in your own idea. You can change any block yourself. Building is open to every signed-in user.
Step 3: turn the rules into code
Once the rules are exact, writing them as code is mostly translation. A strategy is a small program that looks at each new price bar and decides: do nothing, enter, or exit. In Python, a moving average cross looks like this:
class EmaCross(Strategy):
symbol = "MNQ"
timeframe = "5m"
session = ("09:30", "15:55")
params = {"fast": 9, "slow": 21, "stop_points": 20, "target_points": 40}
def on_bar(self, ctx, bar):
fast = ta.ema(ctx.closes, self.p.fast)
slow = ta.ema(ctx.closes, self.p.slow)
if ta.crossed_above(fast, slow):
ctx.buy(1, stop_points=self.p.stop_points, target_points=self.p.target_points)
That's an example for learning, not a recommendation. The point is how little code a clear rule needs.
Many traders first hear about Pine Script, TradingView's language, for this step. It's a fine way to chart an idea, but it only runs on TradingView, and automating it there means relying on a chain of alerts and outside services. A strategy written in Python can run anywhere: on your own computer, on a server, or on a hosted runner, against any broker that offers an API. Pine Script vs Python compares the two honestly.
In TradeHarbor: you don't have to write the code yourself. The builder shows your strategy in plain English and the Python it becomes, side by side, so you can learn the code from your own rules. If you'd rather write Python directly, the automation beta has a strategy code editor using the same building blocks.
Step 4: test it honestly
A backtest runs your rules over past prices to see what they would have done. It's the cheapest way to throw out a bad idea, and the easiest way to fool yourself, because it's tempting to keep adjusting settings until the past looks great. A strategy tuned to fit the past usually disappoints on new data.
Honest testing means realistic fills and fees, checking that the result holds in a period you didn't tune on, and then forward testing: running the unchanged strategy on new sessions as they happen. How to backtest a trading strategy covers the traps.
In TradeHarbor: the builder's Test it splits results into earlier and later sessions, and Try a range shows whether a setting only works on the earlier ones. The Backtester (Pro, using price history from your own ProjectX connection) adds slippage and fees, a stress test, and a run against a real evaluation's rules. Saving a backtest forward-tests it on each new session.
Step 5: run it, on paper first
To trade by itself, a strategy needs three things: live prices coming in, a program that runs your rules on every new bar, and a way to send orders to your broker. That last part is the broker's API, a set of web addresses a program can call to place and manage orders. How trading APIs work explains it in plain words, and how automated trading works follows one trade from signal to filled order, including what can go wrong.
Run any new automation in shadow mode first: the strategy runs on live prices and records what it would do, without placing orders. Compare that with your backtest. Only when they agree should real money be involved, and then with the smallest size and hard risk limits.
In TradeHarbor: automation (in beta) runs your saved strategy on TradeHarbor's servers during market hours, on your broker account linked by API. Shadow mode lets you watch every decision before it trades, Check against backtest lists any trade that differs from the backtest, and in live mode it places the strategy's orders on your account. Risk guards set daily loss, profit lock, trade limits and cooldowns that apply to every trade on the account, placed by you or by the strategy.
Before you automate anything with real money
- Check your firm's or broker's rules. Some prop firms restrict automated or API trading, or the places it can run from, and some don't allow it on funded accounts at all. Read the current rules for your account.
- Know your worst case. Decide the most the strategy may lose in a day and enforce it outside the strategy, with guards, not just inside it.
- Watch it. Automated doesn't mean unattended. Connections drop and brokers have outages.
- Keep records. Journal the automated trades like your own and compare them with the backtest every week.
Automation is a tool for discipline and measurement. It won't find an edge for you, but it will tell you, quickly and honestly, whether you have one.