How to trade automatically: rules, platform, broker and a first test
To trade automatically you need four things in a fixed order: rules a computer can follow, a backtest with costs on data the rules were not tuned on, a platform connected to a broker in simulation, and then one live contract. The testing step comes before the broker step, and it is where most of the work is.
By Soren Huang · Published · updated · Editorial policy
Contents
- How do you trade automatically?
- What does automatic trading mean in practice?
- Rules, platform and broker: what does each part do?
- Can TradingView trade automatically?
- Is buying and selling stocks automatically different from futures?
- How do you test the rules before the first live order?
- Frequently asked questions
- References
How do you trade automatically?
How to trade automatically: write rules a computer can follow, load them into a platform that watches prices and sends orders, connect that platform to a broker account, and test the rules on past prices with costs before the first live order. The testing step comes before the broker step, not after it.
Automatic trading is a setup in which a program, not a person, decides when to send each order and the broker executes it without a click. The idea is like a thermostat. You write the rule once ("turn on the heater below 20 degrees"), the device checks the temperature on a schedule, and it acts on its own. The thermostat is only useful if the rule is exact and the wiring to the heater works. Trading has the same two requirements: exact rules and a working path to the broker.
The four steps, in order:
- Write the rules. Entry condition, exit condition, position size, and the session during which the rule may trade. Every word must be a number or a comparison a program can compute.
- Backtest and validate with costs. A backtest is a replay of the rules on past bars, with commission and slippage charged on every trade. Judge the result on bars the rules were not tuned on. If the rule fails, go back to step 1 and rewrite it.
- Load the rules into a platform and connect the broker in simulation. The platform sends orders to a paper account. You check that the order arrives, fills, and shows the same position the backtest would hold.
- Go live with one contract. The smallest size, for long enough to compare live fills with the simulated ones.
If you have never written a rule before, the 30-day route to a first algo trading strategy walks through step 1 and step 2 at a beginner's pace. The rest of this article explains what each of the four steps needs and where each one usually breaks.
What does automatic trading mean in practice?
In practice the platform checks the rules once per bar and sends an order when a condition is met, so your work moves from clicking buy and sell to writing, testing and supervising rules. A bar is one block of price data: one day, one hour, one minute, or any other fixed length. Most rules that retail traders automate run on the close of each bar.
The loop at every bar close looks like this. The bar closes. The platform computes the indicators the rule uses. It checks the entry condition if you are flat and the exit condition if you hold a position. If a condition is true, it sends an order to the broker. The broker fills the order at the next available price, which for a bar-close rule is a price inside the next bar. The position and the account equity update. The platform waits for the next bar and starts again.
The "next-bar fill" step matters for testing. A rule that decides on a bar's close cannot buy at that same close, because the close is known only when the bar is over. A backtest that fills at the decision bar's close uses a price the live loop never sees. Next-bar execution is the setting that makes the backtest fill where the live loop fills. The general idea behind rule-driven trading, what it costs and why many rules lose after costs, is covered in what algo trading is and what it costs.
Hypothetical example
A daily rule on an index future says: buy at the next open when today's close is above the 20-day average. On Monday the close qualifies. The platform sends a market order after the close, and it fills at Tuesday's open, one tick worse than the printed open because the order joins a queue. If the exit later captures a 10-point move at $20 per point, the gross result is $200. Subtract a $4 round-trip commission and $5 of slippage on each side, and the net result is $186. Every number here is invented to show the arithmetic.
Supervising means watching for three things: the platform stopped receiving data, the platform and the broker disagree about the position, or the live fills are consistently worse than the backtest assumed. None of these is a rule problem. All three stop an automatic strategy from doing what the backtest did.
Rules, platform and broker: what does each part do?
Each of the three parts has one job and one typical failure: unclear rules give different signals on different platforms, a platform without a broker link only shows signals, and a broker without a supported platform or an API cannot receive orders. An API (application programming interface) is a documented way for one program to send instructions to another, in this case for the platform to send orders to the broker.
| Rules | Platform | Broker | |
|---|---|---|---|
| Job | Decide when to enter, exit and how much | Watch prices, compute the rules, send orders | Execute orders and hold the account |
| What you supply | Exact conditions and sizes in writing | Strategy code and a data feed | Account, and an API or a supported platform link |
| Typical failure | Two platforms give different signals from the same text | Signals shown on the chart, no order sent | Orders rejected, or a margin call because the size was wrong |
| Check before live | Same signals on two platforms over the same bars | A simulated order arrives at the paper account | One-lot live order fills and the position matches |
The rule failure is the one traders underestimate. "Buy when RSI is oversold" is not a rule. "Buy at the next open when the 14-bar RSI closes below 30 and the previous bar's RSI was at or above 30" is a rule, because two different programs would compute the same signal on the same bars. Writing at that level of detail is tedious. It is also the only way the backtest and the live platform can agree. When a strategy comes out of research as source code for the platform you run, this step is already done; AlphaPrime (Valynox) writes the rules it finds as strategy code for six platforms, listed on the platform export page, so the same conditions reach MultiCharts, TradingView, TradeStation, NinjaTrader, MetaTrader 4 or MetaTrader 5 as text the platform compiles rather than as a description to be typed again.
The platform failure is easy to see: the chart paints arrows, nothing happens at the broker. The cure is a simulated order, sent on purpose, that you trace to the paper account. The broker failure usually appears as a rejected order. The common causes are a position size the account cannot support, an order type the broker does not accept for that instrument, or trading outside the hours the broker allows. One live order of one contract exposes all three before the strategy does.
Can TradingView trade automatically?
TradingView runs a Pine Script strategy on a chart and can send an alert when a rule fires, and orders reach a broker only through a supported broker integration or through an alert webhook relayed by a third service, so the strategy logic and the order path need separate checks. Pine Script is TradingView's own language for indicators and strategies. A webhook is a web address that receives a message when an event happens; TradingView can post an alert's text to such an address.
The two order paths out of a Pine Script strategy:
- Path A, broker integration. TradingView connects to a list of brokers inside its trading panel. When your broker is on that list, strategy orders can be routed to the account from within TradingView. Which brokers are supported is a fact to check on TradingView's own pages for your region.
- Path B, alert webhook. The strategy creates alerts. Each alert posts a message to a relay service. The relay translates the message into an order on the broker's API. Three independent parts now have to be running at the same time: the alert, the relay and the API connection.
Both paths share one check: the fill price. TradingView's Strategy Tester reports fills from its own bar model, and the live order fills at whatever the market offers when the message arrives. On a liquid future the gap is often a tick or two; through a relay with a delay it can be more. Measure the gap in simulation by recording the strategy's signal price and the paper fill price for a few dozen orders, then put that average into the slippage setting of every later backtest.
A strategy written for research can reach TradingView as Pine Script v6 and the other platforms in their own languages. The point of exporting source code rather than a signal is that the condition that fired in the backtest is the condition the chart compiles, so when path A or path B fails, you know the failure is in the order path and not in the rule.
Is buying and selling stocks automatically different from futures?
The three parts are the same for stocks and futures, but session hours, short selling, the unit you trade and per-trade costs differ, which changes how the rules and the backtest must be set. The loop in the second section runs the same way. The settings around it do not.
| Setting | US stocks | Index futures such as NQ |
|---|---|---|
| Session hours | Regular cash session, 9:30 a.m. to 4:00 p.m. Eastern Time, with thinner pre-market and after-hours trading | Near 24-hour session, Sunday evening to Friday afternoon, with a daily one-hour break (5:00 p.m. to 4:00 p.m. Central Time, break 4:00 to 5:00 p.m.) |
| Short selling | The broker must locate shares to borrow before the sale | Selling a contract works the same way as buying one |
| Trade unit | Shares; one share of a $200 stock moves $1 per $1 of price | One contract with a fixed point value; NQ is $20 per index point |
| Cost per round trip | Commission plus the bid-ask spread | Commission plus exchange and clearing fees plus slippage |
| Overnight holding | You own the shares; margin interest if borrowed | A margin deposit with daily settlement of gains and losses |
| Data to backtest | Split-adjusted share prices | A continuous contract built from the front months with roll adjustments |
Two of these rows change the rules themselves. The session row decides when the rule is allowed to trade: a stock rule that fires at 4:00 p.m. has no cash market until the next morning, while an NQ rule at the same time has an open market for most of the night. A continuous contract is a series stitched from successive futures contracts so a backtest can run across years; without the roll adjustment, the price jump at each roll looks like a trade result that never existed. The free futures market hours tool shows the session of each exchange in your own time zone, which is the first thing to set in the rule. Exchanges change contract hours and tick values from time to time, so take the current values from the exchange's contract page.
The unit row changes the size rule. A stock strategy sizes in shares and can be scaled to almost any dollar amount. A futures strategy sizes in whole contracts, and one NQ contract is a large unit: at $20 per point, a 50-point move is a thousand dollars (CME Group contract specifications). The micro contract exists for exactly this reason. If the rule you want to automate is an intraday stock rule, day trading US stocks: test an intraday idea first covers the cash-session settings and costs for that case.
How do you test the rules before the first live order?
Run the rules on past bars with commission and slippage, judge them on data the rules were not tuned on, then run them in a simulated account for several weeks, and only then trade one contract. The order matters because each stage catches a different failure. The backtest catches a rule with no edge after costs. The out-of-sample check catches a rule that was fitted to the bars it was tuned on. The simulation catches order-path failures. The one-contract stage catches fill differences.
- Backtest with costs from the first run. Set commission per side and at least one tick of slippage per side for a liquid future. Use next-bar execution. Read the average trade after costs, not the gross profit.
- Judge on untouched bars. Split the history by date, tune on the earlier part and read the result on the later part unchanged. How to split and how many trades you need is covered in in-sample vs out-of-sample: how to split and how much is enough.
- Simulate for four weeks or more. Record every signal and every paper fill. Compare the position the platform holds with the position the backtest would hold on the same bars.
- Trade one contract. Compare live fills with paper fills. Only after this does the size rule apply.
Here is what a report of a kept candidate looks like at the end of step 2. The run tested a Fractal rule on NQ daily bars from 2019-01-02 to 2025-06-30, long and short, one contract, with $20 commission and $10 slippage charged on every trade. The Fractal rule is a stand-in built from standard indicators to show what a report looks like; it is not a rule about automatic trading itself. The candidate is the one the search kept out of the 1,024 it tried, chosen for its return against its drawdown. Picking the kept one after the fact flatters it. The best of a thousand tries carries luck that a new period will not repeat, so the numbers describe what that candidate did on those bars, not what the rule earns or what a reader can expect. Bailey, Borwein, López de Prado and Zhu (2014) show how quickly this selection effect grows with the number of variants tried.
Source: AlphaPrime product engine (CPU), run 2026-10-31. NQ daily bars, 2019-01-02 to 2025-06-30, long and short, 1 contract, $20 commission and $10 slippage per trade.
| Number | Result |
|---|---|
| Net profit (closed trades) | $119,660 |
| Max drawdown | $30,220 |
| Trades | 124 |
| Win rate | 58.06% |
| Profit factor | 1.722 |
| Average trade | $965 |
| Time in market | 12.44% |

