Start investing in Bitcoin with Pix, in a few minutesSponsoredOpen free account
How to create a trading robot from scratch: from idea to real account
Trading

How to create a trading robot from scratch: from idea to real account

How to create a trading robot from scratch: Define rules, choose Pine Script, MQL5 or Python, backtest with costs, test demo, and control risk.

Photo: Unsplash

By Boletim Bitcoin newsroom

. 6 min reading.

To create a trading robot from scratch, you need five things: objective rules, a platform to program them, an honest backtest with costs, a demo account period, and a risk plan that the robot follows without exception. Programming is the easy part; The difficult thing is to prove that the rule works outside the history in which it was created.

In short: Start by writing the strategy in Portuguese, with exact numbers. Program in Pine Script (easier), MQL5 (MetaTrader 5) or Python (crypto via API). Test with rates, spread and slippage, validate on data you didn't use to adjust, run in demo and only then operate with small values. No robot guarantees profit.

Step 1: What is the robot going to do, exactly?

Robot doesn't understand “buy when it looks cheap”. He needs answers to these questions:

QuestionExample of objective answer
Which asset and graphical time?BTC/USDT, 4-hour candlesticks
When does it come in?Exponential average of 9 cruz above that of 21 at candle closure
When is it profitable?Opposite crossing or target 2 times the risk
When does it come out with loss?Stop 1.5 ATR below the entrance
How much do you risk?1% of capital per operation
When does it not operate?If there is already an open position or loss of the day greater than 3%

If any lines are left blank, the robot is not ready to be programmed. Entry ideas often come from indicators such as moving averages, IFR and Bollinger bands, or from support and resistance. the guide of robot strategies Compares trend, reversal, grid and DCA.

Put a bot to workGrid, DCA and copy trading ready to use, no coding needed.See the bots

Step 2: Which platform to choose?

Pine Script (TradingView)

  • Short learning curve
  • Direct backtest on the chart
  • Actual execution depends on alerts and integrations
  • Good for validating ideas

MQL5 (MetaTrader 5)

  • Robot runs at the terminal and sends orders to the brokerage
  • Tester with real ticks and optimization
  • Language similar to C++
  • Forex, Gold and CFDs standard

Python

  • Total freedom and many libraries
  • Connects to crypto brokers via API (CCXT)
  • You mount backtest, run, and server
  • Requires more engineering discipline

A common path is to prototype in TradingView and, if the idea survives the tests, rewrite in MQL5 or Python to run. Each language has its own tutorial here: Pine Script, MQL5 Expert Advisor e Python for trading.

Can you start without programming?

Yes. The MQL5 assistant Assembles an Expert Advisor by combining signal modules, capital management and trailing stop, and already delivers the compilable code. In crypto, brokers offer ready-made grid and DCA bots; BingX is an example, with a tutorial on our BingX Grid Bot Guide. They are good to learn, but the logic is limited to what the tool offers.

Step 3: Program the first version

Below, the table rule (without stop by ATR, to stay short) in Pine Script v6. Note that costs and position size are already included in the strategy statement:

//@version=6
strategy("Robô cruzamento EMA", overlay = true, initial_capital = 1000,
     default_qty_type = strategy.percent_of_equity, default_qty_value = 10,
     commission_type = strategy.commission.percent, commission_value = 0.1, slippage = 2)

emaRapida = ta.ema(close, input.int(9, "EMA rápida"))
emaLenta  = ta.ema(close, input.int(21, "EMA lenta"))
plot(emaRapida, "EMA rápida", color.teal)
plot(emaLenta, "EMA lenta", color.orange)

compra = ta.crossover(emaRapida, emaLenta)
venda  = ta.crossunder(emaRapida, emaLenta)

if compra
    strategy.entry("Long", strategy.long)
if venda
    strategy.close("Long")

In V6, the parameter when of the order functions has been removed; the condition goes in a if, as above, according to the TradingView Migration Guide. By default, the simulator executes the order to market in the next available tick, that is, in the opening of the candlestick next to the signal, according to the Strategy Documentation. This avoids the classic “buy in the closing that you only met later” error.

Candles chart on MetaTrader 5 trading platform Candlestick chart in MetaTrader 5, a platform where robots written in MQL5 send orders directly to the brokerage firm. Credit: Enivid, CC BY-SA 4.0 license, via Wikimedia Commons.

Step 4: Backtest with out-of-sample costs and data

