From a5c22a043ddc0f599927a2c66b62b6ed6fc816dc Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Fri, 20 Nov 2026 14:21:47 +0330 Subject: [PATCH] Initial Commit ... --- .gitignore | 2 + DI/XDIHelperExtension.cs | 16 ++ Providers/XMq5ZQBridge.cs | 250 +++++++++++++++++++++ Providers/XMq5ZQBridgeBackgroundService.cs | 33 +++ README.md | 11 + nuget.config | 8 + xMQL5Bridge.csproj | 45 ++++ 7 files changed, 365 insertions(+) create mode 100644 .gitignore create mode 100644 DI/XDIHelperExtension.cs create mode 100644 Providers/XMq5ZQBridge.cs create mode 100644 Providers/XMq5ZQBridgeBackgroundService.cs create mode 100644 README.md create mode 100644 nuget.config create mode 100644 xMQL5Bridge.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8d4a6c0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +bin +obj \ No newline at end of file diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs new file mode 100644 index 0000000..30ffe06 --- /dev/null +++ b/DI/XDIHelperExtension.cs @@ -0,0 +1,16 @@ +using xCommons.Extensions; +using xMQL5Bridge.Providers; +using Microsoft.Extensions.DependencyInjection; + +namespace xMQL5Bridge.DI +{ + public static class XDIHelperExtension + { + public static void AddXMQ5ZQBridgeHandler( + this IServiceCollection source + ) + { + source.AddXBackgroundService(); + } + } +} \ No newline at end of file diff --git a/Providers/XMq5ZQBridge.cs b/Providers/XMq5ZQBridge.cs new file mode 100644 index 0000000..afbef18 --- /dev/null +++ b/Providers/XMq5ZQBridge.cs @@ -0,0 +1,250 @@ +using System; +using NetMQ.Sockets; +using System.Text.Json; +using System.Threading; +using System.Globalization; +using System.Collections.Generic; +using NetMQ; + +namespace xMQL5Bridge.Providers +{ + public sealed class XMq5ZQBridge : IDisposable + { + // + private const string SubscriberName = "xMq5ZqSubscriber"; + private const string DefaultSubAddress = "tcp://127.0.0.1:5555"; + private const string DefaultReqAddress = "tcp://127.0.0.1:5556"; + + // + private static readonly TimeSpan SendTimeout = TimeSpan.FromSeconds(2); + private static readonly TimeSpan ReplyTimeout = TimeSpan.FromSeconds(5); + private static readonly TimeSpan ReceivePollingTimeout = TimeSpan.FromMilliseconds(500); + + // + private readonly Thread _subThread; + private readonly RequestSocket _req; + private readonly SubscriberSocket _sub; + private readonly object _sendLock = new(); + + // + private bool _disposed = false; + private volatile bool _running = true; + + // + public event Action TickReceived; + + public XMq5ZQBridge( + string subAddress = DefaultSubAddress, + string reqAddress = DefaultReqAddress + ) + { + // + try + { + // + _sub = new SubscriberSocket(); + _sub.Connect(subAddress); + _sub.Subscribe(""); + + // + _req = new RequestSocket(); + _req.Connect(reqAddress); + } + catch + { + // + _sub?.Dispose(); + _req?.Dispose(); + + // + throw; + } + + // + _subThread = new Thread(ReceiveLoop) + { + IsBackground = true, + Name = "Mt5ZmqSubscriber" + }; + _subThread.Start(); + } + + public string SendCommand(string action, string symbol, double volume) + { + // + if (_disposed) + throw new ObjectDisposedException(nameof(XMq5ZQBridge)); + + // + //⛔ culture-invariant برای اعشار (0.1 نه 0,1) + string volumeStr = volume.ToString("0.00", CultureInfo.InvariantCulture); + string payload = $"{action}|{symbol}|{volumeStr}"; + + // + //🔒 قفل برای جلوگیری از جابه‌جایی پاسخ‌ها بین threadها + lock (_sendLock) + { + // + if (!_req.TrySendFrame(SendTimeout, payload)) + { + return BuildError("SEND_TIMEOUT"); + } + + // + if (!_req.TryReceiveFrameString(ReplyTimeout, out string? reply)) + { + return BuildError("REPLY_TIMEOUT"); + } + + // + return reply ?? BuildError("EMPTY_REPLY"); + } + } + + public void Dispose() + { + // + if (_disposed) + { + return; + } + + // + _disposed = true; + _running = false; + + // + try + { + _subThread.Join(TimeSpan.FromSeconds(2)); + } + catch (Exception ex) + { + Console.WriteLine($"[DISPOSE] {ex.Message}"); + } + + // + _sub.Dispose(); + _req.Dispose(); + + // + GC.SuppressFinalize(this); + } + + // + #region Private ... + private void ReceiveLoop() + { + // + while (_running) + { + // + string? json; + + // + try + { + // + if (!_sub.TryReceiveFrameString(ReceivePollingTimeout, out json)) + { + continue; + } + } + catch (Exception ex) + { + // + if (!_running) + { + break; + } + + // + Console.WriteLine($"[SUB ERROR] {ex.Message}"); + continue; + } + + // + try + { + // + var tick = ParseTick(json); + if (tick is not null) + { + // + OnTickReceived(tick); + TickReceived?.Invoke(tick); + } + } + catch (Exception ex) when ( + ex is JsonException + or KeyNotFoundException + or InvalidOperationException + or FormatException) + { + Console.WriteLine($"[JSON PARSE ERROR] {ex.Message} | raw={json}"); + } + catch (Exception ex) + { + Console.WriteLine($"[UNEXPECTED ERROR] {ex}"); + } + } + } + #endregion + + // + #region Statics ... + private static string BuildError(string code) => + $"{{\"ok\":false,\"error\":\"{code}\"}}"; + + private static void OnTickReceived(TickData tick) + { + // + Console.WriteLine( + $"[DATA] {tick.Symbol} Bid={tick.Bid:F5} Ask={tick.Ask:F5} Time={tick.Time}"); + } + + private static TickData ParseTick(string json) + { + // + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + // + if (!root.TryGetProperty("symbol", out var symbolEl) || + !root.TryGetProperty("bid", out var bidEl) || + !root.TryGetProperty("ask", out var askEl)) + { + return null; + } + + // // + // return new TickData( + // Symbol: symbolEl.GetString() ?? string.Empty, + // Bid: bidEl.GetDouble(), + // Ask: askEl.GetDouble(), + // Time: root.TryGetProperty("time", out var t) ? t.GetInt64() : 0 + // ); + + // + var result = new TickData + { + Bid = bidEl.GetDouble(), + Ask = askEl.GetDouble(), + Symbol = symbolEl.GetString() ?? string.Empty, + Time = root.TryGetProperty("time", out var t) ? t.GetInt64() : 0, + }; + + // + return result; + } + #endregion + } + + public sealed class TickData + { + public long Time { get; set; } + public double Bid { get; set; } + public double Ask { get; set; } + public string Symbol { get; set; } + } +} diff --git a/Providers/XMq5ZQBridgeBackgroundService.cs b/Providers/XMq5ZQBridgeBackgroundService.cs new file mode 100644 index 0000000..17de358 --- /dev/null +++ b/Providers/XMq5ZQBridgeBackgroundService.cs @@ -0,0 +1,33 @@ +using System; +using System.Threading; +using xCommons.Providers; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace xMQL5Bridge.Providers +{ + public class XMq5ZQBridgeBackgroundService : XBackgroundService + { + private XMq5ZQBridge bridge; + + public XMq5ZQBridgeBackgroundService( + IServiceProvider serviceProvider, + ILogger logger + ) : base(serviceProvider, logger) + { + // + bridge = new XMq5ZQBridge(); + bridge.TickReceived += (tick => + { + // + logger + .LogInformation("Tock: {xSymbol} {xBid}/{xAsk}", tick.Symbol, tick.Bid, tick.Ask); + }); + } + + protected override Task ExecuteAsync(CancellationToken stoppingToken) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..1367ce7 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# xMQL5Bridge + +it is a Part of xDashboard on SaherElm IT Center which provides all MQL5 Related Futures ... + +## Maintainer + +Hadi Khazaee asl + +[https://www.saherelm.ir](https://www.saherelm.ir) + +[hadi_khazaee_asl@yahoo.com](mailto:hadi_khazaee_asl@yahoo.com) diff --git a/nuget.config b/nuget.config new file mode 100644 index 0000000..15cb0f4 --- /dev/null +++ b/nuget.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/xMQL5Bridge.csproj b/xMQL5Bridge.csproj new file mode 100644 index 0000000..73449a6 --- /dev/null +++ b/xMQL5Bridge.csproj @@ -0,0 +1,45 @@ + + + + + 1.0.0 + 12.0 + Hadi Khazaee Asl + SaherElm IT Center + xDashboard.xMQL5Bridge + netstandard2.0 + + + it is a Part of xDashboard on SaherElm IT Center which provides all MQL5 Related Futures ... + + + + icon.png + + + + + + + + + + + + + + + + + + + + + + + $(NoWarn);1591 + true + true + + +