In MQL5, you can easily bypass these correlation caps if an open trade is already secured. Before running either correlation check, inspect the open position's Stop Loss. If the Stop Loss is locked beyond the open price (a risk-free trade), ignore it in your correlation loop.
By adding if(IsPositionRiskFree(PositionGetTicket(i))) continue; to your loops, the EA will automatically clear the runway for new, correlated pyramiding positions using entirely unrealized market profit.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Implementing this in cTrader is highly efficient using the cAlgo.API. Because cTrader natively supports C#, you can bypass the clunky MQL array copying and directly query the MarketData.GetBars() collection.
Here is the lightweight C# implementation for a cBot.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
In cTrader, the ClosePrices.Last(i) index accesses data from right to left, where Last(0) is the currently fluctuating unclosed bar, and Last(1) is the most recently closed bar. This loop locks in the closed bars to ensure stability.
When your core entry logic detects a setup (e.g., on XAGUSD), you iterate through Positions to check for active correlation roadblocks. This loop automatically skips risk-free trades (which are financed by unrealized profit) and scales down the lot size if a highly correlated trade is actively tying up initial risk.
protected override void OnBar()
{
string candidateSymbol = "XAGUSD";
double kellyLotSize = 2.0; // Assume standard calculated lots
double correlationThreshold = 0.75;
// Setup detected...
bool setupTriggered = true;
if (setupTriggered)
{
foreach (var position in Positions)
{
// Ignore trades that can no longer cause an account loss
if (IsPositionRiskFree(position))
continue;
// Ignore the candidate symbol itself (let your pyramiding logic handle this)
if (position.SymbolName == candidateSymbol)
continue;
// Calculate correlation against the open position's symbol
double r = GetPearsonCorrelation(candidateSymbol, position.SymbolName, 30, TimeFrame.Hour4);
// If strongly correlated (positive or negative), apply a 50% haircut
if (Math.Abs(r) >= correlationThreshold)
{
kellyLotSize = Math.Round(kellyLotSize * 0.5, 2);
Print($"Correlated risk detected with {position.SymbolName} (r={r:F2}). Scaled lots to: {kellyLotSize}");
}
}
// Execute trade with final lot size
// ExecuteMarketOrder(TradeType.Buy, candidateSymbol, kellyLotSize, "PyramidEntry", sl, tp);
}
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.