Initial commit

This commit is contained in:
Michael Schimmel
2026-01-28 09:10:52 +01:00
commit a1d2e96f8a
513 changed files with 19503 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
{"version":"2.0.0","tasks":[{"label":"build","command":"dotnet","type":"process","args":["build","${workspaceFolder}","/property:GenerateFullPaths=true","/consoleLoggerParameters:NoSummary"],"problemMatcher":"$msCompile"}]}
@@ -0,0 +1,22 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30011.22
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HmaClusterBot", "HmaClusterBot\HmaClusterBot.csproj", "{5ca67298-283e-4125-b2b7-5ca1cceeb315}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5ca67298-283e-4125-b2b7-5ca1cceeb315}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5ca67298-283e-4125-b2b7-5ca1cceeb315}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5ca67298-283e-4125-b2b7-5ca1cceeb315}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5ca67298-283e-4125-b2b7-5ca1cceeb315}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,936 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class HmaClusterBot : Robot
{
#region Parameters
[Parameter("Symbols (CSV)", DefaultValue = "", Group = "Multi Symbol")]
public string SymbolsCsv { get; set; }
[Parameter("Risk % of Balance", DefaultValue = 1.0, MinValue = 0.1, MaxValue = 10.0, Group = "Risk")]
public double RiskPercent { get; set; }
[Parameter("Entry Significance %", DefaultValue = 20.0, MinValue = 1.0, Group = "Thresholds")]
public double EntrySigThreshold { get; set; }
[Parameter("Stop Loss Significance %", DefaultValue = 10.0, MinValue = 1.0, Group = "Thresholds")]
public double SlSigThreshold { get; set; }
[Parameter("SMA Bias Period", DefaultValue = 200, Group = "Bias")]
public int SmaBiasPeriod { get; set; }
[Parameter("HMA Bias Period", DefaultValue = 250, Group = "Bias")]
public int HmaBiasPeriod { get; set; }
[Parameter("Use Bias Deviation Filter", DefaultValue = true, Group = "Bias Filter")]
public bool UseBiasDeviationFilter { get; set; }
[Parameter("Bias Deviation Avg Period", DefaultValue = 500, Group = "Bias Filter")]
public int BiasDeviationAvgPeriod { get; set; }
[Parameter("Use Dynamic Position Management", DefaultValue = true, Group = "Management")]
public bool UseDynamicPositionManagement { get; set; }
[Parameter("Close Profit on Bias Flip", DefaultValue = false, Group = "Management")]
public bool CloseProfitOnBiasFlip { get; set; }
[Parameter("HMA Cluster Period", DefaultValue = 25, Group = "Clusters")]
public int HmaClusterPeriod { get; set; }
[Parameter("Cluster Max Points", DefaultValue = 2000, Group = "Clusters")]
public int MaxPoints { get; set; }
[Parameter("Cluster Decay (Bars)", DefaultValue = 1000, Group = "Clusters")]
public int DecayPeriod { get; set; }
// --- Telegram Parameters ---
[Parameter("Send Telegram Only", DefaultValue = false, Group = "Telegram")]
public bool SendTelegramOnly { get; set; }
[Parameter("Telegram Bot Token", DefaultValue = "", Group = "Telegram")]
public string TelegramBotToken { get; set; }
[Parameter("Telegram Chat ID", DefaultValue = "", Group = "Telegram")]
public string TelegramChatId { get; set; }
#endregion
private readonly List<ClusterStrategy> _strategies = new List<ClusterStrategy>();
private static readonly HttpClient _httpClient = new HttpClient();
protected override void OnStart()
{
try
{
if (string.IsNullOrWhiteSpace(SymbolsCsv))
{
Print("CSV is empty. Running in Single-Symbol Mode on Chart Symbol.");
var config = new StrategyConfig
{
SymbolName = SymbolName,
EntrySigThreshold = EntrySigThreshold,
SlSigThreshold = SlSigThreshold,
SmaBiasPeriod = SmaBiasPeriod,
HmaBiasPeriod = HmaBiasPeriod,
HmaClusterPeriod = HmaClusterPeriod,
UseBiasDeviationFilter = UseBiasDeviationFilter,
BiasDeviationAvgPeriod = BiasDeviationAvgPeriod,
UseDynamicPositionManagement = UseDynamicPositionManagement,
CloseProfitOnBiasFlip = CloseProfitOnBiasFlip,
SendTelegramOnly = SendTelegramOnly,
RiskPercent = RiskPercent,
MaxPoints = MaxPoints,
DecayPeriod = DecayPeriod
};
var strategy = new ClusterStrategy(this, Symbol, Bars, config, _httpClient, TelegramBotToken, TelegramChatId, BroadcastError);
_strategies.Add(strategy);
strategy.Start();
}
else
{
Print("CSV detected. Running in Multi-Symbol Mode.");
ParseCsvAndCreateStrategies();
}
}
catch (Exception ex)
{
BroadcastError($"CRITICAL STARTUP ERROR: {ex.Message}");
Stop();
}
}
protected override void OnStop()
{
foreach (var strategy in _strategies)
{
strategy.Stop();
}
}
protected override void OnError(Error error)
{
BroadcastError($"TRADING ERROR [{error.Code}]: {error.ToString}");
}
public void BroadcastError(string message)
{
Print(message);
if (!string.IsNullOrWhiteSpace(TelegramBotToken) && !string.IsNullOrWhiteSpace(TelegramChatId))
{
string formattedMsg = $"⚠️ <b>ERROR @ {DateTime.UtcNow:HH:mm:ss} UTC</b>\n\n{message}";
_ = SendTelegramRawAsync(TelegramBotToken, TelegramChatId, formattedMsg);
}
}
private async Task SendTelegramRawAsync(string token, string chatId, string message)
{
try
{
string url = $"https://api.telegram.org/bot{token}/sendMessage?chat_id={chatId}&text={Uri.EscapeDataString(message)}&parse_mode=HTML";
await _httpClient.GetAsync(url);
}
catch (Exception ex)
{
Print("FAILED TO SEND TELEGRAM ERROR: " + ex.Message);
}
}
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))
.ToArray();
int paramsPerSymbol = 10;
if (tokens.Length % paramsPerSymbol != 0)
{
string err = $"CSV Token count ({tokens.Length}) is not a multiple of {paramsPerSymbol}. Check format.";
BroadcastError(err);
}
for (int i = 0; i < tokens.Length; i += paramsPerSymbol)
{
if (i + paramsPerSymbol > tokens.Length) break;
string symName = tokens[i];
try
{
Symbol symbol = Symbols.GetSymbol(symName);
if (symbol == null)
{
BroadcastError($"Symbol '{symName}' not found in cTrader.");
continue;
}
Bars bars = MarketData.GetBars(TimeFrame, symName);
var config = new StrategyConfig
{
SymbolName = symName,
EntrySigThreshold = double.Parse(tokens[i + 1], CultureInfo.InvariantCulture),
SlSigThreshold = double.Parse(tokens[i + 2], CultureInfo.InvariantCulture),
SmaBiasPeriod = int.Parse(tokens[i + 3], CultureInfo.InvariantCulture),
HmaBiasPeriod = int.Parse(tokens[i + 4], CultureInfo.InvariantCulture),
HmaClusterPeriod = int.Parse(tokens[i + 5], CultureInfo.InvariantCulture),
UseBiasDeviationFilter = bool.Parse(tokens[i + 6]),
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,
RiskPercent = RiskPercent,
MaxPoints = MaxPoints,
DecayPeriod = DecayPeriod
};
var strategy = new ClusterStrategy(this, symbol, bars, config, _httpClient, TelegramBotToken, TelegramChatId, BroadcastError);
_strategies.Add(strategy);
strategy.Start();
Print("Initialized Strategy for {0}", symName);
}
catch (Exception ex)
{
BroadcastError($"Config Error for '{symName}': {ex.Message}");
}
}
}
}
public class StrategyConfig
{
public string SymbolName { get; set; }
public double EntrySigThreshold { get; set; }
public double SlSigThreshold { get; set; }
public int SmaBiasPeriod { get; set; }
public int HmaBiasPeriod { get; set; }
public int HmaClusterPeriod { get; set; }
public bool UseBiasDeviationFilter { get; set; }
public int BiasDeviationAvgPeriod { get; set; }
public bool UseDynamicPositionManagement { get; set; }
public bool CloseProfitOnBiasFlip { get; set; }
public bool SendTelegramOnly { get; set; }
public double RiskPercent { get; set; }
public int MaxPoints { get; set; }
public int DecayPeriod { get; set; }
}
public class ClusterStrategy
{
#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;
public double Significance;
}
private readonly Robot _robot;
private readonly Symbol _symbol;
private readonly Bars _bars;
private readonly StrategyConfig _config;
private readonly HttpClient _httpClient;
private readonly string _botToken;
private readonly string _chatId;
private readonly Action<string> _errorCallback;
private SimpleMovingAverage _smaBias;
private HullMovingAverage _hmaBias;
private HullMovingAverage _hmaCluster;
private readonly Queue<double> _deviationQueue = new Queue<double>();
private double _runningDeviationSum;
private bool _deviationConditionMetInCurrentCycle;
private bool _isTradingAllowedBasedOnPrevCycle;
private readonly List<ExtremumPoint> _extremaPoints = new();
private readonly List<double> _amplitudes = new();
private double _trendExtremum;
private int _trendExtremumIndex;
private double _lastExtremumPrice;
private bool? _isUpTrend;
private double _currentDynamicRange;
private const string Label = "HmaClusterBot";
#endregion
public ClusterStrategy(
Robot robot,
Symbol symbol,
Bars bars,
StrategyConfig config,
HttpClient httpClient,
string token,
string chatId,
Action<string> errorCallback)
{
_robot = robot;
_symbol = symbol;
_bars = bars;
_config = config;
_httpClient = httpClient;
_botToken = token;
_chatId = chatId;
_errorCallback = errorCallback;
}
public void Start()
{
int requiredBars = Math.Max(_config.SmaBiasPeriod, _config.HmaBiasPeriod);
requiredBars = Math.Max(requiredBars, _config.BiasDeviationAvgPeriod) + 10;
while (_bars.Count < requiredBars)
{
int loaded = _bars.LoadMoreHistory();
if (loaded == 0)
{
_errorCallback?.Invoke($"Not enough history for {_config.SymbolName}. Loaded: {_bars.Count}, Req: {requiredBars}");
return;
}
}
_smaBias = _robot.Indicators.SimpleMovingAverage(_bars.ClosePrices, _config.SmaBiasPeriod);
_hmaBias = _robot.Indicators.HullMovingAverage(_bars.ClosePrices, _config.HmaBiasPeriod);
_hmaCluster = _robot.Indicators.HullMovingAverage(_bars.ClosePrices, _config.HmaClusterPeriod);
_currentDynamicRange = 5.0 * _symbol.PipSize;
_deviationConditionMetInCurrentCycle = false;
_isTradingAllowedBasedOnPrevCycle = false;
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);
}
_bars.BarOpened += OnBarOpened;
}
public void Stop()
{
_bars.BarOpened -= OnBarOpened;
}
private void OnBarOpened(BarOpenedEventArgs obj)
{
try
{
int index = _bars.Count - 2;
if (index < _config.BiasDeviationAvgPeriod) return;
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)
{
_errorCallback?.Invoke($"Runtime Error ({_config.SymbolName}): {ex.Message}\n{ex.StackTrace}");
}
}
private void CloseReversedPositions(Bias currentBias)
{
if (currentBias == Bias.Neutral) return;
foreach (var pos in _robot.Positions)
{
if (pos.SymbolName != _config.SymbolName || pos.Label != Label) continue;
if (pos.NetProfit <= 0) continue;
bool close = false;
if (currentBias == Bias.Short && pos.TradeType == TradeType.Buy)
close = true;
else if (currentBias == Bias.Long && pos.TradeType == TradeType.Sell)
close = true;
if (close)
{
var result = _robot.ClosePosition(pos);
if (result.IsSuccessful)
{
string msg = $"🔒 <b>CLOSE PROFIT</b> (Bias Flip) @ <b>{_config.SymbolName}</b>\n" +
$"Profit: {pos.NetProfit:F2}";
_ = SendTelegramMessageAsync(msg);
}
}
}
}
private void UpdateFilterState(int index)
{
double currHma = _hmaBias.Result[index];
double currSma = _smaBias.Result[index];
double prevHma = _hmaBias.Result[index - 1];
double prevSma = _smaBias.Result[index - 1];
double currentBiasDeviation = Math.Abs(currHma - currSma);
_deviationQueue.Enqueue(currentBiasDeviation);
_runningDeviationSum += currentBiasDeviation;
if (_deviationQueue.Count > _config.BiasDeviationAvgPeriod)
{
double removed = _deviationQueue.Dequeue();
_runningDeviationSum -= removed;
}
double averageDeviation = (_deviationQueue.Count > 0)
? _runningDeviationSum / _deviationQueue.Count
: 0.0;
bool currHmaAbove = currHma > currSma;
bool prevHmaAbove = prevHma > prevSma;
if (currHmaAbove != prevHmaAbove)
{
_isTradingAllowedBasedOnPrevCycle = _deviationConditionMetInCurrentCycle;
_deviationConditionMetInCurrentCycle = false;
}
if (currentBiasDeviation > averageDeviation)
{
_deviationConditionMetInCurrentCycle = true;
}
}
private Bias GetCurrentBias(int index)
{
double hma = _hmaBias.Result[index];
double sma = _smaBias.Result[index];
double prevSma = _smaBias.Result[index - 1];
if ((hma > sma) && (sma > prevSma)) return Bias.Long;
if ((hma < sma) && (sma < prevSma)) return Bias.Short;
return Bias.Neutral;
}
private void ManagePositions(List<ClusterLevel> clusters)
{
double pNow = _symbol.Bid;
foreach (var pos in _robot.Positions)
{
if (pos.Label != Label || pos.SymbolName != _config.SymbolName) continue;
ClusterLevel? newSl = null;
ClusterLevel? newTp = null;
if (pos.TradeType == TradeType.Buy)
{
double highestSlPrice = double.MinValue;
double highestTpPrice = double.MinValue;
foreach (var c in clusters)
{
if (c.Price < pNow && c.Significance < _config.SlSigThreshold && c.Price > highestSlPrice)
{
newSl = c;
highestSlPrice = c.Price;
}
if (c.Price > pNow && c.Significance >= _config.EntrySigThreshold && c.Price > highestTpPrice)
{
newTp = c;
highestTpPrice = c.Price;
}
}
double proposedSl = (newSl.HasValue) ? newSl.Value.Price : (pos.StopLoss ?? 0);
double proposedTp = (newTp.HasValue) ? newTp.Value.Price : (pos.TakeProfit ?? 0);
bool modifySl = pos.StopLoss.HasValue && (proposedSl > pos.StopLoss.Value + _symbol.TickSize);
if (!pos.StopLoss.HasValue && newSl.HasValue) modifySl = true;
bool modifyTp = newTp.HasValue && Math.Abs(proposedTp - (pos.TakeProfit ?? 0)) > _symbol.TickSize;
if (modifySl || modifyTp)
{
double finalSl = modifySl ? proposedSl : pos.StopLoss ?? 0;
double finalTp = modifyTp ? proposedTp : pos.TakeProfit ?? 0;
if (finalSl < _symbol.Bid && (finalTp == 0 || finalTp > _symbol.Bid))
{
_robot.ModifyPosition(pos, finalSl, finalTp, ProtectionType.Absolute);
}
}
}
else // Sell
{
double lowestSlPrice = double.MaxValue;
double lowestTpPrice = double.MaxValue;
foreach (var c in clusters)
{
if (c.Price > pNow && c.Significance < _config.SlSigThreshold && c.Price < lowestSlPrice)
{
newSl = c;
lowestSlPrice = c.Price;
}
if (c.Price < pNow && c.Significance >= _config.EntrySigThreshold && c.Price < lowestTpPrice)
{
newTp = c;
lowestTpPrice = c.Price;
}
}
double proposedSl = (newSl.HasValue) ? newSl.Value.Price : (pos.StopLoss ?? 0);
double proposedTp = (newTp.HasValue) ? newTp.Value.Price : (pos.TakeProfit ?? 0);
bool modifySl = pos.StopLoss.HasValue && (proposedSl < pos.StopLoss.Value - _symbol.TickSize);
if (!pos.StopLoss.HasValue && newSl.HasValue) modifySl = true;
bool modifyTp = newTp.HasValue && Math.Abs(proposedTp - (pos.TakeProfit ?? 0)) > _symbol.TickSize;
if (modifySl || modifyTp)
{
double finalSl = modifySl ? proposedSl : pos.StopLoss ?? 0;
double finalTp = modifyTp ? proposedTp : pos.TakeProfit ?? 0;
if (finalSl > _symbol.Ask && (finalTp == 0 || finalTp < _symbol.Ask))
{
_robot.ModifyPosition(pos, finalSl, finalTp, ProtectionType.Absolute);
}
}
}
}
}
private void ManageOrders(Bias bias, int index, List<ClusterLevel> clusters)
{
// Standard Cleanup: Orders in wrong direction (Bias Change)
CleanupWrongBiasOrders(bias);
if (_config.UseBiasDeviationFilter && !_isTradingAllowedBasedOnPrevCycle)
return;
if (bias == Bias.Neutral) return;
if (!_config.SendTelegramOnly)
{
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);
return;
}
if (bias == Bias.Short && hasShort)
{
CancelPendingOrders(TradeType.Sell);
return;
}
}
if (clusters.Count < 2) return;
double pNow = _bars.ClosePrices[index];
if (bias == Bias.Short)
ProcessShortSetup(clusters, pNow);
else if (bias == Bias.Long)
ProcessLongSetup(clusters, pNow);
}
private void CancelPendingOrders(TradeType type)
{
foreach (var order in _robot.PendingOrders)
{
if (order.SymbolName == _config.SymbolName && order.Label == Label && order.TradeType == type)
{
_robot.CancelPendingOrder(order);
}
}
}
private void CleanupWrongBiasOrders(Bias currentBias)
{
if (_config.SendTelegramOnly) return;
foreach (var order in _robot.PendingOrders)
{
if (order.Label != Label || order.SymbolName != _config.SymbolName) continue;
if (currentBias == Bias.Long && order.TradeType == TradeType.Sell)
_robot.CancelPendingOrder(order);
else if (currentBias == Bias.Short && order.TradeType == TradeType.Buy)
_robot.CancelPendingOrder(order);
else if (currentBias == Bias.Neutral)
_robot.CancelPendingOrder(order);
}
}
private void ProcessShortSetup(List<ClusterLevel> clusters, double pNow)
{
ClusterLevel? entry = null;
ClusterLevel? sl = null;
ClusterLevel? tp = null;
double highestEntryPrice = double.MinValue;
double lowestSlPrice = double.MaxValue;
double lowestTpPrice = double.MaxValue;
foreach (var c in clusters)
{
if (c.Price > pNow)
{
if ((c.Significance >= _config.EntrySigThreshold) && (c.Price > highestEntryPrice))
{
entry = c;
highestEntryPrice = c.Price;
}
if ((c.Significance < _config.SlSigThreshold) && (c.Price < lowestSlPrice))
{
sl = c;
lowestSlPrice = c.Price;
}
}
}
if (entry == null || sl == null) return;
foreach (var c in clusters)
{
if ((c.Price < entry.Value.Price) && (c.Significance >= _config.EntrySigThreshold))
{
if (c.Price < lowestTpPrice)
{
tp = c;
lowestTpPrice = c.Price;
}
}
}
if (tp != null && (sl.Value.Price > entry.Value.Price))
{
double risk = sl.Value.Price - entry.Value.Price;
double reward = entry.Value.Price - tp.Value.Price;
if (risk <= reward)
UpdateOrPlaceLimitOrder(TradeType.Sell, entry.Value.Price, sl.Value.Price, tp.Value.Price);
}
}
private void ProcessLongSetup(List<ClusterLevel> clusters, double pNow)
{
ClusterLevel? entry = null;
ClusterLevel? sl = null;
ClusterLevel? tp = null;
double lowestEntryPrice = double.MaxValue;
double highestSlPrice = double.MinValue;
double highestTpPrice = double.MinValue;
foreach (var c in clusters)
{
if (c.Price < pNow)
{
if ((c.Significance >= _config.EntrySigThreshold) && (c.Price < lowestEntryPrice))
{
entry = c;
lowestEntryPrice = c.Price;
}
if ((c.Significance < _config.SlSigThreshold) && (c.Price > highestSlPrice))
{
sl = c;
highestSlPrice = c.Price;
}
}
}
if (entry == null || sl == null) return;
foreach (var c in clusters)
{
if ((c.Price > entry.Value.Price) && (c.Significance >= _config.EntrySigThreshold))
{
if (c.Price > highestTpPrice)
{
tp = c;
highestTpPrice = c.Price;
}
}
}
if (tp != null && (sl.Value.Price < entry.Value.Price))
{
double risk = entry.Value.Price - sl.Value.Price;
double reward = tp.Value.Price - entry.Value.Price;
if (risk <= reward)
UpdateOrPlaceLimitOrder(TradeType.Buy, entry.Value.Price, sl.Value.Price, tp.Value.Price);
}
}
private void UpdateOrPlaceLimitOrder(TradeType type, double entry, double sl, double tp)
{
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;
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;
}
// --- 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;
}
double lots = _symbol.VolumeInUnitsToQuantity(volume);
if (_config.SendTelegramOnly)
{
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";
_ = SendTelegramMessageAsync(msg);
return;
}
if (existingOrder != null)
{
bool volumeChanged = Math.Abs(existingOrder.VolumeInUnits - volume) > _symbol.VolumeInUnitsStep;
bool entryChanged = Math.Abs(existingOrder.TargetPrice - entry) > _symbol.TickSize;
bool slChanged = Math.Abs((existingOrder.StopLoss ?? 0) - sl) > _symbol.TickSize;
bool tpChanged = Math.Abs((existingOrder.TakeProfit ?? 0) - tp) > _symbol.TickSize;
if (volumeChanged || entryChanged || slChanged || tpChanged)
{
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
_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);
}
}
private async Task SendTelegramMessageAsync(string message)
{
if (_robot.IsBacktesting) return;
if (string.IsNullOrWhiteSpace(_botToken) || string.IsNullOrWhiteSpace(_chatId)) return;
try
{
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}");
}
}
catch (Exception ex)
{
_errorCallback?.Invoke($"Telegram Exception: {ex.Message}");
}
}
private void UpdateClusterData(int index)
{
double currentHma = _hmaCluster.Result[index];
double prevHma = _hmaCluster.Result[index - 1];
bool currentDirectionUp = (currentHma > prevHma);
if (_isUpTrend == null)
{
_isUpTrend = currentDirectionUp;
SetExtremum(index);
_lastExtremumPrice = _trendExtremum;
return;
}
if (currentDirectionUp != _isUpTrend)
{
double amp = Math.Abs(_trendExtremum - _lastExtremumPrice);
if (amp > 0)
{
_amplitudes.Add(amp);
if (_amplitudes.Count > 50) _amplitudes.RemoveAt(0);
double sum = 0;
for (int i = 0; i < _amplitudes.Count; i++) sum += _amplitudes[i];
_currentDynamicRange = (sum / _amplitudes.Count) * 0.5;
}
_extremaPoints.Add(new ExtremumPoint { Price = _trendExtremum, Index = _trendExtremumIndex, Type = _isUpTrend.Value ? PointType.Peak : PointType.Trough });
if (_extremaPoints.Count > _config.MaxPoints) _extremaPoints.RemoveAt(0);
_lastExtremumPrice = _trendExtremum;
_isUpTrend = currentDirectionUp;
SetExtremum(index);
}
else
{
UpdateExtremum(index);
}
}
private void SetExtremum(int index)
{
_trendExtremum = _isUpTrend.Value ? _bars.HighPrices[index] : _bars.LowPrices[index];
_trendExtremumIndex = index;
}
private void UpdateExtremum(int index)
{
if (_isUpTrend.Value && (_bars.HighPrices[index] > _trendExtremum))
{
_trendExtremum = _bars.HighPrices[index];
_trendExtremumIndex = index;
}
else if (!_isUpTrend.Value && (_bars.LowPrices[index] < _trendExtremum))
{
_trendExtremum = _bars.LowPrices[index];
_trendExtremumIndex = index;
}
}
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++)
{
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;
}
}
}
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="*" />
</ItemGroup>
</Project>
@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
@@ -0,0 +1,22 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("HmaClusterBot")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("HmaClusterBot")]
[assembly: System.Reflection.AssemblyTitleAttribute("HmaClusterBot")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
@@ -0,0 +1 @@
296f6e29070e0927c857564d4a04976a31621cde
@@ -0,0 +1,10 @@
is_global = true
build_property.TargetFramework = net6.0
build_property.TargetPlatformMinVersion =
build_property.UsingMicrosoftNETSdkWeb =
build_property.ProjectTypeGuids =
build_property.InvariantGlobalization =
build_property.PlatformNeutralAssembly =
build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = HmaClusterBot
build_property.ProjectDir = C:\Users\Brummel\Documents\cAlgo\Sources\Robots\HmaClusterBot\HmaClusterBot\
@@ -0,0 +1,66 @@
{
"format": 1,
"restore": {
"C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\HmaClusterBot.csproj": {}
},
"projects": {
"C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\HmaClusterBot.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\HmaClusterBot.csproj",
"projectName": "HmaClusterBot",
"projectPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\HmaClusterBot.csproj",
"packagesPath": "C:\\Users\\Brummel\\.nuget\\packages\\",
"outputPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\obj\\",
"projectStyle": "PackageReference",
"configFilePaths": [
"C:\\Users\\Brummel\\AppData\\Roaming\\NuGet\\NuGet.Config"
],
"originalTargetFrameworks": [
"net6.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net6.0": {
"targetAlias": "net6.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
}
},
"frameworks": {
"net6.0": {
"targetAlias": "net6.0",
"dependencies": {
"cTrader.Automate": {
"target": "Package",
"version": "[*, )"
}
},
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48"
],
"assetTargetFallback": true,
"warn": true,
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\6.0.200\\RuntimeIdentifierGraph.json"
}
}
}
}
}
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(UserProfile)\.nuget\packages\</NuGetPackageRoot>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\Brummel\.nuget\packages\</NuGetPackageFolders>
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.1.0</NuGetToolVersion>
</PropertyGroup>
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<SourceRoot Include="C:\Users\Brummel\.nuget\packages\" />
</ItemGroup>
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<Import Project="$(NuGetPackageRoot)ctrader.automate\1.0.14\build\cTrader.Automate.props" Condition="Exists('$(NuGetPackageRoot)ctrader.automate\1.0.14\build\cTrader.Automate.props')" />
</ImportGroup>
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<PkgcTrader_Automate Condition=" '$(PkgcTrader_Automate)' == '' ">C:\Users\Brummel\.nuget\packages\ctrader.automate\1.0.14</PkgcTrader_Automate>
</PropertyGroup>
</Project>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<Import Project="$(NuGetPackageRoot)ctrader.automate\1.0.14\build\cTrader.Automate.targets" Condition="Exists('$(NuGetPackageRoot)ctrader.automate\1.0.14\build\cTrader.Automate.targets')" />
</ImportGroup>
</Project>
@@ -0,0 +1,139 @@
{
"version": 3,
"targets": {
"net6.0": {
"cTrader.Automate/1.0.14": {
"type": "package",
"compile": {
"lib/net6.0/cAlgo.API.dll": {}
},
"runtime": {
"lib/net6.0/cAlgo.API.dll": {}
},
"build": {
"build/cTrader.Automate.props": {},
"build/cTrader.Automate.targets": {}
}
}
}
},
"libraries": {
"cTrader.Automate/1.0.14": {
"sha512": "eNwE7WL90MGBKb5MuLAtZLdQy0vxkI5EVhLWAQ9S83EAdYkGAzdccvGFLk2oqmtSGBtD+gEpyrJUW/ej4dI4jw==",
"type": "package",
"path": "ctrader.automate/1.0.14",
"hasTools": true,
"files": [
".nupkg.metadata",
".signature.p7s",
"build/cTrader.Automate.props",
"build/cTrader.Automate.targets",
"ctrader.automate.1.0.14.nupkg.sha512",
"ctrader.automate.nuspec",
"eula.md",
"icon.png",
"lib/net40/cAlgo.API.dll",
"lib/net40/cAlgo.API.xml",
"lib/net6.0/cAlgo.API.dll",
"lib/net6.0/cAlgo.API.xml",
"tools/net472/Core.AlgoFormat.Compose.Reflection.dll",
"tools/net472/Core.AlgoFormat.Writer.dll",
"tools/net472/Core.AlgoFormat.dll",
"tools/net472/Core.Domain.Primitives.dll",
"tools/net472/Newtonsoft.Json.dll",
"tools/net472/System.Buffers.dll",
"tools/net472/System.Collections.Immutable.dll",
"tools/net472/System.Memory.dll",
"tools/net472/System.Numerics.Vectors.dll",
"tools/net472/System.Reflection.Metadata.dll",
"tools/net472/System.Reflection.MetadataLoadContext.dll",
"tools/net472/System.Runtime.CompilerServices.Unsafe.dll",
"tools/net472/cTrader.Automate.Sdk.Tasks.dll",
"tools/net6.0/Core.AlgoFormat.Compose.Reflection.dll",
"tools/net6.0/Core.AlgoFormat.Writer.dll",
"tools/net6.0/Core.AlgoFormat.dll",
"tools/net6.0/Core.Connection.Protobuf.Common.dll",
"tools/net6.0/Core.Domain.Primitives.dll",
"tools/net6.0/Microsoft.Win32.SystemEvents.dll",
"tools/net6.0/Newtonsoft.Json.dll",
"tools/net6.0/System.Drawing.Common.dll",
"tools/net6.0/System.Reflection.MetadataLoadContext.dll",
"tools/net6.0/System.Security.Permissions.dll",
"tools/net6.0/System.Windows.Extensions.dll",
"tools/net6.0/cTrader.Automate.Sdk.Tasks.dll",
"tools/net6.0/protobuf-net.Core.dll",
"tools/net6.0/protobuf-net.dll",
"tools/net6.0/runtimes/unix/lib/net6.0/System.Drawing.Common.dll",
"tools/net6.0/runtimes/win/lib/net6.0/Microsoft.Win32.SystemEvents.dll",
"tools/net6.0/runtimes/win/lib/net6.0/System.Drawing.Common.dll",
"tools/net6.0/runtimes/win/lib/net6.0/System.Windows.Extensions.dll"
]
}
},
"projectFileDependencyGroups": {
"net6.0": [
"cTrader.Automate >= *"
]
},
"packageFolders": {
"C:\\Users\\Brummel\\.nuget\\packages\\": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\HmaClusterBot.csproj",
"projectName": "HmaClusterBot",
"projectPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\HmaClusterBot.csproj",
"packagesPath": "C:\\Users\\Brummel\\.nuget\\packages\\",
"outputPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\obj\\",
"projectStyle": "PackageReference",
"configFilePaths": [
"C:\\Users\\Brummel\\AppData\\Roaming\\NuGet\\NuGet.Config"
],
"originalTargetFrameworks": [
"net6.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net6.0": {
"targetAlias": "net6.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
}
},
"frameworks": {
"net6.0": {
"targetAlias": "net6.0",
"dependencies": {
"cTrader.Automate": {
"target": "Package",
"version": "[*, )"
}
},
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48"
],
"assetTargetFallback": true,
"warn": true,
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\6.0.200\\RuntimeIdentifierGraph.json"
}
}
}
}
@@ -0,0 +1,10 @@
{
"version": 2,
"dgSpecHash": "NEYKNJ+0pRHXWSIUJ8meJtMDF84xyxPwtc1chms3WBz34cQ0viYha1RgvvteKYETOCh8y4l1tk9Xm9OxaOeitA==",
"success": true,
"projectFilePath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Robots\\HmaClusterBot\\HmaClusterBot\\HmaClusterBot.csproj",
"expectedPackageFiles": [
"C:\\Users\\Brummel\\.nuget\\packages\\ctrader.automate\\1.0.14\\ctrader.automate.1.0.14.nupkg.sha512"
],
"logs": []
}