/mql5-development:trade-managerfrom mql5-development
Post-entry trade lifecycle management for MQL5 EAs. Use for: ATR-based, swing-based, and chandelier trailing stops; breakeven logic; partial close and scale-out strategies; multi-target take profit; position scaling (pyramiding); trade modification via CTrade; managing multiple open positions; OrderSend/OrderSendAsync retcode handling; position, order, and history iteration APIs; pre-trade margin and profit calculation; standard-library trade wrapper classes (CTrade, CPositionInfo, COrderInfo, CDealInfo, CSymbolInfo, CAccountInfo). Trigger: "trailing stop", "breakeven", "partial close", "scale out", "pyramiding", "take profit", "manage positions", "move SL", "CTrade", "position management", "trade modification", "multi-target TP", "trail", "BE", "OrderSend", "OrderCheck".
Ships in mql5-development. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Trade management is where edge is multiplied. Good entries with poor management underperform. Average entries with excellent management outperform.
Defines Layer 4 of the 5-layer EA architecture: post-entry position management
— trailing stops, breakeven, partial closes, and trade lifecycle. Consumes
STradeSignal from Layer 3 (signal-engine) and manages positions until exit.
Do NOT use for:
signal-enginerisk-engineea-architect#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
class CTradeManager : public IModule {
private:
CTrade m_trade;
CPositionInfo m_position;
int m_magicNumber;
int m_slippage;
double m_beActivationRR;
double m_trailActivationRR;
double m_partialCloseRR;
double m_partialCloseSize;
public:
CTradeManager(int magic, double beRR = 1.0, double trailRR = 1.5,
double partialRR = 1.0, double partialSz = 0.5) {
m_magicNumber = magic; m_slippage = 10;
m_beActivationRR = beRR; m_trailActivationRR = trailRR;
m_partialCloseRR = partialRR; m_partialCloseSize = partialSz;
m_trade.SetExpertMagicNumber(magic);
m_trade.SetDeviationInPoints(m_slippage);
m_trade.SetTypeFilling(ORDER_FILLING_IOC);
}
bool IsReady() { return true; }
void Reset() { }
string GetStatus() { return "TradeManager: " + IntegerToString(PositionsTotal()) + " open"; }
};
bool OpenTrade(STradeSignal &sig, double lots) {
if(lots <= 0 || sig.type == SIGNAL_NONE) return false;
string comment = "M:" + IntegerToString(m_magicNumber) + " " + sig.reason;
bool result = false;
if(sig.type == SIGNAL_BUY)
result = m_trade.Buy(lots, _Symbol, 0, sig.stopLoss, sig.takeProfit, comment);
else if(sig.type == SIGNAL_SELL)
result = m_trade.Sell(lots, _Symbol, 0, sig.stopLoss, sig.takeProfit, comment);
if(!result)
PrintFormat("OpenTrade FAILED: %d - %s | SL:%.5f TP:%.5f",
GetLastError(), _Symbol, sig.stopLoss, sig.takeProfit);
return result;
}
void ManageOpenTrades() {
for(int i = PositionsTotal() - 1; i >= 0; i--) {
if(!m_position.SelectByIndex(i)) continue;
if(m_position.Magic() != m_magicNumber) continue;
ulong ticket = m_position.Ticket();
double open = m_position.PriceOpen();
double sl = m_position.StopLoss();
double tp = m_position.TakeProfit();
double current = m_position.PriceCurrent();
double slDist = MathAbs(open - sl);
if(slDist <= 0) continue;
ApplyPartialClose(ticket, open, sl, tp, current, slDist);
ApplyBreakeven(ticket, open, sl, tp, current, slDist);
ApplyATRTrail(ticket, open, sl, tp, current, slDist);
}
}
void ApplyBreakeven(ulong ticket, double open, double sl, double tp,
double current, double slDist) {
double spread = (double)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point;
if(m_position.PositionType() == POSITION_TYPE_BUY) {
double rr = (current - open) / slDist;
double newSL = open + spread;
if(rr >= m_beActivationRR && sl < newSL - _Point)
m_trade.PositionModify(ticket, newSL, tp);
} else {
double rr = (open - current) / slDist;
double newSL = open - spread;
if(rr >= m_beActivationRR && sl > newSL + _Point)
m_trade.PositionModify(ticket, newSL, tp);
}
}
void ApplyATRTrail(ulong ticket, double open, double sl, double tp,
double current, double slDist) {
double atr = iATR(_Symbol, PERIOD_H1, 14, 1);
double trail = atr * 1.5;
if(m_position.PositionType() == POSITION_TYPE_BUY) {
double rr = (current - open) / slDist;
double newSL = current - trail;
if(rr >= m_trailActivationRR && newSL > sl + _Point)
m_trade.PositionModify(ticket, newSL, tp);
} else {
double rr = (open - current) / slDist;
double newSL = current + trail;
if(rr >= m_trailActivationRR && newSL < sl - _Point)
m_trade.PositionModify(ticket, newSL, tp);
}
}
void ApplyPartialClose(ulong ticket, double open, double sl, double tp,
double current, double slDist) {
static ulong s_done[];
for(int i = 0; i < ArraySize(s_done); i++)
if(s_done[i] == ticket) return;
double rr = (m_position.PositionType() == POSITION_TYPE_BUY)
? (current - open) / slDist : (open - current) / slDist;
if(rr < m_partialCloseRR) return;
double totalLots = m_position.Volume();
double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double lotsToClose = MathFloor(totalLots * m_partialCloseSize / lotStep) * lotStep;
if(lotsToClose < minLot) return;
if(lotsToClose >= totalLots) lotsToClose = totalLots - minLot;
if(m_trade.PositionClosePartial(ticket, lotsToClose)) {
int sz = ArraySize(s_done);
ArrayResize(s_done, sz + 1);
s_done[sz] = ticket;
}
}
void CloseAllPositions(string reason = "") {
for(int i = PositionsTotal() - 1; i >= 0; i--) {
if(!m_position.SelectByIndex(i)) continue;
if(m_position.Magic() != m_magicNumber) continue;
m_trade.PositionClose(m_position.Ticket());
}
if(reason != "") Print("CloseAll reason: ", reason);
}
// Sniper (high R:R, low WR): no partial, BE at 1.5, trail at 2.0
g_TradeMgr = new CTradeManager(magic, 1.5, 2.0, 99.0, 0.0);
// Scalper (quick profit): 50% partial at 1.0, BE at 0.8, tight trail at 1.2
g_TradeMgr = new CTradeManager(magic, 0.8, 1.2, 1.0, 0.5);
// Swing (multi-day): 33% partial at 1.0 and 2.0, wide trail at 2.0
g_TradeMgr = new CTradeManager(magic, 1.0, 2.0, 1.0, 0.33);
total-1 to 0HistorySelect() before reading history — deal/order history
is not available without first selecting a time rangeTRADE_RETCODE_INVALID_VOLUMESetTypeFillingBySymbol()
instead of assuming ORDER_FILLING_IOC works on every brokerINVALID_HANDLE on PositionClose() — a closed or
stale ticket returns false with no error; verify ticket validity first| File | Contents | Read when |
|---|---|---|
references/strategy-profiles.md | Sniper/scalper/swing profile RR configs, constructor examples | Choosing management parameters for a strategy type |
references/raw-ordersend-api.md | MqlTradeRequest/MqlTradeResult fields, TRADE_RETCODE_*, OrderSend vs OrderSendAsync, OrderCheck | Using raw API instead of CTrade; debugging retcode failures |
references/trade-access-api.md | Position selection patterns, ENUM_POSITION_PROPERTY_*, pending order iteration, ENUM_ORDER_PROPERTY_* | Iterating positions or pending orders; reading property enums |
references/history-access-api.md | HistorySelect patterns, deal/order iteration, ENUM_DEAL_ENTRY, ENUM_DEAL_PROPERTY_* | Analysing past trades; duplicate-open prevention |
references/margin-profit-calculation.md | OrderCalcMargin, OrderCalcProfit, RiskToLots, R:R validation | Pre-trade sizing and risk validation |
references/ctrade-class.md | Full CTrade method table (70+ methods: open/modify/close, request/result/check introspection) | Any CTrade wrapper usage |
references/cpositioninfo-class.md | Full CPositionInfo method table (25+ methods: select, read price/SL/TP, snapshot) | Reading open position state |
references/corderinfo-class.md | COrderInfo + CHistoryOrderInfo method tables | Reading active or historical pending orders |
references/cdealinfo-class.md | Full CDealInfo method table (20+ methods: ticket, time, type, entry, profit, commission) | Analysing filled deal records |
references/csymbolinfo-accountinfo.md | CSymbolInfo (70+ methods) + CAccountInfo (30+ methods) method tables | Reading symbol properties, margin rules, account state |
references/cdealinfo-class.md (opens in a new tab)references/corderinfo-class.md (opens in a new tab)references/cpositioninfo-class.md (opens in a new tab)references/csymbolinfo-accountinfo.md (opens in a new tab)references/ctrade-class.md (opens in a new tab)references/history-access-api.md (opens in a new tab)references/margin-profit-calculation.md (opens in a new tab)references/raw-ordersend-api.md (opens in a new tab)references/strategy-profiles.md (opens in a new tab)references/trade-access-api.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
11 skills in this plugin
/constantsCanonical reference skill for MQL5 ENUM_* values, flag combinations, and property identifiers. Use for: looking up any ENUM_* name or property identifier; valid values for AccountInfo*, TerminalInfo*, Chart*, Object*, File* calls; combining bitmask flags (file modes, visibility, fill policy); trade return codes, runtime error codes, symbol property enums, Web colors, Wingdings codes, MessageBox constants. Trigger: "what does ENUM_ mean", "MQL5 error code", "property identifier", "valid values", "ENUM_SYMBOL_", "ENUM_ACCOUNT_", "ENUM_OBJECT_", "file flags", "Wingdings", "trade return code", "chart property", "OBJPROP_", "OrderGetInteger", "PositionGetDouble".
/ea-architectMaster MQL5 Expert Advisor architecture reference. Use for: wiring the 5-layer EA model (risk, regime, signal, trade mgmt, analytics); writing OnInit/OnTick/OnDeinit event handlers; setting up IsNewBar gating; designing include file layouts and .mqh module interfaces; applying naming conventions across all EA files; reading symbol properties in a broker-agnostic way; and integrating CExpert/CExpertSignal/CExpertMoney standard-library classes. Trigger: "5-layer architecture", "module wiring", "OnInit", "OnTick", "IsNewBar", "include files", "mqh", "CExpert", "event handlers", "EA template", "naming conventions", "broker-agnostic", "symbol data access".
npx claudepluginhub algotradingspace-dev/metatrader-skills --plugin mql5-development