Skip to content

Commit

Permalink
Trackers (#19)
Browse files Browse the repository at this point in the history
Updated examples
Updated CryptoExchange.Net to v8.1.0
Moved FormatSymbol to MexcExchange class
Added support Side setting on SharedTrade model
Added MexcTrackerFactory
Added overload to Create method on MexcOrderBookFactory support SharedSymbol parameter
  • Loading branch information
JKorf authored Oct 28, 2024
1 parent a3660af commit 78d136f
Show file tree
Hide file tree
Showing 20 changed files with 440 additions and 11 deletions.
18 changes: 18 additions & 0 deletions Examples/Examples.sln
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mexc.Examples.Api", "Mexc.E
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mexc.Examples.Console", "Mexc.Examples.Console\Mexc.Examples.Console.csproj", "{FD4F95C8-D9B7-4F81-9245-4CE667DFD421}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mexc.Examples.Tracker", "Mexc.Examples.Tracker\Mexc.Examples.Tracker.csproj", "{8620604A-ECA7-4583-983E-84926F270040}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mexc.Examples.OrderBook", "Mexc.Examples.OrderBook\Mexc.Examples.OrderBook.csproj", "{14CCC9D6-F70C-4DC1-8327-E792A39D87E0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mexc.Net", "..\Mexc.Net\Mexc.Net.csproj", "{EAF4B59C-E790-4DA9-98C0-AE0A4E27F464}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -21,6 +27,18 @@ Global
{FD4F95C8-D9B7-4F81-9245-4CE667DFD421}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FD4F95C8-D9B7-4F81-9245-4CE667DFD421}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FD4F95C8-D9B7-4F81-9245-4CE667DFD421}.Release|Any CPU.Build.0 = Release|Any CPU
{8620604A-ECA7-4583-983E-84926F270040}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8620604A-ECA7-4583-983E-84926F270040}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8620604A-ECA7-4583-983E-84926F270040}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8620604A-ECA7-4583-983E-84926F270040}.Release|Any CPU.Build.0 = Release|Any CPU
{14CCC9D6-F70C-4DC1-8327-E792A39D87E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{14CCC9D6-F70C-4DC1-8327-E792A39D87E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{14CCC9D6-F70C-4DC1-8327-E792A39D87E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{14CCC9D6-F70C-4DC1-8327-E792A39D87E0}.Release|Any CPU.Build.0 = Release|Any CPU
{EAF4B59C-E790-4DA9-98C0-AE0A4E27F464}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EAF4B59C-E790-4DA9-98C0-AE0A4E27F464}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EAF4B59C-E790-4DA9-98C0-AE0A4E27F464}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EAF4B59C-E790-4DA9-98C0-AE0A4E27F464}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
7 changes: 5 additions & 2 deletions Examples/Mexc.Examples.Api/Mexc.Examples.Api.csproj
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="JK.Mexc.Net" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Mexc.Net\Mexc.Net.csproj" />
</ItemGroup>

</Project>
4 changes: 2 additions & 2 deletions Examples/Mexc.Examples.Console/Mexc.Examples.Console.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="JK.Mexc.Net" Version="1.1.1" />
<ProjectReference Include="..\..\Mexc.Net\Mexc.Net.csproj" />
</ItemGroup>

</Project>
18 changes: 18 additions & 0 deletions Examples/Mexc.Examples.OrderBook/Mexc.Examples.OrderBook.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Spectre.Console.Cli" Version="0.49.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Mexc.Net\Mexc.Net.csproj" />
</ItemGroup>

</Project>
52 changes: 52 additions & 0 deletions Examples/Mexc.Examples.OrderBook/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Mexc.Net.Interfaces;
using CryptoExchange.Net;
using CryptoExchange.Net.SharedApis;
using Microsoft.Extensions.DependencyInjection;
using Spectre.Console;

var collection = new ServiceCollection();
collection.AddMexc();
var provider = collection.BuildServiceProvider();

var trackerFactory = provider.GetRequiredService<IMexcOrderBookFactory>();

// Creat and start the order book
var book = trackerFactory.Create(new SharedSymbol(TradingMode.Spot, "ETH", "USDT"));
var result = await book.StartAsync();
if (!result.Success)
{
Console.WriteLine(result);
return;
}

// Create Spectre table
var table = new Table();
table.ShowRowSeparators = true;
table.AddColumn("Bid Quantity", x => { x.RightAligned(); })
.AddColumn("Bid Price", x => { x.RightAligned(); })
.AddColumn("Ask Price", x => { x.LeftAligned(); })
.AddColumn("Ask Quantity", x => { x.LeftAligned(); });

for(var i = 0; i < 10; i++)
table.AddEmptyRow();

await AnsiConsole.Live(table)
.StartAsync(async ctx =>
{
while (true)
{
var snapshot = book.Book;
for (var i = 0; i < 10; i++)
{
var bid = snapshot.bids.ElementAt(i);
var ask = snapshot.asks.ElementAt(i);
table.UpdateCell(i, 0, ExchangeHelpers.Normalize(bid.Quantity).ToString());
table.UpdateCell(i, 1, ExchangeHelpers.Normalize(bid.Price).ToString());
table.UpdateCell(i, 2, ExchangeHelpers.Normalize(ask.Price).ToString());
table.UpdateCell(i, 3, ExchangeHelpers.Normalize(ask.Quantity).ToString());
}

ctx.Refresh();
await Task.Delay(500);
}
});
18 changes: 18 additions & 0 deletions Examples/Mexc.Examples.Tracker/Mexc.Examples.Tracker.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Spectre.Console.Cli" Version="0.49.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Mexc.Net\Mexc.Net.csproj" />
</ItemGroup>

</Project>
104 changes: 104 additions & 0 deletions Examples/Mexc.Examples.Tracker/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using Mexc.Net.Interfaces;
using CryptoExchange.Net.SharedApis;
using Microsoft.Extensions.DependencyInjection;
using Spectre.Console;
using System.Globalization;

var collection = new ServiceCollection();
collection.AddMexc();
var provider = collection.BuildServiceProvider();

var trackerFactory = provider.GetRequiredService<IMexcTrackerFactory>();

// Creat and start the tracker, keep track of the last 10 minutes
var tracker = trackerFactory.CreateTradeTracker(new SharedSymbol(TradingMode.Spot, "ETH", "USDT"), period: TimeSpan.FromMinutes(10));
var result = await tracker.StartAsync();
if (!result.Success)
{
Console.WriteLine(result);
return;
}

// Create Spectre table
var table = new Table();
table.ShowRowSeparators = true;
table.AddColumn("5 Min Data").AddColumn("-5 Min", x => { x.RightAligned(); })
.AddColumn("Now", x => { x.RightAligned(); })
.AddColumn("Dif", x => { x.RightAligned(); });

table.AddRow("Count", "", "", "");
table.AddRow("Average price", "", "", "");
table.AddRow("Average weighted price", "", "", "");
table.AddRow("Buy/Sell Ratio", "", "", "");
table.AddRow("Volume", "", "", "");
table.AddRow("Value", "", "", "");
table.AddRow("Complete", "", "", "");
table.AddRow("", "", "", "");
table.AddRow("Status", "", "", "");
table.AddRow("Synced From", "", "", "");

// Set default culture for currency display
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

await AnsiConsole.Live(table)
.StartAsync(async ctx =>
{
while (true)
{
// Get the stats from 10 minutes until 5 minutes ago
var secondLastMinute = tracker.GetStats(DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow.AddMinutes(-5));

// Get the stats from 5 minutes ago until now
var lastMinute = tracker.GetStats(DateTime.UtcNow.AddMinutes(-5));

// Get the differences between them
var compare = secondLastMinute.CompareTo(lastMinute);

// Update the columns
UpdateDec(0, 1, secondLastMinute.TradeCount);
UpdateDec(0, 2, lastMinute.TradeCount);
UpdateStr(0, 3, $"[{(compare.TradeCountDif.Difference < 0 ? "red" : "green")}]{compare.TradeCountDif.Difference} / {compare.TradeCountDif.PercentageDifference}%[/]");

UpdateStr(1, 1, secondLastMinute.AveragePrice?.ToString("C"));
UpdateStr(1, 2, lastMinute.AveragePrice?.ToString("C"));
UpdateStr(1, 3, $"[{(compare.AveragePriceDif?.Difference < 0 ? "red" : "green")}]{compare.AveragePriceDif?.Difference?.ToString("C")} / {compare.AveragePriceDif?.PercentageDifference}%[/]");

UpdateStr(2, 1, secondLastMinute.VolumeWeightedAveragePrice?.ToString("C"));
UpdateStr(2, 2, lastMinute.VolumeWeightedAveragePrice?.ToString("C"));
UpdateStr(2, 3, $"[{(compare.VolumeWeightedAveragePriceDif?.Difference < 0 ? "red" : "green")}]{compare.VolumeWeightedAveragePriceDif?.Difference?.ToString("C")} / {compare.VolumeWeightedAveragePriceDif?.PercentageDifference}%[/]");

UpdateDec(3, 1, secondLastMinute.BuySellRatio);
UpdateDec(3, 2, lastMinute.BuySellRatio);
UpdateStr(3, 3, $"[{(compare.BuySellRatioDif?.Difference < 0 ? "red" : "green")}]{compare.BuySellRatioDif?.Difference} / {compare.BuySellRatioDif?.PercentageDifference}%[/]");

UpdateDec(4, 1, secondLastMinute.Volume);
UpdateDec(4, 2, lastMinute.Volume);
UpdateStr(4, 3, $"[{(compare.VolumeDif.Difference < 0 ? "red" : "green")}]{compare.VolumeDif.Difference} / {compare.VolumeDif.PercentageDifference}%[/]");

UpdateStr(5, 1, secondLastMinute.QuoteVolume.ToString("C"));
UpdateStr(5, 2, lastMinute.QuoteVolume.ToString("C"));
UpdateStr(5, 3, $"[{(compare.QuoteVolumeDif.Difference < 0 ? "red" : "green")}]{compare.QuoteVolumeDif.Difference?.ToString("C")} / {compare.QuoteVolumeDif.PercentageDifference}%[/]");

UpdateStr(6, 1, secondLastMinute.Complete.ToString());
UpdateStr(6, 2, lastMinute.Complete.ToString());

UpdateStr(8, 1, tracker.Status.ToString());
UpdateStr(9, 1, tracker.SyncedFrom?.ToString());

ctx.Refresh();
await Task.Delay(500);
}
});


void UpdateDec(int row, int col, decimal? val)
{
table.UpdateCell(row, col, val?.ToString() ?? string.Empty);
}

void UpdateStr(int row, int col, string? val)
{
table.UpdateCell(row, col, val ?? string.Empty);
}
8 changes: 7 additions & 1 deletion Examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,10 @@
A minimal API showing how to integrate Mexc.Net in a web API project

### Mexc.Examples.Console
A simple console client demonstrating basic usage
A simple console client demonstrating basic usage

### Mexc.Examples.OrderBook
Example of using the client side order book implementation

### Mexc.Examples.Tracker
Example of using the trade tracker
3 changes: 2 additions & 1 deletion Mexc.Net/Clients/SpotApi/MexcRestClientSpotApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ protected override AuthenticationProvider CreateAuthenticationProvider(ApiCreden
=> new MexcAuthenticationProvider(credentials);

/// <inheritdoc />
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverTime = null) => baseAsset.ToUpperInvariant() + quoteAsset.ToUpperInvariant();
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverTime = null)
=> MexcExchange.FormatSymbol(baseAsset, quoteAsset, tradingMode, deliverTime);

internal async Task<WebCallResult<T>> SendRequestInternal<T>(string path, HttpMethod method, CancellationToken cancellationToken,
Dictionary<string, object>? parameters = null, bool signed = false, HttpMethodParameterPosition? postPosition = null,
Expand Down
5 changes: 4 additions & 1 deletion Mexc.Net/Clients/SpotApi/MexcRestClientSpotApiShared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,10 @@ async Task<ExchangeWebResult<IEnumerable<SharedTrade>>> IRecentTradeRestClient.G
if (!result)
return result.AsExchangeResult<IEnumerable<SharedTrade>>(Exchange, null, default);

return result.AsExchangeResult<IEnumerable<SharedTrade>>(Exchange, request.Symbol.TradingMode, result.Data.Select(x => new SharedTrade(x.Quantity, x.Price, x.Timestamp)).ToArray());
return result.AsExchangeResult<IEnumerable<SharedTrade>>(Exchange, request.Symbol.TradingMode, result.Data.Select(x => new SharedTrade(x.Quantity, x.Price, x.Timestamp)
{
Side = x.IsBuyerMaker ? SharedOrderSide.Buy : SharedOrderSide.Sell
}).ToArray());
}

#endregion
Expand Down
3 changes: 2 additions & 1 deletion Mexc.Net/Clients/SpotApi/MexcSocketClientSpotApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ protected override AuthenticationProvider CreateAuthenticationProvider(ApiCreden
=> new MexcAuthenticationProvider(credentials);

/// <inheritdoc />
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverTime = null) => baseAsset.ToUpperInvariant() + quoteAsset.ToUpperInvariant();
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverTime = null)
=> MexcExchange.FormatSymbol(baseAsset, quoteAsset, tradingMode, deliverTime);

public IMexcSocketClientSpotApiShared SharedClient => this;

Expand Down
6 changes: 5 additions & 1 deletion Mexc.Net/Clients/SpotApi/MexcSocketClientSpotApiShared.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Mexc.Net.Interfaces.Clients.SpotApi;
using CryptoExchange.Net.SharedApis;
using CryptoExchange.Net.Objects.Sockets;
using Mexc.Net.Enums;

namespace Mexc.Net.Clients.SpotApi
{
Expand Down Expand Up @@ -37,7 +38,10 @@ async Task<ExchangeResult<UpdateSubscription>> ITradeSocketClient.SubscribeToTra
return new ExchangeResult<UpdateSubscription>(Exchange, validationError);

var symbol = request.Symbol.GetSymbol(FormatSymbol);
var result = await SubscribeToTradeUpdatesAsync(symbol, update => handler(update.AsExchangeEvent<IEnumerable<SharedTrade>>(Exchange, update.Data.Select(x => new SharedTrade(x.Quantity, x.Price, x.Timestamp)).ToArray())), ct).ConfigureAwait(false);
var result = await SubscribeToTradeUpdatesAsync(symbol, update => handler(update.AsExchangeEvent<IEnumerable<SharedTrade>>(Exchange, update.Data.Select(x => new SharedTrade(x.Quantity, x.Price, x.Timestamp)
{
Side = x.Side == OrderSide.Buy ? SharedOrderSide.Buy : SharedOrderSide.Sell
}).ToArray())), ct).ConfigureAwait(false);

return new ExchangeResult<UpdateSubscription>(Exchange, result);
}
Expand Down
2 changes: 2 additions & 0 deletions Mexc.Net/ExtensionMethods/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using CryptoExchange.Net.Clients;
using CryptoExchange.Net.Interfaces;
using Mexc.Net;
using Mexc.Net.Clients;
using Mexc.Net.Interfaces;
using Mexc.Net.Interfaces.Clients;
Expand Down Expand Up @@ -61,6 +62,7 @@ public static IServiceCollection AddMexc(
services.AddTransient<ICryptoRestClient, CryptoRestClient>();
services.AddTransient<ICryptoSocketClient, CryptoSocketClient>();
services.AddTransient<IMexcOrderBookFactory, MexcOrderBookFactory>();
services.AddTransient<IMexcTrackerFactory, MexcTrackerFactory>();
services.AddTransient(x => x.GetRequiredService<IMexcRestClient>().SpotApi.CommonSpotClient);

services.RegisterSharedRestInterfaces(x => x.GetRequiredService<IMexcRestClient>().SpotApi.SharedClient);
Expand Down
9 changes: 9 additions & 0 deletions Mexc.Net/Interfaces/IMexcOrderBookFactory.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.SharedApis;
using Mexc.Net.Objects.Options;
using System;

Expand All @@ -14,6 +15,14 @@ public interface IMexcOrderBookFactory
/// </summary>
public IOrderBookFactory<MexcOrderBookOptions> Spot { get; }

/// <summary>
/// Create a SymbolOrderBook for the symbol
/// </summary>
/// <param name="symbol">The symbol</param>
/// <param name="options">Book options</param>
/// <returns></returns>
ISymbolOrderBook Create(SharedSymbol symbol, Action<MexcOrderBookOptions>? options = null);

/// <summary>
/// Create a new spot SymbolOrderBook
/// </summary>
Expand Down
Loading

0 comments on commit 78d136f

Please sign in to comment.