Skip to main content

Overview

The TradeApi provides methods to retrieve and manage trading operations in MetaTrader 5. This guide covers how to fetch user positions, orders, deals, and close all open positions.

Getting User Positions

Retrieve all open positions for a specific user with the positionsUserLoginGet() method.
1

Initialize the TradeApi

Set up the TradeApi client with your configuration.
use D4T\MT5Sdk\MT5Manager\TradeApi;
use D4T\MT5Sdk\Configuration;
use GuzzleHttp\Client;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://your-mt5-server.com/api')
    ->setAccessToken('your_bearer_token');

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

Fetch Open Positions

Get all currently open positions for a user.
try {
    $userLogin = '12345';
    $positions = $tradeApi->positionsUserLoginGet($userLogin);
    
    echo "Found " . count($positions) . " open positions\n";
    
    foreach ($positions as $position) {
        echo "Symbol: " . $position->getSymbol() . "\n";
        echo "Volume: " . $position->getVolume() . "\n";
        echo "Open Price: " . $position->getPriceOpen() . "\n";
        echo "Current Price: " . $position->getPriceCurrent() . "\n";
        echo "Profit: $" . $position->getProfit() . "\n";
        echo "---\n";
    }
    
} catch (\D4T\MT5Sdk\ApiException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Retrieving Orders

Fetch user orders (pending and executed) using the ordersUserLoginGet() method.
try {
    $userLogin = '12345';
    $daysBack = '7'; // Last 7 days
    $types = 'all'; // Order types to retrieve
    
    $orders = $tradeApi->ordersUserLoginGet($userLogin, $daysBack, $types);
    
    foreach ($orders as $order) {
        echo "Order #" . $order->getOrder() . "\n";
        echo "Symbol: " . $order->getSymbol() . "\n";
        echo "Type: " . $order->getType() . "\n";
        echo "Volume: " . $order->getVolume() . "\n";
        echo "Price: " . $order->getPrice() . "\n";
        echo "State: " . $order->getState() . "\n";
        echo "Time: " . date('Y-m-d H:i:s', $order->getTimeSetup()) . "\n";
        echo "---\n";
    }
    
} catch (\D4T\MT5Sdk\ApiException $e) {
    echo "Error fetching orders: " . $e->getMessage() . "\n";
}
The types parameter accepts values like all, buy, sell, limit, stop, etc. Check your MT5 server documentation for supported order types.

Getting Trade Deals

Retrieve executed deals (trade history) with the dealsUserLoginGet() method.
try {
    $userLogin = '12345';
    $daysBack = '30'; // Last 30 days
    
    $deals = $tradeApi->dealsUserLoginGet($userLogin, $daysBack);
    
    $totalProfit = 0;
    
    foreach ($deals as $deal) {
        echo "Deal #" . $deal->getDeal() . "\n";
        echo "Symbol: " . $deal->getSymbol() . "\n";
        echo "Action: " . $deal->getAction() . "\n";
        echo "Volume: " . $deal->getVolume() . "\n";
        echo "Price: " . $deal->getPrice() . "\n";
        echo "Profit: $" . $deal->getProfit() . "\n";
        echo "Commission: $" . $deal->getCommission() . "\n";
        echo "Time: " . date('Y-m-d H:i:s', $deal->getTime()) . "\n";
        echo "---\n";
        
        $totalProfit += $deal->getProfit();
    }
    
    echo "Total Profit/Loss: $" . number_format($totalProfit, 2) . "\n";
    
} catch (\D4T\MT5Sdk\ApiException $e) {
    echo "Error fetching deals: " . $e->getMessage() . "\n";
}

Closing All Positions

Close all open positions for a user using the closeAllUserLoginDelete() method.
try {
    $userLogin = '12345';
    
    // Close all positions
    $tradeApi->closeAllUserLoginDelete($userLogin);
    
    echo "All positions closed successfully for user $userLogin\n";
    
} catch (\D4T\MT5Sdk\ApiException $e) {
    echo "Error closing positions: " . $e->getMessage() . "\n";
}
The closeAllUserLoginDelete() method immediately closes ALL open positions for the specified user. This action cannot be undone. Use with extreme caution and ensure proper authorization.

Complete Working Examples

<?php
require_once(__DIR__ . '/vendor/autoload.php');

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

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://your-mt5-server.com/api')
    ->setAccessToken('your_bearer_token');

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

function analyzePositions($userLogin) {
    global $tradeApi;
    
    try {
        $positions = $tradeApi->positionsUserLoginGet($userLogin);
        
        $stats = [
            'total_positions' => count($positions),
            'total_profit' => 0,
            'buy_positions' => 0,
            'sell_positions' => 0,
            'symbols' => []
        ];
        
        foreach ($positions as $position) {
            $stats['total_profit'] += $position->getProfit();
            
            // Count position types
            if ($position->getAction() == 0) { // Buy
                $stats['buy_positions']++;
            } else { // Sell
                $stats['sell_positions']++;
            }
            
            // Track by symbol
            $symbol = $position->getSymbol();
            if (!isset($stats['symbols'][$symbol])) {
                $stats['symbols'][$symbol] = [
                    'count' => 0,
                    'volume' => 0,
                    'profit' => 0
                ];
            }
            $stats['symbols'][$symbol]['count']++;
            $stats['symbols'][$symbol]['volume'] += $position->getVolume();
            $stats['symbols'][$symbol]['profit'] += $position->getProfit();
        }
        
        return $stats;
        
    } catch (\D4T\MT5Sdk\ApiException $e) {
        echo "Error: " . $e->getMessage() . "\n";
        return null;
    }
}

// Usage
$stats = analyzePositions('12345');

if ($stats) {
    echo "Position Analysis\n";
    echo "================\n";
    echo "Total Positions: " . $stats['total_positions'] . "\n";
    echo "Total Profit/Loss: $" . number_format($stats['total_profit'], 2) . "\n";
    echo "Buy Positions: " . $stats['buy_positions'] . "\n";
    echo "Sell Positions: " . $stats['sell_positions'] . "\n";
    echo "\nBy Symbol:\n";
    
    foreach ($stats['symbols'] as $symbol => $data) {
        echo "  $symbol: " . $data['count'] . " positions, ";
        echo "Volume: " . $data['volume'] . ", ";
        echo "P/L: $" . number_format($data['profit'], 2) . "\n";
    }
}

API Methods Reference

MethodParametersDescriptionReturns
positionsUserLoginGet($login)login: User login IDGet all open positionsPosition[]
ordersUserLoginGet($login, $days, $types)login: User login ID
days: Days to look back
types: Order types
Get user ordersOrder[]
dealsUserLoginGet($login, $days)login: User login ID
days: Days to look back
Get executed dealsDeal[]
closeAllUserLoginDelete($login)login: User login IDClose all positionsvoid

Position Properties

The Position model includes:
PropertyTypeDescription
positionintegerPosition ticket number
symbolstringTrading symbol
actioninteger0 = Buy, 1 = Sell
volumefloatPosition volume (lots)
price_openfloatOpening price
price_currentfloatCurrent market price
profitfloatCurrent profit/loss
storagefloatSwap/rollover fees
timeintegerOpen time (Unix timestamp)

Order Properties

The Order model includes:
PropertyTypeDescription
orderintegerOrder ticket number
symbolstringTrading symbol
typeintegerOrder type
stateintegerOrder state
volumefloatOrder volume
pricefloatOrder price
time_setupintegerSetup time (Unix timestamp)
time_expirationintegerExpiration time

Deal Properties

The Deal model includes:
PropertyTypeDescription
dealintegerDeal ticket number
symbolstringTrading symbol
actionintegerDeal action
volumefloatDeal volume
pricefloatExecution price
profitfloatDeal profit/loss
commissionfloatCommission charged
swapfloatSwap/rollover
timeintegerExecution time (Unix timestamp)
All time values are returned as Unix timestamps. Use PHP’s date() function to convert them to readable formats.

Best Practices

  1. Rate Limiting: Implement appropriate delays between API calls to avoid server overload
  2. Error Handling: Always wrap API calls in try-catch blocks
  3. Data Validation: Validate user login IDs and parameters before making requests
  4. Historical Data: Use appropriate days_back values to balance data completeness with performance
  5. Position Monitoring: Regularly monitor open positions for risk management
  6. Async Operations: Use async methods when retrieving data for multiple users

Risk Management

When implementing trading operations:
  • Monitor margin levels before allowing new positions
  • Set up automated position closure for critical drawdown levels
  • Track total exposure across all symbols
  • Implement maximum position size limits
  • Log all position closures for audit trails
Always implement proper authorization checks before allowing position closures or trade operations. Unauthorized trading operations can result in significant financial losses and legal liability.

Next Steps

Build docs developers (and LLMs) love