Skip to content

Commit

Permalink
Trackers (#58)
Browse files Browse the repository at this point in the history
Updated examples
Updated CryptoExchange.Net to v8.1.0
Moved FormatSymbol to OKXExchange class
Added support Side setting on SharedTrade model
Added OKXTrackerFactory
Added overload to Create method on OKXOrderBookFactory support SharedSymbol parameter
  • Loading branch information
JKorf authored Oct 28, 2024
1 parent 875107c commit 22efa7d
Show file tree
Hide file tree
Showing 20 changed files with 449 additions and 33 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}") = "OKX.Examples.Api", "OKX.Exa
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OKX.Examples.Console", "OKX.Examples.Console\OKX.Examples.Console.csproj", "{FD4F95C8-D9B7-4F81-9245-4CE667DFD421}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OKX.Examples.OrderBook", "OKX.Examples.OrderBook\OKX.Examples.OrderBook.csproj", "{9A2BB791-261C-454F-BE8A-E9E4DEBA1CCF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OKX.Examples.Tracker", "OKX.Examples.Tracker\OKX.Examples.Tracker.csproj", "{97340F25-D437-482B-94F9-39D66CDB3532}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OKX.Net", "..\OKX.Net\OKX.Net.csproj", "{2B509082-8525-4FF7-8595-8106A8F702D9}"
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
{9A2BB791-261C-454F-BE8A-E9E4DEBA1CCF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9A2BB791-261C-454F-BE8A-E9E4DEBA1CCF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9A2BB791-261C-454F-BE8A-E9E4DEBA1CCF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9A2BB791-261C-454F-BE8A-E9E4DEBA1CCF}.Release|Any CPU.Build.0 = Release|Any CPU
{97340F25-D437-482B-94F9-39D66CDB3532}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97340F25-D437-482B-94F9-39D66CDB3532}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97340F25-D437-482B-94F9-39D66CDB3532}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97340F25-D437-482B-94F9-39D66CDB3532}.Release|Any CPU.Build.0 = Release|Any CPU
{2B509082-8525-4FF7-8595-8106A8F702D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2B509082-8525-4FF7-8595-8106A8F702D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2B509082-8525-4FF7-8595-8106A8F702D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2B509082-8525-4FF7-8595-8106A8F702D9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
9 changes: 6 additions & 3 deletions Examples/OKX.Examples.Api/OKX.Examples.Api.csproj
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<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.OKX.Net" Version="1.7.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

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

</Project>
4 changes: 2 additions & 2 deletions Examples/OKX.Examples.Console/OKX.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.OKX.Net" Version="1.7.1" />
<ProjectReference Include="..\..\OKX.Net\OKX.Net.csproj" />
</ItemGroup>

</Project>
18 changes: 18 additions & 0 deletions Examples/OKX.Examples.OrderBook/OKX.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="..\..\..\..\..\..\Projects\OKX.Net\OKX.Net\OKX.Net.csproj" />
</ItemGroup>

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

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

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

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

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

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

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

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

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

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

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

/// <inheritdoc />
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverTime = null)
{
if (tradingMode == TradingMode.Spot)
return baseAsset.ToUpperInvariant() + "-" + quoteAsset.ToUpperInvariant();

if (deliverTime == null)
return baseAsset.ToUpperInvariant() + "-" + quoteAsset.ToUpperInvariant() + "-SWAP";

return baseAsset.ToUpperInvariant() + "-" + quoteAsset.ToUpperInvariant() + "-" + deliverTime.Value.ToString("yyMMdd");
}
=> OKXExchange.FormatSymbol(baseAsset, quoteAsset, tradingMode, deliverTime);

internal Task<WebCallResult> SendAsync(RequestDefinition definition, ParameterCollection? parameters, CancellationToken cancellationToken, int? weight = null)
=> base.SendAsync(BaseAddress, definition, parameters, cancellationToken, null, weight);
Expand Down
13 changes: 8 additions & 5 deletions OKX.Net/Clients/UnifiedApi/OKXRestClientUnifiedApiShared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,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.Time)).ToArray());
return result.AsExchangeResult<IEnumerable<SharedTrade>>(Exchange, request.Symbol.TradingMode, result.Data.Select(x => new SharedTrade(x.Quantity, x.Price, x.Time)
{
Side = x.Side == OrderSide.Buy ? SharedOrderSide.Buy : SharedOrderSide.Sell
}).ToArray());
}

