VALYNOXSTRATEGY RESEARCH TECHNOLOGY
AlphaPrimeAlphaPrime
ACADEMY / Strategy generation

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 · Published · updated · Editorial policy

Contents
  1. How do you trade automatically?
  2. What does automatic trading mean in practice?
  3. Rules, platform and broker: what does each part do?
  4. Can TradingView trade automatically?
  5. Is buying and selling stocks automatically different from futures?
  6. How do you test the rules before the first live order?
  7. Frequently asked questions
  8. 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:

  1. 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.
  2. 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.
  3. 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.
  4. Go live with one contract. The smallest size, for long enough to compare live fills with the simulated ones.
Four steps in order: write the rules, backtest with costs, simulate on a paper account, then trade one live contract; a failed backtest sends you back to rewrite the rules Test before the broker Four steps, in this order 1 2 3 4 Write the rules Backtest with costs Simulate on paper One live contract Fails? Rewrite Testing comes before any order. So: a failed test means new rules.
The four steps from written rules to a live automatic order. Testing sits before any broker order, and a failed test sends you back to the rules.

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 loop at every bar: the bar closes, the platform checks the rules and sends an order, and the fill lands in the next bar; then the loop repeats Fills land in the next bar What the platform does each bar Close Check Order Fill This bar Next bar Repeat every bar The close is known too late to buy. So: backtest with next-bar fills.
What the platform does at every bar close. Automatic trading is this loop repeated, not a single action, and the fill always lands in the bar after the decision.

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.

RulesPlatformBroker
JobDecide when to enter, exit and how muchWatch prices, compute the rules, send ordersExecute orders and hold the account
What you supplyExact conditions and sizes in writingStrategy code and a data feedAccount, and an API or a supported platform link
Typical failureTwo platforms give different signals from the same textSignals shown on the chart, no order sentOrders rejected, or a margin call because the size was wrong
Check before liveSame signals on two platforms over the same barsA simulated order arrives at the paper accountOne-lot live order fills and the position matches
The three parts of automatic trading: rules decide trades and fail when the text is vague, the platform sends orders and fails when no order is sent, the broker fills orders and fails when an order is rejected Each part has one job And one typical failure Rules Platform Broker Decide trades Send orders Fill orders Vague text No order sent Orderrejected
The three parts of automatic trading side by side: what each does, what you must supply, and what a typical failure looks like.

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:

  1. 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.
  2. 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.
A Pine Script strategy reaches the broker either through a built-in broker link or through an alert and a webhook relay; the relay path adds two more parts that each need a check Check each order path From a TradingView strategy Pine Built-in link 2 more parts Alert Relay Broker Right arrows can still miss orders. So: test rule and path separately.
Two order paths out of a TradingView strategy and the points where each one needs a check: where the alert runs, how long the relay takes, and whether the live fill matches the backtest fill.

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.

SettingUS stocksIndex futures such as NQ
Session hoursRegular cash session, 9:30 a.m. to 4:00 p.m. Eastern Time, with thinner pre-market and after-hours tradingNear 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 sellingThe broker must locate shares to borrow before the saleSelling a contract works the same way as buying one
Trade unitShares; one share of a $200 stock moves $1 per $1 of priceOne contract with a fixed point value; NQ is $20 per index point
Cost per round tripCommission plus the bid-ask spreadCommission plus exchange and clearing fees plus slippage
Overnight holdingYou own the shares; margin interest if borrowedA margin deposit with daily settlement of gains and losses
Data to backtestSplit-adjusted share pricesA continuous contract built from the front months with roll adjustments
US stocks and NQ futures compared: a 6.5-hour cash session versus about 23 hours a day, short sales that need borrowed shares versus selling like a buy, and shares versus whole contracts Same rules, new settings US stocks vs NQ futures US stocks NQ futures Session 6.5 hours 23 hours Short sale Borrow first Like a buy Unit Shares Contracts Session and unit change the rule. So: set them before the backtest.
How the settings of an automatic strategy and its backtest differ between US stocks and an index future. The rules can be the same; the session, the unit and the costs cannot.

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.

NumberResult
Net profit (closed trades)$119,660
Max drawdown$30,220
Trades124
Win rate58.06%
Profit factor1.722
Average trade$965
Time in market12.44%
The equity curve of the kept candidate with its drawdown band and the out-of-sample stretch marked. Judge the slope and the depth of the dips inside the marked stretch, not the shape of the whole curve.
The equity curve of the kept candidate with its drawdown band and the out-of-sample stretch marked. Judge the slope and the depth of the dips inside the marked stretch, not the shape of the whole curve. NQ · daily · 2019-01-02 to 2025-06-30 · CPU engine backtest

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