Skip to main content
This guide will help you make your first API call to your MetaTrader 5 server using the PHP SDK. You’ll learn how to authenticate, retrieve account information, and handle responses.

Before You Begin

Ensure you have:
  1. Installed the SDK
  2. Access to a MetaTrader 5 server with:
    • Server IP address and port (e.g., 127.0.0.1:443)
    • Manager login credentials
    • Manager password
The MT5 Manager API uses bearer token authentication. You must first call /init/ to obtain a token before making other API requests.

Complete Example

Here’s a complete example that demonstrates the full workflow from initialization to making API calls:
1

Initialize and Authenticate

First, create a Configuration object and use the BasicApi to authenticate with your MT5 server:
<?php
require_once __DIR__ . '/vendor/autoload.php';

use D4T\MT5Sdk\Configuration;
use D4T\MT5Sdk\MT5Manager\BasicApi;
use GuzzleHttp\Client;

// Create configuration
$config = new Configuration();
$config->setHost('http://your-mt5-api-host.com/v1');

// Initialize the Basic API
$basicApi = new BasicApi(
    new Client(),
    $config
);

try {
    // Authenticate and get token
    $result = $basicApi->initGet(
        '127.0.0.1:443',  // MT5 server IP:port
        '10001',           // Manager login
        'ManagerPass123'   // Manager password
    );
    
    // Extract the authentication token
    $token = $result->getToken();
    echo "Authentication successful! Token: " . $token . "\n";
    
    // Set the token for subsequent requests
    $config->setAccessToken($token);
    
} catch (Exception $e) {
    echo 'Authentication failed: ' . $e->getMessage() . "\n";
    exit(1);
}
?>
Replace your-mt5-api-host.com, the server IP, login, and password with your actual MT5 server details.
2

Make Your First API Call

Once authenticated, you can make API calls. Let’s retrieve account information:
<?php
use D4T\MT5Sdk\MT5Manager\AccountApi;

// Create Account API instance with authenticated config
$accountApi = new AccountApi(
    new Client(),
    $config  // This config now has the access token set
);

try {
    // Get account by login
    $account = $accountApi->accountLoginGet('12345');
    
    echo "Account Information:\n";
    echo "Login: " . $account->getLogin() . "\n";
    echo "Balance: " . $account->getBalance() . "\n";
    echo "Equity: " . $account->getEquity() . "\n";
    
} catch (Exception $e) {
    echo 'Error retrieving account: ' . $e->getMessage() . "\n";
}
?>
3

Working with Users

Create, update, and manage users on your MT5 server:
<?php
use D4T\MT5Sdk\MT5Manager\UserApi;
use D4T\MT5Sdk\Models\User;

// Create User API instance
$userApi = new UserApi(
    new Client(),
    $config
);

// Get user information
try {
    $user = $userApi->userUserLoginGet('12345');
    echo "User: " . $user->getName() . "\n";
    echo "Email: " . $user->getEmail() . "\n";
    echo "Group: " . $user->getGroup() . "\n";
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage() . "\n";
}

// Create a new user
$newUser = new User();
$newUser->setPassword('123456Aa');
$newUser->setPasswordInvestor('123456Aa');
$newUser->setName('John Doe');
$newUser->setEmail('john@example.com');
$newUser->setGroup('demo\\demoforex');
$newUser->setLeverage(100);

try {
    $result = $userApi->userAddPost($newUser);
    echo "User created with login: " . $result->getUser()->getLogin() . "\n";
} catch (Exception $e) {
    echo 'Error creating user: ' . $e->getMessage() . "\n";
}
?>

Full Working Example

Here’s a complete script that ties everything together:
<?php
require_once __DIR__ . '/vendor/autoload.php';

use D4T\MT5Sdk\Configuration;
use D4T\MT5Sdk\MT5Manager\BasicApi;
use D4T\MT5Sdk\MT5Manager\AccountApi;
use D4T\MT5Sdk\MT5Manager\UserApi;
use GuzzleHttp\Client;

// Configuration
$config = new Configuration();
$config->setHost('http://your-mt5-api-host.com/v1');

