Optimizing and Refactoring HmaClusterBot & -Indicator

This commit is contained in:
Michael Schimmel
2026-01-28 13:47:53 +01:00
parent a1d2e96f8a
commit eaaa507c34
54 changed files with 909 additions and 2928 deletions
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using Myc; // Referenz auf die extrahierte Cluster-Logik
namespace cAlgo.Robots
{
@@ -71,12 +72,12 @@ namespace cAlgo.Robots
protected override void OnStart()
{
try
try
{
if (string.IsNullOrWhiteSpace(SymbolsCsv))
{
Print("CSV is empty. Running in Single-Symbol Mode on Chart Symbol.");
var config = new StrategyConfig
{
SymbolName = SymbolName,
@@ -129,6 +130,10 @@ namespace cAlgo.Robots
{
Print(message);
// WICHTIG: Im Backtest NIEMALS Netzwerk-Calls machen, auch nicht bei Fehlern.
// Das führt bei vielen Fehlern zum Stillstand der Simulation.
if (IsBacktesting) return;
if (!string.IsNullOrWhiteSpace(TelegramBotToken) && !string.IsNullOrWhiteSpace(TelegramChatId))
{
string formattedMsg = $"⚠️ <b>ERROR @ {DateTime.UtcNow:HH:mm:ss} UTC</b>\n\n{message}";
@@ -138,6 +143,8 @@ namespace cAlgo.Robots
private async Task SendTelegramRawAsync(string token, string chatId, string message)
{
if (IsBacktesting) return;
try
{
string url = $"https://api.telegram.org/bot{token}/sendMessage?chat_id={chatId}&text={Uri.EscapeDataString(message)}&parse_mode=HTML";
@@ -152,7 +159,7 @@ namespace cAlgo.Robots
private void ParseCsvAndCreateStrategies()
{
var normalizedCsv = SymbolsCsv.Replace("\n", ",").Replace("\r", ",");
var tokens = normalizedCsv.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim())
.Where(t => !string.IsNullOrEmpty(t))
@@ -195,9 +202,8 @@ namespace cAlgo.Robots
BiasDeviationAvgPeriod = int.Parse(tokens[i + 7], CultureInfo.InvariantCulture),
UseDynamicPositionManagement = bool.Parse(tokens[i + 8]),
SendTelegramOnly = bool.Parse(tokens[i + 9]),
// Defaults from global params
CloseProfitOnBiasFlip = CloseProfitOnBiasFlip,
CloseProfitOnBiasFlip = CloseProfitOnBiasFlip,
RiskPercent = RiskPercent,
MaxPoints = MaxPoints,
DecayPeriod = DecayPeriod
@@ -239,16 +245,8 @@ namespace cAlgo.Robots
{
#region Types & Fields
private enum PointType { Peak, Trough }
private enum Bias { Long, Short, Neutral }
private struct ExtremumPoint
{
public double Price;
public int Index;
public PointType Type;
}
public struct ClusterLevel
{
public double Price;
@@ -270,13 +268,14 @@ namespace cAlgo.Robots
private readonly Queue<double> _deviationQueue = new Queue<double>();
private double _runningDeviationSum;
private bool _deviationConditionMetInCurrentCycle;
private bool _isTradingAllowedBasedOnPrevCycle;
private readonly List<ExtremumPoint> _extremaPoints = new();
// --- OPTIMIERUNG: Nutzt Calculator statt Liste ---
private readonly Myc.ClusterCalculator _clusterCalculator;
private readonly List<double> _amplitudes = new();
private double _trendExtremum;
private int _trendExtremumIndex;
private double _lastExtremumPrice;
@@ -288,12 +287,12 @@ namespace cAlgo.Robots
#endregion
public ClusterStrategy(
Robot robot,
Symbol symbol,
Bars bars,
StrategyConfig config,
HttpClient httpClient,
string token,
Robot robot,
Symbol symbol,
Bars bars,
StrategyConfig config,
HttpClient httpClient,
string token,
string chatId,
Action<string> errorCallback)
{
@@ -305,17 +304,20 @@ namespace cAlgo.Robots
_botToken = token;
_chatId = chatId;
_errorCallback = errorCallback;
// Calculator mit Reserve initialisieren
_clusterCalculator = new Myc.ClusterCalculator(_config.MaxPoints + 200);
}
public void Start()
{
int requiredBars = Math.Max(_config.SmaBiasPeriod, _config.HmaBiasPeriod);
requiredBars = Math.Max(requiredBars, _config.BiasDeviationAvgPeriod) + 10;
requiredBars = Math.Max(requiredBars, _config.BiasDeviationAvgPeriod) + 10;
while (_bars.Count < requiredBars)
{
int loaded = _bars.LoadMoreHistory();
if (loaded == 0)
if (loaded == 0)
{
_errorCallback?.Invoke($"Not enough history for {_config.SymbolName}. Loaded: {_bars.Count}, Req: {requiredBars}");
return;
@@ -332,11 +334,11 @@ namespace cAlgo.Robots
int startIndex = Math.Max(_config.SmaBiasPeriod, _config.HmaBiasPeriod);
startIndex = Math.Max(startIndex, _config.BiasDeviationAvgPeriod);
for (int i = startIndex; i < _bars.Count; i++)
{
UpdateFilterState(i);
UpdateClusterData(i);
UpdateClusterData(i);
}
_bars.BarOpened += OnBarOpened;
@@ -356,24 +358,21 @@ namespace cAlgo.Robots
UpdateFilterState(index);
UpdateClusterData(index);
var clusters = CalculateClusters(index);
// 1. Dynamic SL/TP Management
if (!_config.SendTelegramOnly && _config.UseDynamicPositionManagement && clusters.Count >= 2)
{
ManagePositions(clusters);
}
var currentBias = GetCurrentBias(index);
// 2. Check for Profit Close on Bias Flip
if (!_config.SendTelegramOnly && _config.CloseProfitOnBiasFlip)
{
CloseReversedPositions(currentBias);
}
// 3. New Entry Logic with FIXED Orphan-Cleanup and Validations
ManageOrders(currentBias, index, clusters);
}
catch (Exception ex)
@@ -389,7 +388,7 @@ namespace cAlgo.Robots
foreach (var pos in _robot.Positions)
{
if (pos.SymbolName != _config.SymbolName || pos.Label != Label) continue;
if (pos.NetProfit <= 0) continue;
if (pos.NetProfit <= 0) continue;
bool close = false;
@@ -405,7 +404,7 @@ namespace cAlgo.Robots
{
string msg = $"🔒 <b>CLOSE PROFIT</b> (Bias Flip) @ <b>{_config.SymbolName}</b>\n" +
$"Profit: {pos.NetProfit:F2}";
_ = SendTelegramMessageAsync(msg);
_ = SendTelegramMessageAsync(msg);
}
}
}
@@ -419,7 +418,7 @@ namespace cAlgo.Robots
double prevSma = _smaBias.Result[index - 1];
double currentBiasDeviation = Math.Abs(currHma - currSma);
_deviationQueue.Enqueue(currentBiasDeviation);
_runningDeviationSum += currentBiasDeviation;
@@ -429,8 +428,8 @@ namespace cAlgo.Robots
_runningDeviationSum -= removed;
}
double averageDeviation = (_deviationQueue.Count > 0)
? _runningDeviationSum / _deviationQueue.Count
double averageDeviation = (_deviationQueue.Count > 0)
? _runningDeviationSum / _deviationQueue.Count
: 0.0;
bool currHmaAbove = currHma > currSma;
@@ -462,7 +461,7 @@ namespace cAlgo.Robots
private void ManagePositions(List<ClusterLevel> clusters)
{
double pNow = _symbol.Bid;
double pNow = _symbol.Bid;
foreach (var pos in _robot.Positions)
{
@@ -509,7 +508,7 @@ namespace cAlgo.Robots
}
}
}
else // Sell
else
{
double lowestSlPrice = double.MaxValue;
double lowestTpPrice = double.MaxValue;
@@ -552,10 +551,9 @@ namespace cAlgo.Robots
private void ManageOrders(Bias bias, int index, List<ClusterLevel> clusters)
{
// Standard Cleanup: Orders in wrong direction (Bias Change)
CleanupWrongBiasOrders(bias);
if (_config.UseBiasDeviationFilter && !_isTradingAllowedBasedOnPrevCycle)
if (_config.UseBiasDeviationFilter && !_isTradingAllowedBasedOnPrevCycle)
return;
if (bias == Bias.Neutral) return;
@@ -565,11 +563,9 @@ namespace cAlgo.Robots
bool hasLong = _robot.Positions.Any(p => p.SymbolName == _config.SymbolName && p.Label == Label && p.TradeType == TradeType.Buy);
bool hasShort = _robot.Positions.Any(p => p.SymbolName == _config.SymbolName && p.Label == Label && p.TradeType == TradeType.Sell);
// --- FIX 1: Open Positions Cleanup ---
// If we are already invested, we ensure no pending orders for the same direction are lingering around.
if (bias == Bias.Long && hasLong)
{
CancelPendingOrders(TradeType.Buy);
CancelPendingOrders(TradeType.Buy);
return;
}
if (bias == Bias.Short && hasShort)
@@ -723,38 +719,18 @@ namespace cAlgo.Robots
{
var existingOrder = _robot.PendingOrders.FirstOrDefault(o => o.SymbolName == _config.SymbolName && o.Label == Label && o.TradeType == type);
// --- FIX 4: Market Proximity Check ---
// If the limit price is invalid (e.g. Buy Limit above Ask), we must abort/cancel.
bool priceInvalid = false;
double buffer = _symbol.PipSize;
double buffer = _symbol.PipSize;
if (type == TradeType.Buy && entry >= (_symbol.Ask - buffer)) return;
if (type == TradeType.Sell && entry <= (_symbol.Bid + buffer)) return;
if (type == TradeType.Buy && entry >= (_symbol.Ask - buffer)) priceInvalid = true;
if (type == TradeType.Sell && entry <= (_symbol.Bid + buffer)) priceInvalid = true;
if (priceInvalid)
{
if (existingOrder != null) _robot.CancelPendingOrder(existingOrder);
return;
}
// --- FIX 3: SL Distance Check ---
double slDistPips = Math.Abs(entry - sl) / _symbol.PipSize;
if (slDistPips <= 0)
{
if (existingOrder != null) _robot.CancelPendingOrder(existingOrder);
return;
}
if (slDistPips <= 0) return;
// --- FIX 2: Volume Check ---
double riskAmount = _robot.Account.Balance * (_config.RiskPercent / 100.0);
double volume = _symbol.VolumeForFixedRisk(riskAmount, slDistPips);
volume = _symbol.NormalizeVolumeInUnits(volume, RoundingMode.Down);
if (volume < _symbol.VolumeInUnitsMin)
{
if (existingOrder != null) _robot.CancelPendingOrder(existingOrder);
return;
}
if (volume < _symbol.VolumeInUnitsMin) return;
double lots = _symbol.VolumeInUnitsToQuantity(volume);
@@ -763,11 +739,11 @@ namespace cAlgo.Robots
string directionStr = type == TradeType.Buy ? "BUY" : "SELL";
string directionIcon = type == TradeType.Buy ? "📈" : "📉";
string msg = $"{directionIcon} <b>{directionStr}</b> Signal @ <b>{_config.SymbolName}</b>\n\n" +
$"<b>Entry:</b> {entry}\n" +
$"<b>SL:</b> {sl}\n" +
$"<b>TP:</b> {tp}\n" +
$"<b>Vol:</b> {lots:F2} Lots";
$"<b>Entry:</b> {entry}\n" +
$"<b>SL:</b> {sl}\n" +
$"<b>TP:</b> {tp}\n" +
$"<b>Vol:</b> {lots:F2} Lots";
_ = SendTelegramMessageAsync(msg);
return;
}
@@ -784,16 +760,13 @@ namespace cAlgo.Robots
var result = _robot.ModifyPendingOrder(existingOrder, entry, sl, tp, ProtectionType.Absolute, null, volume);
if (!result.IsSuccessful)
{
// Fallback: If modify fails (e.g. spread jump), cancel it to avoid stale orders
// Falls Modifikation fehlschlägt (z.B. Spread), löschen wir die Order, um keine veralteten Levels zu handeln
_robot.CancelPendingOrder(existingOrder);
}
}
}
else
{
_robot.Print("[SIGNAL] {0} {1} | Entry: {2} | SL: {3} | TP: {4} | Vol: {5:F2} Lots",
(type == TradeType.Buy ? "BUY" : "SELL"), _config.SymbolName, entry, sl, tp, lots);
_robot.PlaceLimitOrder(type, _config.SymbolName, volume, entry, Label, sl, tp, ProtectionType.Absolute);
}
}
@@ -807,7 +780,7 @@ namespace cAlgo.Robots
{
string url = $"https://api.telegram.org/bot{_botToken}/sendMessage?chat_id={_chatId}&text={Uri.EscapeDataString(message)}&parse_mode=HTML";
HttpResponseMessage response = await _httpClient.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
_errorCallback?.Invoke($"Telegram Error: {response.StatusCode}");
@@ -842,11 +815,18 @@ namespace cAlgo.Robots
if (_amplitudes.Count > 50) _amplitudes.RemoveAt(0);
double sum = 0;
for (int i = 0; i < _amplitudes.Count; i++) sum += _amplitudes[i];
for(int i=0; i<_amplitudes.Count; i++) sum += _amplitudes[i];
_currentDynamicRange = (sum / _amplitudes.Count) * 0.5;
if (_currentDynamicRange < _symbol.PipSize) _currentDynamicRange = _symbol.PipSize;
}
_extremaPoints.Add(new ExtremumPoint { Price = _trendExtremum, Index = _trendExtremumIndex, Type = _isUpTrend.Value ? PointType.Peak : PointType.Trough });
if (_extremaPoints.Count > _config.MaxPoints) _extremaPoints.RemoveAt(0);
// Neuen Punkt in den optimierten Calculator einspeisen
_clusterCalculator.AddPoint(new Myc.ExtremumPoint
{
Price = _trendExtremum,
Index = _trendExtremumIndex,
Type = _isUpTrend.Value ? Myc.PointType.Peak : Myc.PointType.Trough
});
_lastExtremumPrice = _trendExtremum;
_isUpTrend = currentDirectionUp;
@@ -880,57 +860,23 @@ namespace cAlgo.Robots
private List<ClusterLevel> CalculateClusters(int currentIndex)
{
int count = _extremaPoints.Count;
if (count == 0) return new List<ClusterLevel>();
double currentPrice = _bars.ClosePrices[currentIndex];
double[] weights = new double[count];
double totalWeightSum = 0;
for (int i = 0; i < count; i++)
var result = _clusterCalculator.Calculate(
currentIndex,
currentPrice,
_currentDynamicRange,
_config.DecayPeriod,
100
);
if (result.TotalWeight == 0 || result.Zones.Count == 0) return new List<ClusterLevel>();
return result.Zones.Select(z => new ClusterLevel
{
weights[i] = GetWeight(_extremaPoints[i], currentIndex, currentPrice);
totalWeightSum += weights[i];
}
if (totalWeightSum == 0) return new List<ClusterLevel>();
var zones = new List<ClusterLevel>();
for (int i = count - 1; i >= 0; i--)
{
var p = _extremaPoints[i];
bool exists = false;
for (int j = 0; j < zones.Count; j++)
{
if (Math.Abs(zones[j].Price - p.Price) < _currentDynamicRange)
{
exists = true;
break;
}
}
if (exists) continue;
double score = 0;
for (int k = 0; k < count; k++)
{
if (Math.Abs(_extremaPoints[k].Price - p.Price) <= _currentDynamicRange)
{
score += weights[k];
}
}
zones.Add(new ClusterLevel { Price = p.Price, Significance = (score / totalWeightSum) * 100.0 });
}
return zones;
}
private double GetWeight(ExtremumPoint point, int currentIndex, double currentPrice)
{
double weight = Math.Max(0.0, 1.0 - ((double)(currentIndex - point.Index) / _config.DecayPeriod));
if ((point.Type == PointType.Peak) && (point.Price < currentPrice)) weight *= 2.0;
else if ((point.Type == PointType.Trough) && (point.Price > currentPrice)) weight *= 2.0;
return weight;
Price = z.Price,
Significance = (z.Score / result.TotalWeight) * 100.0
}).ToList();
}
}
}
@@ -6,4 +6,9 @@
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="*" />
</ItemGroup>
<ItemGroup>
<Reference Include="MSLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>..\..\..\Common\MSLib\obj\Debug\net6.0\MSLib.dll</HintPath>
</Reference>
</ItemGroup>
</Project>