MetaFive

My open-source Laravel package for the MetaTrader 5 Web API. It runs in broker back offices serving 10,000+ users.

Floors
B1officesB2mailroom
Stack
Laravel, PHP, MetaTrader 5 Web API
Links
Repository
Packagist

What it is

An open-source Laravel package for the MetaTrader 5 Web API, the API brokers use to run their back offices: trading accounts and groups, balance operations like deposits and withdrawals, orders, positions and deals. It runs in broker back offices serving 10,000+ users. It started as MetaFive, and the current code lives on as meta-trader-client on Packagist.

The problem

The MetaTrader 5 Web API isn't a web API in the way most people mean it. It's a raw socket speaking text commands in UTF-16, with a challenge-response login and its own encryption on top. The official PHP client works, but it reads like the protocol: results come back through by-reference parameters, errors are one of more than a hundred integer codes, and every app that uses it has to learn all of that again.

What I built

  • A Laravel client with plain methods that return values, for accounts, groups, symbols, orders, positions, deals, history, ticks and balance operations
  • MetaTrader's error codes mapped to typed exceptions, so an authentication problem and a refused trade are different things to catch, with the raw code still on the exception
  • One connection per request, opened the first time it's needed, so the login handshake happens once instead of on every call
  • A service provider, a facade and a config file that reads everything from the environment
  • Artisan commands to check the connection and list groups and symbols from the terminal

The interesting parts

Hiding the protocol

Under the methods there's a TCP socket sending commands shaped like COMMAND|PARAM=value in UTF-16LE, packets with a 9-byte header, answers that can span several packets, and a login where the client and the server each have to prove they know the password. The package keeps all of it underneath, so a Laravel app asks for an account and gets an account.

Errors you can catch

In the raw API every call returns a number, and success is just one of them. The package sorts the number ranges into exceptions you can catch by kind, and keeps MetaTrader's own code on each one, because that's the first thing anyone asks for when a trade goes wrong.

One login per request

Logging in to MetaTrader is a handshake, not a header. The client lives in Laravel's container as a single shared instance and connects the first time it's used, so a request that makes twenty calls logs in once.

From MetaFive to version two

The first version kept the shape of the vendor's code. Version two is a rewrite: readable method names, return values instead of out-parameters, typed exceptions and lazy connections, on PHP 8.2 with Laravel 11 and 12.

Ring the bell

Want something like this built, or one of these explained? The intercom is downstairs.

Get in touch