How to use the MQL API from another class

There can be only a single instance of your expert advisor class (EA), because it’s the entrance point into your code. At some point the EA code might grow and become too big to manage in one file. You might want to split that file into separate classes where each one does a part of the EA job.

Suppose that you want to call OrderSend() and any other MQL methods of the MqlApi base class from another class OrderManager. You can do it by passing this from the EA to OrderManager and storing it in a field. This field would have a type IMqlApi. The trading strategy indicator logic (trade signal) could be separated in the same fashion.

// RobotEA.cs: the main EA class
class RobotEA : MqlApi {
	private OrderManager orderManager;
	private TradeSignal tradeSignal;

	public override int init() {
		orderManager = new OrderManager(this);
		tradeSignal = new TradeSignal(this);
		return 0;
	}

	public override int start() {
		if (tradeSignal.HasDetectedLowPrice()) {
			orderManager.Buy();
		}
		return 0;
	}
}

// OrderManager.cs: managing orders
class OrderManager {
	private IMqlApi api;
	private int orderTicket;

	public OrderManager(IMqlApi api) {
		this.api = api;
	}

	public void Buy(double price) { 
		int ticket = api.OrderSend(api.Symbol(),
			MqlApi.OP_BUY, 0.01, api.Ask, 0, 0, 0);
		if (ticket >= 0) {
			orderTicket = ticket;
		} else {
			int error = api.GetLastError();
			...
		}
	}
}

// TradeSignal.cs: detecting good market conditions
class TradeSignal {
	private IMqlApi api;

	public TradeSignal(IMqlApi api) {
		this.api = api;
	}

	public boolean HasDetectedLowPrice() {
		double price = api.Ask;
		return (price < 0.001);
	}
}