using System;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static decimal? mexcPrice = null;
static decimal? gatePrice = null;
static async Task Main()
{
var mexcTask = ConnectToMexc("SOPH_USDT");
var gateTask = ConnectToGate("SOPH_USDT");
await Task.WhenAll(mexcTask, gateTask);
}
static async Task ConnectToMexc(string _symbol)
{
var ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri("wss://contract.mexc.com/edge"),
CancellationToken.None);
string subscribeMessage = JsonSerializer.Serialize(new
{
method = "sub.ticker",
param = new { symbol = _symbol }
});
await ws.SendAsync(Encoding.UTF8.GetBytes(subscribeMessage),
WebSocketMessageType.Text, true, CancellationToken.None);
var buffer = new byte[4096];
while (true)
{
var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer),
CancellationToken.None);
var json = Encoding.UTF8.GetString(buffer, 0, result.Count);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("data", out var data))
{
if (json.Contains("lastPrice"))
if (data.TryGetProperty("lastPrice", out var priceEl))
{
mexcPrice = priceEl.GetDecimal();
PrintSpread();
}
}
}
}
static async Task ConnectToGate(string symbol)
{
var ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri("wss://fx-webws.gateio.live/v4/ws/usdt"),
CancellationToken.None);
string subscribeMessage = JsonSerializer.Serialize(new
{
time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
channel = "futures.tickers",
@event = "subscribe",
payload = new[] { symbol }
});
await ws.SendAsync(Encoding.UTF8.GetBytes(subscribeMessage),
WebSocketMessageType.Text, true, CancellationToken.None);
var buffer = new byte[4096];
while (true)
{
var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer),
CancellationToken.None);
var json = Encoding.UTF8.GetString(buffer, 0, result.Count);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("result", out var resultEl))
{
if (json.Contains("mark_price"))
{
var ststt =
JsonDocument.Parse(json).RootElement.GetProperty("result")
[0].GetProperty("last").GetString();
var last = decimal.Parse(ststt.Replace(".", ","));
gatePrice = last;
PrintSpread();
}
}
}
}
static void PrintSpread()
{
if (mexcPrice.HasValue && gatePrice.HasValue)
{
var avg = (mexcPrice.Value + gatePrice.Value) / 2m;
var diff = Math.Abs(mexcPrice.Value - gatePrice.Value);
var spreadPercent = diff / avg * 100m;
Console.Clear();
Console.WriteLine($"MEXC Price: {mexcPrice:F2}");
Console.WriteLine($"Gate Price: {gatePrice:F2}");
Console.WriteLine($"Spread: {spreadPercent:F4}%");
}
}
}