O backtest answers whether the rule would have worked in the past. Three golden rules:

  1. Include all costs. Brokerage fee, spread and slippage (difference between the expected price and the executed). If the robot earns 0.25% gross per operation and pays 0.30% of costs, it loses.
  2. Separate in-sample and out-of-sample. Set parameters in, for example, 2019 to 2023 and test only once in 2024 to 2026. If the result collapses, it is a sign of overfitting.
  3. Do walk-forward. Optimize in a window, test the following, go ahead. The MetaTrader 5 tester has the “forward” option, which reserves 1/2, 1/3 or 1/4 of the period for this test, and allows simulating execution delay, according to the Official tester help.
Warning: Testing hundreds of parameter combinations until you find the perfect curve almost always produces a robot that fails live. Few parameters, wide ranges that work and logic that you can explain are signs of robustness.

Step 5: Demo account and actual execution

Even a good backtest hides problems that only appear live: order rejected by minimum batch, disconnection, scrolling schedule with high spread, difference between the price of the graph and the broker's price. therefore:

  • Rotate in Demo for a few weeks and compare each operation with what the backtest would do.
  • Use a Server (VPS) If the robot needs to be turned on 24 hours, as in crypto.
  • Record everything in log: Signal, price requested, price executed, reason for leaving.
  • Have a “turn off button”: Daily loss limit and maximum number of orders.

If the robot operates crypto by API, protect the keys: read-only permission, never withdrawal, and list of authorized IPs. The step by step is in Crypto brokerage API.

Step 6: Position size and risk control

Robot Risk Roadmap

  1. Risk per operationSet a fixed percentage, such as 0.5% to 1% of the capital.
  2. Lot by stopCalculate the amount from the distance from the stop, not by guessing.
  3. Daily limitTurn off the robot if the loss of the day passes from a roof, like 3%.
  4. Maximum drawdownIf the capital's fall goes from the worst case of the backtest, stop and re-evaluate.

Example: with US$ 1,000 and a risk of 1%, the maximum loss per operation is US$ 10. If the stop is 2% below the entry, the position is US$ 500 (10 ÷ 0.02). the complete logic, with drawdown tables, is in Risk Management in Trading. Escape from Martingale's logic, which bends the position after losses: they seem to work until the bad sequence that resets the count is zero.

To see a robot being mounted in practice with Python connected to MetaTrader 5, the video below shows the process from start to finish.

Checklist before turning on the robot with real money

  • Written rules, unambiguously.
  • Backtest with costs and several years, including high, fall and lateralization.
  • Out-of-sample result consistent with in-sample.
  • Weeks of demo with similar execution.
  • Position size per risk, always active stop, daily limit.
  • API keys without withdrawal permission.
  • Capital you can lose without excessive leverage.

Creating the robot is an engineering and statistics project at the same time. Whoever treats the code as the main part usually discovers, live, that the test was too optimistic. To understand the general context, see also What is Algorithmic Trading?.

Informational content, not investment advice.

Frequently asked questions

How to create a trading robot?

Write objective rules of input, output and position size, program on a platform (Pine Script, MQL5 or Python), backtest with costs, validate data outside the sample, run the demo account and only then operate with little money.

What is the best language to create robot trader?

It depends on the market. Pine Script is the easiest to prototype in TradingView. MQL5 executes direct orders in MetaTrader 5 (Forex and CFDs). Python is the most flexible for crypto via API and for data search.

Can you create a trading robot without programming?

Yes, with limitations. The MQL5 wizard generates Expert Advisors from ready-made modules, and crypto brokers offer configurable Grid and DCA bots. For own strategies, programming gives more control.

How much testing time does it take before using real money?

There is no magic deadline. A prudent script is backtest with several years and different market regimes, validation out-of-sample and a few weeks into account demo comparing the result with the expected.

References

  1. TradingView: Pine Script docs, Strategies
  2. TradingView: Pine Script Docs, Migration to V6
  3. MetaTrader 5: MQL5 Assistant
  4. MetaTrader 5: Strategy Testing (Tick Modes, Forward, Delays)
  5. MQL5 Reference: CTrade
  6. Manual CCXT
  7. Investopedia: Slippage
  • trading robot
  • robot trader
  • Algorithmic Trading
  • backtest
  • Pine Script
  • MQL5
  • Python

This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.

Read also

Start in crypto today

Open your free account, deposit with PIX and access Spot, Futures, Copy Trading and Trading Robots in one app.

  • Easy deposits
  • Copy trading
  • Grid and DCA bots
  • All-in-one app
Advertising. Crypto involves risk, invest responsibly.
Create free account