Automated Position Sizing
Estimate volume from a risk budget and stop distance, then validate symbol volume steps, costs and margin before any order.
MetaTrader 4 & 5 automation guide
Forex trade management software is an automation utility or Expert Advisor (EA) running inside MetaTrader 4 or MetaTrader 5 that may support position sizing, automated stop loss and take profit placement, break-even shifts, trailing stops, and multi-stage partial exits. Verify these functions in the specific software; this page describes implementation choices.
Covering MT4 trade managers, MT5 trade managers, and custom trade management EAs.
Core capabilities
Effective trade management separates entry strategy from risk-control requests. Coverage depends on its code, terminal availability and whether the broker accepts each request.
Estimate volume from a risk budget and stop distance, then validate symbol volume steps, costs and margin before any order.
Move stop loss to break-even after reaching a target profit distance, and trail price using fixed steps, ATR volatility, or swing points.
Close predefined percentages of a position at successive profit targets (such as 50% at 1R, 25% at 2R) while letting the remainder run.
Define account-level checks and close-request triggers. Execution failures, gaps and terminal outages can prevent a threshold from capping actual losses.
Execution architecture
Whether operating in MT4 or MT5, a trade manager utility consists of distinct functional modules that coordinate order entry, ticket tracking, and position modification.
Specify a risk budget and estimate loss at the intended stop. Validate symbol valuation, round volume down and check free margin separately. Position sizing alone does not prevent leverage risk or cap losses during gaps.
Trade management panels place visual drag-and-drop lines on MetaTrader charts for entry, stop loss, and take profit. Traders can preview risk amounts in account currency before clicking Buy or Sell, with the trade manager applying predefined risk limits instantly upon execution.
An implemented manager can request stop changes or partial closes after configured triggers. A stop at entry plus a buffer is not guaranteed break-even after commission, financing, slippage or a gap. Verify acceptance and the actual remaining position.
For multi-pair or grid traders, a trade manager monitors aggregate open profit and loss across all tickets. It can trigger a global profit target exit, close all open trades if a daily loss threshold is reached, or delete pending orders upon market close.
Software comparison
Evaluate trade management options by code transparency, customization, execution latency, and licensing boundaries.
| Dimension | Commercial Trade Manager | Custom MQL4 / MQL5 Trade Manager | Manual Trade Execution |
|---|---|---|---|
| Source code access | Check whether source is supplied; binaries are common | Full editable .mq4 or .mq5 source code | No code involved |
| License & account locks | Terms and account restrictions vary by product | Review code licenses, broker support and account rules | No license required |
| Custom rule adaptation | Restricted to developer-defined settings and options | Editable logic still requires implementation and testing | Dependent on manual calculation speed |
| Execution latency | Depends on implementation, terminal, network and broker | Direct local execution inside MetaTrader terminal | Operator response and broker execution both matter |
| External dependencies | Inspect the actual dependency and permission list | Can use native APIs; verify generated dependencies | None |
| Multi-target partial closes | Included in selected commercial utility panels | Must respect account mode, volume steps and residual size | Submit partial-close requests within broker constraints |
The underlying trading engine differs between MetaTrader 4 and MetaTrader 5. Understanding how orders and positions are tracked is essential when designing a trade manager.
MT4 treats each entry as an independent order ticket. A trade manager selects tickets using OrderSelect(), checks the Magic Number and symbol, modifies price levels with OrderModify(), and executes partial exits using OrderClose() with fractional lot sizes.
MT5 separates orders, deals, and positions. In hedging mode, each position has a unique identifier. The standard CTrade class simplifies trade operations via PositionModify() and PositionClosePartial(), the latter for hedging accounts only. Netting reduction needs a correctly sized opposite deal. Inspect ResultRetcode() and actual position state; a true return value is not proof of execution.
// Illustrative MQL5 helper: no orders are submitted.
// 0 means invalid inputs or no admissible volume within this estimate.
double CalculateLotSize(double riskPercent, double slPoints) {
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE_LOSS);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
if(!MathIsValidNumber(riskPercent) || !MathIsValidNumber(slPoints) ||
!MathIsValidNumber(balance) || !MathIsValidNumber(tickValue) ||
!MathIsValidNumber(tickSize) || !MathIsValidNumber(point) ||
!MathIsValidNumber(minLot) || !MathIsValidNumber(maxLot) ||
!MathIsValidNumber(lotStep) ||
riskPercent <= 0 || riskPercent > 100 || slPoints <= 0 ||
balance <= 0 || tickValue <= 0 || tickSize <= 0 || point <= 0 ||
minLot <= 0 || maxLot < minLot || lotStep <= 0) return 0;
double riskAmount = balance * riskPercent / 100.0;
double moneyPerLot = slPoints * point / tickSize * tickValue;
if(!MathIsValidNumber(moneyPerLot) || moneyPerLot <= 0) return 0;
double rawLots = riskAmount / moneyPerLot;
if(!MathIsValidNumber(rawLots) || rawLots < minLot) return 0;
double lots = MathFloor(MathMin(rawLots, maxLot) / lotStep) * lotStep;
if(lots < minLot || lots * moneyPerLot > riskAmount) return 0;
return lots;
}This tick-value estimate omits commissions, financing and slippage. Compare with OrderCalcProfit for the actual symbol and entry/stop prices, then use OrderCheck and margin checks. It does not place a stop, enforce a loss cap or submit an order.
Implementation workflow
Follow this five-step engineering process to design, generate, verify, and execute your own trade management software on MetaTrader.
Define position sizing basis (equity vs balance), risk percentage, break-even trigger distance, trailing stop type (fixed points, ATR, or bar highs/lows), and partial close milestones.
Ask Pineify to draft editable .mq4 or .mq5 code for the specified rules, then review the implementation and dependencies.
Open MetaEditor (shortcut F4 in MetaTrader), paste the generated code, and compile (shortcut F7). Review diagnostics to confirm zero errors and zero warnings.
Attach the compiled trade manager to a demo chart or test execution mechanics in the MetaTrader Strategy Tester to verify lot calculation, trailing stops, and scale-outs.
Attach the EA to your trading chart with AutoTrading enabled. Optionally deploy on a low-latency VPS to maintain continuous trade management around the clock.
Pineify AI Coding Agents
Build single-file, editable MQL4 and MQL5 trade manager EAs from a written specification. Review code, dependencies and current plan limits; generation does not guarantee execution correctness or eliminate broker restrictions.
What to Review in Generated MQL Code
Generate and revise editable MQL5 Expert Advisors, indicators, and trade scripts.
Create single-file MT4 Expert Advisors and indicators from plain English prompts.
Learn how to open, write, compile, and debug MQL4 and MQL5 code in MetaEditor.
Explore automated strategy creation and trade execution workflows in MetaTrader 4.
Configure position sizing, stop loss limits, and drawdown management in MT5.
Track trade execution metrics, risk-reward performance, and psychological discipline.
This page provides technical software engineering information, not financial or investment advice. Trading foreign exchange on margin carries significant risk of loss. Always test trade management algorithms on a demo account before applying real capital.