#endregion
Expand Down Expand Up @@ -1368,9 +1371,9 @@ async Task<ExchangeWebResult<SharedFuturesTicker>> IFuturesTickerRestClient.GetF
request.Symbol.TradingMode,
new SharedFuturesTicker(
resultTicker.Result.Data.Symbol,
resultTicker.Result.Data.LastPrice ?? 0,
resultTicker.Result.Data.HighPrice ?? 0,
resultTicker.Result.Data.LowPrice ?? 0,
resultTicker.Result.Data.LastPrice,
resultTicker.Result.Data.HighPrice,
resultTicker.Result.Data.LowPrice,
resultTicker.Result.Data.Volume,
resultTicker.Result.Data.OpenPrice == null ? null : Math.Round((resultTicker.Result.Data.LastPrice ?? 0) / resultTicker.Result.Data.OpenPrice.Value * 100 - 100, 2))
{
Expand Down Expand Up @@ -1402,7 +1405,7 @@ async Task<ExchangeWebResult<IEnumerable<SharedFuturesTicker>>> IFuturesTickerRe
resultTickers.Result.Data.Select(x =>
{
var markPrice = resultMarkPrice.Result.Data.Single(p => p.Symbol == x.Symbol);
return new SharedFuturesTicker(x.Symbol, x.LastPrice ?? 0, x.HighPrice ?? 0, x.LowPrice ?? 0, x.Volume, x.OpenPrice == null ? null : Math.Round((x.LastPrice ?? 0) / x.OpenPrice.Value * 100 - 100, 2))
return new SharedFuturesTicker(x.Symbol, x.LastPrice, x.HighPrice, x.LowPrice, x.Volume, x.OpenPrice == null ? null : Math.Round((x.LastPrice ?? 0) / x.OpenPrice.Value * 100 - 100, 2))
{
MarkPrice = markPrice.MarkPrice
};
Expand Down
10 changes: 1 addition & 9 deletions OKX.Net/Clients/UnifiedApi/OKXSocketClientUnifiedApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,7 @@ internal OKXSocketClientUnifiedApi(ILogger logger, OKXSocketOptions options) :

/// <inheritdoc />
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverTime = null)
{
if (tradingMode == TradingMode.Spot)
return baseAsset.ToUpperInvariant() + "-" + quoteAsset.ToUpperInvariant();

if (deliverTime == null)
return baseAsset.ToUpperInvariant() + "-" + quoteAsset.ToUpperInvariant() + "-SWAP";

return baseAsset.ToUpperInvariant() + "-" + quoteAsset.ToUpperInvariant() + "-" + deliverTime.Value.ToString("yyMMdd");
}
=> OKXExchange.FormatSymbol(baseAsset, quoteAsset, tradingMode, deliverTime);

/// <inheritdoc />
public override string GetListenerIdentifier(IMessageAccessor message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ async Task<ExchangeResult<UpdateSubscription>> ITradeSocketClient.SubscribeToTra
return new ExchangeResult<UpdateSubscription>(Exchange, validationError);

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

return new ExchangeResult<UpdateSubscription>(Exchange, result);
}
Expand Down
2 changes: 2 additions & 0 deletions OKX.Net/ExtensionMethods/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using CryptoExchange.Net.Clients;
using OKX.Net;
using OKX.Net.Clients;
using OKX.Net.Interfaces;
using OKX.Net.Interfaces.Clients;
Expand Down Expand Up @@ -58,6 +59,7 @@ public static IServiceCollection AddOKX(
services.AddTransient<ICryptoRestClient, CryptoRestClient>();
services.AddTransient<ICryptoSocketClient, CryptoSocketClient>();
services.AddTransient<IOKXOrderBookFactory, OKXOrderBookFactory>();
services.AddTransient<IOKXTrackerFactory, OKXTrackerFactory>();
services.AddTransient(x => x.GetRequiredService<IOKXRestClient>().UnifiedApi.CommonSpotClient);

services.RegisterSharedRestInterfaces(x => x.GetRequiredService<IOKXRestClient>().UnifiedApi.SharedClient);
Expand Down
11 changes: 10 additions & 1 deletion OKX.Net/Interfaces/IOKXOrderBookFactory.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using OKX.Net.Objects.Options;
using CryptoExchange.Net.SharedApis;
using OKX.Net.Objects.Options;

namespace OKX.Net.Interfaces;

Expand All @@ -12,6 +13,14 @@ public interface IOKXOrderBookFactory
/// </summary>
IOrderBookFactory<OKXOrderBookOptions> Unified { 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<OKXOrderBookOptions>? options = null);

/// <summary>
/// Create a new order book
/// </summary>
Expand Down
Loading

0 comments on commit 22efa7d

Please sign in to comment.