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.
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 );
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
Position Analysis
Trading Report
Risk Management
<? 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 " \n By 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
Method Parameters Description Returns positionsUserLoginGet($login)login: User login IDGet all open positions Position[] ordersUserLoginGet($login, $days, $types)login: User login IDdays: Days to look backtypes: Order typesGet user orders Order[] dealsUserLoginGet($login, $days)login: User login IDdays: Days to look backGet executed deals Deal[] closeAllUserLoginDelete($login)login: User login IDClose all positions void
Position Properties
The Position model includes:
Property Type Description positioninteger Position ticket number symbolstring Trading symbol actioninteger 0 = Buy, 1 = Sell volumefloat Position volume (lots) price_openfloat Opening price price_currentfloat Current market price profitfloat Current profit/loss storagefloat Swap/rollover fees timeinteger Open time (Unix timestamp)
Order Properties
The Order model includes:
Property Type Description orderinteger Order ticket number symbolstring Trading symbol typeinteger Order type stateinteger Order state volumefloat Order volume pricefloat Order price time_setupinteger Setup time (Unix timestamp) time_expirationinteger Expiration time
Deal Properties
The Deal model includes:
Property Type Description dealinteger Deal ticket number symbolstring Trading symbol actioninteger Deal action volumefloat Deal volume pricefloat Execution price profitfloat Deal profit/loss commissionfloat Commission charged swapfloat Swap/rollover timeinteger Execution time (Unix timestamp)
All time values are returned as Unix timestamps. Use PHP’s date() function to convert them to readable formats.
Best Practices
Rate Limiting : Implement appropriate delays between API calls to avoid server overload
Error Handling : Always wrap API calls in try-catch blocks
Data Validation : Validate user login IDs and parameters before making requests
Historical Data : Use appropriate days_back values to balance data completeness with performance
Position Monitoring : Regularly monitor open positions for risk management
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