1.3 From idea to precise rules
The hardest thing about algorithmic trading is not the programming. It is turning an idea into rules that cannot be misunderstood. A computer does exactly what you tell it – no more, no less.
From vague to precise
| Vague | Precise |
|---|---|
| “Buy when the trend is up” | Buy when the close is above the 200-period SMA |
| “Buy when the RSI is low” | Buy when RSI(14) crosses up through 30 on a closed candle |
| “Set a sensible stop loss” | Stop loss 1.5 × ATR(14) below the entry |
| “Take profit when it has gone well” | Take profit 2 × the distance to the stop loss |
| “Don’t trade when it’s volatile” | No new trades when the spread is above 2 pips |
Five questions every strategy must answer
- Market and time frame: Which instrument and which chart?
- Entry: Exactly what has to happen to buy – and to sell?
- Exit: Where are the stop loss and take profit? Do you close on the opposite signal?
- Size: How much do you risk per trade?
- Filters: When should the robot not trade?
Use closed candles
One of the most important rules in algorithmic trading: Make decisions on candles that have finished. A candle that is still open keeps changing. An indicator can show buy one second and sell the next. Robots that trade on the open candle often give completely different results live than in the test.
In code we call the last closed candle candle 1 and the one before it candle 2. Candle 0 is the one that is open now.
A complete rulebook
Strategy: Moving average crossover on EUR/USD, 1-hour chart.
- Buy: EMA(10) crosses above EMA(30) – that is, EMA(10) was below EMA(30) on candle 2 and above it on candle 1.
- Sell: The opposite.
- Stop loss: 30 pips. Take profit: 60 pips.
- Size: 1% of equity.
- Filter: At most one open position. Close on the opposite signal.
Write it down before you code
Write the rulebook in plain English before you write a single line of code. If you cannot explain the rule in one sentence, you cannot program it either.
Try it yourself
Create rules for a simple strategy in our algo builder and read the code. Do you recognise your rules?
Key takeaways
- A robot needs rules that cannot be misunderstood.
- Every strategy must define market, entry, exit, size and filters.
- Make decisions on closed candles – candle 1 is the last finished candle.
How much do you remember from “What is algorithmic trading?”?
Recalling what you have read is one of the most effective ways to learn. Pick the answer you think is right – you get the explanation straight away.
1What does a trading robot do better than you?
A robot gives discipline and speed, but does not make a bad strategy good.
2Which language does cTrader use?
MetaTrader 4 uses MQL4, MetaTrader 5 uses MQL5.
3Which candle should the robot use for decisions?
An open candle can change. Decisions on closed candles make the robot predictable.
65% of retail investor accounts lose money when trading CFDs with this provider.