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
+22
View File
@@ -0,0 +1,22 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSLib", "MSLib\MSLib.csproj", "{81C5B946-7D77-4DDD-B9E0-9AE6E47ADE2E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{81C5B946-7D77-4DDD-B9E0-9AE6E47ADE2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{81C5B946-7D77-4DDD-B9E0-9AE6E47ADE2E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{81C5B946-7D77-4DDD-B9E0-9AE6E47ADE2E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{81C5B946-7D77-4DDD-B9E0-9AE6E47ADE2E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
+450
View File
@@ -0,0 +1,450 @@
using System;
using System.Collections.Generic; // Required for List and Queue
using System.Linq; // Required for .Any() and .ToArray()
using System.Diagnostics; // For Debug.WriteLine, if needed for warnings/errors
namespace MS
{
// ICalculation interface defines a contract for updatable and resettable calculation objects.
// This allows different types of indicators or filters to be used interchangeably
// if they adhere to this structure.
public interface ICalculation
{
// Update processes a new data point (inputValue).
// inputValue: The new data point to incorporate into the calculation.
// commitState: If true, the internal state of the calculator is permanently updated.
// If false, the calculation is performed as a "peek" or "what-if" scenario
// without altering the persistent state of the calculator.
// Returns: The calculated value (e.g., median, MMI, filtered output) as a double.
// May return double.NaN if the calculation cannot be performed (e.g., insufficient data).
double Update(double inputValue, bool commitState = true);
// Reset re-initializes the calculator to its default state.
// This typically involves clearing any stored historical data or state variables,
// making the calculator ready for a new sequence of data.
void Reset();
}
// Median class calculates a rolling median over a specified period.
// The median is the middle value of a data set sorted in ascending order.
// This implementation allows for committing state changes or calculating a "what-if" median.
public class Median : ICalculation
{
private readonly int _period; // The number of data points in the rolling window.
private readonly List<double> _windowValues; // Stores the sorted values within the current window. Used for efficient median calculation.
private readonly Queue<double> _windowOrder; // Stores the values in insertion order to manage the rolling window (FIFO).
// Constructor for the Median calculator.
// period: The number of data points to include in the median calculation window. Must be positive.
public Median(int period)
{
if (period <= 0)
throw new ArgumentOutOfRangeException(nameof(period), "Period must be positive.");
_period = period;
_windowValues = new List<double>(_period); // Initialize with capacity for performance.
_windowOrder = new Queue<double>(_period); // Initialize with capacity.
}
// Updates the median calculation with a new data point (inputValue).
// If commitState is true, the inputValue is added to the window, and the oldest value is removed if the window is full.
// The median is then calculated from this updated (persisted) window.
// If commitState is false, the median is calculated based on a temporary window:
// - If the persisted window is full, it simulates replacing the oldest values with inputValue (current logic uses P-1 smallest).
// - If the persisted window is not full, it adds inputValue to the current persisted values.
// This temporary calculation does not alter the actual persisted state of _windowValues or _windowOrder.
public double Update(double inputValue, bool commitState = true)
{
List<double> tempWindowForCalc = new List<double>(); // Temporary list for performing the median calculation.
if (commitState) // Persist the new value and update the window.
{
_windowOrder.Enqueue(inputValue); // Add to FIFO queue to track age.
int insertIndex = _windowValues.BinarySearch(inputValue); // Find position in sorted list.
if (insertIndex < 0) insertIndex = ~insertIndex; // If not found, get complement for insertion index.
_windowValues.Insert(insertIndex, inputValue); // Insert into sorted list.
if (_windowOrder.Count > _period) // If window size exceeds period.
{
double oldestValue = _windowOrder.Dequeue(); // Remove oldest from FIFO queue.
_windowValues.Remove(oldestValue); // Remove oldest from sorted list (can be slow if list is large).
}
tempWindowForCalc.AddRange(_windowValues); // Calculation based on the actual, updated window.
}
else // Calculate "what-if" median without persisting state.
{
if (_windowValues.Any()) // If there are existing values.
{
if (_windowValues.Count == _period) // If the persisted window is full.
{
// Current "what-if" logic: takes the _period-1 smallest values from the current window
// and adds the new inputValue. This might not always reflect replacing the "oldest" actual item.
for (int i = 0; i < _period - 1; ++i) tempWindowForCalc.Add(_windowValues[i]);
}
else // Persisted window is not yet full.
{
tempWindowForCalc.AddRange(_windowValues); // Use all current values.
}
}
tempWindowForCalc.Add(inputValue); // Add the new input value to the temporary set.
}
if (!tempWindowForCalc.Any()) // If no data in the temporary window.
{
return double.NaN; // Cannot calculate median.
}
tempWindowForCalc.Sort(); // Median calculation requires a sorted list.
int n = tempWindowForCalc.Count;
double calculatedMedian;
if (n == 0) return double.NaN; // Should be caught by .Any() check above.
if (n % 2 == 0) // Even number of elements.
{
if (n >= 2) { // Median is the average of the two middle elements.
calculatedMedian = (tempWindowForCalc[n / 2 - 1] + tempWindowForCalc[n / 2]) / 2.0;
} else {
return double.NaN; // Not enough elements for a meaningful even median.
}
}
else // Odd number of elements.
{
calculatedMedian = tempWindowForCalc[n / 2]; // Median is the middle element.
}
return calculatedMedian;
}
// Resets the Median calculator to its initial state.
// Clears all stored values from the calculation window.
public void Reset()
{
_windowValues.Clear(); // Empties the sorted list of values.
_windowOrder.Clear(); // Empties the queue tracking insertion order.
}
}
// MMI (Market Meanness Index) class calculates a rolling index indicating if a market is trending or mean-reverting.
// It uses a Median calculator internally.
// The MMI value is typically between 0 and 100.
public class MMI : ICalculation
{
private readonly int _period; // The period for MMI and its internal Median calculation.
private readonly Median _medianCalculator; // Internal Median calculator instance.
private readonly Queue<double> _priceWindow; // Stores raw price values in insertion order for MMI logic.
// Constructor for the MMI calculator.
// period: The number of data points for the MMI window. Must be at least 2.
public MMI(int period)
{
if (period < 2) // MMI calculation requires at least 2 data points to compare.
throw new ArgumentOutOfRangeException(nameof(period), "Period must be at least 2 for MMI calculation.");
_period = period;
_medianCalculator = new Median(period); // Initialize the Median helper.
_priceWindow = new Queue<double>(period); // Initialize price queue.
}
// Updates the MMI calculation with a new data point (inputValue).
// It first updates its internal Median calculator.
// Then, it updates its own price window based on commitState.
// Finally, it calculates MMI based on the median and the price window.
// MMI is calculated as 100 * (nl + nh) / (period - 1), where:
// nl: count of prices > median and > previous price.
// nh: count of prices < median and < previous price.
// Returns NaN if the median is NaN or if the price window for MMI isn't full (_period size).
public double Update(double inputValue, bool commitState = true)
{
// Update the median, passing through the commitState.
double calculatedMedian = _medianCalculator.Update(inputValue, commitState);
double[] pricesForMmiLoop; // Array to hold prices for the MMI loop.
if (commitState) // Persist inputValue in MMI's price window.
{
_priceWindow.Enqueue(inputValue);
if (_priceWindow.Count > _period)
{
_priceWindow.Dequeue(); // Maintain window size.
}
pricesForMmiLoop = _priceWindow.ToArray(); // Use the actual, updated price window.
}
else // "What-if" scenario for MMI price window.
{
List<double> tempList = new List<double>();
if (_priceWindow.Any())
{
if (_priceWindow.Count == _period) // If full, simulate replacing the oldest.
{
var tempQueue = new Queue<double>(_priceWindow.Skip(1)); // Create a new queue, skipping the oldest.
tempQueue.Enqueue(inputValue); // Add the new value.
pricesForMmiLoop = tempQueue.ToArray();
}
else // Not full, just add to current MMI prices.
{
tempList.AddRange(_priceWindow);
tempList.Add(inputValue);
pricesForMmiLoop = tempList.ToArray();
}
}
else // Price window is empty.
{
tempList.Add(inputValue);
pricesForMmiLoop = tempList.ToArray();
}
}
// MMI can only be calculated if median is valid and the price window for the loop is full.
if (double.IsNaN(calculatedMedian) || pricesForMmiLoop.Length != _period)
{
return double.NaN;
}
int nl = 0; // Counter for "trending up" conditions.
int nh = 0; // Counter for "trending down" conditions.
// Loop starts from 1 because it compares price[i] with price[i-1].
for (int i = 1; i < _period; i++)
{
double priceInWindow = pricesForMmiLoop[i];
double prevPriceInWindow = pricesForMmiLoop[i - 1];
// Condition for nl: price is above median and current price is greater than previous price.
if (priceInWindow > calculatedMedian && priceInWindow > prevPriceInWindow) nl++;
// Condition for nh: price is below median and current price is less than previous price.
else if (priceInWindow < calculatedMedian && priceInWindow < prevPriceInWindow) nh++;
}
// Denominator (_period - 1) is safe because constructor enforces _period >= 2.
return 100.0 * (nl + nh) / (_period - 1);
}
// Resets the MMI calculator to its initial state.
// This involves resetting its internal Median calculator and clearing its own price window.
public void Reset()
{
_medianCalculator.Reset(); // Reset the dependent Median calculator.
_priceWindow.Clear(); // Clear the MMI's specific price data.
}
}
// LowPassFilter class implements a 2nd order IIR (Infinite Impulse Response) digital filter.
// It can be configured as various types of low-pass filters (Butterworth, Bessel, Chebyshev)
// using static factory methods.
// The filter equation is:
// y[n] = b0*x[n] + b1*x[n-1] + b2*x[n-2] - a1*y[n-1] - a2*y[n-2]
public class LowPassFilter : ICalculation
{
// Filter coefficients for the numerator (feedforward)
private readonly double _b0, _b1, _b2;
// Filter coefficients for the denominator (feedback), signs are for the direct subtraction in formula.
private readonly double _a1, _a2;
// State variables storing previous input values.
private double _x1; // x[n-1]
private double _x2; // x[n-2]
// State variables storing previous output values.
private double _y1; // y[n-1]
private double _y2; // y[n-2]
// Constructor to initialize the filter with specific coefficients.
// Used by the static factory methods or for custom filter designs.
// b0_coeff, b1_coeff, b2_coeff: Numerator (feedforward) coefficients.
// a1_coeff, a2_coeff: Denominator (feedback) coefficients for the form y[n] = ... - a1*y[n-1] - a2*y[n-2].
public LowPassFilter(double b0_coeff, double b1_coeff, double b2_coeff, double a1_coeff, double a2_coeff)
{
_b0 = b0_coeff;
_b1 = b1_coeff;
_b2 = b2_coeff;
_a1 = a1_coeff; // Corresponds to a1 in y[n] = ... - a1*y[n-1]
_a2 = a2_coeff; // Corresponds to a2 in y[n] = ... - a2*y[n-2]
Reset(); // Initialize state variables to zero.
}
// Factory method to create a 2nd order Butterworth low-pass filter.
// Butterworth filters are known for their maximally flat passband response.
// cutoffFrequency: The -3dB cutoff frequency of the filter.
// samplingFrequency: The sampling frequency of the input signal.
public static LowPassFilter CreateButterworthLowPass(double cutoffFrequency, double samplingFrequency)
{
if (cutoffFrequency <= 0)
throw new ArgumentOutOfRangeException(nameof(cutoffFrequency), "Cutoff frequency must be positive.");
if (samplingFrequency <= 0)
throw new ArgumentOutOfRangeException(nameof(samplingFrequency), "Sampling frequency must be positive.");
// Cutoff frequency must be less than Nyquist frequency (samplingFrequency / 2.0).
if (cutoffFrequency >= samplingFrequency / 2.0)
throw new ArgumentOutOfRangeException(nameof(cutoffFrequency), $"Cutoff frequency ({cutoffFrequency}) must be strictly less than half the sampling frequency ({samplingFrequency / 2.0}).");
double b0_calc, b1_calc, b2_calc, a1_calc, a2_calc;
// Prewarp the cutoff frequency for the bilinear transform.
// C = tan(pi * fc / fs)
double C = Math.Tan(Math.PI * cutoffFrequency / samplingFrequency);
if (Math.Abs(C) < 1e-12) // Handle extremely low cutoff (approaching DC).
{
b0_calc = 0; b1_calc = 0; b2_calc = 0; // Effectively blocks AC signals.
// Coefficients for y[n] = 2*y[n-1] - y[n-2] (integrator-like behavior for output).
a1_calc = -2.0; // So that -a1_calc*y[n-1] becomes +2*y[n-1].
a2_calc = 1.0; // So that -a2_calc*y[n-2] becomes -1*y[n-2].
}
else
{
double sqrt2 = Math.Sqrt(2.0);
// Denominator factor for Butterworth coefficients after bilinear transform.
double D_butter = 1.0 / (1.0 + sqrt2 * C + C * C);
// Numerator coefficients
b0_calc = C * C * D_butter;
b1_calc = 2.0 * b0_calc;
b2_calc = b0_calc;
// Denominator coefficients (for 1 + a1_std*z^-1 + a2_std*z^-2)
// These are directly used as _a1, _a2 in the filter update equation.
a1_calc = 2.0 * (C * C - 1.0) * D_butter;
a2_calc = (1.0 - sqrt2 * C + C * C) * D_butter;
}
return new LowPassFilter(b0_calc, b1_calc, b2_calc, a1_calc, a2_calc);
}
// Factory method to create a 2nd order Bessel low-pass filter.
// Bessel filters are known for their maximally flat group delay (linear phase response in passband).
// cutoffFrequency: The -3dB cutoff frequency. Note: Bessel filter design often refers to other frequency points.
// This implementation aims for -3dB at the specified cutoffFrequency.
// samplingFrequency: The sampling frequency of the input signal.
public static LowPassFilter CreateBesselLowPass(double cutoffFrequency, double samplingFrequency)
{
if (cutoffFrequency <= 0) throw new ArgumentOutOfRangeException(nameof(cutoffFrequency), "Cutoff frequency must be positive.");
if (samplingFrequency <= 0) throw new ArgumentOutOfRangeException(nameof(samplingFrequency), "Sampling frequency must be positive.");
if (cutoffFrequency >= samplingFrequency / 2.0) throw new ArgumentOutOfRangeException(nameof(cutoffFrequency), $"Cutoff frequency ({cutoffFrequency}) must be strictly less than half the sampling frequency ({samplingFrequency / 2.0}).");
// C_bessel = tan(pi * fc / fs), prewarped frequency factor.
double C_bessel = Math.Tan(Math.PI * cutoffFrequency / samplingFrequency);
if (Math.Abs(C_bessel) < 1e-12) // Handle low cutoff.
{
return new LowPassFilter(0, 0, 0, -2.0, 1.0); // Similar to Butterworth low cutoff.
}
// Coefficients derived from analog Bessel prototype (s^2 + 3s + 3),
// frequency scaled for -3dB at cutoffFrequency, then transformed using bilinear method.
// omega_c_analog_warped = 2 * fs * tan(pi * fc / fs)
double omega_c_analog_warped = 2.0 * samplingFrequency * C_bessel;
// k_bessel_norm_3db is a scaling factor for the Bessel prototype's natural frequency
// to achieve the -3dB point at the desired warped analog cutoff. Value is approx. 1.3617.
double k_bessel_norm_3db = 1.3617070504; // Sqrt(3 * (Sqrt(5.0) - 1.0) / 2.0)
double omega_0_scaled = omega_c_analog_warped / k_bessel_norm_3db; // Scaled analog natural frequency for prototype.
// Analog prototype denominator: s^2 + A_s*s + B_s
// For Bessel n=2, scaled: s^2 + (3*omega_0_scaled)*s + (3*omega_0_scaled^2)
double as_coeff_analog = 3.0 * omega_0_scaled; // Coefficient for s-term.
double bs_coeff_analog = 3.0 * omega_0_scaled * omega_0_scaled; // Constant term (and numerator for DC gain 1).
// K_T_bilinear = 2 * fs, factor in bilinear transform s = K_T * (1-z^-1)/(1+z^-1) (if K_T is used for 2/T_sample)
// Here, K_T_bilinear is 2*fs.
double K_T_bilinear = 2.0 * samplingFrequency;
// Denominator after bilinear transform of H(s) = bs_coeff_analog / (s^2 + as_coeff_analog*s + bs_coeff_analog)
// gives A0_prime_denom = (K_T^2) + as_coeff_analog*K_T + bs_coeff_analog for normalization.
double A0_prime_denom = K_T_bilinear * K_T_bilinear + as_coeff_analog * K_T_bilinear + bs_coeff_analog;
if (Math.Abs(A0_prime_denom) < 1e-12) throw new InvalidOperationException("Denominator term A0_prime_denom is zero in Bessel filter calculation.");
// Digital filter coefficients b_i = Bi_prime / A0_prime_denom, a_i = Ai_prime_std / A0_prime_denom
double b0_calc = bs_coeff_analog / A0_prime_denom;
double b1_calc = (2.0 * bs_coeff_analog) / A0_prime_denom; // From bilinear transform structure.
double b2_calc = bs_coeff_analog / A0_prime_denom;
// Denominator coefficients for 1 + a1_std*z^-1 + a2_std*z^-2 form.
double a1_calc = (2.0 * bs_coeff_analog - 2.0 * K_T_bilinear * K_T_bilinear) / A0_prime_denom;
double a2_calc = (K_T_bilinear * K_T_bilinear - as_coeff_analog * K_T_bilinear + bs_coeff_analog) / A0_prime_denom;
return new LowPassFilter(b0_calc, b1_calc, b2_calc, a1_calc, a2_calc);
}
// Factory method to create a 2nd order Chebyshev Type I low-pass filter.
// Chebyshev Type I filters have a steeper roll-off than Butterworth, but exhibit ripple in the passband.
// cutoffFrequency: The frequency at which the passband ripple ends (e.g., gain drops by rippleDb).
// samplingFrequency: The sampling frequency of the input signal.
// rippleDb: The passband ripple in decibels (e.g., 0.5 dB, 1 dB). Must be positive.
public static LowPassFilter CreateChebyshevLowPass(double cutoffFrequency, double samplingFrequency, double rippleDb)
{
if (cutoffFrequency <= 0) throw new ArgumentOutOfRangeException(nameof(cutoffFrequency), "Cutoff frequency must be positive.");
if (samplingFrequency <= 0) throw new ArgumentOutOfRangeException(nameof(samplingFrequency), "Sampling frequency must be positive.");
if (cutoffFrequency >= samplingFrequency / 2.0) throw new ArgumentOutOfRangeException(nameof(cutoffFrequency), $"Cutoff frequency ({cutoffFrequency}) must be strictly less than half the sampling frequency ({samplingFrequency / 2.0}).");
if (rippleDb <= 0) throw new ArgumentOutOfRangeException(nameof(rippleDb), "Passband ripple must be positive.");
// C_cheby = tan(pi * fc / fs), prewarped frequency factor.
double C_cheby = Math.Tan(Math.PI * cutoffFrequency / samplingFrequency);
if (Math.Abs(C_cheby) < 1e-12) // Handle low cutoff.
{
return new LowPassFilter(0,0,0, -2.0, 1.0); // Similar to Butterworth low cutoff.
}
// Epsilon is derived from the passband ripple.
double epsilon = Math.Sqrt(Math.Pow(10, rippleDb / 10.0) - 1.0);
int N_order = 2; // Filter order is fixed at 2.
// Parameters for locating analog prototype poles on an ellipse.
// alpha_val determines the eccentricity of the ellipse.
double alpha_val = Math.Asinh(1.0 / epsilon) / N_order;
// For N=2, poles are at s_k = -sigma_k +/- j*omega_k.
// These are scaled by C_cheby (warped cutoff frequency) for the specific filter.
double sin_pi_over_2N = Math.Sin(Math.PI / (2.0 * N_order)); // sin(pi/4) for N=2
double cos_pi_over_2N = Math.Cos(Math.PI / (2.0 * N_order)); // cos(pi/4) for N=2
double sigma_k_scaled = Math.Sinh(alpha_val) * sin_pi_over_2N * C_cheby;
double omega_k_scaled = Math.Cosh(alpha_val) * cos_pi_over_2N * C_cheby;
// Analog prototype denominator: s^2 + A_s*s + B_s
// Derived from poles: (s + sigma_k_scaled)^2 + omega_k_scaled^2
double as_coeff_analog = 2.0 * sigma_k_scaled; // s-term coefficient.
double bs_coeff_analog = sigma_k_scaled * sigma_k_scaled + omega_k_scaled * omega_k_scaled; // Constant term.
// Analog numerator: For Chebyshev Type I, N=2 (even order), DC gain H(0) = 1.
// So, numerator constant of analog prototype is bs_coeff_analog.
double num_s_coeff = bs_coeff_analog;
double K_T_bilinear = 2.0 * samplingFrequency; // Factor for bilinear transform.
// Denominator for normalization after bilinear transform.
double A0_prime_denom = K_T_bilinear * K_T_bilinear + as_coeff_analog * K_T_bilinear + bs_coeff_analog;
if (Math.Abs(A0_prime_denom) < 1e-12) throw new InvalidOperationException("Denominator term A0_prime_denom is zero in Chebyshev filter calculation.");
// Digital filter coefficients.
double b0_calc = num_s_coeff / A0_prime_denom;
double b1_calc = (2.0 * num_s_coeff) / A0_prime_denom;
double b2_calc = num_s_coeff / A0_prime_denom;
double a1_calc = (2.0 * bs_coeff_analog - 2.0 * K_T_bilinear * K_T_bilinear) / A0_prime_denom;
double a2_calc = (K_T_bilinear * K_T_bilinear - as_coeff_analog * K_T_bilinear + bs_coeff_analog) / A0_prime_denom;
return new LowPassFilter(b0_calc, b1_calc, b2_calc, a1_calc, a2_calc);
}
// Updates the filter with a new input sample (inputValue).
// Applies the difference equation:
// y[n] = b0*x[n] + b1*x[n-1] + b2*x[n-2] - a1*y[n-1] - a2*y[n-2]
// If commitState is true, the internal state variables (previous inputs and outputs) are updated.
// If false, the output is calculated using the current state, but the state is not advanced.
public double Update(double inputValue, bool commitState = true)
{
// Calculate the current output y[n] based on current input x[n] and previous states.
double output = _b0 * inputValue + _b1 * _x1 + _b2 * _x2 - _a1 * _y1 - _a2 * _y2;
if (commitState) // If true, update the filter's internal state.
{
// Shift previous inputs: x[n-2] = x[n-1], x[n-1] = x[n] (current inputValue).
_x2 = _x1;
_x1 = inputValue;
// Shift previous outputs: y[n-2] = y[n-1], y[n-1] = y[n] (current calculated output).
_y2 = _y1;
_y1 = output;
}
return output; // Return the filtered output.
}
// Resets the filter's internal state variables to zero.
// This clears any memory of previous input or output values, useful for starting a new filtering sequence.
public void Reset()
{
_x1 = 0; _x2 = 0; // Reset previous input states.
_y1 = 0; _y2 = 0; // Reset previous output states.
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+286
View File
@@ -0,0 +1,286 @@
using System;
using System.Collections.Generic; // Required for List<T>
using System.IO; // For File operations
using System.Runtime.InteropServices; // Required for StructLayout and Marshal
namespace Zorro
{
/// <summary>
/// Provides generic methods for loading and saving arrays of structures
/// from/to binary files using marshalling.
/// This class is intended for internal use within this assembly.
/// </summary>
internal static class BinaryFileHandler
{
public static void SaveArrayAsBlock<T>(string filePath, T[] data) where T : struct
{
if (data == null || data.Length == 0)
{
File.WriteAllBytes(filePath, Array.Empty<byte>());
return;
}
int structSize = Marshal.SizeOf(typeof(T));
byte[] byteArray = new byte[data.Length * structSize];
IntPtr buffer = Marshal.AllocHGlobal(structSize);
try
{
for (int i = 0; i < data.Length; i++)
{
Marshal.StructureToPtr(data[i], buffer, false);
Marshal.Copy(buffer, byteArray, i * structSize, structSize);
}
File.WriteAllBytes(filePath, byteArray);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
public static T[]? LoadArrayAsBlock<T>(string filePath) where T : struct
{
if (!File.Exists(filePath))
{
return null;
}
byte[] byteArray = File.ReadAllBytes(filePath);
if (byteArray.Length == 0)
{
return Array.Empty<T>();
}
int structSize = Marshal.SizeOf(typeof(T));
if (byteArray.Length % structSize != 0)
{
throw new ArgumentException($"File size ({byteArray.Length} bytes) is not a valid multiple of the structure size ({structSize} bytes) for type {typeof(T).Name}. The file may be corrupted or not in the expected format.");
}
int itemCount = byteArray.Length / structSize;
T[] dataArray = new T[itemCount];
IntPtr buffer = Marshal.AllocHGlobal(structSize);
try
{
for (int i = 0; i < itemCount; i++)
{
Marshal.Copy(byteArray, i * structSize, buffer, structSize);
dataArray[i] = Marshal.PtrToStructure<T>(buffer);
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return dataArray;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct ZorroT1
{
public double OADate;
public float Value;
/// <summary>
/// Returns the time as a UTC DateTime object.
/// Note: DateTime.FromOADate returns a DateTime with Kind=Unspecified.
/// We specify it as UTC as Zorro DATEs are GMT/UTC.
/// </summary>
public DateTime TimeUtc => DateTime.SpecifyKind(DateTime.FromOADate(OADate), DateTimeKind.Utc);
public ZorroT1(double oaDate, float value)
{
OADate = oaDate;
Value = value;
}
public ZorroT1(DateTime dateTime, float value)
{
// Ensure the DateTime is converted to its UTC equivalent for OADate
OADate = dateTime.ToUniversalTime().ToOADate();
Value = value;
}
public static void SaveToFile(string filePath, ZorroT1[] data) => BinaryFileHandler.SaveArrayAsBlock<ZorroT1>(filePath, data);
public static ZorroT1[]? LoadFromFile(string filePath) => BinaryFileHandler.LoadArrayAsBlock<ZorroT1>(filePath);
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct ZorroT2
{
public double OADate;
public float Price;
public float Volume;
public DateTime TimeUtc => DateTime.SpecifyKind(DateTime.FromOADate(OADate), DateTimeKind.Utc);
public ZorroT2(double oaDate, float price, float volume)
{
OADate = oaDate;
Price = price;
Volume = volume;
}
public ZorroT2(DateTime dateTime, float price, float volume)
{
OADate = dateTime.ToUniversalTime().ToOADate();
Price = price;
Volume = volume;
}
public static void SaveToFile(string filePath, ZorroT2[] data) => BinaryFileHandler.SaveArrayAsBlock<ZorroT2>(filePath, data);
public static ZorroT2[]? LoadFromFile(string filePath) => BinaryFileHandler.LoadArrayAsBlock<ZorroT2>(filePath);
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct ZorroT6
{
public double OADate;
public float High;
public float Low;
public float Open;
public float Close;
public float AdditionalValue1;
public float AdditionalValue2;
public DateTime TimeUtc => DateTime.SpecifyKind(DateTime.FromOADate(OADate), DateTimeKind.Utc);
public ZorroT6(double oaDate, float high, float low, float open, float close, float additionalValue1, float additionalValue2)
{
OADate = oaDate;
High = high;
Low = low;
Open = open;
Close = close;
AdditionalValue1 = additionalValue1;
AdditionalValue2 = additionalValue2;
}
public ZorroT6(DateTime dateTime, float high, float low, float open, float close, float additionalValue1, float additionalValue2)
{
OADate = dateTime.ToUniversalTime().ToOADate();
High = high;
Low = low;
Open = open;
Close = close;
AdditionalValue1 = additionalValue1;
AdditionalValue2 = additionalValue2;
}
public static void SaveToFile(string filePath, ZorroT6[] data) => BinaryFileHandler.SaveArrayAsBlock<ZorroT6>(filePath, data);
public static ZorroT6[]? LoadFromFile(string filePath) => BinaryFileHandler.LoadArrayAsBlock<ZorroT6>(filePath);
}
// --- Builder Classes for Incremental Array Construction ---
public class ZorroT1ArrayBuilder
{
private readonly List<ZorroT1> _items;
public ZorroT1ArrayBuilder(int initialCapacity = 0)
{
_items = initialCapacity > 0 ? new List<ZorroT1>(initialCapacity) : new List<ZorroT1>();
}
public ZorroT1ArrayBuilder Add(DateTime time, float value)
{
// Constructor of ZorroT1 now handles UTC conversion
_items.Add(new ZorroT1(time, value));
return this;
}
public ZorroT1ArrayBuilder Add(double oaDate, float value)
{
_items.Add(new ZorroT1(oaDate, value));
return this;
}
public ZorroT1ArrayBuilder Add(ZorroT1 item)
{
_items.Add(item);
return this;
}
public ZorroT1[] ToArray() => _items.ToArray();
public void Clear() => _items.Clear();
public int Count => _items.Count;
public void SaveToFile(string filePath)
{
ZorroT1.SaveToFile(filePath, _items.ToArray());
}
}
public class ZorroT2ArrayBuilder
{
private readonly List<ZorroT2> _items;
public ZorroT2ArrayBuilder(int initialCapacity = 0)
{
_items = initialCapacity > 0 ? new List<ZorroT2>(initialCapacity) : new List<ZorroT2>();
}
public ZorroT2ArrayBuilder Add(DateTime time, float price, float volume)
{
_items.Add(new ZorroT2(time, price, volume));
return this;
}
public ZorroT2ArrayBuilder Add(double oaDate, float price, float volume)
{
_items.Add(new ZorroT2(oaDate, price, volume));
return this;
}
public ZorroT2ArrayBuilder Add(ZorroT2 item)
{
_items.Add(item);
return this;
}
public ZorroT2[] ToArray() => _items.ToArray();
public void Clear() => _items.Clear();
public int Count => _items.Count;
public void SaveToFile(string filePath)
{
ZorroT2.SaveToFile(filePath, _items.ToArray());
}
}
public class ZorroT6ArrayBuilder
{
private readonly List<ZorroT6> _items;
public ZorroT6ArrayBuilder(int initialCapacity = 0)
{
_items = initialCapacity > 0 ? new List<ZorroT6>(initialCapacity) : new List<ZorroT6>();
}
public ZorroT6ArrayBuilder Add(DateTime time, float high, float low, float open, float close, float additionalValue1, float additionalValue2)
{
_items.Add(new ZorroT6(time, high, low, open, close, additionalValue1, additionalValue2));
return this;
}
public ZorroT6ArrayBuilder Add(double oaDate, float high, float low, float open, float close, float additionalValue1, float additionalValue2)
{
_items.Add(new ZorroT6(oaDate, high, low, open, close, additionalValue1, additionalValue2));
return this;
}
public ZorroT6ArrayBuilder Add(ZorroT6 item)
{
_items.Add(item);
return this;
}
public ZorroT6[] ToArray() => _items.ToArray();
public void Clear() => _items.Clear();
public int Count => _items.Count;
public void SaveToFile(string filePath)
{
ZorroT6.SaveToFile(filePath, _items.ToArray());
}
}
}
@@ -0,0 +1,23 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v6.0",
"signature": ""
},
"compilationOptions": {},
"targets": {
".NETCoreApp,Version=v6.0": {
"MSLib/1.0.0": {
"runtime": {
"MSLib.dll": {}
}
}
}
},
"libraries": {
"MSLib/1.0.0": {
"type": "project",
"serviceable": false,
"sha512": ""
}
}
}
Binary file not shown.
Binary file not shown.
@@ -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("MSLib")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("MSLib")]
[assembly: System.Reflection.AssemblyTitleAttribute("MSLib")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
@@ -0,0 +1 @@
5bd6cf3423e8e65d9421c371ad2c6b9a30b6eb1d
@@ -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 = MSLib
build_property.ProjectDir = C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\
@@ -0,0 +1,8 @@
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;
@@ -0,0 +1 @@
375eb7427a13a6a1a036f49ce73cc2a66452e118
@@ -0,0 +1,12 @@
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\bin\Debug\net6.0\MSLib.deps.json
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\bin\Debug\net6.0\MSLib.dll
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\bin\Debug\net6.0\MSLib.pdb
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\MSLib.csproj.AssemblyReference.cache
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\MSLib.GeneratedMSBuildEditorConfig.editorconfig
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\MSLib.AssemblyInfoInputs.cache
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\MSLib.AssemblyInfo.cs
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\MSLib.csproj.CoreCompileInputs.cache
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\MSLib.dll
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\refint\MSLib.dll
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\MSLib.pdb
C:\Users\Brummel\Documents\cAlgo\Sources\Common\MSLib\obj\Debug\net6.0\ref\MSLib.dll
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,60 @@
{
"format": 1,
"restore": {
"C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\MSLib.csproj": {}
},
"projects": {
"C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\MSLib.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\MSLib.csproj",
"projectName": "MSLib",
"projectPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\MSLib.csproj",
"packagesPath": "C:\\Users\\Brummel\\.nuget\\packages\\",
"outputPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\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",
"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,15 @@
<?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>
</Project>
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />
@@ -0,0 +1,65 @@
{
"version": 3,
"targets": {
"net6.0": {}
},
"libraries": {},
"projectFileDependencyGroups": {
"net6.0": []
},
"packageFolders": {
"C:\\Users\\Brummel\\.nuget\\packages\\": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\MSLib.csproj",
"projectName": "MSLib",
"projectPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\MSLib.csproj",
"packagesPath": "C:\\Users\\Brummel\\.nuget\\packages\\",
"outputPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\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",
"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,8 @@
{
"version": 2,
"dgSpecHash": "Oo9DgV2PMMwBLALF97djBTxT9Wgbo3xT86Zo8aWAwrxLBxF4zrxrwtxR5/TCIXpFczNFbEDKftQZxvjl9Y6BHQ==",
"success": true,
"projectFilePath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Common\\MSLib\\MSLib.csproj",
"expectedPackageFiles": [],
"logs": []
}
Binary file not shown.
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bar times", "Bar times\Bar times.csproj", "{373DED72-A17B-4903-8EC9-FA9589B99D5D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{373DED72-A17B-4903-8EC9-FA9589B99D5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{373DED72-A17B-4903-8EC9-FA9589B99D5D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{373DED72-A17B-4903-8EC9-FA9589B99D5D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{373DED72-A17B-4903-8EC9-FA9589B99D5D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,47 @@
// -------------------------------------------------------------------------------------------------
//
// This code is a cAlgo API MACD Crossover indicator provided by njardim@email.com on Dec 2015.
//
// Based on the original MACD Crossover indicator from cTrade.
//
// -------------------------------------------------------------------------------------------------
using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
namespace cAlgo
{
[Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class BarTimes : Indicator
{
[Output("Signal", LineColor = "Blue", PlotType = PlotType.Line, LineStyle = LineStyle.Lines, Thickness = 1)]
public IndicatorDataSeries Signal { get; set; }
public IndicatorDataSeries Times { get; set; }
private MovingAverage TimesMa;
protected override void Initialize()
{
Times = CreateDataSeries();
TimesMa = Indicators.MovingAverage(Times, 200, MovingAverageType.Simple );
}
public override void Calculate(int index)
{
if( index>0 )
{
var t0 = Bars.OpenTimes[index];
var t1 = Bars.OpenTimes[index-1];
if( t0.ToLocalTime().Date == t1.ToLocalTime().Date )
Times[index] = (t0-t1).TotalMinutes;
else
Times[index] = 0;
}
Signal[index] = Times[index]>0? TimesMa.Result[index] / Times[index] : 0;
}
}
}
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<EnableDefaultItems>False</EnableDefaultItems>
<GenerateAssemblyInfo>False</GenerateAssemblyInfo>
</PropertyGroup>
<PropertyGroup>
<LangVersion>7.2</LangVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>cAlgo</RootNamespace>
<AssemblyName>Bar times</AssemblyName>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="1.*" />
</ItemGroup>
<ItemGroup>
<Compile Include="Bar times.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,20 @@
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Bar times")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Bar times")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("35f19c43-c7cc-4f53-b8e0-61caaf9cd8e8")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
#if DEBUG
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations)]
#endif
Binary file not shown.
@@ -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}") = "BarCloseAlert", "BarCloseAlert\BarCloseAlert.csproj", "{5de69e58-aff2-4b56-be9b-3de3b4fc7e82}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5de69e58-aff2-4b56-be9b-3de3b4fc7e82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5de69e58-aff2-4b56-be9b-3de3b4fc7e82}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5de69e58-aff2-4b56-be9b-3de3b4fc7e82}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5de69e58-aff2-4b56-be9b-3de3b4fc7e82}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,72 @@
using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
namespace cAlgo.Indicators
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class BarCloseAlert : Indicator
{
private HullMovingAverage _hma;
[Parameter("Bar Close Sound File", Group = "Sounds", DefaultValue = "C:\\Windows\\Media\\Alarm07.wav")]
public string BarCloseSoundFileName { get; set; }
[Parameter("HMA Sound File", Group = "Sounds", DefaultValue = "C:\\Windows\\Media\\Alarm08.wav")]
public string HmaSoundFileName { get; set; }
[Parameter("HMA Period", Group = "HMA Settings", DefaultValue = 200)]
public int HmaPeriod { get; set; }
protected override void Initialize()
{
_hma = Indicators.HullMovingAverage(Bars.ClosePrices, HmaPeriod);
Bars.BarClosed += OnBarsClosed;
}
private void OnBarsClosed(BarClosedEventArgs obj)
{
// 1. Play Bar Close Sound
if (!string.IsNullOrEmpty(BarCloseSoundFileName))
{
Notifications.PlaySound(BarCloseSoundFileName);
}
// 2. Check HMA High/Low
// We need enough bars for Last(0), Last(1), Last(2)
if (Bars.Count < 3 || string.IsNullOrEmpty(HmaSoundFileName))
{
return;
}
// Adjusted Indexing per user requirement:
// Last(0) is treated as the bar that just closed.
double hmaJustClosed = _hma.Result.Last(0);
double hmaPrev = _hma.Result.Last(1);
double hmaPrePrev = _hma.Result.Last(2);
// Check for High Point (Peak): Rising then Falling
// Shape: / \
bool isHigh = (hmaPrePrev < hmaPrev) && (hmaPrev > hmaJustClosed);
// Check for Low Point (Valley): Falling then Rising
// Shape: \ /
bool isLow = (hmaPrePrev > hmaPrev) && (hmaPrev < hmaJustClosed);
if (isHigh || isLow)
{
Notifications.PlaySound(HmaSoundFileName);
}
}
public override void Calculate(int index)
{
}
protected override void OnDestroy()
{
Bars.BarClosed -= OnBarsClosed;
}
}
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="*" />
</ItemGroup>
</Project>
Binary file not shown.
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Candlestick Patterns DEMO", "Candlestick Patterns DEMO\Candlestick Patterns DEMO.csproj", "{B9F710D0-7DD5-4E04-B2E9-98C1878E7674}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B9F710D0-7DD5-4E04-B2E9-98C1878E7674}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B9F710D0-7DD5-4E04-B2E9-98C1878E7674}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B9F710D0-7DD5-4E04-B2E9-98C1878E7674}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B9F710D0-7DD5-4E04-B2E9-98C1878E7674}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,504 @@
using System;
using System.IO;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
namespace cAlgo
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.FileSystem)]
public class CP : Indicator
{
#region Parameters
[Parameter("Show names", DefaultValue = false)]
public bool Name_Status { get; set; }
[Parameter("Show more info", DefaultValue = true)]
public bool Add_info { get; set; }
[Parameter("Show Doji", DefaultValue = true)]
public bool Show_Doji { get; set; }
[Parameter("Show Hammer", DefaultValue = true)]
public bool Show_Hammer { get; set; }
[Parameter("MACD Long Cycle", DefaultValue = 26)]
public int LongCycle { get; set; }
[Parameter("MACD Short Cycle", DefaultValue = 12)]
public int ShortCycle { get; set; }
[Parameter("MACD Signal Periods", DefaultValue = 9)]
public int Periods { get; set; }
[Parameter("Doji", DefaultValue = "✝")]
public string Doji_s { get; set; }
[Parameter("Hammer", DefaultValue = "☨")]
public string Hammer_s { get; set; }
#endregion Parameters
private MacdHistogram macd;
private const VerticalAlignment vAlign = VerticalAlignment.Top;
private const HorizontalAlignment hAlign = HorizontalAlignment.Center;
private const double n = 0.618;
private const string UpArrow = "▲";
private const string DownArrow = "▼";
private string Pattern_name;
private double offset;
private struct Candle
{
#region Data
public double High;
public double Close;
public double Open;
public double Low;
#endregion Data
#region Functions
public bool IsFallCandle()
{
if (Close < Open)
return true;
else
return false;
}
public bool IsRiseCandle()
{
if (Open < Close)
return true;
else
return false;
}
public double Median()
{
return (High + Low) / 2;
}
#endregion Functions
}
private enum PatternType : int
{
Doji = 1,
Hammer = 2
}
protected override void Initialize()
{
macd = Indicators.MacdHistogram(MarketSeries.Close, LongCycle, ShortCycle, Periods);
offset = Symbol.PipSize * 5;
}
private void DrawText(int index, int _Type)
{
var high = MarketSeries.High[index];
var low = MarketSeries.Low[index];
int x = index;
double h_y = high + offset;
double h_d_y = h_y + offset * 2.5;
double h_t_y = h_d_y + offset;
double l_y = low - offset * 2.5;
double l_d_y = l_y - offset;
if (TimeFrame == TimeFrame.Minute)
{
h_y = high + offset / 2;
h_d_y = h_y + offset / 2;
h_t_y = h_d_y + offset;
l_y = low - offset / 2;
l_d_y = l_y - offset / 2;
}
if (TimeFrame == TimeFrame.Minute15)
{
h_y = high + offset / 1.5;
h_d_y = h_y + offset;
h_t_y = h_d_y + offset;
l_y = low - offset * 1.5;
l_d_y = l_y - offset * 1.1;
}
if (TimeFrame == TimeFrame.Hour)
{
h_y = high + offset;
h_d_y = h_y + offset * 3;
h_t_y = h_d_y + offset;
l_y = low - offset * 3;
l_d_y = l_y - offset * 3;
}
if (TimeFrame == TimeFrame.Hour4)
{
h_y = high + offset;
h_d_y = h_y + offset * 5;
h_t_y = h_d_y + offset;
l_y = low - offset * 5;
l_d_y = l_y - offset * 5;
}
if (TimeFrame == TimeFrame.Daily)
{
h_y = high + offset * 3;
h_d_y = h_y + offset * 12;
h_t_y = h_d_y + offset;
l_y = low - offset * 12;
l_d_y = l_y - offset * 12;
}
if (TimeFrame == TimeFrame.Weekly)
{
h_y = high + offset * 6;
h_d_y = h_y + offset * 24;
h_t_y = h_d_y + offset;
l_y = low - offset * 24;
l_d_y = l_y - offset * 24;
}
if (TimeFrame == TimeFrame.Monthly)
{
h_y = high + offset * 24;
h_d_y = h_y + offset * 64;
h_t_y = h_d_y + offset;
l_y = low - offset * 64;
l_d_y = l_y - offset * 64;
}
string f_ObjName;
string s_ObjName;
switch (_Type)
{
case (int)PatternType.Doji:
f_ObjName = string.Format("Doji {0}", index);
s_ObjName = string.Format("Doji | {0}", index);
ChartObjects.DrawText(f_ObjName, "Doji", x, h_d_y, vAlign, hAlign, Colors.White);
ChartObjects.DrawText(s_ObjName, "\n|", x, h_y, vAlign, hAlign, Colors.White);
break;
case (int)PatternType.Hammer:
f_ObjName = string.Format("Hammer {0}", index);
s_ObjName = string.Format("Hammer | {0}", index);
ChartObjects.DrawText(f_ObjName, "Hammer", x, h_d_y, vAlign, hAlign, Colors.White);
ChartObjects.DrawText(s_ObjName, "\n|", x, h_y, vAlign, hAlign, Colors.White);
break;
}
}
private void DrawSymbols(int index, int _Type)
{
var high = MarketSeries.High[index];
var low = MarketSeries.Low[index];
int x = index;
double h_y = high + offset;
double h_d_y = h_y + offset * 2.5;
double h_t_y = h_d_y + offset;
double l_y = low - offset * 2.5;
double l_d_y = l_y - offset;
if (TimeFrame == TimeFrame.Minute)
{
h_y = high + offset / 2;
h_d_y = h_y + offset / 2;
h_t_y = h_d_y + offset;
l_y = low - offset / 2;
l_d_y = l_y - offset / 2;
}
if (TimeFrame == TimeFrame.Minute15)
{
h_y = high + offset / 1.5;
h_d_y = h_y + offset;
h_t_y = h_d_y + offset;
l_y = low - offset * 1.5;
l_d_y = l_y - offset * 1.1;
}
if (TimeFrame == TimeFrame.Hour)
{
h_y = high + offset;
h_d_y = h_y + offset * 3;
h_t_y = h_d_y + offset;
l_y = low - offset * 3;
l_d_y = l_y - offset * 3;
}
if (TimeFrame == TimeFrame.Hour4)
{
h_y = high + offset;
h_d_y = h_y + offset * 5;
h_t_y = h_d_y + offset;
l_y = low - offset * 5;
l_d_y = l_y - offset * 5;
}
if (TimeFrame == TimeFrame.Daily)
{
h_y = high + offset * 3;
h_d_y = h_y + offset * 12;
h_t_y = h_d_y + offset;
l_y = low - offset * 12;
l_d_y = l_y - offset * 12;
}
if (TimeFrame == TimeFrame.Weekly)
{
h_y = high + offset * 6;
h_d_y = h_y + offset * 24;
h_t_y = h_d_y + offset;
l_y = low - offset * 24;
l_d_y = l_y - offset * 24;
}
if (TimeFrame == TimeFrame.Monthly)
{
h_y = high + offset * 24;
h_d_y = h_y + offset * 64;
h_t_y = h_d_y + offset;
l_y = low - offset * 64;
l_d_y = l_y - offset * 64;
}
string f_ObjName;
string s_ObjName;
switch (_Type)
{
case (int)PatternType.Doji:
f_ObjName = string.Format("Doji {0}", index);
s_ObjName = string.Format("Doji | {0}", index);
ChartObjects.DrawText(f_ObjName, Doji_s, x, h_d_y, vAlign, hAlign, Colors.White);
ChartObjects.DrawText(s_ObjName, "\n|", x, h_y, vAlign, hAlign, Colors.White);
break;
case (int)PatternType.Hammer:
f_ObjName = string.Format("Hammer {0}", index);
s_ObjName = string.Format("Hammer | {0}", index);
ChartObjects.DrawText(f_ObjName, Hammer_s, x, h_d_y, vAlign, hAlign, Colors.DarkOrange);
ChartObjects.DrawText(s_ObjName, "\n|", x, h_y, vAlign, hAlign, Colors.White);
break;
}
}
private bool Size(Candle candle)
{
if (candle.IsFallCandle())
{
if ((candle.Open - candle.Close) > (candle.High - candle.Low) * n)
return true;
}
else if (candle.IsRiseCandle())
{
if ((candle.Close - candle.Open) > (candle.High - candle.Low) * n)
return true;
}
return false;
}
private void Text_Info(int index, string Pattern_name)
{
if (Add_info == true)
{
#region Pattern
ChartObjects.DrawText("PATTERN", "LAST PATTERN : " + Pattern_name, StaticPosition.TopLeft, Colors.White);
#endregion Pattern
#region MACD
if (MACD_Info(index) == "UP")
{
ChartObjects.DrawText("MACD", "\nMACD : ", StaticPosition.TopLeft, Colors.White);
ChartObjects.DrawText("ARROW MACD", "\n\t" + UpArrow, StaticPosition.TopLeft, Colors.DodgerBlue);
}
else if (MACD_Info(index) == "DOWN")
{
ChartObjects.DrawText("MACD", "\nMACD : ", StaticPosition.TopLeft, Colors.White);
ChartObjects.DrawText("ARROW MACD", "\n\t" + DownArrow, StaticPosition.TopLeft, Colors.Crimson);
}
#endregion MACD
}
}
private string MACD_Info(int index)
{
if (macd.Histogram[index] > 0)
{
return "UP";
}
if (macd.Histogram[index] < 0)
{
return "DOWN";
}
return "ZERO";
}
private bool Doji(Candle candle)
{
if (candle.IsFallCandle() & (candle.Close != candle.Low))
{
if ((candle.High - candle.Low) > 12 * (candle.Open - candle.Close))
return true;
}
if (candle.IsRiseCandle() & (candle.Close != candle.High))
{
if ((candle.High - candle.Low) > 12 * (candle.Close - candle.Open))
return true;
}
return false;
}
private bool Hammer(Candle candle)
{
if (candle.IsFallCandle() & (candle.Close == candle.Low))
{
if ((candle.Median() > candle.Open) & (candle.Median() > candle.Close))
{
if ((candle.Median() - candle.Low) > 1.618 * (candle.Open - candle.Close))
return true;
}
}
if (candle.IsRiseCandle() & (candle.Close == candle.High))
{
if ((candle.Median() < candle.Open) & (candle.Median() < candle.Close))
{
if ((candle.High - candle.Median()) > 1.618 * (candle.Close - candle.Open))
return true;
}
}
return false;
}
public override void Calculate(int index)
{
#region structs
Candle candle = new Candle();
#endregion structs
#region variables
int candle_index = 0;
candle.High = MarketSeries.High.Last(candle_index);
candle.Open = MarketSeries.Open.Last(candle_index);
candle.Close = MarketSeries.Close.Last(candle_index);
candle.Low = MarketSeries.Low.Last(candle_index);
#endregion variables
#region Patterns
// Doji
if (Doji(candle))
{
if (Show_Doji == true)
{
Pattern_name = "Doji";
if (Name_Status == true)
{
DrawText(index, (int)PatternType.Doji);
}
else
{
DrawSymbols(index, (int)PatternType.Doji);
}
}
}
//Hammer
if (Hammer(candle))
{
if (Show_Hammer == true)
{
Pattern_name = "Hammer";
if (Name_Status == true)
{
DrawText(index, (int)PatternType.Hammer);
}
else
{
DrawSymbols(index, (int)PatternType.Hammer);
}
}
}
#endregion Patterns
#region Text
Text_Info(index, Pattern_name);
#endregion Text
}
}
}
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B9F710D0-7DD5-4E04-B2E9-98C1878E7674}</ProjectGuid>
<ProjectTypeGuids>{DD87C1B2-3799-4CA2-93B6-5288EE928820};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>cAlgo</RootNamespace>
<AssemblyName>Candlestick Patterns DEMO</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="cAlgo.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3499da3018340880, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\API\cAlgo.API.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Candlestick Patterns DEMO.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,16 @@
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Candlestick Patterns DEMO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Candlestick Patterns DEMO")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("35f19c43-c7cc-4f53-b8e0-61caaf9cd8e8")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Binary file not shown.
@@ -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}") = "Correlation with angle v1.1", "Correlation with angle v1.1\Correlation with angle v1.1.csproj", "{0e2c43ed-8f8d-446b-848e-ed1fe9ef49a2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0e2c43ed-8f8d-446b-848e-ed1fe9ef49a2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0e2c43ed-8f8d-446b-848e-ed1fe9ef49a2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0e2c43ed-8f8d-446b-848e-ed1fe9ef49a2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0e2c43ed-8f8d-446b-848e-ed1fe9ef49a2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,249 @@
using System;
using System.Linq;
using System.Threading;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace cAlgo
{
[Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class Correlationwithanglev11 : Indicator
{
[Parameter("Symbol Selection Method", DefaultValue = SymbolSelectionMethodType.SymbolList, Group = "Symbole Choice \n(Uncomment code for more than 6 Symbole)")]
public SymbolSelectionMethodType SymbolSelectionMethod { get; set; }
public enum SymbolSelectionMethodType
{
WatchList,
SymbolList
}
[Parameter("Symbol List 1 / WatchList Name 1:", DefaultValue = "XAUUSD", Group = "Symbol Management (5 Symbol / List Maximum)")]
public string TradedSymbols1 { get; set; }
[Parameter("Symbol List 2 / WatchList Name 2:", DefaultValue = "SpotBrent", Group = "Symbol Management (5 Symbol / List Maximum)")]
public string TradedSymbols2 { get; set; }
[Parameter("ExtraLevel", DefaultValue = 50, Group = "Angle Level")]
public int ExtraLevel { get; set; }
[Parameter("PeriodA ngle", DefaultValue = 14, Group = "Angle Setting")]
public int PeriodAngle { get; set; }
[Parameter("Loockback Periods Angle", DefaultValue = 1, Group = "Angle Setting")]
public int LookbackAngle { get; set; }
[Parameter("Price Smooth Type", DefaultValue = MovingAverageType.Weighted, Group = "Angle Setting")]
public MovingAverageType MaTypeAngle { get; set; }
[Parameter("History Diff Angle", DefaultValue = 1, Group = "Base Setting")]
public int HistoryTextLookback { get; set; }
[Parameter("ShowSignals", DefaultValue = true, Group = "Histogram Setting")]
public bool ShowSignal { get; set; }
[Parameter("Sensibility Histogram", DefaultValue = 0.3, Group = "Histogram Setting")]
public double SensibilityHisto { get; set; }
[Parameter("Signal Periods", DefaultValue = 55, Group = "Histogram Setting")]
public int SignalPeriods { get; set; }
[Parameter("Price Smooth Type", DefaultValue = MovingAverageType.Weighted, Group = "Histogram Setting")]
public MovingAverageType MaTypeSignal { get; set; }
[Output("List 1 : Symb n° 1", LineColor = "Lime", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN1 { get; set; }
[Output("List 1 : Symb n° 2", LineColor = "Lime", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN2 { get; set; }
[Output("List 1 : Symb n° 3", LineColor = "Lime", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN3 { get; set; }
[Output("List 1 : Symb n° 4", LineColor = "Lime", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN4 { get; set; }
[Output("List 1 : Symb n° 5", LineColor = "Lime", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN5 { get; set; }
[Output("List 2 : Symb n° 6", LineColor = "Red", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN6 { get; set; }
[Output("List 2 : Symb n° 7", LineColor = "Red", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN7 { get; set; }
[Output("List 2 : Symb n° 8", LineColor = "Red", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN8 { get; set; }
[Output("List 2 : Symb n° 9", LineColor = "Red", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN9 { get; set; }
[Output("List 2 : Symb n° 10", LineColor = "Red", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN10 { get; set; }
[Output("LevelHigh", LineColor = "Gold", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries LevelHigh { get; set; }
[Output("LevelMid", LineColor = "White", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries LevelMid { get; set; }
[Output("LevelLow", LineColor = "Gold", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries LevelLow { get; set; }
private MovingAverage[] angleIndex1, angleIndex2;
private AverageTrueRange[] atrIndex1, atrIndex2;
private Symbol[] TradeList1, TradeList2;
private Bars[] bars1, bars2;
private IndicatorDataSeries[] ResPaireWatchlist1, ResPaireWatchlist2;
private int[] indexBars1, indexBars2;
protected override void Initialize()
{
if (SymbolSelectionMethod == SymbolSelectionMethodType.WatchList)
{
// Get the trade list from the watchlist 1 provided by the user
foreach (Watchlist w in Watchlists)
{
if (w.Name == TradedSymbols1)
{
TradeList1 = Symbols.GetSymbols(w.SymbolNames.ToArray());
}
}
// Get the trade list from the watchlist 2 provided by the user
foreach (Watchlist w in Watchlists)
{
if (w.Name == TradedSymbols2)
{
TradeList2 = Symbols.GetSymbols(w.SymbolNames.ToArray());
}
}
Print();
Print("Watchlist 1 : [ {0} ] = {1} symbols || Watchlist 2 : [ {2} ] = {3} symbols", Bars.ToString().Substring(0, 3), TradeList1.Length, Bars.ToString().Substring(3, 3), TradeList2.Length);
Print();
}
else if (SymbolSelectionMethod == SymbolSelectionMethodType.SymbolList)
{
// Get the trade list from the SymbolList provided by the user
string[] SymbolList = TradedSymbols1.Split(' ');
TradeList1 = Symbols.GetSymbols(SymbolList);
// Get the trade list from the SymbolList provided by the user
string[] SymbolList2 = TradedSymbols2.Split(' ');
TradeList2 = Symbols.GetSymbols(SymbolList2);
}
//Create Indicators for Watchlist 1
angleIndex1 = new MovingAverage[TradeList1.Length];
atrIndex1 = new AverageTrueRange[TradeList1.Length];
bars1 = new Bars[TradeList1.Length];
indexBars1 = new int[TradeList1.Length];
ResPaireWatchlist1 = new IndicatorDataSeries[TradeList1.Length];
//Create Indicators for Watchlist 2
angleIndex2 = new MovingAverage[TradeList2.Length];
atrIndex2 = new AverageTrueRange[TradeList2.Length];
bars2 = new Bars[TradeList2.Length];
indexBars2 = new int[TradeList2.Length];
ResPaireWatchlist2 = new IndicatorDataSeries[TradeList2.Length];
//Initialize Indicators for Watchlist 1
int i = 0;
foreach (var symbol in TradeList1)
{
Print("Watchlist : [ {0} ] => {1} symbols = {2}", Bars.SymbolName, (i + 1), symbol.Name);
//Load bars of watchlist 1
bars1[i] = MarketData.GetBars(TimeFrame, symbol.Name);
while (bars1[i].OpenTimes[0] > Bars.OpenTimes[0])
bars1[i].LoadMoreHistory();
//Load Futurs DataSerie watchlist 1 (calculation in Calculate(int index))
ResPaireWatchlist1[i] = CreateDataSeries();
//Load Indicators watchlist 1
atrIndex1[i] = Indicators.AverageTrueRange(bars1[i], 500, MovingAverageType.Simple);
angleIndex1[i] = Indicators.MovingAverage(bars1[i].ClosePrices, PeriodAngle, MaTypeAngle);
i++;
}
//Initialize Indicators for Watchlist 2
Print();
int j = 0;
foreach (var symbol2 in TradeList2)
{
Print("Watchlist : [ {0} ] => {1} symbols = {2}", Bars.SymbolName, (j + 1), symbol2.Name);
//Load bars of watchlist 2
bars2[j] = MarketData.GetBars(TimeFrame, symbol2.Name);
while (bars2[j].OpenTimes[0] > Bars.OpenTimes[0])
bars2[j].LoadMoreHistory();
//Load Futurs DataSerie watchlist 2 (calculation in Calculate(int index))
ResPaireWatchlist2[j] = CreateDataSeries();
//Load Indicators watchlist 2
atrIndex2[j] = Indicators.AverageTrueRange(bars2[j], 500, MovingAverageType.Simple);
angleIndex2[j] = Indicators.MovingAverage(bars2[j].ClosePrices, PeriodAngle, MaTypeAngle);
j++;
}
Print();
}
public override void Calculate(int index)
{
//Plot Static level on indicator
LevelHigh[index] = ExtraLevel;
LevelMid[index] = 0;
LevelLow[index] = 0 - ExtraLevel;
if (index < PeriodAngle)
return;
//Calculate angle by symbol list 1
for (int i = 0; i < TradeList1.Length; i++)
{
indexBars1[i] = bars1[i].OpenTimes.GetIndexByTime(Bars.OpenTimes[index]);
ResPaireWatchlist1[i][index] = GetCalculationAngle(angleIndex1[i].Result[indexBars1[i]], angleIndex1[i].Result[indexBars1[i] - LookbackAngle], atrIndex1[i].Result[indexBars1[i]]);
}
//Remove Static text of difference into index and index - HistoryTextLookback
if (IndicatorArea.FindAllObjects(ChartObjectType.Text).Length > 0)
IndicatorArea.RemoveAllObjects();
//Calculate difference into index and index - HistoryTextLookback list 1
for (int i = 0; i < TradeList1.Length; i++)
IndicatorArea.DrawText((TradeList1[i]).ToString() + index, TradeList1[i] + " : " + ResPaireWatchlist1[i][index].ToString("F2"), index + 2, double.IsNaN(ResPaireWatchlist1[i][index]) ? 0 : ResPaireWatchlist1[i][index], ResPaireWatchlist1[i][index] > ResPaireWatchlist1[i][index - HistoryTextLookback] ? Color.Lime : Color.Red);
//Output the result like symbolList number != output number list 1
int j = TradeList1.Length - 1;
SymbN1[index] = ResPaireWatchlist1[0 < j ? 0 : j][index];
SymbN2[index] = ResPaireWatchlist1[1 < j ? 1 : j][index];
SymbN3[index] = ResPaireWatchlist1[2 < j ? 2 : j][index];
SymbN4[index] = ResPaireWatchlist1[3 < j ? 3 : j][index];
SymbN5[index] = ResPaireWatchlist1[4 < j ? 4 : j][index];
//Calculate angle by symbol list 2
for (int i = 0; i < TradeList2.Length; i++)
{
indexBars2[i] = bars2[i].OpenTimes.GetIndexByTime(Bars.OpenTimes[index]);
ResPaireWatchlist2[i][index] = GetCalculationAngle(angleIndex2[i].Result[indexBars2[i]], angleIndex2[i].Result[indexBars2[i] - LookbackAngle], atrIndex2[i].Result[indexBars2[i]]);
}
//Calculate difference into index and index - HistoryTextLookback list 2
for (int i = 0; i < TradeList2.Length; i++)
IndicatorArea.DrawText((TradeList2[i]).ToString() + index, TradeList2[i] + " : " + ResPaireWatchlist2[i][index].ToString("F2"), index + 2, double.IsNaN(ResPaireWatchlist2[i][index]) ? 0 : ResPaireWatchlist2[i][index], ResPaireWatchlist2[i][index] > ResPaireWatchlist2[i][index - HistoryTextLookback] ? Color.Lime : Color.Red);
//Output the result like symbolList number != output number list 2
int k = TradeList2.Length - 1;
SymbN6[index] = ResPaireWatchlist2[0 < k ? 0 : k][index];
SymbN7[index] = ResPaireWatchlist2[1 < k ? 1 : k][index];
SymbN8[index] = ResPaireWatchlist2[2 < k ? 2 : k][index];
SymbN9[index] = ResPaireWatchlist2[3 < k ? 3 : k][index];
SymbN10[index] = ResPaireWatchlist2[4 < k ? 4 : k][index];
}
//Function for angle calculation with atr normalization
public double GetCalculationAngle(double priceSmooth, double priceSmoothLoockBack, double atr)
{
var _momentumpositive = priceSmooth - priceSmoothLoockBack;
var _momentumnegative = priceSmoothLoockBack - priceSmooth;
var _momentum = priceSmooth > priceSmoothLoockBack
? _momentumpositive / atr
: _momentumnegative / atr;
var _hypothenuse = Math.Sqrt((_momentum * _momentum) + (LookbackAngle * LookbackAngle));
var _cos = (LookbackAngle / _hypothenuse);
var _angle = priceSmooth > priceSmoothLoockBack
? (0 + (Math.Acos(_cos) * 100))
: (0 - (Math.Acos(_cos) * 100));
return _angle;
}
}
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="1.*" />
</ItemGroup>
</Project>
@@ -0,0 +1,182 @@
using System;
using System.Linq;
using System.Threading;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace cAlgo
{
//[Cloud("Fast Smooth", "Slow Smooth", FirstColor = "Green", SecondColor = "Red", Opacity = 0.1)]
[Levels(0)]
[Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class AngleOfMultiSymbol : Indicator
{
[Parameter("Symbol Selection Method", DefaultValue = SymbolSelectionMethodType.SymbolList, Group = "Symbole Choice \n(Uncomment code for more than 6 Symbole)")]
public SymbolSelectionMethodType SymbolSelectionMethod { get; set; }
[Parameter("Symbol List", DefaultValue = "EURUSD GBPUSD AUDUSD USDCHF", Group = "Symbole Choice \n(Uncomment code for more than 6 Symbole)")]
public string TradedSymbols { get; set; }
[Parameter("Watchlist Name", DefaultValue = "My Watchlist", Group = "Symbole Choice \n(Uncomment code for more than 6 Symbole)")]
public string WatchlistName { get; set; }
public enum SymbolSelectionMethodType
{
CurrentChart,
SymbolList,
WatchList
}
[Parameter("History Diff Angle", DefaultValue = 1, Group = "Base Setting")]
public int HistoryTextLookback { get; set; }
[Parameter("Tf", DefaultValue = "Hour1", Group = "Base Setting")]
public TimeFrame Tf { get; set; }
[Parameter("Price Smooth Period (255)", DefaultValue = 255, Group = "Angle Setting")]
public int SmoothPeriods { get; set; }
[Parameter("Price Smooth Type", DefaultValue = MovingAverageType.Weighted, Group = "Angle Setting")]
public MovingAverageType MaType { get; set; }
[Parameter("Loockback Periods Angle", DefaultValue = 1, Group = "Angle Setting")]
public int LookbackPeriodsAngle { get; set; }
[Parameter("Sensitivity (1.0)", DefaultValue = 1, Group = "Angle Setting")]
public double Sensitivity { get; set; }
[Output("Symb n° 1", LineColor = "White", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN1 { get; set; }
[Output("Symb n° 2", LineColor = "Lime", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN2 { get; set; }
[Output("Symb n° 3", LineColor = "Green", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN3 { get; set; }
[Output("Symb n° 4", LineColor = "DeepSkyBlue", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN4 { get; set; }
[Output("Symb n° 5", LineColor = "Red", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN5 { get; set; }
[Output("Symb n° 6", LineColor = "Magenta", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN6 { get; set; }
/*Uncomment For more Symbole on the chart
[Output("Symb n° 7", LineColor = "Green", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN7 { get; set; }
[Output("Symb n° 8", LineColor = "DeepSkyBlue", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN8 { get; set; }
[Output("Symb n° 9", LineColor = "Red", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN9 { get; set; }
[Output("Symb n° 10", LineColor = "Magenta", PlotType = PlotType.Line, LineStyle = LineStyle.Solid, Thickness = 1)]
public IndicatorDataSeries SymbN10 { get; set; }
*/
private MovingAverage[] ma;
private AverageTrueRange[] atr;
private Symbol[] TradeList;
private Bars[] bars;
private IndicatorDataSeries[] Sources, ResSymbol;
private int[] indexBars;
protected override void Initialize()
{
if (SymbolSelectionMethod == SymbolSelectionMethodType.WatchList)
{
// Get the trade list from the watchlist provided by the user
foreach (Watchlist w in Watchlists)
{
if (w.Name == WatchlistName)
{
TradeList = Symbols.GetSymbols(w.SymbolNames.ToArray());
}
}
}
else if (SymbolSelectionMethod == SymbolSelectionMethodType.SymbolList)
{
// Get the trade list from the sysmbol list provided by the user
string[] SymbolList = TradedSymbols.ToUpper().Split(' ');
TradeList = Symbols.GetSymbols(SymbolList);
}
else
{
TradeList = new Symbol[1];
TradeList[0] = Symbol;
}
atr = new AverageTrueRange[TradeList.Length];
ma = new MovingAverage[TradeList.Length];
bars = new Bars[TradeList.Length];
indexBars = new int[TradeList.Length];
Sources = new IndicatorDataSeries[TradeList.Length];
ResSymbol = new IndicatorDataSeries[TradeList.Length];
Print("{0} traded symbols: ", TradeList.Length);
int i = 0;
foreach (var symbol in TradeList)
{
Print(symbol.Name);
bars[i] = MarketData.GetBars(Tf, symbol.Name);
if (bars[i].OpenTimes[0] > Bars.OpenTimes[0])
bars[i].LoadMoreHistory();
//Load indicators on start up EP5-ATR
Sources[i] = CreateDataSeries();
ResSymbol[i] = CreateDataSeries();
atr[i] = Indicators.AverageTrueRange(bars[i], 500, MovingAverageType.Simple);
ma[i] = Indicators.MovingAverage(Sources[i], SmoothPeriods, MaType);
i++;
}
}
public override void Calculate(int index)
{
if (index < SmoothPeriods)
return;
for (int i = 0; i < TradeList.Length; i++)
{
//indexBars[i] = GetIndexByDate(bars[i], Bars.OpenTimes[index]);
indexBars[i] = bars[i].OpenTimes.GetIndexByTime(Bars.OpenTimes[index]);
Sources[i][index] = bars[i].ClosePrices[indexBars[i]];
ResSymbol[i][index] = GetCalculationSymbol(ma[i].Result[index], ma[i].Result[index - LookbackPeriodsAngle], atr[i].Result[indexBars[i]]);
}
SymbN1[index] = ResSymbol[0][index];
SymbN2[index] = ResSymbol[1][index];
SymbN3[index] = ResSymbol[2][index];
SymbN4[index] = ResSymbol[3][index];
SymbN5[index] = ResSymbol[4][index];
SymbN6[index] = ResSymbol[5][index];
/* Uncomment For More Symbols on chart
SymbN7[index] = ResSymbol[2][index];
SymbN8[index] = ResSymbol[3][index];
SymbN9[index] = ResSymbol[4][index];
SymbN10[index] = ResSymbol[5][index];
*/
IndicatorArea.RemoveAllObjects();
for (int i = 0; i < TradeList.Length; i++)
{
IndicatorArea.DrawText((TradeList[i]).ToString() + index, TradeList[i] + " : " + ResSymbol[i][index].ToString("F2"), index, ResSymbol[i][index], ResSymbol[i][index] > ResSymbol[i][index - HistoryTextLookback] ? Color.Lime : Color.Red);
}
}
public double GetCalculationSymbol(double priceSmooth, double priceSmoothLoockBack, double atr)
{
var _momentumpositive = priceSmooth - priceSmoothLoockBack;
var _momentumnegative = priceSmoothLoockBack - priceSmooth;
var _momentum = priceSmooth > priceSmoothLoockBack
? _momentumpositive / atr
: _momentumnegative / atr;
var _hypothenuse = Math.Sqrt((_momentum * _momentum) + (LookbackPeriodsAngle * LookbackPeriodsAngle));
var _cos = (LookbackPeriodsAngle / _hypothenuse);
var _angle = priceSmooth > priceSmoothLoockBack
? (0 + (Math.Acos(_cos) * 100)) * Sensitivity
: (0 - (Math.Acos(_cos) * 100)) * Sensitivity;
return _angle;
}
}
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="1.*" />
</ItemGroup>
</Project>
Binary file not shown.
@@ -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}") = "Difference", "Difference\Difference.csproj", "{3ebc950e-1111-4055-9211-b51d7d4ac02e}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3ebc950e-1111-4055-9211-b51d7d4ac02e}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3ebc950e-1111-4055-9211-b51d7d4ac02e}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3ebc950e-1111-4055-9211-b51d7d4ac02e}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3ebc950e-1111-4055-9211-b51d7d4ac02e}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,32 @@
using System;
using cAlgo.API;
using cAlgo.API.Internals;
namespace cAlgo.Indicators
{
// Calculates the difference or absolute distance between two data sources
[Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class DifferenceIndicator : Indicator
{
[Parameter("Source 1")]
public DataSeries Source1 { get; set; }
[Parameter("Source 2")]
public DataSeries Source2 { get; set; }
[Parameter("Use Absolute Distance", DefaultValue = false)]
public bool UseAbsoluteDistance { get; set; }
[Output("Result", LineColor = "MainColor", PlotType = PlotType.Line, Thickness = 1)]
public IndicatorDataSeries Result { get; set; }
// Core calculation logic
public override void Calculate(int index)
{
double diff = Source1[index] - Source2[index];
// Result is either raw difference or absolute distance
Result[index] = UseAbsoluteDistance ? Math.Abs(diff) : diff;
}
}
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="*" />
</ItemGroup>
</Project>
Binary file not shown.
@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
@@ -0,0 +1,363 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Economic Events On Chart", "Economic Events On Chart\Economic Events On Chart.csproj", "{7D9A4560-D021-4B46-8D58-83DCBEBBE654}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7D9A4560-D021-4B46-8D58-83DCBEBBE654}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7D9A4560-D021-4B46-8D58-83DCBEBBE654}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7D9A4560-D021-4B46-8D58-83DCBEBBE654}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7D9A4560-D021-4B46-8D58-83DCBEBBE654}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,345 @@
using System;
using cAlgo.API;
using System.Collections.Generic;
using System.Xml;
using System.Net;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System.Linq;
using System.Globalization;
namespace cAlgo
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.Internet)]
public class EconomicEventsOnChart : Indicator
{
private Color _colorHighImpact, _colorMediumImpact, _colorLowImpact, _colorOthers;
private TextBlock _textBlock;
[Parameter("Data URI", DefaultValue = "https://nfs.faireconomy.media/ff_calendar_thisweek.xml", Group = "General")]
public string DataUri { get; set; }
[Parameter("Only Symbol Events", DefaultValue = true, Group = "General")]
public bool OnlySymbolEvents { get; set; }
[Parameter("Show Past Events", DefaultValue = true, Group = "General")]
public bool ShowPastEvents { get; set; }
[Parameter("Show", DefaultValue = true, Group = "High Impact")]
public bool ShowHighImpact { get; set; }
[Parameter("Color", DefaultValue = "Red", Group = "High Impact")]
public string ColorHighImpact { get; set; }
[Parameter("Style", DefaultValue = LineStyle.Solid, Group = "High Impact")]
public LineStyle LineStyleHighImpact { get; set; }
[Parameter("Thickness", DefaultValue = 1, Group = "High Impact")]
public int ThicknessHighImpact { get; set; }
[Parameter("Show", DefaultValue = true, Group = "Medium Impact")]
public bool ShowMediumImpact { get; set; }
[Parameter("Color", DefaultValue = "Gold", Group = "Medium Impact")]
public string ColorMediumImpact { get; set; }
[Parameter("Style", DefaultValue = LineStyle.Solid, Group = "Medium Impact")]
public LineStyle LineStyleMediumImpact { get; set; }
[Parameter("Thickness", DefaultValue = 1, Group = "Medium Impact")]
public int ThicknessMediumImpact { get; set; }
[Parameter("Show", DefaultValue = true, Group = "Low Impact")]
public bool ShowLowImpact { get; set; }
[Parameter("Color", DefaultValue = "Yellow", Group = "Low Impact")]
public string ColorLowImpact { get; set; }
[Parameter("Style", DefaultValue = LineStyle.Solid, Group = "Low Impact")]
public LineStyle LineStyleLowImpact { get; set; }
[Parameter("Thickness", DefaultValue = 1, Group = "Low Impact")]
public int ThicknessLowImpact { get; set; }
[Parameter("Show", DefaultValue = false, Group = "Others")]
public bool ShowOthers { get; set; }
[Parameter("Color", DefaultValue = "Gray", Group = "Others")]
public string ColorOthers { get; set; }
[Parameter("Style", DefaultValue = LineStyle.Solid, Group = "Others")]
public LineStyle LineStyleOthers { get; set; }
[Parameter("Thickness", DefaultValue = 1, Group = "Others")]
public int ThicknessOthers { get; set; }
[Parameter("Show", DefaultValue = true, Group = "Text Block")]
public bool ShowTextBlock { get; set; }
[Parameter("Background Color", DefaultValue = "#969696", Group = "Text Block")]
public string TextBlockBackgroundColor { get; set; }
[Parameter("Color", DefaultValue = "White", Group = "Text Block")]
public string TextBlockColor { get; set; }
[Parameter("Horizontal Alignment", DefaultValue = HorizontalAlignment.Center, Group = "Text Block")]
public HorizontalAlignment TextBlockHorizontalAlignment { get; set; }
[Parameter("Vertical Alignment", DefaultValue = VerticalAlignment.Bottom, Group = "Text Block")]
public VerticalAlignment TextBlockVerticalAlignment { get; set; }
[Parameter("Text Alignment", DefaultValue = TextAlignment.Center, Group = "Text Block")]
public TextAlignment TextBlockTextAlignment { get; set; }
[Parameter("Font Weight", DefaultValue = FontWeight.Bold, Group = "Text Block")]
public FontWeight TextBlockFontWeight { get; set; }
protected override void Initialize()
{
RemoveEventLines();
if (ShowTextBlock)
{
_textBlock = new TextBlock
{
IsVisible = false,
HorizontalAlignment = TextBlockHorizontalAlignment,
VerticalAlignment = TextBlockVerticalAlignment,
BackgroundColor = GetColor(TextBlockBackgroundColor),
ForegroundColor = GetColor(TextBlockColor),
TextAlignment = TextBlockTextAlignment,
FontWeight = TextBlockFontWeight,
Padding = 5
};
Chart.AddControl(_textBlock);
Chart.ObjectHoverChanged += Chart_ObjectHoverChanged;
}
_colorHighImpact = GetColor(ColorHighImpact);
_colorMediumImpact = GetColor(ColorMediumImpact);
_colorLowImpact = GetColor(ColorLowImpact);
_colorOthers = GetColor(ColorOthers);
var events = GetNewsEvents();
DisplayEvents(events);
}
private void Chart_ObjectHoverChanged(ChartObjectHoverChangedEventArgs obj)
{
if (!obj.IsObjectHovered || obj.ChartObject == null || string.IsNullOrWhiteSpace(obj.ChartObject.Name) || !obj.ChartObject.Name.EndsWith("Event", StringComparison.OrdinalIgnoreCase))
{
_textBlock.IsVisible = false;
return;
}
_textBlock.Text = string.Format("{0} | {1}", obj.ChartObject.Name.Replace(" | Event", string.Empty), obj.ChartObject.Comment);
_textBlock.IsVisible = true;
}
public override void Calculate(int index)
{
}
private IEnumerable<NewsEvent> GetNewsEvents()
{
using (var webClient = new WebClient())
{
var data = webClient.DownloadString(DataUri);
return GetNewsEventsFromXml(data);
}
}
private IEnumerable<NewsEvent> GetNewsEventsFromXml(string xml)
{
var xmlSerializer = new XmlSerializer(typeof(WeeklyEvents));
var stream = new StringReader(xml);
var weeklyEvents = xmlSerializer.Deserialize(stream) as WeeklyEvents;
foreach (var newsEvent in weeklyEvents.Events)
{
var timeString = string.Format("{0} {1}", newsEvent.UtcDate, newsEvent.UtcTime);
DateTimeOffset time;
if (DateTimeOffset.TryParseExact(timeString, "MM-dd-yyyy h:mmtt", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out time))
{
newsEvent.Time = time;
}
}
return weeklyEvents.Events;
}
private void DisplayEvents(IEnumerable<NewsEvent> events)
{
foreach (var newsEvent in events)
{
if (!newsEvent.Time.HasValue
|| (newsEvent.Impact == NewsEventImpact.High && !ShowHighImpact)
|| (newsEvent.Impact == NewsEventImpact.Medium && !ShowMediumImpact)
|| (newsEvent.Impact == NewsEventImpact.Low && !ShowLowImpact)
|| ((newsEvent.Impact == NewsEventImpact.None || newsEvent.Impact == NewsEventImpact.Holiday) && !ShowOthers)
|| (OnlySymbolEvents && !IsEventRelatedToSymbol(newsEvent.Currency))
|| (!ShowPastEvents && newsEvent.Time < Server.TimeInUtc)) continue;
var lineSettings = GetLineSettings(newsEvent.Impact);
var eventLine = Chart.DrawVerticalLine(string.Format("{0} | {1} | {2} | Event", newsEvent.Title, newsEvent.Currency, newsEvent.Impact), newsEvent.Time.Value.UtcDateTime, lineSettings.Color, lineSettings.Thickness, lineSettings.Style);
var stringBuilder = new StringBuilder();
if (!string.IsNullOrWhiteSpace(newsEvent.Forecast))
{
stringBuilder.Append(string.Format("Forecast: {0} | ", newsEvent.Forecast));
}
if (!string.IsNullOrWhiteSpace(newsEvent.Previous))
{
stringBuilder.Append(string.Format("Previous: {0} | ", newsEvent.Previous));
}
if (newsEvent.Time.HasValue)
{
var time = newsEvent.Time.Value.ToOffset(Application.UserTimeOffset);
stringBuilder.Append(string.Format("Time: {0:s}", time));
}
eventLine.Comment = stringBuilder.ToString();
eventLine.IsInteractive = true;
eventLine.IsLocked = true;
}
}
private bool IsEventRelatedToSymbol(string eventCurrency)
{
return SymbolName.StartsWith(eventCurrency, StringComparison.OrdinalIgnoreCase) || SymbolName.EndsWith(eventCurrency, StringComparison.OrdinalIgnoreCase);
}
private Color GetColor(string colorString, int alpha = 255)
{
var color = colorString[0] == '#' ? Color.FromHex(colorString) : Color.FromName(colorString);
return Color.FromArgb(alpha, color);
}
private LineSettings GetLineSettings(NewsEventImpact impact)
{
switch (impact)
{
case NewsEventImpact.High:
return new LineSettings
{
Color = _colorHighImpact,
Style = LineStyleHighImpact,
Thickness = ThicknessHighImpact
};
case NewsEventImpact.Medium:
return new LineSettings
{
Color = _colorMediumImpact,
Style = LineStyleMediumImpact,
Thickness = ThicknessMediumImpact
};
case NewsEventImpact.Low:
return new LineSettings
{
Color = _colorLowImpact,
Style = LineStyleLowImpact,
Thickness = ThicknessLowImpact
};
default:
return new LineSettings
{
Color = _colorOthers,
Style = LineStyleOthers,
Thickness = ThicknessOthers
};
}
}
private void RemoveEventLines()
{
var chartObjects = Chart.Objects.ToArray();
foreach (var chartObject in chartObjects)
{
if (chartObject.ObjectType != ChartObjectType.VerticalLine || !chartObject.IsInteractive || string.IsNullOrEmpty(chartObject.Name) || !chartObject.Name.EndsWith("Event", StringComparison.OrdinalIgnoreCase))
{
continue;
}
Chart.RemoveObject(chartObject.Name);
}
}
}
[XmlRoot("weeklyevents")]
public class WeeklyEvents
{
[XmlElement("event")]
public List<NewsEvent> Events { get; set; }
}
public class NewsEvent
{
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("country")]
public string Currency { get; set; }
[XmlElement("date")]
public string UtcDate { get; set; }
[XmlElement("time")]
public string UtcTime { get; set; }
[XmlIgnore]
public DateTimeOffset? Time { get; set; }
[XmlElement("impact")]
public NewsEventImpact Impact { get; set; }
[XmlElement("previous")]
public string Previous { get; set; }
[XmlElement("forecast")]
public string Forecast { get; set; }
}
public enum NewsEventImpact
{
None,
High,
Medium,
Low,
Holiday
}
public struct LineSettings
{
public Color Color { get; set; }
public LineStyle Style { get; set; }
public int Thickness { get; set; }
}
}
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<LangVersion>7.2</LangVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{7D9A4560-D021-4B46-8D58-83DCBEBBE654}</ProjectGuid>
<ProjectTypeGuids>{DD87C1B2-3799-4CA2-93B6-5288EE928820};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>cAlgo</RootNamespace>
<AssemblyName>Economic Events On Chart</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="cAlgo.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3499da3018340880, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\API\cAlgo.API.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Economic Events On Chart.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,20 @@
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Economic Events On Chart")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Economic Events On Chart")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("35f19c43-c7cc-4f53-b8e0-61caaf9cd8e8")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
#if DEBUG
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations)]
#endif
Binary file not shown.
@@ -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}") = "HmaClusterDisplay", "HmaClusterDisplay\HmaClusterDisplay.csproj", "{9a7d3632-3200-43b4-9d1a-032be8e9a37e}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9a7d3632-3200-43b4-9d1a-032be8e9a37e}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9a7d3632-3200-43b4-9d1a-032be8e9a37e}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9a7d3632-3200-43b4-9d1a-032be8e9a37e}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9a7d3632-3200-43b4-9d1a-032be8e9a37e}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,135 @@
using System;
using System.IO;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
namespace cAlgo
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
public class HmaClusterDisplay : Indicator
{
#region Parameters
[Parameter("Config File Path", DefaultValue = @"\\COFFEE\cTrader\HmaCluster.txt")]
public string ConfigFilePath { get; set; }
#endregion
#region Outputs
// SMA with Length SmaBias, Col=#FF01FF01, thickness=2
[Output("SMA Bias", LineColor = "#FF01FF01", Thickness = 2)]
public IndicatorDataSeries SmaBiasOutput { get; set; }
// HMA with Length HmaBias, Col=#FFFF6666, thickness=2
[Output("HMA Bias", LineColor = "#FFFF6666", Thickness = 2)]
public IndicatorDataSeries HmaBiasOutput { get; set; }
// HMA with Length HmaCluster, Col=White, thickness=2
[Output("HMA Cluster", LineColor = "White", Thickness = 2)]
public IndicatorDataSeries HmaClusterOutput { get; set; }
#endregion
#region Variables
private SimpleMovingAverage _smaBiasIndicator;
private HullMovingAverage _hmaBiasIndicator;
private HullMovingAverage _hmaClusterIndicator;
// Default values from prompt header
private int _smaBiasLength = 200;
private int _hmaBiasLength = 250;
private int _hmaClusterLength = 25;
#endregion
protected override void Initialize()
{
LoadConfiguration();
// Initialize indicators with loaded or default values
_smaBiasIndicator = Indicators.SimpleMovingAverage(Bars.ClosePrices, _smaBiasLength);
_hmaBiasIndicator = Indicators.HullMovingAverage(Bars.ClosePrices, _hmaBiasLength);
_hmaClusterIndicator = Indicators.HullMovingAverage(Bars.ClosePrices, _hmaClusterLength);
Print($"Initialized: {_smaBiasLength} SMA | {_hmaBiasLength} HMA Bias | {_hmaClusterLength} HMA Cluster");
}
public override void Calculate(int index)
{
if (_smaBiasIndicator != null)
SmaBiasOutput[index] = _smaBiasIndicator.Result[index];
if (_hmaBiasIndicator != null)
HmaBiasOutput[index] = _hmaBiasIndicator.Result[index];
if (_hmaClusterIndicator != null)
HmaClusterOutput[index] = _hmaClusterIndicator.Result[index];
}
private void LoadConfiguration()
{
if (!File.Exists(ConfigFilePath))
{
Print($"Config file not found at {ConfigFilePath}. Using defaults.");
return;
}
try
{
var lines = File.ReadAllLines(ConfigFilePath);
var currentSymbol = SymbolName;
// cTrader ShortName returns "m5", "h1", etc. which matches your file format
var currentTimeframe = TimeFrame.ShortName;
foreach (var line in lines)
{
var trimmedLine = line.Trim();
// Skip comments and empty lines
if (string.IsNullOrWhiteSpace(trimmedLine) || trimmedLine.StartsWith("#"))
continue;
// Split by whitespace
var columns = trimmedLine.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
// Ensure we have enough columns (need at least up to index 6)
if (columns.Length < 7)
continue;
var cfgSymbol = columns[0];
var cfgTimeframe = columns[1];
// Check for match (case-insensitive)
if (string.Equals(cfgSymbol, currentSymbol, StringComparison.OrdinalIgnoreCase) &&
string.Equals(cfgTimeframe, currentTimeframe, StringComparison.OrdinalIgnoreCase))
{
// Parse values
// Col 4: SmaBias
// Col 5: HmaBias
// Col 6: HmaCluster
if (int.TryParse(columns[4], out int sBias) &&
int.TryParse(columns[5], out int hBias) &&
int.TryParse(columns[6], out int hCluster))
{
_smaBiasLength = sBias;
_hmaBiasLength = hBias;
_hmaClusterLength = hCluster;
Print($"Configuration found for {currentSymbol} {currentTimeframe}");
return; // Stop searching after match
}
}
}
Print($"No specific config found for {currentSymbol} {currentTimeframe}. Using defaults.");
}
catch (Exception ex)
{
Print($"Error reading config file: {ex.Message}. Using defaults.");
}
}
}
}
@@ -0,0 +1,9 @@
<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("HmaClusterDisplay")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("HmaClusterDisplay")]
[assembly: System.Reflection.AssemblyTitleAttribute("HmaClusterDisplay")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
@@ -0,0 +1 @@
c64656f30d6316c2781214813c004e91eeb999a2
@@ -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 = HmaClusterDisplay
build_property.ProjectDir = C:\Users\Brummel\Documents\cAlgo\Sources\Indicators\HmaClusterDisplay\HmaClusterDisplay\
@@ -0,0 +1,66 @@
{
"format": 1,
"restore": {
"C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\HmaClusterDisplay.csproj": {}
},
"projects": {
"C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\HmaClusterDisplay.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\HmaClusterDisplay.csproj",
"projectName": "HmaClusterDisplay",
"projectPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\HmaClusterDisplay.csproj",
"packagesPath": "C:\\Users\\Brummel\\.nuget\\packages\\",
"outputPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\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\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\HmaClusterDisplay.csproj",
"projectName": "HmaClusterDisplay",
"projectPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\HmaClusterDisplay.csproj",
"packagesPath": "C:\\Users\\Brummel\\.nuget\\packages\\",
"outputPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\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": "yHH60uYu212/ZwKBjFEs3QIJ5FpzVGBMwmFDYLX2rhH2Cs1IBW+Oz5ZVjZ6S4fBauvoGBarOvV07SnxXEk/83g==",
"success": true,
"projectFilePath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaClusterDisplay\\HmaClusterDisplay\\HmaClusterDisplay.csproj",
"expectedPackageFiles": [
"C:\\Users\\Brummel\\.nuget\\packages\\ctrader.automate\\1.0.14\\ctrader.automate.1.0.14.nupkg.sha512"
],
"logs": []
}
Binary file not shown.
@@ -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}") = "HmaClusterSR", "HmaClusterSR\HmaClusterSR.csproj", "{31e3888d-35c4-4e2d-8ad6-4fc04fd7ebb7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{31e3888d-35c4-4e2d-8ad6-4fc04fd7ebb7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{31e3888d-35c4-4e2d-8ad6-4fc04fd7ebb7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{31e3888d-35c4-4e2d-8ad6-4fc04fd7ebb7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{31e3888d-35c4-4e2d-8ad6-4fc04fd7ebb7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,875 @@
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 = "8569913524:AAE9RGsvkBPa0yhTFCKBjVeST0fuzdOx5w0", Group = "Telegram")]
public string TelegramBotToken { get; set; }
[Parameter("Telegram Chat ID", DefaultValue = "5171721381", 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]),
// Default values for parameters not in CSV yet
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
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)
{
CleanupOrders(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);
if ((bias == Bias.Long && hasLong) || (bias == Bias.Short && hasShort))
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 CleanupOrders(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)
{
double slDistPips = Math.Abs(entry - sl) / _symbol.PipSize;
if (slDistPips <= 0) return;
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) 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;
}
var existingOrder = _robot.PendingOrders.FirstOrDefault(o => o.SymbolName == _config.SymbolName && o.Label == Label && o.TradeType == type);
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)
{
_robot.ModifyPendingOrder(existingOrder, entry, sl, tp, ProtectionType.Absolute, null, volume);
}
}
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 < 2) return new List<ClusterLevel>();
double currentPrice = _bars.ClosePrices[currentIndex];
double range = _currentDynamicRange;
// Score-First / Global Density Approach (Matches Indicator)
var candidates = _extremaPoints
.Select(p => {
double weightedScore = _extremaPoints
.Where(other => Math.Abs(other.Price - p.Price) <= range)
.Sum(other => GetWeight(other, currentIndex, currentPrice));
return new { Price = p.Price, Score = weightedScore };
})
.OrderByDescending(z => z.Score)
.ToList();
var topZones = new List<ClusterLevel>();
foreach (var zone in candidates)
{
// Filter Overlap
if (!topZones.Any(z => Math.Abs(z.Price - zone.Price) < range))
{
// Normalize Score relative to total Weight of all points (Matches Indicator Normalization)
double totalWeightSum = _extremaPoints.Sum(p => GetWeight(p, currentIndex, currentPrice));
double sigPercent = (totalWeightSum > 0) ? (zone.Score / totalWeightSum) * 100.0 : 0;
topZones.Add(new ClusterLevel { Price = zone.Price, Significance = sigPercent });
}
}
return topZones;
}
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 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="*" />
</ItemGroup>
</Project>
@@ -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}") = "HmaMitigationCount", "HmaMitigationCount\HmaMitigationCount.csproj", "{a7f42ba9-479c-418c-83b4-228416c67510}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{a7f42ba9-479c-418c-83b4-228416c67510}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{a7f42ba9-479c-418c-83b4-228416c67510}.Debug|Any CPU.Build.0 = Debug|Any CPU
{a7f42ba9-479c-418c-83b4-228416c67510}.Release|Any CPU.ActiveCfg = Release|Any CPU
{a7f42ba9-479c-418c-83b4-228416c67510}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,162 @@
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using System.Collections.Generic;
using System.Linq;
using System;
namespace cAlgo.Indicators
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class HmaMitigationCount : Indicator
{
[Parameter("HMA Period", DefaultValue = 20, MinValue = 2)]
public int HmaPeriod { get; set; }
[Parameter("Session Close Time (UTC)", DefaultValue = "17:30")]
public TimeSpan SessionCloseTimeUtc { get; set; }
[Output("HMA", LineColor = "Orange")]
public IndicatorDataSeries HmaOutput { get; set; }
private HullMovingAverage _hma;
private Stack<double> _peakStack;
private Stack<double> _troughStack;
private int lblCnt = 0;
private int mitigatedPeaks = 0;
private int mitigatedTroughs = 0;
private int dir = 0;
private DateTime _currentSessionEndTimeUtc = DateTime.MinValue;
protected override void Initialize()
{
_hma = Indicators.HullMovingAverage(Bars.ClosePrices, HmaPeriod);
_peakStack = new Stack<double>();
_troughStack = new Stack<double>();
}
public override void Calculate(int index)
{
HmaOutput[index] = _hma.Result[index];
DateTime barOpenTime = Bars.OpenTimes[index]; // This is UTC
// --- Session Initialization (run once) ---
if (_currentSessionEndTimeUtc == DateTime.MinValue)
{
// Find the session close time for the *current* bar's day
DateTime sessionCloseToday = barOpenTime.Date.Add(SessionCloseTimeUtc);
// If the bar is already *after* today's close, the session ends *tomorrow*
if (barOpenTime >= sessionCloseToday)
{
_currentSessionEndTimeUtc = sessionCloseToday.AddDays(1);
}
// If the bar is *before* today's close, the session ends *today*
else
{
_currentSessionEndTimeUtc = sessionCloseToday;
}
}
// --- Session Check ---
// Check if the current bar has crossed the session boundary
if (barOpenTime >= _currentSessionEndTimeUtc)
{
// New session starts, clear stacks
_peakStack.Clear();
_troughStack.Clear();
//Chart.RemoveAllObjects(); // Optional: Clear old session text
// Set the *next* session end time, looping in case of market gaps (weekends)
while (barOpenTime >= _currentSessionEndTimeUtc)
{
_currentSessionEndTimeUtc = _currentSessionEndTimeUtc.AddDays(1);
}
}
// Stop logic from running on the forming bar
if (IsLastBar)
{
return;
}
// We need at least 3 bars to identify a peak/trough at index - 1
if (index < 2)
{
return;
}
// --- 1. Identify new peaks/troughs at index - 1 AND check mitigation ---
// All HMA values are now based on closed bars (index, index-1, index-2).
double prevHma = _hma.Result[index - 1];
double prevHma2 = _hma.Result[index - 2];
double currentHma = _hma.Result[index];
// A peak at index-1
bool isPeak = (prevHma > prevHma2) && (prevHma > currentHma);
// A trough at index-1
bool isTrough = (prevHma < prevHma2) && (prevHma < currentHma);
if (isPeak)
{
// New Peak: Check if it mitigates any *previous Peaks*
if( dir < 0 )
{
mitigatedPeaks = 0;
lblCnt++;
}
// A new peak (prevHma) mitigates old peaks that are *lower*
while (_peakStack.Count > 0 && prevHma >= _peakStack.Peek())
{
_peakStack.Pop(); // Pop the mitigated (lower) peak
mitigatedPeaks++;
}
if (mitigatedPeaks > 0)
{
// Draw mitigation count above the peak bar
// The remaining count is the peaks *higher* than the new one
string label = $"Mit: {mitigatedPeaks} / Rem: {_peakStack.Count}";
double yPos = Bars.HighPrices[index - 1] + Symbol.PipSize * 5;
Chart.DrawText($"peak_mit_{lblCnt}", label, index - 1, yPos, Color.Red);
dir = 1;
}
// Add the new peak to its own stack
_peakStack.Push(prevHma);
}
if (isTrough)
{
// New Trough: Check if it mitigates any *previous Troughs*
if( dir > 0 )
{
mitigatedTroughs = 0;
lblCnt++;
}
// A new trough (prevHma) mitigates old troughs that are *higher*
while (_troughStack.Count > 0 && prevHma <= _troughStack.Peek())
{
_troughStack.Pop(); // Pop the mitigated (higher) trough
mitigatedTroughs++;
}
if (mitigatedTroughs > 0)
{
// Draw mitigation count below the trough bar
// The remaining count is the troughs *lower* than the new one
string label = $"Mit: {mitigatedTroughs} / Rem: {_troughStack.Count}";
double yPos = Bars.LowPrices[index - 1] - Symbol.PipSize * 5;
Chart.DrawText($"trough_mit_{lblCnt}", label, index - 1, yPos, Color.Lime);
dir = -1;
}
// Add the new trough to its own stack
_troughStack.Push(prevHma);
}
}
}
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="cTrader.Automate" Version="*" />
</ItemGroup>
</Project>
Binary file not shown.
@@ -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}") = "HmaMitigationSignals", "HmaMitigationSignals\HmaMitigationSignals.csproj", "{46b07fe6-e609-40d3-a15f-e381ff0f058e}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{46b07fe6-e609-40d3-a15f-e381ff0f058e}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{46b07fe6-e609-40d3-a15f-e381ff0f058e}.Debug|Any CPU.Build.0 = Debug|Any CPU
{46b07fe6-e609-40d3-a15f-e381ff0f058e}.Release|Any CPU.ActiveCfg = Release|Any CPU
{46b07fe6-e609-40d3-a15f-e381ff0f058e}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,204 @@
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using System.Collections.Generic;
using System.Linq;
using System;
namespace cAlgo.Indicators
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class HmaMitigationSignals : Indicator
{
[Parameter("HMA Period", DefaultValue = 20, MinValue = 2)]
public int HmaPeriod { get; set; }
// Use the chart's TimeZone for this input
[Parameter("Session Close Time (Chart TZ)", DefaultValue = "17:30")]
public TimeSpan SessionCloseTime { get; set; }
[Parameter("Enable Alerts", DefaultValue = true)]
public bool EnableAlerts { get; set; }
[Parameter("Alert Sound Path", DefaultValue = "")]
public string AlertSoundPath { get; set; }
[Output("HMA", LineColor = "Orange")]
public IndicatorDataSeries HmaOutput { get; set; }
private HullMovingAverage _hma;
private Stack<double> _peakStack;
private Stack<double> _troughStack;
private DateTime _currentSessionEndTimeUtc = DateTime.MinValue;
// State flags for entry setup
private bool _buySetupActive = false;
private bool _sellSetupActive = false;
protected override void Initialize()
{
_hma = Indicators.HullMovingAverage(Bars.ClosePrices, HmaPeriod);
_peakStack = new Stack<double>();
_troughStack = new Stack<double>();
}
public override void Calculate(int index)
{
HmaOutput[index] = _hma.Result[index];
DateTime barOpenTime = Bars.OpenTimes[index]; // This is UTC
// --- Session Initialization (run once) ---
if (_currentSessionEndTimeUtc == DateTime.MinValue)
{
// Convert the current UTC bar time to the chart's local time zone
DateTime barOpenTimeChartTz = TimeZoneInfo.ConvertTimeFromUtc(barOpenTime, this.TimeZone);
// Create the session close time for "today" *in the chart's timezone*
DateTime sessionCloseChartTz = barOpenTimeChartTz.Date.Add(SessionCloseTime);
// Convert this chart-timezone-based closing time back to UTC
DateTime sessionCloseTodayUtc = TimeZoneInfo.ConvertTimeToUtc( sessionCloseChartTz, this.TimeZone);
if (barOpenTime >= sessionCloseTodayUtc)
{
// Bar is after today's close. Session end is tomorrow (chart time).
// Add 1 day *in chart time* (handles DST)
DateTime nextSessionEndChartTz = sessionCloseChartTz.AddDays(1);
// Convert back to UTC
_currentSessionEndTimeUtc = TimeZoneInfo.ConvertTime(nextSessionEndChartTz, this.TimeZone, TimeZoneInfo.Utc);
}
else
{
// Bar is before today's close. Session end is today (chart time).
_currentSessionEndTimeUtc = sessionCloseTodayUtc;
}
}
// --- Session Check ---
// Check if the current bar has crossed the session boundary
if (barOpenTime >= _currentSessionEndTimeUtc)
{
// New session starts, clear stacks and drawings
_peakStack.Clear();
_troughStack.Clear();
//Chart.RemoveAllObjects(); // Clear old session text and icons
// Reset setup flags
_buySetupActive = false;
_sellSetupActive = false;
// Set the *next* session end time, looping in case of market gaps (weekends)
while (barOpenTime >= _currentSessionEndTimeUtc)
{
// Convert current UTC end time to chart time
DateTime currentSessionEndChartTz = TimeZoneInfo.ConvertTimeFromUtc(_currentSessionEndTimeUtc, this.TimeZone);
// Add 1 day *in chart time* (handles DST)
DateTime nextSessionEndChartTz = currentSessionEndChartTz.AddDays(1);
// Convert back to UTC for the next comparison
_currentSessionEndTimeUtc = TimeZoneInfo.ConvertTime(nextSessionEndChartTz, this.TimeZone, TimeZoneInfo.Utc);
}
}
// Stop signal logic from running on the forming bar (which causes repainting)
if (IsLastBar)
{
return;
}
// We need at least 3 bars to identify a peak/trough at index - 1
if (index < 2)
{
return;
}
// --- 1. Identify new peaks/troughs at index - 1 AND check for entry ---
// All HMA values are now based on closed bars (index, index-1, index-2).
double prevHma = _hma.Result[index - 1];
double prevHma2 = _hma.Result[index - 2];
double currentHma = _hma.Result[index];
// A peak at index-1
bool isPeak = (prevHma > prevHma2) && (prevHma > currentHma);
// A trough at index-1
bool isTrough = (prevHma < prevHma2) && (prevHma < currentHma);
if (isPeak)
{
// Check if a sell setup was active *before* pushing the new peak
if (_sellSetupActive)
{
// Draw sell icon at the peak (index - 1)
Chart.DrawIcon($"sell_{index - 1}", ChartIconType.DownArrow, index - 1, Bars.HighPrices[index - 1] + Symbol.PipSize * 10, Color.Red);
_sellSetupActive = false; // Reset setup
}
_peakStack.Push(prevHma);
// Draw count above the peak bar
string peakLabel = $"{_peakStack.Count}";
double yPos = Bars.HighPrices[index - 1] + Symbol.PipSize * 5;
Chart.DrawText($"peak_{index - 1}", peakLabel, index - 1, yPos, Color.Red);
}
if (isTrough)
{
// Check if a buy setup was active *before* pushing the new trough
if (_buySetupActive)
{
// Draw buy icon at the trough (index - 1)
Chart.DrawIcon($"buy_{index - 1}", ChartIconType.UpArrow, index - 1, Bars.LowPrices[index - 1] - Symbol.PipSize * 10, Color.Lime);
_buySetupActive = false; // Reset setup
}
_troughStack.Push(prevHma);
// Draw count below the trough bar
string troughLabel = $"{_troughStack.Count}";
double yPos = Bars.LowPrices[index - 1] - Symbol.PipSize * 5;
Chart.DrawText($"trough_{index - 1}", troughLabel, index - 1, yPos, Color.Lime);
}
// --- 2. Check for mitigation (Setup) based on the hma value ---
// Mitigation is checked against the closed bar 'currentHma' (at index).
// Check peak mitigation (testing highs)
bool peakMitigationTriggeredSetup = false;
while (_peakStack.Count > 0 && currentHma >= _peakStack.Peek())
{
_peakStack.Pop();
if (_peakStack.Count <= 1)
{
peakMitigationTriggeredSetup = true;
}
}
if (peakMitigationTriggeredSetup)
{
// Alert only on the first bar the setup becomes active
if (EnableAlerts && !_sellSetupActive && !string.IsNullOrEmpty(AlertSoundPath))
{
Notifications.PlaySound(AlertSoundPath);
}
_sellSetupActive = true; // Activate sell setup
}
// Check trough mitigation (testing lows)
bool troughMitigationTriggeredSetup = false;
while (_troughStack.Count > 0 && currentHma <= _troughStack.Peek())
{
_troughStack.Pop();
if (_troughStack.Count <= 1)
{
troughMitigationTriggeredSetup = true;
}
}
if (troughMitigationTriggeredSetup)
{
// Alert only on the first bar the setup becomes active
if (EnableAlerts && !_buySetupActive && !string.IsNullOrEmpty(AlertSoundPath))
{
Notifications.PlaySound(AlertSoundPath);
}
_buySetupActive = true; // Activate buy setup
}
}
}
}
@@ -0,0 +1,9 @@
<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("HmaMitigationSignals")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("HmaMitigationSignals")]
[assembly: System.Reflection.AssemblyTitleAttribute("HmaMitigationSignals")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
@@ -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 = HmaMitigationSignals
build_property.ProjectDir = C:\Users\Brummel\Documents\cAlgo\Sources\Indicators\HmaMitigationSignals\HmaMitigationSignals\
@@ -0,0 +1,66 @@
{
"format": 1,
"restore": {
"C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\HmaMitigationSignals.csproj": {}
},
"projects": {
"C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\HmaMitigationSignals.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\HmaMitigationSignals.csproj",
"projectName": "HmaMitigationSignals",
"projectPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\HmaMitigationSignals.csproj",
"packagesPath": "C:\\Users\\Brummel\\.nuget\\packages\\",
"outputPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\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\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\HmaMitigationSignals.csproj",
"projectName": "HmaMitigationSignals",
"projectPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\HmaMitigationSignals.csproj",
"packagesPath": "C:\\Users\\Brummel\\.nuget\\packages\\",
"outputPath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\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": "DxEeUy28ZBdzEtfthwL77wzQ4ke6Qq+9ihU8hGHHq9Zkz9SR9yfNrOVC7zcjvC2fluF4I2zsexRZHVqmVVc3IA==",
"success": true,
"projectFilePath": "C:\\Users\\Brummel\\Documents\\cAlgo\\Sources\\Indicators\\HmaMitigationSignals\\HmaMitigationSignals\\HmaMitigationSignals.csproj",
"expectedPackageFiles": [
"C:\\Users\\Brummel\\.nuget\\packages\\ctrader.automate\\1.0.14\\ctrader.automate.1.0.14.nupkg.sha512"
],
"logs": []
}
Binary file not shown.
@@ -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}") = "HmaSmaCrossoverSignal", "HmaSmaCrossoverSignal\HmaSmaCrossoverSignal.csproj", "{82d7192b-57bd-41f4-b4a0-b60264330377}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{82d7192b-57bd-41f4-b4a0-b60264330377}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{82d7192b-57bd-41f4-b4a0-b60264330377}.Debug|Any CPU.Build.0 = Debug|Any CPU
{82d7192b-57bd-41f4-b4a0-b60264330377}.Release|Any CPU.ActiveCfg = Release|Any CPU
{82d7192b-57bd-41f4-b4a0-b60264330377}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,101 @@
using cAlgo.API;
using cAlgo.API.Indicators;
namespace cAlgo.Indicators
{
// Indicator in a separate window, shows HMA A (fast HMA) and trade signals.
[Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class HmaSmaCrossoverSignal : Indicator
{
[Parameter("HMA A Period (Fast)", DefaultValue = 20, Group = "Periods")]
public int HmaAPeriod { get; set; }
[Parameter("HMA B Period (Slow)", DefaultValue = 250, Group = "Periods")]
public int HmaBPeriod { get; set; }
[Parameter("SMA C Period (Base)", DefaultValue = 200, Group = "Periods")]
public int SmaCPeriod { get; set; }
// Output for HMA A to provide context for signals
[Output("HMA A", LineColor = "Cyan")]
public IndicatorDataSeries HmaAOutput { get; set; }
// Output for Buy signals
[Output("Buy Signal", LineColor = "Green", PlotType = PlotType.Points, Thickness = 8)]
public IndicatorDataSeries BuySignal { get; set; }
// Output for Sell signals
[Output("Sell Signal", LineColor = "Red", PlotType = PlotType.Points, Thickness = 8)]
public IndicatorDataSeries SellSignal { get; set; }
// Internal indicator references
private HullMovingAverage _hmaA;
private HullMovingAverage _hmaB;
private SimpleMovingAverage _smaC;
protected override void Initialize()
{
// Initialize the internal indicators using the close prices
_hmaA = Indicators.HullMovingAverage(Bars.ClosePrices, HmaAPeriod);
_hmaB = Indicators.HullMovingAverage(Bars.ClosePrices, HmaBPeriod);
_smaC = Indicators.SimpleMovingAverage(Bars.ClosePrices, SmaCPeriod);
}
public override void Calculate(int index)
{
// Assign HMA A value to the output series for the current index
HmaAOutput[index] = _hmaA.Result[index];
// We need at least 3 bars (index, index-1, index-2) for peak/trough detection at index-1
if (index < 2)
{
BuySignal[index] = double.NaN;
SellSignal[index] = double.NaN;
return;
}
// Get HMA A values for peak/trough detection
double hmaA_curr = _hmaA.Result[index];
double hmaA_prev = _hmaA.Result[index - 1];
double hmaA_prev2 = _hmaA.Result[index - 2];
// Get values for signal conditions (at index - 1)
double hmaB_prev = _hmaB.Result[index - 1];
double smaC_prev = _smaC.Result[index - 1];
// Detect peak or trough at index - 1 (the last closed bar confirmed by the current bar)
// A peak occurs if the middle bar (index-1) is higher than its neighbors (index-2 and index)
bool isPeak = (hmaA_prev2 < hmaA_prev) && (hmaA_prev > hmaA_curr);
// A trough occurs if the middle bar (index-1) is lower than its neighbors
bool isTrough = (hmaA_prev2 > hmaA_prev) && (hmaA_prev < hmaA_curr);
// Initialize signals for the current bar (index) to NaN
BuySignal[index] = double.NaN;
SellSignal[index] = double.NaN;
// Reset signals at index - 1 (to handle repainting if the current bar 'index' changes)
BuySignal[index - 1] = double.NaN;
SellSignal[index - 1] = double.NaN;
// --- Sell Signal Condition ---
// B < C (Slow HMA below Base SMA)
// A > C (Fast HMA above Base SMA)
// A forms a peak (at index - 1)
if ((hmaB_prev < smaC_prev) && (hmaA_prev > smaC_prev) && isPeak)
{
// Place the signal dot at the peak (index - 1) at the HMA A level
SellSignal[index - 1] = hmaA_prev;
}
// --- Buy Signal Condition ---
// B > C (Slow HMA above Base SMA)
// A < C (Fast HMA below Base SMA)
// A forms a trough (at index - 1)
if ((hmaB_prev > smaC_prev) && (hmaA_prev < smaC_prev) && isTrough)
{
// Place the signal dot at the trough (index - 1) at the HMA A level
BuySignal[index - 1] = hmaA_prev;
}
}
}
}
@@ -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 = "")]

Some files were not shown because too many files have changed in this diff Show More