3.2 Your first robot, part 2: signal and order
In part 1 we created the settings and indicators. Now the robot has to think and act.
Step 5: Helper functions
// Reads one value from an indicator
double Value(int handle, int shift)
{
double buf[1];
if(CopyBuffer(handle, 0, shift, 1, buf) != 1) return(EMPTY_VALUE);
return(buf[0]);
}
// Counts the robot's own open positions in this market
int CountPositions()
{
int count = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
PositionGetInteger(POSITION_MAGIC) == (long)InpMagic) count++;
}
return(count);
}The for loop goes through all open positions on the account. We only count those that have our market and our magic number.
Step 6: OnTick – the brain
void OnTick()
{
// 1. Only once per new candle
datetime barTime = iTime(_Symbol, _Period, 0);
if(barTime == lastBarTime) return;
lastBarTime = barTime;
// 2. Read the indicators on candles 1 and 2
double fast1 = Value(hFast, 1), fast2 = Value(hFast, 2);
double slow1 = Value(hSlow, 1), slow2 = Value(hSlow, 2);
if(fast1 == EMPTY_VALUE || slow1 == EMPTY_VALUE ||
fast2 == EMPTY_VALUE || slow2 == EMPTY_VALUE) return;
bool buySignal = (fast2 <= slow2 && fast1 > slow1);
bool sellSignal = (fast2 >= slow2 && fast1 < slow1);
// 3. At most one position
if(CountPositions() > 0) return;
// 4. Send the order
if(buySignal)
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double sl = NormalizeDouble(ask - InpStopLossPips * pip, _Digits);
double tp = NormalizeDouble(ask + InpTakeProfitPips * pip, _Digits);
if(!trade.Buy(InpLots, _Symbol, ask, sl, tp, "MaCross"))
Print("Buy failed: ", trade.ResultRetcodeDescription());
}
else if(sellSignal)
{
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double sl = NormalizeDouble(bid + InpStopLossPips * pip, _Digits);
double tp = NormalizeDouble(bid - InpTakeProfitPips * pip, _Digits);
if(!trade.Sell(InpLots, _Symbol, bid, sl, tp, "MaCross"))
Print("Sell failed: ", trade.ResultRetcodeDescription());
}
}Why ask and bid?
You buy at the ask price and sell at the bid price – you learned that in the basics course. The stop loss for a buy position is below the entry, for a sell position above. NormalizeDouble rounds to the right number of decimals, otherwise the broker may reject the order.
Compile and try it
- Put part 1 and part 2 together in one file, and press Compile.
- In MetaTrader: open the Navigator (Ctrl+N), right-click Expert Advisors and choose Refresh.
- Drag MaCross onto a EUR/USD chart on a demo account. Tick Allow Algo Trading on the Common tab.
- Turn on the Algo Trading button in the toolbar.
Congratulations – you have built a working robot.
What is missing?
The robot trades a fixed size, has no filters and does not close on the opposite signal. We add that in module 4. If you want to see a complete version with everything in place, you can create one in the algo builder and compare.
Try it yourself
Finish the robot and run it in the strategy tester on one year of data. Does it open trades where you expect?
Key takeaways
- Read the signal on candles 1 and 2, and check that the values are valid.
- Only count positions with your market and your magic number.
- Buy at the ask and sell at the bid, and normalise the prices before sending the order.
65% of retail investor accounts lose money when trading CFDs with this provider.