// Step 1: Authenticate
$basicApi = new BasicApi(new Client(), $config);

try {
    $initResult = $basicApi->initGet(
        '127.0.0.1:443',
        '10001',
        'ManagerPass123'
    );
    
    $token = $initResult->getToken();
    $config->setAccessToken($token);
    
    echo "✓ Authentication successful\n";
    
} catch (Exception $e) {
    die("✗ Authentication failed: " . $e->getMessage() . "\n");
}

// Step 2: Get account information
$accountApi = new AccountApi(new Client(), $config);

try {
    $account = $accountApi->accountLoginGet('12345');
    echo "\n✓ Account {$account->getLogin()} retrieved\n";
    echo "  Balance: {$account->getBalance()}\n";
    echo "  Equity: {$account->getEquity()}\n";
} catch (Exception $e) {
    echo "✗ Error: " . $e->getMessage() . "\n";
}

// Step 3: Get user information
$userApi = new UserApi(new Client(), $config);

try {
    $user = $userApi->userUserLoginGet('12345');
    echo "\n✓ User information retrieved\n";
    echo "  Name: {$user->getName()}\n";
    echo "  Email: {$user->getEmail()}\n";
    echo "  Group: {$user->getGroup()}\n";
} catch (Exception $e) {
    echo "✗ Error: " . $e->getMessage() . "\n";
}

// Step 4: Test ping endpoint
try {
    $pingResult = $basicApi->pingGet();
    echo "\n✓ Server ping successful\n";
} catch (Exception $e) {
    echo "✗ Ping failed: " . $e->getMessage() . "\n";
}
?>

Common Operations

Here are some common operations you’ll perform with the SDK:
Test your connection to the API:
$basicApi = new BasicApi(new Client(), $config);

try {
    $pingResult = $basicApi->pingGet();
    echo "Server is responding\n";
} catch (Exception $e) {
    echo "Server not responding: " . $e->getMessage() . "\n";
}
Retrieve all available trading groups:
use D4T\MT5Sdk\MT5Manager\GroupApi;

$groupApi = new GroupApi(new Client(), $config);

try {
    $groups = $groupApi->groupsGet();
    foreach ($groups as $group) {
        echo $group->getName() . "\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
Add funds to a user’s account:
use D4T\MT5Sdk\Models\BalanceType;

$userApi = new UserApi(new Client(), $config);

$deposit = new BalanceType();
$deposit->setLogin(12345);
$deposit->setAmount(1000.00);
$deposit->setType(3);  // Deposit type
$deposit->setComment('Initial deposit');

try {
    $userApi->userDepositPost($deposit);
    echo "Deposit successful\n";
} catch (Exception $e) {
    echo "Deposit failed: " . $e->getMessage() . "\n";
}
Retrieve open positions for a user:
use D4T\MT5Sdk\MT5Manager\TradeApi;

$tradeApi = new TradeApi(new Client(), $config);

try {
    $positions = $tradeApi->positionsUserLoginGet('12345');
    foreach ($positions as $position) {
        echo "Symbol: {$position->getSymbol()}, "
           . "Volume: {$position->getVolume()}, "
           . "Profit: {$position->getProfit()}\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Error Handling

The SDK throws exceptions when API calls fail. Always wrap your API calls in try-catch blocks:
use D4T\MT5Sdk\ApiException;

try {
    $result = $accountApi->accountLoginGet('12345');
} catch (ApiException $e) {
    echo "API Error: " . $e->getMessage() . "\n";
    echo "HTTP Code: " . $e->getCode() . "\n";
    echo "Response Body: " . $e->getResponseBody() . "\n";
} catch (Exception $e) {
    echo "General Error: " . $e->getMessage() . "\n";
}

Best Practices

Security: Never hardcode credentials in your source code. Use environment variables or secure configuration management.
Token Management: The authentication token should be reused for multiple requests. Store it securely and refresh it when it expires.
Error Handling: Always implement proper error handling to gracefully handle network issues, authentication failures, and API errors.

Next Steps

Now that you’ve made your first API calls, explore the complete API reference: