Skip to content

Commit

Permalink
Trackers (#234)
Browse files Browse the repository at this point in the history
Updated examples
Updated CryptoExchange.Net to v8.1.0
Moved FormatSymbol to KucoinExchange class
Added support Side setting on SharedTrade model
Added KucoinTrackerFactory
Added overload to Create method on KucoinOrderBookFactory support SharedSymbol parameter
  • Loading branch information
JKorf authored Oct 28, 2024
1 parent 86c699e commit 42e0d16
Show file tree
Hide file tree
Showing 24 changed files with 501 additions and 37 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}") = "Kucoin.Examples.Api", "Kuco
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Kucoin.Examples.Console", "Kucoin.Examples.Console\Kucoin.Examples.Console.csproj", "{FD4F95C8-D9B7-4F81-9245-4CE667DFD421}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Kucoin.Net", "..\Kucoin.Net\Kucoin.Net.csproj", "{5A503CA9-F47D-4961-8669-F39CBC358F93}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Kucoin.Examples.OrderBook", "Kucoin.Examples.OrderBook\Kucoin.Examples.OrderBook.csproj", "{2FEAA7EE-782F-4C56-AE24-DB734B1B5F5F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Kucoin.Examples.Tracker", "Kucoin.Examples.Tracker\Kucoin.Examples.Tracker.csproj", "{9C3D888D-CF72-40E9-B0D2-0FD272A716A6}"
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
{5A503CA9-F47D-4961-8669-F39CBC358F93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5A503CA9-F47D-4961-8669-F39CBC358F93}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5A503CA9-F47D-4961-8669-F39CBC358F93}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5A503CA9-F47D-4961-8669-F39CBC358F93}.Release|Any CPU.Build.0 = Release|Any CPU
{2FEAA7EE-782F-4C56-AE24-DB734B1B5F5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2FEAA7EE-782F-4C56-AE24-DB734B1B5F5F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2FEAA7EE-782F-4C56-AE24-DB734B1B5F5F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2FEAA7EE-782F-4C56-AE24-DB734B1B5F5F}.Release|Any CPU.Build.0 = Release|Any CPU
{9C3D888D-CF72-40E9-B0D2-0FD272A716A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9C3D888D-CF72-40E9-B0D2-0FD272A716A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9C3D888D-CF72-40E9-B0D2-0FD272A716A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9C3D888D-CF72-40E9-B0D2-0FD272A716A6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
7 changes: 5 additions & 2 deletions Examples/Kucoin.Examples.Api/Kucoin.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="Kucoin.Net" Version="5.3.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

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

</Project>
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="Kucoin.Net" Version="5.3.2" />
<ProjectReference Include="..\..\Kucoin.Net\Kucoin.Net.csproj" />
</ItemGroup>

</Project>
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="..\..\Kucoin.Net\Kucoin.Net.csproj" />
</ItemGroup>

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

var collection = new ServiceCollection();
collection.AddKucoin(opts =>
{
// NOTE Kucoin requires credentials to subscribe order book data
opts.ApiCredentials = new KucoinApiCredentials("APIKEY", "APISECRET", "APIPASS");
});
var provider = collection.BuildServiceProvider();

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

// 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/Kucoin.Examples.Tracker/Kucoin.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="..\..\Kucoin.Net\Kucoin.Net.csproj" />
</ItemGroup>

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

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

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

// 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 Kucoin.Net in a web API project

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

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

### Kucoin.Examples.Tracker
Example of using the trade tracker
10 changes: 1 addition & 9 deletions Kucoin.Net/Clients/FuturesApi/KucoinRestClientFuturesApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,7 @@ protected override AuthenticationProvider CreateAuthenticationProvider(ApiCreden

/// <inheritdoc />
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverTime = null)
{
if (baseAsset.Equals("BTC", StringComparison.OrdinalIgnoreCase))
baseAsset = "XBT";

if (!deliverTime.HasValue)
return baseAsset.ToUpperInvariant() + quoteAsset.ToUpperInvariant() + "M";

return baseAsset.ToUpperInvariant() + "M" + ExchangeHelpers.GetDeliveryMonthSymbol(deliverTime.Value) + deliverTime.Value.ToString("yy");
}
=> KucoinExchange.FormatSymbol(baseAsset, quoteAsset, tradingMode, deliverTime);

internal async Task<WebCallResult> SendAsync(RequestDefinition definition, ParameterCollection? parameters, CancellationToken cancellationToken, int? weight = null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async Task<ExchangeWebResult<SharedFuturesTicker>> IFuturesTickerRestClient.GetF
request.Symbol.TradingMode,
new SharedFuturesTicker(
result.Data.Symbol,
result.Data.LastTradePrice ?? 0,
result.Data.LastTradePrice,
result.Data.HighPrice,
result.Data.LowPrice,
result.Data.Volume24H,
Expand Down Expand Up @@ -95,7 +95,7 @@ async Task<ExchangeWebResult<IEnumerable<SharedFuturesTicker>>> IFuturesTickerRe
return result.AsExchangeResult<IEnumerable<SharedFuturesTicker>>(Exchange,
request.TradingMode == null ? SupportedTradingModes : new[] { request.TradingMode.Value },
result.Data.Select(x =>
new SharedFuturesTicker(x.Symbol, x.LastTradePrice ?? 0, x.HighPrice, x.LowPrice, x.Volume24H, x.PriceChangePercentage * 100)
new SharedFuturesTicker(x.Symbol, x.LastTradePrice, x.HighPrice, x.LowPrice, x.Volume24H, x.PriceChangePercentage * 100)
{
IndexPrice = x.IndexPrice,
MarkPrice = x.MarkPrice,
Expand Down Expand Up @@ -598,7 +598,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.Take(request.Limit ?? 100).Select(x => new SharedTrade(x.Quantity, x.Price, x.Timestamp)).ToArray());
return result.AsExchangeResult<IEnumerable<SharedTrade>>(Exchange, request.Symbol.TradingMode, result.Data.Take(request.Limit ?? 100).Select(x => new SharedTrade(x.Quantity, x.Price, x.Timestamp)
{
Side = x.Side == OrderSide.Buy ? SharedOrderSide.Buy : SharedOrderSide.Sell
}).ToArray());
}

#endregion
Expand Down
11 changes: 2 additions & 9 deletions Kucoin.Net/Clients/FuturesApi/KucoinSocketClientFuturesApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,10 @@ public override string GetListenerIdentifier(IMessageAccessor message)
protected override AuthenticationProvider CreateAuthenticationProvider(ApiCredentials credentials)
=> new KucoinAuthenticationProvider((KucoinApiCredentials)credentials);


/// <inheritdoc />
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverTime = null)
{
if (baseAsset.Equals("BTC", StringComparison.OrdinalIgnoreCase))
baseAsset = "XBT";

if (!deliverTime.HasValue)
return baseAsset.ToUpperInvariant() + quoteAsset.ToUpperInvariant() + "M";

return baseAsset.ToUpperInvariant() + "M" + ExchangeHelpers.GetDeliveryMonthSymbol(deliverTime.Value) + deliverTime.Value.ToString("yy");
}
=> KucoinExchange.FormatSymbol(baseAsset, quoteAsset, tradingMode, deliverTime);

/// <inheritdoc />
protected override Query? GetAuthenticationRequest(SocketConnection connection) => null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ 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, new[] { new SharedTrade(update.Data.Quantity, update.Data.Price, update.Data.Timestamp) })), ct).ConfigureAwait(false);
var result = await SubscribeToTradeUpdatesAsync(symbol, update => handler(update.AsExchangeEvent<IEnumerable<SharedTrade>>(Exchange, new[] { new SharedTrade(update.Data.Quantity, update.Data.Price, update.Data.Timestamp){
Side = update.Data.Side == OrderSide.Buy ? SharedOrderSide.Buy : SharedOrderSide.Sell
} })), ct).ConfigureAwait(false);

return new ExchangeResult<UpdateSubscription>(Exchange, result);
}
Expand Down
3 changes: 2 additions & 1 deletion Kucoin.Net/Clients/SpotApi/KucoinRestClientSpotApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ protected override AuthenticationProvider CreateAuthenticationProvider(ApiCreden
=> new KucoinAuthenticationProvider((KucoinApiCredentials)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)
=> KucoinExchange.FormatSymbol(baseAsset, quoteAsset, tradingMode, deliverTime);

#region common interface

Expand Down
5 changes: 4 additions & 1 deletion Kucoin.Net/Clients/SpotApi/KucoinRestClientSpotApiShared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,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.Side == OrderSide.Buy ? SharedOrderSide.Buy : SharedOrderSide.Sell
}).ToArray());
}

#endregion
Expand Down
5 changes: 3 additions & 2 deletions Kucoin.Net/Clients/SpotApi/KucoinSocketClientSpotApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,10 @@ internal KucoinSocketClientSpotApi(ILogger logger, KucoinSocketClient baseClient
/// <inheritdoc />
protected override AuthenticationProvider CreateAuthenticationProvider(ApiCredentials credentials)
=> new KucoinAuthenticationProvider((KucoinApiCredentials)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)
=> KucoinExchange.FormatSymbol(baseAsset, quoteAsset, tradingMode, deliverTime);

public IKucoinSocketClientSpotApiShared SharedClient => this;

Expand Down
Loading

0 comments on commit 42e0d16

Please sign in to comment.