1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-08-12 00:43:03 +00:00

Compare commits

...

13 Commits

Author SHA1 Message Date
Jkorf 204bda8622 Updated to version 10.7.1 2026-02-25 11:00:43 +01:00
Jkorf 78e3523a4f Updated SocketConnection internal locking to fix potential deadlock 2026-02-25 09:26:12 +01:00
Jkorf 89a73747b0 Fix for test socket not working correctly with read/write socket connection lock 2026-02-24 13:15:08 +01:00
Jkorf 02b70398b3 Updated lock call SocketConnection to outside the try 2026-02-24 13:14:48 +01:00
Jkorf 73fcb47b17 Updated to version 10.7.0 2026-02-24 11:51:37 +01:00
Jkorf d41ca3459e Updated internal lock for subscription to ReaderWriterLockSlim on SocketConnection 2026-02-24 11:32:35 +01:00
Jkorf bea2b2bd7b Added Http options to Rest client options 2026-02-24 09:58:48 +01:00
Jan Korf b29cdc41f3 Shared interfaces pagination update (#274)
Updated INextPageToken parameter on Shared interfaces to PageRequest type, functionality unchanged
Added SupportsAscending and SupportsDescending properties to PaginatedEndpointOptions to expose supported data directions
Added MaxAge property to PaginatedEndpointOptions to expose the max age of data that can be requested
Added Direction property to Shared interfaces paginated requests to configure pagination data direction 
Removed PaginationSupport property from PaginatedEndpointOptions, replaced by above new properties
Updated Shared GetTradeHistoryRequest EndTime property to be optional
Updated I(Futures/Spot)OrderRestClient.GetClosed(Futures/Spot)OrdersOptions from PaginatedEndpointOptions<GetClosedOrdersRequest> to GetClosedOrdersOptions 
Updated I(Futures/Spot)OrderRestClient.Get(Futures/Spot)UserTradesOptions from PaginatedEndpointOptions<GetUserTradesRequest> to GetUserTradesOptions
Updated rate limiting PathStartFilter to ignore added or missing slash before the path
Fixed KlineTracker throwing exception if there is no data in the initial snapshot
2026-02-23 14:53:38 +01:00
JKorf 0ce2e778f4 Added check for invalid json in JsonSocketMessageHandler and virtual GetTypeIdentifierNonJson for handling non-json messages 2026-02-22 16:29:05 +01:00
JKorf 36c2411d46 Added parsing of REST response data up to 128 characters for error responses 2026-02-22 16:05:49 +01:00
Jkorf 6d3e72745a Removed check for OnlyTrackProvidedSymbols and empty initial tracking list 2026-02-17 14:54:57 +01:00
Jkorf 51c74baa26 Updated to version 10.6.2 2026-02-17 14:39:06 +01:00
Jkorf 419e01d009 Fix for websocket queries which don't expects response getting stuck in subscribing state 2026-02-17 14:35:02 +01:00
53 changed files with 1220 additions and 458 deletions
@@ -81,6 +81,25 @@ namespace CryptoExchange.Net.UnitTests
Assert.That(result.Error is ServerError);
}
[TestCase]
public async Task ReceivingErrorAndNotParsingErrorAndInvalidJson_Should_ContainData()
{
// arrange
var client = new TestRestClient();
var response = "<html>...</html>";
client.SetErrorWithResponse(response, System.Net.HttpStatusCode.BadRequest);
// act
var result = await client.Api1.Request<TestObject>();
// assert
ClassicAssert.IsFalse(result.Success);
Assert.That(result.Error != null);
Assert.That(result.Error is DeserializeError);
Assert.That(result.Error.Message.Contains(response));
}
[TestCase]
public async Task ReceivingErrorAndParsingError_Should_ResultInParsedError()
{
@@ -19,11 +19,14 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
private ErrorMapping _errorMapping = new ErrorMapping([]);
public override JsonSerializerOptions Options => new JsonSerializerOptions();
public override ValueTask<Error> ParseErrorResponse(int httpStatusCode, HttpResponseHeaders responseHeaders, Stream responseStream)
public override async ValueTask<Error> ParseErrorResponse(int httpStatusCode, HttpResponseHeaders responseHeaders, Stream responseStream)
{
var errorData = JsonSerializer.Deserialize<TestError>(responseStream);
var result = await GetJsonDocument(responseStream).ConfigureAwait(false);
if (result.Item1 != null)
return result.Item1;
return new ValueTask<Error>(new ServerError(errorData.ErrorCode, _errorMapping.GetErrorInfo(errorData.ErrorCode.ToString(), errorData.ErrorMessage)));
var errorData = result.Item2.Deserialize<TestError>();
return new ServerError(errorData.ErrorCode, _errorMapping.GetErrorInfo(errorData.ErrorCode.ToString(), errorData.ErrorMessage));
}
}
}
+21 -17
View File
@@ -437,23 +437,19 @@ namespace CryptoExchange.Net.Clients
responseStream = await response.GetResponseStreamAsync(cancellationToken).ConfigureAwait(false);
string? originalData = null;
var outputOriginalData = ApiOptions.OutputOriginalData ?? ClientOptions.OutputOriginalData;
if (outputOriginalData || MessageHandler.RequiresSeekableStream)
if (outputOriginalData || MessageHandler.RequiresSeekableStream || !response.IsSuccessStatusCode)
{
// If we want to return the original string data from the stream, but still want to process it
// we'll need to copy it as the stream isn't seekable, and thus we can only read it once
var memoryStream = new MemoryStream();
await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
using var reader = new StreamReader(memoryStream, Encoding.UTF8, false, 4096, true);
if (outputOriginalData)
// Create a seekable stream from the response stream if:
// 1. We need to output the original data
// 2. The message handler requires a seekable stream
// 3. The response indicates error and we want to output (part of) the returned data
responseStream = await CopyStreamAsync(responseStream).ConfigureAwait(false);
using var reader = new StreamReader(responseStream, Encoding.UTF8, false, 4096, true);
if (outputOriginalData)
{
memoryStream.Position = 0;
originalData = await reader.ReadToEndAsync().ConfigureAwait(false);
responseStream.Position = 0;
}
// Continue processing from the memory stream since the response stream is already read and we can't seek it
responseStream.Close();
memoryStream.Position = 0;
responseStream = memoryStream;
}
if (!response.IsSuccessStatusCode && !requestDefinition.TryParseOnNonSuccess)
@@ -479,13 +475,12 @@ namespace CryptoExchange.Net.Clients
else
{
// Handle a 'normal' error response. Can still be either a json error message or some random HTML or other string
try
{
error = await MessageHandler.ParseErrorResponse(
(int)response.StatusCode,
response.ResponseHeaders,
responseStream).ConfigureAwait(false);
(int)response.StatusCode,
response.ResponseHeaders,
responseStream).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -769,6 +764,15 @@ namespace CryptoExchange.Net.Clients
}
}
private async Task<Stream> CopyStreamAsync(Stream responseStream)
{
var memoryStream = new MemoryStream();
await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
responseStream.Close();
memoryStream.Position = 0;
return memoryStream;
}
private bool ShouldCache(RequestDefinition definition)
=> ClientOptions.CachingEnabled
&& definition.Method == HttpMethod.Get
@@ -18,6 +18,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson.MessageHandlers
public abstract class JsonRestMessageHandler : IRestMessageHandler
{
private static MediaTypeWithQualityHeaderValue _acceptJsonContent = new MediaTypeWithQualityHeaderValue(Constants.JsonContentHeader);
private const int _errorResponseSnippetLimit = 128;
/// <summary>
/// Empty rate limit error
@@ -80,7 +81,20 @@ namespace CryptoExchange.Net.Converters.SystemTextJson.MessageHandlers
}
catch (Exception ex)
{
return (new ServerError(new ErrorInfo(ErrorType.DeserializationFailed, false, "Deserialization failed, invalid JSON"), ex), null);
var errorMsg = "Deserialization failed, invalid JSON";
if (stream.CanSeek)
{
var dataSnippet = new char[_errorResponseSnippetLimit];
stream.Seek(0, SeekOrigin.Begin);
var written = new StreamReader(stream).ReadBlock(dataSnippet, 0, _errorResponseSnippetLimit);
var data = new string(dataSnippet, 0, written);
errorMsg += $": {data}";
if (data.Length == _errorResponseSnippetLimit)
errorMsg += " (truncated)";
}
var error = new DeserializeError(errorMsg, ex);
return (error, null);
}
}
@@ -165,6 +165,14 @@ namespace CryptoExchange.Net.Converters.SystemTextJson.MessageHandlers
return null;
}
/// <summary>
/// Return type identifier for non-json messages
/// </summary>
protected virtual string? GetTypeIdentifierNonJson(ReadOnlySpan<byte> data, WebSocketMessageType? webSocketMessageType)
{
return null;
}
/// <inheritdoc />
public virtual string? GetTypeIdentifier(ReadOnlySpan<byte> data, WebSocketMessageType? webSocketMessageType)
{
@@ -173,6 +181,12 @@ namespace CryptoExchange.Net.Converters.SystemTextJson.MessageHandlers
int? arrayIndex = null;
_searchResult.Clear();
if (data[0] != 0x5B && data[0] != 0x7B)
{
// Message doesn't start with `{` or `[`, not valid for processing as json
return GetTypeIdentifierNonJson(data, webSocketMessageType);
}
var reader = new Utf8JsonReader(data);
while (reader.Read())
{
+3 -3
View File
@@ -6,9 +6,9 @@
<PackageId>CryptoExchange.Net</PackageId>
<Authors>JKorf</Authors>
<Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description>
<PackageVersion>10.6.1</PackageVersion>
<AssemblyVersion>10.6.1</AssemblyVersion>
<FileVersion>10.6.1</FileVersion>
<PackageVersion>10.7.1</PackageVersion>
<AssemblyVersion>10.7.1</AssemblyVersion>
<FileVersion>10.7.1</FileVersion>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange;CryptoExchange.Net</PackageTags>
<RepositoryType>git</RepositoryType>
+34 -3
View File
@@ -4,6 +4,7 @@ using CryptoExchange.Net.SharedApis;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading;
@@ -310,11 +311,11 @@ namespace CryptoExchange.Net
/// <param name="request">The request parameters</param>
/// <param name="ct">Cancellation token</param>
/// <returns></returns>
public static async IAsyncEnumerable<ExchangeWebResult<T[]>> ExecutePages<T, U>(Func<U, INextPageToken?, CancellationToken, Task<ExchangeWebResult<T[]>>> paginatedFunc, U request, [EnumeratorCancellation]CancellationToken ct = default)
public static async IAsyncEnumerable<ExchangeWebResult<T[]>> ExecutePages<T, U>(Func<U, PageRequest?, CancellationToken, Task<ExchangeWebResult<T[]>>> paginatedFunc, U request, [EnumeratorCancellation]CancellationToken ct = default)
{
var result = new List<T>();
ExchangeWebResult<T[]> batch;
INextPageToken? nextPageToken = null;
PageRequest? nextPageToken = null;
while (true)
{
batch = await paginatedFunc(request, nextPageToken, ct).ConfigureAwait(false);
@@ -323,12 +324,42 @@ namespace CryptoExchange.Net
break;
result.AddRange(batch.Data);
nextPageToken = batch.NextPageToken;
nextPageToken = batch.NextPageRequest;
if (nextPageToken == null)
break;
}
}
/// <summary>
/// Apply filters to the data set
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="data">Data set</param>
/// <param name="timeSelector">Time selector for the data</param>
/// <param name="startTime">Start time filter</param>
/// <param name="endTime">End time filter</param>
/// <param name="direction">Data direction</param>
public static IEnumerable<T> ApplyFilter<T>(
IEnumerable<T> data,
Func<T, DateTime> timeSelector,
DateTime? startTime,
DateTime? endTime,
DataDirection direction)
{
if (direction == DataDirection.Ascending)
data = data.OrderBy(timeSelector);
else
data = data.OrderByDescending(timeSelector);
if (startTime != null)
data = data.Where(x => timeSelector(x) >= startTime.Value);
if (endTime != null)
data = data.Where(x => timeSelector(x) < endTime.Value);
return data;
}
/// <summary>
/// Apply the rules (price and quantity step size and decimals precision, min/max quantity) from the symbol to the quantity and price
/// </summary>
+15 -9
View File
@@ -1,4 +1,5 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects.Options;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@@ -105,31 +106,36 @@ namespace CryptoExchange.Net
/// <summary>
/// Create a new HttpMessageHandler instance
/// </summary>
public static HttpMessageHandler CreateHttpClientMessageHandler(ApiProxy? proxy, TimeSpan? keepAliveInterval)
public static HttpMessageHandler CreateHttpClientMessageHandler(RestExchangeOptions options)
{
#if NET5_0_OR_GREATER
var socketHandler = new SocketsHttpHandler();
try
{
if (keepAliveInterval != null && keepAliveInterval != TimeSpan.Zero)
if (options.HttpKeepAliveInterval != null && options.HttpKeepAliveInterval != TimeSpan.Zero)
{
socketHandler.KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always;
socketHandler.KeepAlivePingDelay = keepAliveInterval.Value;
socketHandler.KeepAlivePingDelay = options.HttpKeepAliveInterval.Value;
socketHandler.KeepAlivePingTimeout = TimeSpan.FromSeconds(10);
}
socketHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
socketHandler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
socketHandler.EnableMultipleHttp2Connections = options.HttpEnableMultipleHttp2Connections;
socketHandler.PooledConnectionLifetime = options.HttpPooledConnectionLifetime;
socketHandler.PooledConnectionIdleTimeout = options.HttpPooledConnectionIdleTimeout;
socketHandler.MaxConnectionsPerServer = options.HttpMaxConnectionsPerServer;
}
catch (PlatformNotSupportedException) { }
catch (NotImplementedException) { } // Mono runtime throws NotImplementedException
if (proxy != null)
if (options.Proxy != null)
{
socketHandler.Proxy = new WebProxy
{
Address = new Uri($"{proxy.Host}:{proxy.Port}"),
Credentials = proxy.Password == null ? null : new NetworkCredential(proxy.Login, proxy.Password)
Address = new Uri($"{options.Proxy.Host}:{options.Proxy.Port}"),
Credentials = options.Proxy.Password == null ? null : new NetworkCredential(options.Proxy.Login, options.Proxy.Password)
};
}
return socketHandler;
@@ -143,12 +149,12 @@ namespace CryptoExchange.Net
catch (PlatformNotSupportedException) { }
catch (NotImplementedException) { } // Mono runtime throws NotImplementedException
if (proxy != null)
if (options.Proxy != null)
{
httpHandler.Proxy = new WebProxy
{
Address = new Uri($"{proxy.Host}:{proxy.Port}"),
Credentials = proxy.Password == null ? null : new NetworkCredential(proxy.Login, proxy.Password)
Address = new Uri($"{options.Proxy.Host}:{options.Proxy.Port}"),
Credentials = options.Proxy.Password == null ? null : new NetworkCredential(options.Proxy.Login, options.Proxy.Password)
};
}
return httpHandler;
+6 -6
View File
@@ -531,11 +531,11 @@ namespace CryptoExchange.Net.Objects
/// <param name="exchange">The exchange</param>
/// <param name="tradeMode">Trade mode the result applies to</param>
/// <param name="data">Data</param>
/// <param name="nextPageToken">Next page token</param>
/// <param name="nextPageRequest">Next page request</param>
/// <returns></returns>
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode tradeMode, [AllowNull] K data, INextPageToken? nextPageToken = null)
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode tradeMode, [AllowNull] K data, PageRequest? nextPageRequest = null)
{
return new ExchangeWebResult<K>(exchange, tradeMode, As<K>(data), nextPageToken);
return new ExchangeWebResult<K>(exchange, tradeMode, As<K>(data), nextPageRequest);
}
/// <summary>
@@ -545,11 +545,11 @@ namespace CryptoExchange.Net.Objects
/// <param name="exchange">The exchange</param>
/// <param name="tradeModes">Trade modes the result applies to</param>
/// <param name="data">Data</param>
/// <param name="nextPageToken">Next page token</param>
/// <param name="nextPageRequest">Next page token</param>
/// <returns></returns>
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode[]? tradeModes, [AllowNull] K data, INextPageToken? nextPageToken = null)
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode[]? tradeModes, [AllowNull] K data, PageRequest? nextPageRequest = null)
{
return new ExchangeWebResult<K>(exchange, tradeModes, As<K>(data), nextPageToken);
return new ExchangeWebResult<K>(exchange, tradeModes, As<K>(data), nextPageRequest);
}
/// <summary>
+9 -1
View File
@@ -211,7 +211,15 @@ namespace CryptoExchange.Net.Objects
/// <summary>
/// ctor
/// </summary>
public DeserializeError(string? message = null, Exception? exception = null) : base(null, _errorInfo with { Message = (message?.Length > 0 ? _errorInfo.Message + ": " + message : _errorInfo.Message) }, exception) { }
public DeserializeError(string? message = null, Exception? exception = null)
: base(null,
_errorInfo with
{
Message = message?.Length > 0
? message
: _errorInfo.Message
},
exception) { }
}
/// <summary>
@@ -32,10 +32,29 @@ namespace CryptoExchange.Net.Objects.Options
#else
= new Version(1, 1);
#endif
/// <summary>
/// Http client keep alive interval for keeping connections open
/// Http client keep alive interval for keeping connections open. Only applied when using dotnet8.0 or higher and dependency injection
/// </summary>
public TimeSpan? HttpKeepAliveInterval { get; set; } = TimeSpan.FromSeconds(15);
#if NET5_0_OR_GREATER
/// <summary>
/// Enable multiple simultaneous HTTP 2 connections. Only applied when using dependency injection
/// </summary>
public bool HttpEnableMultipleHttp2Connections { get; set; } = false;
/// <summary>
/// Lifetime of pooled HTTP connections; the time before a connection is recreated. Only applied when using dependency injection
/// </summary>
public TimeSpan HttpPooledConnectionLifetime { get; set; } = TimeSpan.FromMinutes(15);
/// <summary>
/// Idle timeout of pooled HTTP connections; the time before an open connection is closed when there are no requests. Only applied when using dependency injection
/// </summary>
public TimeSpan HttpPooledConnectionIdleTimeout { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>
/// Max number of connections per server. Only applied when using dependency injection
/// </summary>
public int HttpMaxConnectionsPerServer { get; set; } = int.MaxValue;
#endif
/// <summary>
/// Set the values of this options on the target options
@@ -54,6 +73,12 @@ namespace CryptoExchange.Net.Objects.Options
item.CachingMaxAge = CachingMaxAge;
item.HttpVersion = HttpVersion;
item.HttpKeepAliveInterval = HttpKeepAliveInterval;
#if NET5_0_OR_GREATER
item.HttpMaxConnectionsPerServer = HttpMaxConnectionsPerServer;
item.HttpPooledConnectionLifetime = HttpPooledConnectionLifetime;
item.HttpPooledConnectionIdleTimeout = HttpPooledConnectionIdleTimeout;
item.HttpEnableMultipleHttp2Connections = HttpEnableMultipleHttp2Connections;
#endif
return item;
}
}
@@ -170,6 +170,6 @@ namespace CryptoExchange.Net.Objects.Sockets
}
/// <inheritdoc />
public override string ToString() => base.ToString().TrimEnd('-') + Data?.ToString();
public override string ToString() => base.ToString().TrimEnd(' ', '-') + " - " + Data?.ToString();
}
}
@@ -17,11 +17,11 @@ namespace CryptoExchange.Net.RateLimiting.Filters
/// <param name="path"></param>
public PathStartFilter(string path)
{
_path = path;
_path = path.TrimStart('/');
}
/// <inheritdoc />
public bool Passes(RateLimitItemType type, RequestDefinition definition, string host, string? apiKey)
=> definition.Path.StartsWith(_path, StringComparison.OrdinalIgnoreCase);
=> definition.Path.TrimStart('/').StartsWith(_path, StringComparison.OrdinalIgnoreCase);
}
}
+12 -5
View File
@@ -12,14 +12,16 @@ namespace CryptoExchange.Net.Requests
public class RequestFactory : IRequestFactory
{
private HttpClient? _httpClient;
private RestExchangeOptions? _options;
/// <inheritdoc />
public void Configure(RestExchangeOptions options, HttpClient? client = null)
{
if (client == null)
client = CreateClient(options.Proxy, options.RequestTimeout, options.HttpKeepAliveInterval);
client = CreateClient(options);
_httpClient = client;
_options = options;
}
/// <inheritdoc />
@@ -39,15 +41,20 @@ namespace CryptoExchange.Net.Requests
/// <inheritdoc />
public void UpdateSettings(ApiProxy? proxy, TimeSpan requestTimeout, TimeSpan? httpKeepAliveInterval)
{
_httpClient = CreateClient(proxy, requestTimeout, httpKeepAliveInterval);
var newOptions = new RestExchangeOptions();
_options!.Set(newOptions);
newOptions.Proxy = proxy;
newOptions.RequestTimeout = requestTimeout;
newOptions.HttpKeepAliveInterval = httpKeepAliveInterval;
_httpClient = CreateClient(newOptions);
}
private static HttpClient CreateClient(ApiProxy? proxy, TimeSpan requestTimeout, TimeSpan? httpKeepAliveInterval)
private static HttpClient CreateClient(RestExchangeOptions options)
{
var handler = LibraryHelpers.CreateHttpClientMessageHandler(proxy, httpKeepAliveInterval);
var handler = LibraryHelpers.CreateHttpClientMessageHandler(options);
var client = new HttpClient(handler)
{
Timeout = requestTimeout
Timeout = options.RequestTimeout
};
return client;
}
@@ -1,111 +0,0 @@
using System;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// A token which a request can use to retrieve the next page if there are more pages in the result set
/// </summary>
public interface INextPageToken
{
}
/// <summary>
/// A datetime offset token
/// </summary>
public record DateTimeToken: INextPageToken
{
/// <summary>
/// Last result time
/// </summary>
public DateTime LastTime { get; set; }
/// <summary>
/// ctor
/// </summary>
public DateTimeToken(DateTime timestamp)
{
LastTime = timestamp;
}
}
/// <summary>
/// A current page index token
/// </summary>
public record PageToken: INextPageToken
{
/// <summary>
/// The next page index
/// </summary>
public int Page { get; set; }
/// <summary>
/// Page size
/// </summary>
public int PageSize { get; set; }
/// <summary>
/// ctor
/// </summary>
public PageToken(int page, int pageSize)
{
Page = page;
PageSize = pageSize;
}
}
/// <summary>
/// A id offset token
/// </summary>
public record FromIdToken : INextPageToken
{
/// <summary>
/// The last id from previous result
/// </summary>
public string FromToken { get; set; }
/// <summary>
/// ctor
/// </summary>
public FromIdToken(string fromToken)
{
FromToken = fromToken;
}
}
/// <summary>
/// A cursor token
/// </summary>
public record CursorToken : INextPageToken
{
/// <summary>
/// The next page cursor
/// </summary>
public string Cursor { get; set; }
/// <summary>
/// ctor
/// </summary>
public CursorToken(string cursor)
{
Cursor = cursor;
}
}
/// <summary>
/// A result offset token
/// </summary>
public record OffsetToken : INextPageToken
{
/// <summary>
/// Offset in the result set
/// </summary>
public int Offset { get; set; }
/// <summary>
/// ctor
/// </summary>
public OffsetToken(int offset)
{
Offset = offset;
}
}
}
@@ -16,8 +16,8 @@ namespace CryptoExchange.Net.SharedApis
/// Get funding rate records
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
Task<ExchangeWebResult<SharedFundingRate[]>> GetFundingRateHistoryAsync(GetFundingRateHistoryRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedFundingRate[]>> GetFundingRateHistoryAsync(GetFundingRateHistoryRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
}
}
@@ -73,14 +73,14 @@ namespace CryptoExchange.Net.SharedApis
/// <summary>
/// Spot get closed orders request options
/// </summary>
PaginatedEndpointOptions<GetClosedOrdersRequest> GetClosedFuturesOrdersOptions { get; }
GetClosedOrdersOptions GetClosedFuturesOrdersOptions { get; }
/// <summary>
/// Get info on closed futures orders
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
Task<ExchangeWebResult<SharedFuturesOrder[]>> GetClosedFuturesOrdersAsync(GetClosedOrdersRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedFuturesOrder[]>> GetClosedFuturesOrdersAsync(GetClosedOrdersRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
/// <summary>
/// Futures get order trades request options
@@ -96,14 +96,14 @@ namespace CryptoExchange.Net.SharedApis
/// <summary>
/// Futures user trades request options
/// </summary>
PaginatedEndpointOptions<GetUserTradesRequest> GetFuturesUserTradesOptions { get; }
GetUserTradesOptions GetFuturesUserTradesOptions { get; }
/// <summary>
/// Get futures user trade records
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
Task<ExchangeWebResult<SharedUserTrade[]>> GetFuturesUserTradesAsync(GetUserTradesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedUserTrade[]>> GetFuturesUserTradesAsync(GetUserTradesRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
/// <summary>
/// Futures cancel order request options
@@ -16,8 +16,8 @@ namespace CryptoExchange.Net.SharedApis
/// Get index price kline/candlestick data
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
Task<ExchangeWebResult<SharedFuturesKline[]>> GetIndexPriceKlinesAsync(GetKlinesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedFuturesKline[]>> GetIndexPriceKlinesAsync(GetKlinesRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
}
}
@@ -16,8 +16,8 @@ namespace CryptoExchange.Net.SharedApis
/// Get mark price kline/candlestick data
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
Task<ExchangeWebResult<SharedFuturesKline[]>> GetMarkPriceKlinesAsync(GetKlinesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedFuturesKline[]>> GetMarkPriceKlinesAsync(GetKlinesRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
}
}
@@ -16,8 +16,8 @@ namespace CryptoExchange.Net.SharedApis
/// Get position history
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
Task<ExchangeWebResult<SharedPositionHistory[]>> GetPositionHistoryAsync(GetPositionHistoryRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedPositionHistory[]>> GetPositionHistoryAsync(GetPositionHistoryRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
}
}
@@ -30,9 +30,9 @@ namespace CryptoExchange.Net.SharedApis
/// Get deposit records
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
/// <returns></returns>
Task<ExchangeWebResult<SharedDeposit[]>> GetDepositsAsync(GetDepositsRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedDeposit[]>> GetDepositsAsync(GetDepositsRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
}
}
@@ -17,9 +17,9 @@ namespace CryptoExchange.Net.SharedApis
/// Get kline/candlestick data
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
/// <returns></returns>
Task<ExchangeWebResult<SharedKline[]>> GetKlinesAsync(GetKlinesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedKline[]>> GetKlinesAsync(GetKlinesRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
}
}
@@ -17,9 +17,9 @@ namespace CryptoExchange.Net.SharedApis
/// Get public trade history
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
/// <returns></returns>
Task<ExchangeWebResult<SharedTrade[]>> GetTradeHistoryAsync(GetTradeHistoryRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedTrade[]>> GetTradeHistoryAsync(GetTradeHistoryRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
}
}
@@ -17,9 +17,9 @@ namespace CryptoExchange.Net.SharedApis
/// Get withdrawal records
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
/// <returns></returns>
Task<ExchangeWebResult<SharedWithdrawal[]>> GetWithdrawalsAsync(GetWithdrawalsRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedWithdrawal[]>> GetWithdrawalsAsync(GetWithdrawalsRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
}
}
@@ -72,14 +72,14 @@ namespace CryptoExchange.Net.SharedApis
/// <summary>
/// Spot get closed orders request options
/// </summary>
PaginatedEndpointOptions<GetClosedOrdersRequest> GetClosedSpotOrdersOptions { get; }
GetClosedOrdersOptions GetClosedSpotOrdersOptions { get; }
/// <summary>
/// Get info on closed spot orders
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
Task<ExchangeWebResult<SharedSpotOrder[]>> GetClosedSpotOrdersAsync(GetClosedOrdersRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedSpotOrder[]>> GetClosedSpotOrdersAsync(GetClosedOrdersRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
/// <summary>
/// Spot get order trades request options
@@ -95,14 +95,14 @@ namespace CryptoExchange.Net.SharedApis
/// <summary>
/// Spot user trades request options
/// </summary>
PaginatedEndpointOptions<GetUserTradesRequest> GetSpotUserTradesOptions { get; }
GetUserTradesOptions GetSpotUserTradesOptions { get; }
/// <summary>
/// Get spot user trade records
/// </summary>
/// <param name="request">Request info</param>
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
/// <param name="nextPageToken">The pagination request from the previous request result `NextPageRequest` property to continue pagination</param>
/// <param name="ct">Cancellation token</param>
Task<ExchangeWebResult<SharedUserTrade[]>> GetSpotUserTradesAsync(GetUserTradesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
Task<ExchangeWebResult<SharedUserTrade[]>> GetSpotUserTradesAsync(GetUserTradesRequest request, PageRequest? nextPageToken = null, CancellationToken ct = default);
/// <summary>
/// Spot cancel order request options
@@ -24,9 +24,9 @@ namespace CryptoExchange.Net.SharedApis
public TradingMode[]? DataTradeMode { get; }
/// <summary>
/// Token to retrieve the next page with
/// Next page request, can be passed to the next request on the same endpoint to get the next page
/// </summary>
public INextPageToken? NextPageToken { get; }
public PageRequest? NextPageRequest { get; }
/// <summary>
/// ctor
@@ -46,7 +46,7 @@ namespace CryptoExchange.Net.SharedApis
string exchange,
TradingMode dataTradeMode,
WebCallResult<T> result,
INextPageToken? nextPageToken = null) :
PageRequest? nextPageToken = null) :
base(result.ResponseStatusCode,
result.HttpVersion,
result.ResponseHeaders,
@@ -64,7 +64,7 @@ namespace CryptoExchange.Net.SharedApis
{
DataTradeMode = new[] { dataTradeMode };
Exchange = exchange;
NextPageToken = nextPageToken;
NextPageRequest = nextPageToken;
}
/// <summary>
@@ -74,7 +74,7 @@ namespace CryptoExchange.Net.SharedApis
string exchange,
TradingMode[]? dataTradeModes,
WebCallResult<T> result,
INextPageToken? nextPageToken = null) :
PageRequest? nextPageRequest = null) :
base(result.ResponseStatusCode,
result.HttpVersion,
result.ResponseHeaders,
@@ -92,7 +92,7 @@ namespace CryptoExchange.Net.SharedApis
{
DataTradeMode = dataTradeModes;
Exchange = exchange;
NextPageToken = nextPageToken;
NextPageRequest = nextPageRequest;
}
/// <summary>
@@ -115,7 +115,7 @@ namespace CryptoExchange.Net.SharedApis
ResultDataSource dataSource,
[AllowNull] T data,
Error? error,
INextPageToken? nextPageToken = null) : base(
PageRequest? nextPageToken = null) : base(
code,
httpVersion,
responseHeaders,
@@ -133,7 +133,7 @@ namespace CryptoExchange.Net.SharedApis
{
DataTradeMode = dataTradeModes;
Exchange = exchange;
NextPageToken = nextPageToken;
NextPageRequest = nextPageToken;
}
/// <summary>
@@ -144,7 +144,7 @@ namespace CryptoExchange.Net.SharedApis
/// <returns></returns>
public new ExchangeWebResult<K> As<K>([AllowNull] K data)
{
return new ExchangeWebResult<K>(Exchange, DataTradeMode, ResponseStatusCode, HttpVersion, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, data, Error, NextPageToken);
return new ExchangeWebResult<K>(Exchange, DataTradeMode, ResponseStatusCode, HttpVersion, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, data, Error, NextPageRequest);
}
/// <inheritdoc />
@@ -1,4 +1,5 @@
using CryptoExchange.Net.Objects;
using System;
using System.Text;
namespace CryptoExchange.Net.SharedApis
@@ -8,24 +9,36 @@ namespace CryptoExchange.Net.SharedApis
/// </summary>
public class GetClosedOrdersOptions : PaginatedEndpointOptions<GetClosedOrdersRequest>
{
/// <summary>
/// Whether the start/end time filter is supported
/// </summary>
public bool TimeFilterSupported { get; set; }
/// <summary>
/// ctor
/// </summary>
public GetClosedOrdersOptions(SharedPaginationSupport paginationType, bool timeFilterSupported, int maxLimit) : base(paginationType, timeFilterSupported, maxLimit, true)
public GetClosedOrdersOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, true)
{
TimeFilterSupported = timeFilterSupported;
}
/// <inheritdoc />
public override Error? ValidateRequest(string exchange, GetClosedOrdersRequest request, TradingMode? tradingMode, TradingMode[] supportedApiTypes)
{
if (!TimeFilterSupported && request.StartTime != null)
return ArgumentError.Invalid(nameof(GetClosedOrdersRequest.StartTime), $"Time filter is not supported");
if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Ascending direction is not supported");
if (!SupportsDescending && request.Direction == DataDirection.Descending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Descending direction is not supported");
if (MaxAge.HasValue && request.StartTime < DateTime.UtcNow.Add(-MaxAge.Value))
return ArgumentError.Invalid(nameof(GetKlinesRequest.StartTime), $"Only the most recent {MaxAge} period data is available");
if (!TimePeriodFilterSupport)
{
// When going descending we can still allow startTime filter to limit the results
var now = DateTime.UtcNow;
if ((request.Direction != DataDirection.Descending && request.StartTime != null)
|| (request.EndTime != null && now - request.EndTime > TimeSpan.FromSeconds(5)))
{
return ArgumentError.Invalid(nameof(GetDepositsRequest.StartTime), $"Time filter is not supported");
}
}
return base.ValidateRequest(exchange, request, tradingMode, supportedApiTypes);
}
@@ -34,7 +47,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
sb.AppendLine($"Time filter supported: {TimeFilterSupported}");
sb.AppendLine($"Time filter supported: {TimePeriodFilterSupport}");
return sb.ToString();
}
}
@@ -1,4 +1,5 @@
using CryptoExchange.Net.Objects;
using System;
using System.Text;
namespace CryptoExchange.Net.SharedApis
@@ -8,24 +9,36 @@ namespace CryptoExchange.Net.SharedApis
/// </summary>
public class GetDepositsOptions : PaginatedEndpointOptions<GetDepositsRequest>
{
/// <summary>
/// Whether the start/end time filter is supported
/// </summary>
public bool TimeFilterSupported { get; set; }
/// <summary>
/// ctor
/// </summary>
public GetDepositsOptions(SharedPaginationSupport paginationType, bool timeFilterSupported, int maxLimit) : base(paginationType, timeFilterSupported, maxLimit, true)
public GetDepositsOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, true)
{
TimeFilterSupported = timeFilterSupported;
}
/// <inheritdoc />
public override Error? ValidateRequest(string exchange, GetDepositsRequest request, TradingMode? tradingMode, TradingMode[] supportedApiTypes)
{
if (!TimeFilterSupported && request.StartTime != null)
return ArgumentError.Invalid(nameof(GetDepositsRequest.StartTime), $"Time filter is not supported");
if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Ascending direction is not supported");
if (!SupportsDescending && request.Direction == DataDirection.Descending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Descending direction is not supported");
if (MaxAge.HasValue && request.StartTime < DateTime.UtcNow.Add(-MaxAge.Value))
return ArgumentError.Invalid(nameof(GetKlinesRequest.StartTime), $"Only the most recent {MaxAge} period data is available");
if (!TimePeriodFilterSupport)
{
// When going descending we can still allow startTime filter to limit the results
var now = DateTime.UtcNow;
if ((request.Direction != DataDirection.Descending && request.StartTime != null)
|| (request.EndTime != null && now - request.EndTime > TimeSpan.FromSeconds(5)))
{
return ArgumentError.Invalid(nameof(GetDepositsRequest.StartTime), $"Time filter is not supported");
}
}
return base.ValidateRequest(exchange, request, tradingMode, supportedApiTypes);
}
@@ -34,7 +47,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
sb.AppendLine($"Time filter supported: {TimeFilterSupported}");
sb.AppendLine($"Time filter supported: {TimePeriodFilterSupport}");
return sb.ToString();
}
}
@@ -1,4 +1,8 @@
namespace CryptoExchange.Net.SharedApis
using CryptoExchange.Net.Objects;
using System;
using System.Text;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Options for requesting funding rate history
@@ -8,8 +12,43 @@
/// <summary>
/// ctor
/// </summary>
public GetFundingRateHistoryOptions(SharedPaginationSupport paginationType, bool timeFilterSupported, int maxLimit, bool needsAuthentication) : base(paginationType, timeFilterSupported, maxLimit, needsAuthentication)
public GetFundingRateHistoryOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit, bool needsAuthentication)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, needsAuthentication)
{
}
/// <inheritdoc />
public override Error? ValidateRequest(string exchange, GetFundingRateHistoryRequest request, TradingMode? tradingMode, TradingMode[] supportedApiTypes)
{
if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Ascending direction is not supported");
if (!SupportsDescending && request.Direction == DataDirection.Descending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Descending direction is not supported");
if (MaxAge.HasValue && request.StartTime < DateTime.UtcNow.Add(-MaxAge.Value))
return ArgumentError.Invalid(nameof(GetKlinesRequest.StartTime), $"Only the most recent {MaxAge} period data is available");
if (!TimePeriodFilterSupport)
{
// When going descending we can still allow startTime filter to limit the results
var now = DateTime.UtcNow;
if ((request.Direction != DataDirection.Descending && request.StartTime != null)
|| (request.EndTime != null && now - request.EndTime > TimeSpan.FromSeconds(5)))
{
return ArgumentError.Invalid(nameof(GetDepositsRequest.StartTime), $"Time filter is not supported");
}
}
return base.ValidateRequest(exchange, request, tradingMode, supportedApiTypes);
}
/// <inheritdoc />
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
sb.AppendLine($"Time filter supported: {TimePeriodFilterSupport}");
return sb.ToString();
}
}
}
@@ -18,15 +18,12 @@ namespace CryptoExchange.Net.SharedApis
/// Max number of data points which can be requested
/// </summary>
public int? MaxTotalDataPoints { get; set; }
/// <summary>
/// The max age of the data that can be requested
/// </summary>
public TimeSpan? MaxAge { get; set; }
/// <summary>
/// ctor
/// </summary>
public GetKlinesOptions(SharedPaginationSupport paginationType, bool timeFilterSupported, int maxLimit, bool needsAuthentication) : base(paginationType, timeFilterSupported, maxLimit, needsAuthentication)
public GetKlinesOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit, bool needsAuthentication)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, needsAuthentication)
{
SupportIntervals = new[]
{
@@ -50,7 +47,8 @@ namespace CryptoExchange.Net.SharedApis
/// <summary>
/// ctor
/// </summary>
public GetKlinesOptions(SharedPaginationSupport paginationType, bool timeFilterSupported, int maxLimit, bool needsAuthentication, params SharedKlineInterval[] intervals) : base(paginationType, timeFilterSupported, maxLimit, needsAuthentication)
public GetKlinesOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit, bool needsAuthentication, params SharedKlineInterval[] intervals)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, needsAuthentication)
{
SupportIntervals = intervals;
}
@@ -68,12 +66,29 @@ namespace CryptoExchange.Net.SharedApis
if (!IsSupported(request.Interval))
return ArgumentError.Invalid(nameof(GetKlinesRequest.Interval), "Interval not supported");
if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Ascending direction is not supported");
if (!SupportsDescending && request.Direction == DataDirection.Descending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Descending direction is not supported");
if (MaxAge.HasValue && request.StartTime < DateTime.UtcNow.Add(-MaxAge.Value))
return ArgumentError.Invalid(nameof(GetKlinesRequest.StartTime), $"Only the most recent {MaxAge} klines are available");
if (request.Limit > MaxLimit)
return ArgumentError.Invalid(nameof(GetKlinesRequest.Limit), $"Only {MaxLimit} klines can be retrieved per request");
if (!TimePeriodFilterSupport)
{
// When going descending we can still allow startTime filter to limit the results
var now = DateTime.UtcNow;
if ((request.Direction == DataDirection.Ascending && request.StartTime != null)
|| (request.EndTime != null && now - request.EndTime > TimeSpan.FromSeconds(5)))
{
return ArgumentError.Invalid(nameof(GetDepositsRequest.StartTime), $"Time filter is not supported");
}
}
if (MaxTotalDataPoints.HasValue)
{
if (request.Limit > MaxTotalDataPoints.Value)
@@ -93,6 +108,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
sb.AppendLine($"Time filter supported: {TimePeriodFilterSupport}");
sb.AppendLine($"Supported SharedKlineInterval values: {string.Join(", ", SupportIntervals)}");
if (MaxAge != null)
sb.AppendLine($"Max age of data: {MaxAge}");
@@ -1,4 +1,8 @@
namespace CryptoExchange.Net.SharedApis
using CryptoExchange.Net.Objects;
using System;
using System.Text;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Options for requesting position history
@@ -8,8 +12,43 @@
/// <summary>
/// ctor
/// </summary>
public GetPositionHistoryOptions(SharedPaginationSupport paginationType, bool timeFilterSupported, int maxLimit) : base(paginationType, timeFilterSupported, maxLimit, true)
public GetPositionHistoryOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, true)
{
}
/// <inheritdoc />
public override Error? ValidateRequest(string exchange, GetPositionHistoryRequest request, TradingMode? tradingMode, TradingMode[] supportedApiTypes)
{
if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Ascending direction is not supported");
if (!SupportsDescending && request.Direction == DataDirection.Descending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Descending direction is not supported");
if (MaxAge.HasValue && request.StartTime < DateTime.UtcNow.Add(-MaxAge.Value))
return ArgumentError.Invalid(nameof(GetKlinesRequest.StartTime), $"Only the most recent {MaxAge} period data is available");
if (!TimePeriodFilterSupport)
{
// When going descending we can still allow startTime filter to limit the results
var now = DateTime.UtcNow;
if ((request.Direction != DataDirection.Descending && request.StartTime != null)
|| (request.EndTime != null && now - request.EndTime > TimeSpan.FromSeconds(5)))
{
return ArgumentError.Invalid(nameof(GetDepositsRequest.StartTime), $"Time filter is not supported");
}
}
return base.ValidateRequest(exchange, request, tradingMode, supportedApiTypes);
}
/// <inheritdoc />
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
sb.AppendLine($"Time filter supported: {TimePeriodFilterSupport}");
return sb.ToString();
}
}
}
@@ -9,34 +9,27 @@ namespace CryptoExchange.Net.SharedApis
/// </summary>
public class GetTradeHistoryOptions : PaginatedEndpointOptions<GetTradeHistoryRequest>
{
/// <summary>
/// The max age of data that can be requested
/// </summary>
public TimeSpan? MaxAge { get; set; }
/// <summary>
/// ctor
/// </summary>
public GetTradeHistoryOptions(SharedPaginationSupport paginationType, bool timeFilterSupported, int maxLimit, bool needsAuthentication) : base(paginationType, timeFilterSupported, maxLimit, needsAuthentication)
public GetTradeHistoryOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit, bool needsAuthentication)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, needsAuthentication)
{
}
/// <inheritdoc />
public override Error? ValidateRequest(string exchange, GetTradeHistoryRequest request, TradingMode? tradingMode, TradingMode[] supportedApiTypes)
{
if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Ascending direction is not supported");
if (!SupportsDescending && request.Direction == DataDirection.Descending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Descending direction is not supported");
if (MaxAge.HasValue && request.StartTime < DateTime.UtcNow.Add(-MaxAge.Value))
return ArgumentError.Invalid(nameof(GetTradeHistoryRequest.StartTime), $"Only the most recent {MaxAge} trades are available");
return ArgumentError.Invalid(nameof(GetKlinesRequest.StartTime), $"Only the most recent {MaxAge} period data is available");
return base.ValidateRequest(exchange, request, tradingMode, supportedApiTypes);
}
/// <inheritdoc />
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
if (MaxAge != null)
sb.AppendLine($"Max age of data: {MaxAge}");
return sb.ToString();
}
}
}
@@ -0,0 +1,54 @@
using CryptoExchange.Net.Objects;
using System;
using System.Text;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Options for requesting user trades
/// </summary>
public class GetUserTradesOptions : PaginatedEndpointOptions<GetUserTradesRequest>
{
/// <summary>
/// ctor
/// </summary>
public GetUserTradesOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, true)
{
}
/// <inheritdoc />
public override Error? ValidateRequest(string exchange, GetUserTradesRequest request, TradingMode? tradingMode, TradingMode[] supportedApiTypes)
{
if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Ascending direction is not supported");
if (!SupportsDescending && request.Direction == DataDirection.Descending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Descending direction is not supported");
if (MaxAge.HasValue && request.StartTime < DateTime.UtcNow.Add(-MaxAge.Value))
return ArgumentError.Invalid(nameof(GetKlinesRequest.StartTime), $"Only the most recent {MaxAge} period data is available");
if (!TimePeriodFilterSupport)
{
// When going descending we can still allow startTime filter to limit the results
var now = DateTime.UtcNow;
if ((request.Direction != DataDirection.Descending && request.StartTime != null)
|| (request.EndTime != null && now - request.EndTime > TimeSpan.FromSeconds(5)))
{
return ArgumentError.Invalid(nameof(GetDepositsRequest.StartTime), $"Time filter is not supported");
}
}
return base.ValidateRequest(exchange, request, tradingMode, supportedApiTypes);
}
/// <inheritdoc />
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
sb.AppendLine($"Time filter supported: {TimePeriodFilterSupport}");
return sb.ToString();
}
}
}
@@ -1,4 +1,5 @@
using CryptoExchange.Net.Objects;
using System;
using System.Text;
namespace CryptoExchange.Net.SharedApis
@@ -8,24 +9,36 @@ namespace CryptoExchange.Net.SharedApis
/// </summary>
public class GetWithdrawalsOptions : PaginatedEndpointOptions<GetWithdrawalsRequest>
{
/// <summary>
/// Whether the start/end time filter is supported
/// </summary>
public bool TimeFilterSupported { get; set; }
/// <summary>
/// ctor
/// </summary>
public GetWithdrawalsOptions(SharedPaginationSupport paginationType, bool timeFilterSupported, int maxLimit) : base(paginationType, timeFilterSupported, maxLimit, true)
public GetWithdrawalsOptions(bool supportsAscending, bool supportsDescending, bool timeFilterSupported, int maxLimit)
: base(supportsAscending, supportsDescending, timeFilterSupported, maxLimit, true)
{
TimeFilterSupported = timeFilterSupported;
}
/// <inheritdoc />
public override Error? ValidateRequest(string exchange, GetWithdrawalsRequest request, TradingMode? tradingMode, TradingMode[] supportedApiTypes)
{
if (!TimeFilterSupported && request.StartTime != null)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.StartTime), $"Time filter is not supported");
if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Ascending direction is not supported");
if (!SupportsDescending && request.Direction == DataDirection.Descending)
return ArgumentError.Invalid(nameof(GetWithdrawalsRequest.Direction), $"Descending direction is not supported");
if (MaxAge.HasValue && request.StartTime < DateTime.UtcNow.Add(-MaxAge.Value))
return ArgumentError.Invalid(nameof(GetKlinesRequest.StartTime), $"Only the most recent {MaxAge} period data is available");
if (!TimePeriodFilterSupport)
{
// When going descending we can still allow startTime filter to limit the results
var now = DateTime.UtcNow;
if ((request.Direction != DataDirection.Descending && request.StartTime != null)
|| (request.EndTime != null && now - request.EndTime > TimeSpan.FromSeconds(5)))
{
return ArgumentError.Invalid(nameof(GetDepositsRequest.StartTime), $"Time filter is not supported");
}
}
return base.ValidateRequest(exchange, request, tradingMode, supportedApiTypes);
}
@@ -34,7 +47,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
sb.AppendLine($"Time filter supported: {TimeFilterSupported}");
sb.AppendLine($"Time filter supported: {TimePeriodFilterSupport}");
return sb.ToString();
}
}
@@ -1,4 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace CryptoExchange.Net.SharedApis
@@ -14,9 +15,13 @@ namespace CryptoExchange.Net.SharedApis
#endif
{
/// <summary>
/// Type of pagination supported
/// Whether ascending data retrieval and pagination is available
/// </summary>
public SharedPaginationSupport PaginationSupport { get; }
public bool SupportsAscending { get; set; }
/// <summary>
/// Whether ascending data retrieval and pagination is available
/// </summary>
public bool SupportsDescending { get; set; }
/// <summary>
/// Whether filtering based on start/end time is supported
@@ -28,12 +33,23 @@ namespace CryptoExchange.Net.SharedApis
/// </summary>
public int MaxLimit { get; set; }
/// <summary>
/// Max age of data that can be requested
/// </summary>
public TimeSpan? MaxAge { get; set; }
/// <summary>
/// ctor
/// </summary>
public PaginatedEndpointOptions(SharedPaginationSupport paginationType, bool timePeriodSupport, int maxLimit, bool needsAuthentication) : base(needsAuthentication)
public PaginatedEndpointOptions(
bool supportsAscending,
bool supportsDescending,
bool timePeriodSupport,
int maxLimit,
bool needsAuthentication) : base(needsAuthentication)
{
PaginationSupport = paginationType;
SupportsAscending = supportsAscending;
SupportsDescending = supportsDescending;
TimePeriodFilterSupport = timePeriodSupport;
MaxLimit = maxLimit;
}
@@ -42,9 +58,11 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString(string exchange)
{
var sb = new StringBuilder(base.ToString(exchange));
sb.AppendLine($"Pagination type: {PaginationSupport}");
sb.AppendLine($"Ascending retrieval supported: {SupportsAscending}");
sb.AppendLine($"Descending retrieval supported: {SupportsDescending}");
sb.AppendLine($"Time period filter support: {TimePeriodFilterSupport}");
sb.AppendLine($"Max limit: {MaxLimit}");
sb.AppendLine($"Max age: {MaxAge}");
return sb.ToString();
}
}
@@ -0,0 +1,17 @@
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Data direction
/// </summary>
public enum DataDirection
{
/// <summary>
/// Old to new order
/// </summary>
Ascending,
/// <summary>
/// New to old order
/// </summary>
Descending
}
}
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Next page request info
/// </summary>
public class PageRequest
{
/// <summary>
/// Pagination cursor
/// </summary>
public string? Cursor { get; set; }
/// <summary>
/// Page number
/// </summary>
public int? Page { get; set; }
/// <summary>
/// Result offset
/// </summary>
public int? Offset { get; set; }
/// <summary>
/// From id filter
/// </summary>
public string? FromId { get; set; }
/// <summary>
/// Start time filter
/// </summary>
public DateTime? StartTime { get; set; }
/// <summary>
/// End time filter
/// </summary>
public DateTime? EndTime { get; set; }
}
}
@@ -0,0 +1,405 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Pagination methods
/// </summary>
public static class Pagination
{
/// <summary>
/// Get pagination parameters
/// </summary>
/// <param name="direction">The data direction</param>
/// <param name="limit">Result limit</param>
/// <param name="requestStartTime">User request start time</param>
/// <param name="requestEndTime">User request end time</param>
/// <param name="paginationRequest">Provided page request</param>
/// <param name="setOtherTimeLimiter">Whether to set start time if direction is descending, or end time if direction is ascending</param>
/// <param name="maxPeriod">Max period the time filters can span</param>
/// <returns></returns>
public static PaginationParameters GetPaginationParameters(
DataDirection direction,
int limit,
DateTime? requestStartTime,
DateTime requestEndTime,
PageRequest? paginationRequest,
bool setOtherTimeLimiter = true,
TimeSpan? maxPeriod = null
)
{
var startTime = paginationRequest?.StartTime ?? requestStartTime;
var endTime = paginationRequest?.EndTime ?? requestEndTime;
if (maxPeriod != null)
{
if (direction == DataDirection.Ascending)
{
if (startTime == null)
{
startTime = endTime.Add(-maxPeriod.Value);
}
else
{
endTime = startTime.Value.Add(maxPeriod.Value);
if (endTime > DateTime.UtcNow)
endTime = DateTime.UtcNow;
}
}
else
{
startTime = endTime.Add(-maxPeriod.Value);
}
}
return new PaginationParameters
{
Limit = limit,
StartTime = direction == DataDirection.Ascending || setOtherTimeLimiter ? startTime : null,
EndTime = direction == DataDirection.Descending || setOtherTimeLimiter ? endTime : null,
Direction = direction,
FromId = paginationRequest?.FromId,
Offset = paginationRequest?.Offset,
Page = paginationRequest?.Page,
Cursor = paginationRequest?.Cursor
};
}
/// <summary>
/// Get the next page request parameters from result kline data
/// </summary>
/// <param name="nextPageRequest">Callback for returning the next page request</param>
/// <param name="resultCount">Number of results in data</param>
/// <param name="timestamps">Timestamps of the result data</param>
/// <param name="requestStartTime">User request start time</param>
/// <param name="requestEndTime">User request end time</param>
/// <param name="lastPaginationData">The last used pagination data</param>
/// <param name="interval">Kline interval</param>
/// <returns></returns>
public static PageRequest? GetNextPageRequestKlines(
Func<PageRequest?> nextPageRequest,
int resultCount,
IEnumerable<DateTime> timestamps,
DateTime? requestStartTime,
DateTime requestEndTime,
PaginationParameters lastPaginationData,
SharedKlineInterval interval
)
{
if (HasNextPageKlines(resultCount, timestamps, requestStartTime, requestEndTime, lastPaginationData.Limit, lastPaginationData.Direction, interval))
{
var result = nextPageRequest();
if (result != null)
{
result.StartTime ??= lastPaginationData.StartTime;
result.EndTime ??= lastPaginationData.EndTime;
return result;
}
}
return null;
}
/// <summary>
/// Get the next page request parameters from result data
/// </summary>
/// <param name="nextPageRequest">Callback for returning the next page request</param>
/// <param name="resultCount">Number of results in data</param>
/// <param name="timestamps">Timestamps of the result data</param>
/// <param name="requestStartTime">User request start time</param>
/// <param name="requestEndTime">User request end time</param>
/// <param name="lastPaginationData">The last used pagination data</param>
/// <param name="maxPeriod">Max period the time filters can span</param>
/// <param name="maxAge">Max age of the data</param>
/// <returns></returns>
public static PageRequest? GetNextPageRequest(
Func<PageRequest?> nextPageRequest,
int resultCount,
IEnumerable<DateTime> timestamps,
DateTime? requestStartTime,
DateTime requestEndTime,
PaginationParameters lastPaginationData,
TimeSpan? maxPeriod = null,
TimeSpan? maxAge = null
)
{
if (HasNextPage(resultCount, timestamps, requestStartTime, requestEndTime, lastPaginationData.Limit, lastPaginationData.Direction))
{
var result = nextPageRequest();
if (result != null)
{
result.StartTime ??= lastPaginationData.StartTime;
result.EndTime ??= lastPaginationData.EndTime;
return result;
}
}
if (maxPeriod != null)
{
if (HasNextPeriod(requestStartTime, requestEndTime, lastPaginationData.Direction, lastPaginationData, maxPeriod.Value, maxAge))
{
var (startTime, endTime) = GetNextPeriod(requestStartTime, requestEndTime, lastPaginationData.Direction, lastPaginationData, maxPeriod.Value, maxAge);
return new PageRequest
{
StartTime = startTime,
EndTime = endTime
};
}
}
return null;
}
/// <summary>
/// Check whether there is (potentially) another page available
/// </summary>
/// <param name="resultCount">Number of result entries</param>
/// <param name="timestamps">Timestamps</param>
/// <param name="requestStartTime">User request start time</param>
/// <param name="requestEndTime">User request end time</param>
/// <param name="limit">Max number of results requested</param>
/// <param name="direction">Data direction</param>
/// <param name="interval">Kline interval</param>
/// <returns></returns>
public static bool HasNextPageKlines(
int resultCount,
IEnumerable<DateTime> timestamps,
DateTime? requestStartTime,
DateTime requestEndTime,
int limit,
DataDirection direction,
SharedKlineInterval interval
)
{
if (resultCount < limit)
return false;
if (direction == DataDirection.Ascending)
{
if (timestamps.Max().AddSeconds((int)interval) >= requestEndTime)
return false;
return true;
}
else
{
if (timestamps.Min().AddSeconds((int)interval) < requestStartTime)
return false;
return true;
}
}
/// <summary>
/// Check whether there is (potentially) another page available
/// </summary>
/// <param name="resultCount">Number of result entries</param>
/// <param name="timestamps">Timestamps</param>
/// <param name="requestStartTime">User request start time</param>
/// <param name="requestEndTime">User request end time</param>
/// <param name="limit">Max number of results requested</param>
/// <param name="direction">Data direction</param>
/// <returns></returns>
public static bool HasNextPage(
int resultCount,
IEnumerable<DateTime> timestamps,
DateTime? requestStartTime,
DateTime requestEndTime,
int limit,
DataDirection direction)
{
if (resultCount < limit)
return false;
if (!timestamps.Any())
return false;
if (direction == DataDirection.Ascending)
{
if (timestamps.Max() >= requestEndTime)
return false;
return true;
}
else
{
if (timestamps.Min() < requestStartTime)
return false;
return true;
}
}
/// <summary>
/// Get the next page PageRequest
/// </summary>
public static PageRequest NextPageFromPage(PaginationParameters lastPaginationData)
{
return new PageRequest { Page = (lastPaginationData.Page ?? 1) + 1 };
}
/// <summary>
/// Get the next offset PageRequest
/// </summary>
public static PageRequest NextPageFromOffset(PaginationParameters lastPaginationData, int resultCount)
{
return new PageRequest { Offset = (lastPaginationData.Offset ?? 0) + resultCount };
}
/// <summary>
/// Get the next page cursor PageRequest
/// </summary>
public static PageRequest NextPageFromCursor(string nextCursor)
{
return new PageRequest { Cursor = nextCursor };
}
/// <summary>
/// Get the next id PageRequest
/// </summary>
public static PageRequest NextPageFromId(long nextFromId)
{
return new PageRequest { FromId = nextFromId.ToString() };
}
/// <summary>
/// Get the next id PageRequest
/// </summary>
public static PageRequest NextPageFromId(string nextFromId)
{
return new PageRequest { FromId = nextFromId };
}
/// <summary>
/// Get the next start/end time PageRequest
/// </summary>
public static PageRequest NextPageFromTime(PaginationParameters lastPaginationData, DateTime lastTimestamp, bool setOtherTimeLimiter = true)
{
if (lastPaginationData.Direction == DataDirection.Ascending)
return new PageRequest { StartTime = lastTimestamp.AddMilliseconds(1), EndTime = setOtherTimeLimiter ? lastPaginationData.EndTime : null };
else
return new PageRequest { EndTime = lastTimestamp.AddMilliseconds(-1), StartTime = setOtherTimeLimiter ? lastPaginationData.StartTime : null };
}
/// <summary>
/// Get the next start/end time klines PageRequest
/// </summary>
public static PageRequest NextPageFromTimeKlines(DataDirection direction, GetKlinesRequest request, DateTime lastTimestamp, int limit)
{
if (direction == DataDirection.Ascending)
{
var nextStartTime = lastTimestamp.AddSeconds((int)request.Interval);
var endTime = nextStartTime.AddSeconds(limit * (int)request.Interval);
var requestEndTime = request.EndTime ?? DateTime.UtcNow;
if (endTime > requestEndTime)
endTime = requestEndTime;
return new PageRequest { StartTime = nextStartTime, EndTime = endTime };
}
else
{
var nextEndTime = lastTimestamp.AddSeconds(-(int)request.Interval);
var startTime = nextEndTime.AddSeconds(-(limit * (int)request.Interval));
var requestStartTime = request.StartTime ?? DateTime.UtcNow;
if (startTime < requestStartTime)
startTime = requestStartTime;
return new PageRequest { StartTime = startTime, EndTime = nextEndTime };
}
}
/// <summary>
/// Whether another time period is to be requested
/// </summary>
/// <param name="requestStartTime">User request start time</param>
/// <param name="requestEndTime">User request end time</param>
/// <param name="direction">Data direction</param>
/// <param name="lastPaginationParameters">Pagination parameters used</param>
/// <param name="period">Max time period a request can span</param>
/// <param name="maxAge">Max age of data that can be requested</param>
public static bool HasNextPeriod(
DateTime? requestStartTime,
DateTime requestEndTime,
DataDirection direction,
PaginationParameters lastPaginationParameters,
TimeSpan period,
TimeSpan? maxAge)
{
if (direction == DataDirection.Ascending && lastPaginationParameters.StartTime == null)
throw new InvalidOperationException("Invalid pagination data; no start time for ascending pagination");
if (direction == DataDirection.Ascending)
{
return (requestEndTime - lastPaginationParameters.EndTime!.Value).TotalSeconds > 1;
}
else
{
var lastPageStartTime = lastPaginationParameters.StartTime ?? lastPaginationParameters.EndTime!.Value.Add(-period);
if (requestStartTime != null)
{
var nextPeriodDuration = lastPageStartTime - requestStartTime.Value;
return nextPeriodDuration.TotalSeconds > 1;
}
else
{
var nextStartTime = lastPageStartTime - period;
if (maxAge != null)
{
var minStartTime = DateTime.UtcNow - maxAge.Value;
if ((nextStartTime.Add(period) - minStartTime).TotalSeconds < 1)
return false;
}
var nextPeriodDuration = lastPageStartTime - nextStartTime;
return (nextPeriodDuration).TotalSeconds > 1;
}
}
}
/// <summary>
/// Get the start/end time for the next data period
/// </summary>
/// <param name="requestStartTime">User request start time</param>
/// <param name="requestEndTime">User request end time</param>
/// <param name="direction">Data direction</param>
/// <param name="lastPaginationParameters">Pagination parameters used</param>
/// <param name="period">Max time period a request can span</param>
/// <param name="maxAge">Max age of data that can be requested</param>
public static (DateTime? startTime, DateTime? endTime) GetNextPeriod(
DateTime? requestStartTime,
DateTime requestEndTime,
DataDirection direction,
PaginationParameters lastPaginationParameters,
TimeSpan period,
TimeSpan? maxAge
)
{
DateTime? nextStartTime = null;
DateTime? nextEndTime = null;
if (direction == DataDirection.Ascending)
{
if (lastPaginationParameters.StartTime != null)
nextStartTime = lastPaginationParameters.StartTime.Value.Add(period);
if (lastPaginationParameters.EndTime != null)
nextEndTime = lastPaginationParameters.EndTime.Value.Add(period);
}
else
{
if (lastPaginationParameters.StartTime != null)
nextStartTime = lastPaginationParameters.StartTime.Value.Add(-period);
if (lastPaginationParameters.EndTime != null)
nextEndTime = lastPaginationParameters.EndTime.Value.Add(-period);
}
if (nextStartTime != null && nextStartTime < requestStartTime)
nextStartTime = requestStartTime;
if (nextStartTime != null && maxAge != null && nextStartTime < DateTime.UtcNow - maxAge)
{
nextStartTime = DateTime.UtcNow.Add(-maxAge.Value);
// Add 30 seconds to max sure the client/server time offset and latency doesn't push the timestamp over the limit
nextStartTime = nextStartTime.Value.Add(TimeSpan.FromSeconds(30));
}
if (nextEndTime != null && nextEndTime > requestEndTime)
nextEndTime = requestEndTime;
return (nextStartTime, nextEndTime);
}
}
}
@@ -0,0 +1,43 @@
using System;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Pagination parameters
/// </summary>
public record PaginationParameters
{
/// <summary>
/// Data direction
/// </summary>
public DataDirection Direction { get; set; }
/// <summary>
/// Start time filter
/// </summary>
public DateTime? StartTime { get; set; }
/// <summary>
/// End time filter
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// Id filter
/// </summary>
public string? FromId { get; set; }
/// <summary>
/// Result offset
/// </summary>
public int? Offset { get; set; }
/// <summary>
/// Page number
/// </summary>
public int? Page { get; set; }
/// <summary>
/// Pagination cursor
/// </summary>
public string? Cursor { get; set; }
/// <summary>
/// Max number of results
/// </summary>
public int Limit { get; set; }
}
}
@@ -19,6 +19,10 @@ namespace CryptoExchange.Net.SharedApis
/// Max number of results
/// </summary>
public int? Limit { get; }
/// <summary>
/// Data direction
/// </summary>
public DataDirection? Direction { get; set; }
/// <summary>
/// ctor
@@ -27,12 +31,14 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetClosedOrdersRequest(SharedSymbol symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
public GetClosedOrdersRequest(SharedSymbol symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
{
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
}
}
@@ -23,6 +23,10 @@ namespace CryptoExchange.Net.SharedApis
/// Max number of results
/// </summary>
public int? Limit { get; }
/// <summary>
/// Data direction
/// </summary>
public DataDirection? Direction { get; set; }
/// <summary>
/// ctor
@@ -31,13 +35,15 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetDepositsRequest(string? asset = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(exchangeParameters)
public GetDepositsRequest(string? asset = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(exchangeParameters)
{
Asset = asset;
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
}
}
@@ -19,6 +19,10 @@ namespace CryptoExchange.Net.SharedApis
/// Max number of results
/// </summary>
public int? Limit { get; set; }
/// <summary>
/// Data direction
/// </summary>
public DataDirection? Direction { get; set; }
/// <summary>
/// ctor
@@ -27,12 +31,14 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetFundingRateHistoryRequest(SharedSymbol symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
public GetFundingRateHistoryRequest(SharedSymbol symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
{
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
}
}
@@ -23,6 +23,10 @@ namespace CryptoExchange.Net.SharedApis
/// Max number of results
/// </summary>
public int? Limit { get; set; }
/// <summary>
/// Data direction
/// </summary>
public DataDirection? Direction { get; set; }
/// <summary>
/// ctor
@@ -32,13 +36,15 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetKlinesRequest(SharedSymbol symbol, SharedKlineInterval interval, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
public GetKlinesRequest(SharedSymbol symbol, SharedKlineInterval interval, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
{
Interval = interval;
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
}
}
@@ -27,6 +27,10 @@ namespace CryptoExchange.Net.SharedApis
/// Max number of results
/// </summary>
public int? Limit { get; set; }
/// <summary>
/// Data direction
/// </summary>
public DataDirection? Direction { get; set; }
/// <summary>
/// ctor
@@ -35,13 +39,15 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetPositionHistoryRequest(SharedSymbol symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(exchangeParameters)
public GetPositionHistoryRequest(SharedSymbol symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(exchangeParameters)
{
Symbol = symbol;
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
/// <summary>
@@ -51,13 +57,15 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetPositionHistoryRequest(TradingMode? tradeMode = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(exchangeParameters)
public GetPositionHistoryRequest(TradingMode? tradeMode = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(exchangeParameters)
{
TradingMode = tradeMode;
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
}
}
@@ -10,15 +10,19 @@ namespace CryptoExchange.Net.SharedApis
/// <summary>
/// Filter by start time
/// </summary>
public DateTime StartTime { get; }
public DateTime StartTime { get; set; }
/// <summary>
/// Filter by end time
/// </summary>
public DateTime EndTime { get; }
public DateTime? EndTime { get; set; }
/// <summary>
/// Max number of results
/// </summary>
public int? Limit { get; }
public int? Limit { get; set; }
/// <summary>
/// Data direction
/// </summary>
public DataDirection? Direction { get; set; }
/// <summary>
/// ctor
@@ -27,12 +31,14 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetTradeHistoryRequest(SharedSymbol symbol, DateTime startTime, DateTime endTime, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
public GetTradeHistoryRequest(SharedSymbol symbol, DateTime startTime, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
{
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
}
}
@@ -19,6 +19,10 @@ namespace CryptoExchange.Net.SharedApis
/// Max number of results
/// </summary>
public int? Limit { get; }
/// <summary>
/// Data direction
/// </summary>
public DataDirection? Direction { get; set; }
/// <summary>
/// ctor
@@ -27,12 +31,14 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetUserTradesRequest(SharedSymbol symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
public GetUserTradesRequest(SharedSymbol symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(symbol, exchangeParameters)
{
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
}
}
@@ -23,6 +23,10 @@ namespace CryptoExchange.Net.SharedApis
/// Max number of results
/// </summary>
public int? Limit { get; }
/// <summary>
/// Data direction
/// </summary>
public DataDirection? Direction { get; set; }
/// <summary>
/// ctor
@@ -31,13 +35,15 @@ namespace CryptoExchange.Net.SharedApis
/// <param name="startTime">Filter by start time</param>
/// <param name="endTime">Filter by end time</param>
/// <param name="limit">Max number of results</param>
/// <param name="direction">Data direction</param>
/// <param name="exchangeParameters">Exchange specific parameters</param>
public GetWithdrawalsRequest(string? asset = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, ExchangeParameters? exchangeParameters = null) : base(exchangeParameters)
public GetWithdrawalsRequest(string? asset = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, DataDirection? direction = null, ExchangeParameters? exchangeParameters = null) : base(exchangeParameters)
{
Asset = asset;
StartTime = startTime;
EndTime = endTime;
Limit = limit;
Direction = direction;
}
}
}
@@ -8,7 +8,9 @@ using CryptoExchange.Net.Sockets.Default.Interfaces;
using CryptoExchange.Net.Sockets.Interfaces;
using Microsoft.Extensions.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
@@ -123,8 +125,7 @@ namespace CryptoExchange.Net.Sockets.Default
{
get
{
lock (_listenersLock)
return _listeners.OfType<Subscription>().Count(h => h.UserSubscription);
return _listeners.OfType<Subscription>().Count(h => h.UserSubscription);
}
}
@@ -135,8 +136,7 @@ namespace CryptoExchange.Net.Sockets.Default
{
get
{
lock (_listenersLock)
return _listeners.OfType<Subscription>().Where(h => h.UserSubscription).ToArray();
return _listeners.OfType<Subscription>().Where(h => h.UserSubscription).ToArray();
}
}
@@ -240,8 +240,7 @@ namespace CryptoExchange.Net.Sockets.Default
{
get
{
lock (_listenersLock)
return _listeners.OfType<Subscription>().Select(x => x.Topic).Where(t => t != null).ToArray()!;
return _listeners.OfType<Subscription>().Select(x => x.Topic).Where(t => t != null).ToArray()!;
}
}
@@ -252,8 +251,7 @@ namespace CryptoExchange.Net.Sockets.Default
{
get
{
lock (_listenersLock)
return _listeners.OfType<Query>().Where(x => !x.Completed).Count();
return _listeners.OfType<Query>().Where(x => !x.Completed).Count();
}
}
@@ -264,7 +262,7 @@ namespace CryptoExchange.Net.Sockets.Default
#else
private readonly object _listenersLock = new object();
#endif
private readonly List<IMessageProcessor> _listeners;
private ReadOnlyCollection<IMessageProcessor> _listeners;
private readonly ILogger _logger;
private SocketStatus _status;
@@ -313,7 +311,7 @@ namespace CryptoExchange.Net.Sockets.Default
_socket.OnError += HandleErrorAsync;
_socket.GetReconnectionUrl = GetReconnectionUrlAsync;
_listeners = new List<IMessageProcessor>();
_listeners = new ReadOnlyCollection<IMessageProcessor>([]);
_serializer = apiClient.CreateSerializer();
}
@@ -340,21 +338,18 @@ namespace CryptoExchange.Net.Sockets.Default
if (ApiClient._socketConnections.ContainsKey(SocketId))
ApiClient._socketConnections.TryRemove(SocketId, out _);
lock (_listenersLock)
foreach (var subscription in _listeners.OfType<Subscription>().Where(l => l.UserSubscription && !l.IsClosingConnection))
{
foreach (var subscription in _listeners.OfType<Subscription>().Where(l => l.UserSubscription && !l.IsClosingConnection))
{
subscription.IsClosingConnection = true;
subscription.Reset();
}
foreach (var query in _listeners.OfType<Query>().ToList())
{
query.Fail(new WebError("Connection interrupted"));
_listeners.Remove(query);
}
subscription.IsClosingConnection = true;
subscription.Reset();
}
var queryList = _listeners.OfType<Query>().ToList();
foreach (var query in queryList)
query.Fail(new WebError("Connection interrupted"));
RemoveMessageProcessors(queryList);
_ = Task.Run(() => ConnectionClosed?.Invoke());
return Task.CompletedTask;
}
@@ -369,17 +364,14 @@ namespace CryptoExchange.Net.Sockets.Default
Authenticated = false;
_lastSequenceNumber = 0;
lock (_listenersLock)
{
foreach (var subscription in _listeners.OfType<Subscription>().Where(l => l.UserSubscription))
subscription.Reset();
foreach (var subscription in _listeners.OfType<Subscription>().Where(l => l.UserSubscription))
subscription.Reset();
foreach (var query in _listeners.OfType<Query>().ToList())
{
query.Fail(new WebError("Connection interrupted"));
_listeners.Remove(query);
}
}
var queryList = _listeners.OfType<Query>().ToList();
foreach (var query in queryList)
query.Fail(new WebError("Connection interrupted"));
RemoveMessageProcessors(queryList);
_ = Task.Run(() => ConnectionLost?.Invoke());
return Task.CompletedTask;
@@ -401,14 +393,11 @@ namespace CryptoExchange.Net.Sockets.Default
{
Status = SocketStatus.Resubscribing;
lock (_listenersLock)
{
foreach (var query in _listeners.OfType<Query>().ToList())
{
query.Fail(new WebError("Connection interrupted"));
_listeners.Remove(query);
}
}
var queryList = _listeners.OfType<Query>().ToList();
foreach (var query in queryList)
query.Fail(new WebError("Connection interrupted"));
RemoveMessageProcessors(queryList);
// Can't wait for this as it would cause a deadlock
_ = Task.Run(async () =>
@@ -463,12 +452,7 @@ namespace CryptoExchange.Net.Sockets.Default
/// <returns></returns>
protected virtual Task HandleRequestRateLimitedAsync(int requestId)
{
Query? query;
lock (_listenersLock)
{
query = _listeners.OfType<Query>().FirstOrDefault(x => x.Id == requestId);
}
var query = _listeners.OfType<Query>().FirstOrDefault(x => x.Id == requestId);
if (query == null)
return Task.CompletedTask;
@@ -492,12 +476,7 @@ namespace CryptoExchange.Net.Sockets.Default
/// <param name="requestId">Id of the request sent</param>
protected virtual Task HandleRequestSentAsync(int requestId)
{
Query? query;
lock (_listenersLock)
{
query = _listeners.OfType<Query>().FirstOrDefault(x => x.Id == requestId);
}
var query = _listeners.OfType<Query>().FirstOrDefault(x => x.Id == requestId);
if (query == null)
return Task.CompletedTask;
@@ -543,22 +522,19 @@ namespace CryptoExchange.Net.Sockets.Default
}
Type? deserializationType = null;
lock (_listenersLock)
foreach (var subscription in _listeners)
{
foreach (var subscription in _listeners)
foreach (var route in subscription.MessageRouter.Routes)
{
foreach (var route in subscription.MessageRouter.Routes)
{
if (!route.TypeIdentifier.Equals(typeIdentifier, StringComparison.Ordinal))
continue;
if (!route.TypeIdentifier.Equals(typeIdentifier, StringComparison.Ordinal))
continue;
deserializationType = route.DeserializationType;
break;
}
if (deserializationType != null)
break;
deserializationType = route.DeserializationType;
break;
}
if (deserializationType != null)
break;
}
if (deserializationType == null)
@@ -605,84 +581,69 @@ namespace CryptoExchange.Net.Sockets.Default
var topicFilter = messageConverter.GetTopicFilter(result);
bool processed = false;
lock (_listenersLock)
foreach (var processor in _listeners)
{
var currentCount = _listeners.Count;
for(var i = 0; i < _listeners.Count; i++)
bool isQuery = false;
Query? query = null;
if (processor is Query cquery)
{
if (_listeners.Count != currentCount)
{
// Possible a query added or removed. If added it's not a problem, if removed it is
if (_listeners.Count < currentCount)
throw new Exception("Listeners list adjusted, can't continue processing");
}
var processor = _listeners[i];
bool isQuery = false;
Query? query = null;
if (processor is Query cquery)
{
isQuery = true;
query = cquery;
}
var complete = false;
foreach (var route in processor.MessageRouter.Routes)
{
if (route.TypeIdentifier != typeIdentifier)
continue;
// Forward message rules:
// | Message Topic | Route Topic Filter | Topics Match | Forward | Description
// | N | N | - | Y | No topic filter applied
// | N | Y | - | N | Route only listens to specific topic
// | Y | N | - | Y | Route listens to all message regardless of topic
// | Y | Y | Y | Y | Route listens to specific message topic
// | Y | Y | N | N | Route listens to different topic
if (topicFilter == null)
{
if (route.TopicFilter != null)
// No topic on message, but route is filtering on topic
continue;
}
else
{
if (route.TopicFilter != null && !route.TopicFilter.Equals(topicFilter, StringComparison.Ordinal))
// Message has a topic, and the route has a filter for another topic
continue;
}
processed = true;
if (isQuery && query!.Completed)
continue;
processor.Handle(this, receiveTime, originalData, result, route);
if (isQuery && !route.MultipleReaders)
{
complete = true;
break;
}
}
if (complete)
break;
isQuery = true;
query = cquery;
}
var complete = false;
foreach (var route in processor.MessageRouter.Routes)
{
if (route.TypeIdentifier != typeIdentifier)
continue;
// Forward message rules:
// | Message Topic | Route Topic Filter | Topics Match | Forward | Description
// | N | N | - | Y | No topic filter applied
// | N | Y | - | N | Route only listens to specific topic
// | Y | N | - | Y | Route listens to all message regardless of topic
// | Y | Y | Y | Y | Route listens to specific message topic
// | Y | Y | N | N | Route listens to different topic
if (topicFilter == null)
{
if (route.TopicFilter != null)
// No topic on message, but route is filtering on topic
continue;
}
else
{
if (route.TopicFilter != null && !route.TopicFilter.Equals(topicFilter, StringComparison.Ordinal))
// Message has a topic, and the route has a filter for another topic
continue;
}
processed = true;
if (isQuery && query!.Completed)
continue;
processor.Handle(this, receiveTime, originalData, result, route);
if (isQuery && !route.MultipleReaders)
{
complete = true;
break;
}
}
if (complete)
break;
}
if (!processed)
{
if (!ApiClient.HandleUnhandledMessage(this, typeIdentifier, data))
{
lock (_listenersLock)
{
_logger.ReceivedMessageNotMatchedToAnyListener(
SocketId,
typeIdentifier,
topicFilter!,
string.Join(",", _listeners.Select(x => string.Join(",", x.MessageRouter.Routes.Where(x => x.TypeIdentifier == typeIdentifier).Select(x => x.TopicFilter != null ? string.Join(",", x.TopicFilter) : "[null]")))));
}
_logger.ReceivedMessageNotMatchedToAnyListener(
SocketId,
typeIdentifier,
topicFilter!,
string.Join(",", _listeners.Select(x => string.Join(",", x.MessageRouter.Routes.Where(x => x.TypeIdentifier == typeIdentifier).Select(x => x.TopicFilter != null ? string.Join(",", x.TopicFilter) : "[null]")))));
}
}
}
@@ -727,13 +688,10 @@ namespace CryptoExchange.Net.Sockets.Default
if (ApiClient._socketConnections.ContainsKey(SocketId))
ApiClient._socketConnections.TryRemove(SocketId, out _);
lock (_listenersLock)
foreach (var subscription in _listeners.OfType<Subscription>())
{
foreach (var subscription in _listeners.OfType<Subscription>())
{
if (subscription.CancellationTokenRegistration.HasValue)
subscription.CancellationTokenRegistration.Value.Dispose();
}
if (subscription.CancellationTokenRegistration.HasValue)
subscription.CancellationTokenRegistration.Value.Dispose();
}
await _socket.CloseAsync().ConfigureAwait(false);
@@ -763,20 +721,12 @@ namespace CryptoExchange.Net.Sockets.Default
if (subscription.CancellationTokenRegistration.HasValue)
subscription.CancellationTokenRegistration.Value.Dispose();
bool anyDuplicateSubscription;
lock (_listenersLock)
anyDuplicateSubscription = _listeners.OfType<Subscription>().Any(x => x != subscription && x.MessageRouter.Routes.All(l => subscription.MessageRouter.ContainsCheck(l)));
bool shouldCloseConnection;
lock (_listenersLock)
shouldCloseConnection = _listeners.OfType<Subscription>().All(r => !r.UserSubscription || r.Status == SubscriptionStatus.Closing || r.Status == SubscriptionStatus.Closed) && !DedicatedRequestConnection.IsDedicatedRequestConnection;
bool anyDuplicateSubscription = _listeners.OfType<Subscription>().Any(x => x != subscription && x.MessageRouter.Routes.All(l => subscription.MessageRouter.ContainsCheck(l)));
bool shouldCloseConnection = _listeners.OfType<Subscription>().All(r => !r.UserSubscription || r.Status == SubscriptionStatus.Closing || r.Status == SubscriptionStatus.Closed) && !DedicatedRequestConnection.IsDedicatedRequestConnection;
if (!anyDuplicateSubscription)
{
bool needUnsub;
lock (_listenersLock)
needUnsub = _listeners.Contains(subscription) && !shouldCloseConnection;
var needUnsub = _listeners.Contains(subscription) && !shouldCloseConnection;
if (needUnsub && _socket.IsOpen)
await UnsubscribeAsync(subscription).ConfigureAwait(false);
}
@@ -800,8 +750,7 @@ namespace CryptoExchange.Net.Sockets.Default
await CloseAsync().ConfigureAwait(false);
}
lock (_listenersLock)
_listeners.Remove(subscription);
RemoveMessageProcessor(subscription);
subscription.Status = SubscriptionStatus.Closed;
}
@@ -825,8 +774,7 @@ namespace CryptoExchange.Net.Sockets.Default
if (Status != SocketStatus.None && Status != SocketStatus.Connected)
return false;
lock (_listenersLock)
_listeners.Add(subscription);
AddMessageProcessor(subscription);
if (subscription.UserSubscription)
_logger.AddingNewSubscription(SocketId, subscription.Id, UserSubscriptionCount);
@@ -839,8 +787,7 @@ namespace CryptoExchange.Net.Sockets.Default
/// <param name="id"></param>
public Subscription? GetSubscription(int id)
{
lock (_listenersLock)
return _listeners.OfType<Subscription>().SingleOrDefault(s => s.Id == id);
return _listeners.OfType<Subscription>().SingleOrDefault(s => s.Id == id);
}
/// <summary>
@@ -888,15 +835,12 @@ namespace CryptoExchange.Net.Sockets.Default
private async Task SendAndWaitIntAsync(Query query, CancellationToken ct = default)
{
lock (_listenersLock)
_listeners.Add(query);
AddMessageProcessor(query);
var sendResult = await SendAsync(query.Id, query.Request, query.Weight).ConfigureAwait(false);
if (!sendResult)
{
query.Fail(sendResult.Error!);
lock (_listenersLock)
_listeners.Remove(query);
RemoveMessageProcessor(query);
return;
}
@@ -927,8 +871,7 @@ namespace CryptoExchange.Net.Sockets.Default
}
finally
{
lock (_listenersLock)
_listeners.Remove(query);
RemoveMessageProcessor(query);
}
}
@@ -1034,9 +977,7 @@ namespace CryptoExchange.Net.Sockets.Default
if (!DedicatedRequestConnection.IsDedicatedRequestConnection)
{
bool anySubscriptions;
lock (_listenersLock)
anySubscriptions = _listeners.OfType<Subscription>().Any(s => s.UserSubscription);
var anySubscriptions = _listeners.OfType<Subscription>().Any(s => s.UserSubscription);
if (!anySubscriptions)
{
// No need to resubscribe anything
@@ -1046,13 +987,8 @@ namespace CryptoExchange.Net.Sockets.Default
}
}
bool anyAuthenticated;
lock (_listenersLock)
{
anyAuthenticated = _listeners.OfType<Subscription>().Any(s => s.Authenticated)
bool anyAuthenticated = _listeners.OfType<Subscription>().Any(s => s.Authenticated)
|| DedicatedRequestConnection.IsDedicatedRequestConnection && DedicatedRequestConnection.Authenticated;
}
if (anyAuthenticated)
{
// If we reconnected a authenticated connection we need to re-authenticate
@@ -1075,10 +1011,7 @@ namespace CryptoExchange.Net.Sockets.Default
if (!_socket.IsOpen)
return new CallResult(new WebError("Socket not connected"));
List<Subscription> subList;
lock (_listenersLock)
subList = _listeners.OfType<Subscription>().Where(x => x.Active).Skip(batch * batchSize).Take(batchSize).ToList();
var subList = _listeners.OfType<Subscription>().Where(x => x.Active).Skip(batch * batchSize).Take(batchSize).ToList();
if (subList.Count == 0)
break;
@@ -1137,7 +1070,7 @@ namespace CryptoExchange.Net.Sockets.Default
return CallResult.SuccessResult;
}
subQuery.OnComplete = () =>
var subCompleteHandler = () =>
{
subscription.Status = subQuery.Result!.Success ? SubscriptionStatus.Subscribed : SubscriptionStatus.Pending;
subscription.HandleSubQueryResponse(this, subQuery.Response);
@@ -1150,6 +1083,7 @@ namespace CryptoExchange.Net.Sockets.Default
}, false);
}
};
subQuery.OnComplete = subCompleteHandler;
var subQueryResult = await SendAndWaitQueryAsync(subQuery).ConfigureAwait(false);
if (!subQueryResult)
@@ -1161,6 +1095,9 @@ namespace CryptoExchange.Net.Sockets.Default
return new CallResult<UpdateSubscription>(subQueryResult.Error!);
}
if (!subQuery.ExpectsResponse)
subCompleteHandler();
return subQueryResult;
}
@@ -1256,6 +1193,37 @@ namespace CryptoExchange.Net.Sockets.Default
});
}
private void AddMessageProcessor(IMessageProcessor processor)
{
lock (_listenersLock)
{
var updatedList = new List<IMessageProcessor>(_listeners);
updatedList.Add(processor);
_listeners = updatedList.AsReadOnly();
}
}
private void RemoveMessageProcessor(IMessageProcessor processor)
{
lock (_listenersLock)
{
var updatedList = new List<IMessageProcessor>(_listeners);
updatedList.Remove(processor);
_listeners = updatedList.AsReadOnly();
}
}
private void RemoveMessageProcessors(IEnumerable<IMessageProcessor> processors)
{
lock (_listenersLock)
{
var updatedList = new List<IMessageProcessor>(_listeners);
foreach (var processor in processors)
updatedList.Remove(processor);
_listeners = updatedList.AsReadOnly();
}
}
}
}
@@ -112,6 +112,8 @@ namespace CryptoExchange.Net.Testing.Implementations
public async Task ReconnectAsync()
{
await Task.Delay(1).ConfigureAwait(false);
if (OnReconnecting != null)
await OnReconnecting().ConfigureAwait(false);
@@ -332,7 +332,8 @@ namespace CryptoExchange.Net.Trackers.Klines
_data.Add(item.OpenTime, item);
}
_firstTimestamp = _data.Min(v => v.Key);
_firstTimestamp = _data.Count == 0 ? null : _data.Min(v => v.Key);
ApplyWindow(false);
_logger.KlineTrackerInitialDataSet(SymbolName, _data.Last().Key);
}
@@ -375,7 +376,7 @@ namespace CryptoExchange.Net.Trackers.Klines
}
}
_firstTimestamp = _data.Min(x => x.Key);
_firstTimestamp = _data.Count == 0 ? null : _data.Min(x => x.Key);
_changed = true;
SetSyncStatus();
@@ -259,11 +259,11 @@ namespace CryptoExchange.Net.Trackers.Trades
var startTime = Period == null ? DateTime.UtcNow.AddMinutes(-5) : DateTime.UtcNow.Add(-Period.Value);
var request = new GetTradeHistoryRequest(Symbol, startTime, DateTime.UtcNow);
var data = new List<SharedTrade>();
await foreach(var result in ExchangeHelpers.ExecutePages(_historyRestClient.GetTradeHistoryAsync, request).ConfigureAwait(false))
await foreach (var result in ExchangeHelpers.ExecutePages(_historyRestClient.GetTradeHistoryAsync, request).ConfigureAwait(false))
{
if (!result)
return result;
if (Limit != null && data.Count > Limit)
break;
@@ -71,9 +71,6 @@ namespace CryptoExchange.Net.Trackers.UserData
UserDataTrackerConfig config,
string? userIdentifier)
{
if (config.OnlyTrackProvidedSymbols && !config.TrackedSymbols.Any())
throw new ArgumentException(nameof(config.TrackedSymbols), "Conflicting options; `OnlyTrackProvidedSymbols` but no symbols specific in `TrackedSymbols`");
_logger = logger;
SymbolTracker = new UserDataSymbolTracker(logger, config);
+24
View File
@@ -67,6 +67,30 @@ Make a one time donation in a crypto currency of your choice. If you prefer to d
Alternatively, sponsor me on Github using [Github Sponsors](https://github.com/sponsors/JKorf).
## Release notes
* Version 10.7.1 - 25 Feb 2026
* Fixed deadlock scenario in websocket connection when subscribe and handling message concurrently
* Version 10.7.0 - 24 Feb 2026
* Added parsing of REST response data up to 128 characters for error responses
* Added check for invalid json in JsonSocketMessageHandler
* Added virtual GetTypeIdentifierNonJson for handling non-json messages in JsonSocketMessageHandler
* Added additional options to Rest client options for configuring HttpClient
* Updated INextPageToken parameter on Shared interfaces to PageRequest type, functionality unchanged
* Added SupportsAscending and SupportsDescending properties to PaginatedEndpointOptions to expose supported data directions
* Added MaxAge property to PaginatedEndpointOptions to expose the max age of data that can be requested
* Added Direction property to Shared interfaces paginated requests to configure pagination data direction
* Removed PaginationSupport property from PaginatedEndpointOptions, replaced by above new properties
* Updated Shared GetTradeHistoryRequest EndTime property to be optional
* Updated I(Futures/Spot)OrderRestClient.GetClosed(Futures/Spot)OrdersOptions from PaginatedEndpointOptions<GetClosedOrdersRequest> to GetClosedOrdersOptions
* Updated I(Futures/Spot)OrderRestClient.Get(Futures/Spot)UserTradesOptions from PaginatedEndpointOptions<GetUserTradesRequest> to GetUserTradesOptions
* Updated rate limiting PathStartFilter to ignore added or missing slash before the path
* Updated internal lock for subscription to ReaderWriterLockSlim on SocketConnection
* Removed check for OnlyTrackProvidedSymbols in combination with empty TrackedSymbols list
* Fixed KlineTracker throwing exception if there is no data in the initial snapshot
* Version 10.6.2 - 17 Feb 2026
* Fix for websocket queries which don't expects response getting stuck in subscribing state
* Version 10.6.1 - 16 Feb 2026
* Fixed exception when stopping SymbolOrderBook instance when update is received while closing