Read the report the way step 2 asks. The 124 trades over six and a half years are about 19 a year, which is a small sample for a per-trade figure. The average trade of $965 after $30 of costs is large next to the cost, which is the first thing to want from a rule you will automate. The $30,220 drawdown is the number to size the account against, and because the candidate was picked for its drawdown, the live drawdown is more likely to be deeper than shallower. In AlphaPrime this out-of-sample reading is one of the checks inside strategy validation, with the thresholds set before the search so the decision to keep or discard a candidate was written down before the result existed.
Before the one-contract stage, go through the six checks before going live with an algo with your own strategy's signal log and paper fills side by side. Count the orders where the paper fill was worse than the signal price, work out the average gap in ticks, and rerun the backtest with that gap as the slippage setting. If the average trade after that rerun is still several times the round-trip cost, the rule has earned its first live contract.
Frequently asked questions
How do you automatically buy and sell stocks?
You need the same three parts as for futures: written rules, a platform that runs them, and a broker connected to the platform. For stocks, set the rule to trade inside the regular cash session, size in shares, and give the backtest the bid-ask spread as a cost. Short sales need the broker to locate shares first, so a rule that sells short must handle a rejected order.
Can I trade automatically without writing code?
Yes, if the strategy arrives as source code that the platform compiles. Research tools can write the rules they find as strategy code for mainstream platforms, and the trader then loads the file, connects the broker and tests in simulation. You still read and understand the rule, because supervising an automatic strategy requires knowing what it should do at each bar.
Does automatic trading need the computer on all the time?
The platform must be running whenever the rule may trade. For a daily rule that fires once at the bar close, a short window each day is enough. For an intraday rule on a near 24-hour futures market, traders run the platform on a machine that stays on, often a hosted server, so a sleeping laptop does not miss a signal or an exit.
How long should I run a strategy in simulation before going live?
Long enough to collect a few dozen paper orders and compare them with the signals. Four weeks is a common minimum for an intraday rule; a daily rule that trades twice a month needs longer. The purpose is to measure the gap between signal price and fill price and to confirm that the position in the platform matches the position the backtest would hold.
References
- Bailey, D. H., Borwein, J., López de Prado, M., & Zhu, Q. J. (2014). Pseudo-Mathematics and Financial Charlatanism: The Effects of Backtest Overfitting on Out-of-Sample Performance. Notices of the American Mathematical Society, 61(5), 458–471.
- CME Group. E-mini Nasdaq-100 Futures Contract Specs. https://www.cmegroup.com/markets/equities/nasdaq/e-mini-nasdaq-100.contractSpecs.html
- U.S. Securities and Exchange Commission. Understanding Order Types (Investor Bulletin). https://www.investor.gov/introduction-investing/general-resources/news-alerts/alerts-bulletins/investor-bulletins-14

