Our partnerSkilling
  • Spreads from 0.1 pips
  • 1,000+ instruments
  • Free demo account

65% of retail investor accounts lose money when trading CFDs with this provider.

Open account
Module 4 · Risk management in code

4.3 Filters and error handling

Lesson 13 of 19Reading time: 2 min

A robot that works in the tester can run into problems live. Filters and good error handling are the difference between a toy robot and a robot you can trust.

Three useful filters

Trend filter – only trade with the trend: ``mql5 double trend = Value(hTrend, 1); // SMA(200) on candle 1 if(iClose(_Symbol, _Period, 1) <= trend) buySignal = false; if(iClose(_Symbol, _Period, 1) >= trend) sellSignal = false; ``

Time filter – only trade at certain hours: ``mql5 MqlDateTime t; TimeToStruct(TimeCurrent(), t); // server time if(t.hour < 8 || t.hour >= 20) return; // only between 08 and 20 ``

Spread filter – do not trade when the spread is high: ``mql5 double spreadPips = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / pip; if(spreadPips > 2.0) return; ``

Server time is not your time

TimeCurrent() in MetaTrader gives the broker’s server time, which is often GMT+2 or GMT+3 – one hour ahead of Central European Time. In cTrader you can choose the time zone in [Robot(TimeZone = ...)].

Check whether the order succeeded

Orders can be rejected: the market is closed, the size is wrong, there is not enough margin, or the price has moved. Always check the response:

MQL5
if(!trade.Buy(lots, _Symbol, ask, sl, tp, "Robot"))
   Print("The order failed: ", trade.ResultRetcode(), " ", trade.ResultRetcodeDescription());

In cTrader: ``csharp var result = ExecuteMarketOrder(TradeType.Buy, SymbolName, volume, Label, slPips, tpPips); if (!result.IsSuccessful) Print("The order failed: ", result.Error); ``

Use the log

Everything you write with Print(...) ends up in the log:

PlatformWhere
MetaTrader 5Toolbox (Ctrl+T) → the Experts tab
MetaTrader 4Terminal (Ctrl+T) → the Experts tab
cTraderThe Log tab under the robot

When the robot does not do what you expect, the log is the first place to look. While testing, it helps to print the values the robot uses, for example Print("fast1=", fast1, " slow1=", slow1);.

Common errors live

  • Invalid filling in MT5: solved with trade.SetTypeFillingBySymbol(_Symbol).
  • Invalid stop loss: too close to the price, or on the wrong side.
  • The market is closed: weekend or public holiday.
  • Size too small: below the minimum allowed lot.

Try it yourself

Add a time filter and test again. Did you get fewer, but better trades?

Key takeaways

  • Trend, time and spread filters prevent many bad trades.
  • Always check whether the order succeeded, and print the error if not.
  • The log is the first place to look when the robot does not behave as expected.
Test yourself · Module 4

How much do you remember from “Risk management in code”?

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.

  1. 1How does the robot calculate the size?

  2. 2Which way should a trailing stop be moved?

  3. 3Where do you look first when the robot does not behave as expected?

Practise what you have learned – without riskTry it on a free demo account with Skilling, with real prices and virtual money.
Open a free demo account

65% of retail investor accounts lose money when trading CFDs with this provider.