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

Compare commits

...

38 Commits

Author SHA1 Message Date
Jkorf cd78dbf575 Updated to version 8.8.0 2025-02-10 14:38:19 +01:00
Jkorf a258532d6a Fixed DataTime copying in DataEvent 2025-02-10 14:32:25 +01:00
JKorf d2a87a1069 Added additional enum values to default SupportIntervals for shared rest and socket kline operations 2025-02-09 21:43:18 +01:00
JKorf e07f24ea0a Fixed various info-warnings and spelling issues 2025-02-09 21:25:26 +01:00
JKorf 024e8dcfe2 Added SharedKlineInterval values 2025-02-09 20:12:55 +01:00
JKorf 4bb5aae40a Split DataEvent.Timestamp in DataEvent.ReceivedTimestamp and 2025-02-09 16:40:28 +01:00
JKorf dec94678ec Updated to version 8.7.4 2025-02-08 14:28:29 +01:00
JKorf 1a49fc8251 Fix exception when creating rest client for mono runtime 2025-02-08 14:25:19 +01:00
Jkorf 29b0875960 Updated examples 2025-02-07 13:50:00 +01:00
Jkorf 976ccab1da Added BitMEX reference 2025-02-07 13:20:54 +01:00
Jkorf 02bbd37bb6 Updated to version 8.7.3 2025-02-05 09:15:25 +01:00
Jkorf 1bbbec7f2b Fixed issue with serialization of nullable types in System.Text.Json ArrayConverter 2025-02-05 09:12:12 +01:00
Jkorf 0262f04913 Added handling of negative number DateTime deserialization to default 2025-02-05 08:25:59 +01:00
Jkorf fd1ec17d72 Fix for unnecessary error message in logging when closing connection 2025-02-04 08:28:48 +01:00
Jkorf 4bdad7fe0c Updated SharedSymbol from class to record 2025-02-04 08:28:21 +01:00
Jkorf 74f73dc790 Updated to version 8.7.2 2025-01-27 13:24:08 +01:00
Jkorf 0527a8a76e Some small fixes in the System.Text.Json ArrayConverter, added support for flags in EnumConverter 2025-01-27 11:52:07 +01:00
Jkorf c693eb8c02 Updated to version 8.7.1 2025-01-24 08:42:08 +01:00
Jkorf 3eb28c7fed Added HyperLiquid referral 2025-01-23 09:35:44 +01:00
JKorf 618c4922b9 Added Authenticated property to IBaseApiClient interface 2025-01-22 19:11:38 +01:00
Jkorf c81b15861d Updated examples and docs with HyperLiquid references 2025-01-21 15:24:23 +01:00
Jkorf 4a5832cccd Updated to version 8.7.0 2025-01-21 14:02:42 +01:00
Jkorf 4e47c4cbdf Updated CheckForMissingInterfaces test 2025-01-21 14:00:30 +01:00
Jkorf 2af1520ecc Added PriceSignificationFigures to SharedSpotSymbol model 2025-01-21 14:00:08 +01:00
Jkorf cf397af3ab Added GetMillisecondTimestampLong helper method to AuthenticationProvider 2025-01-21 13:47:05 +01:00
JKorf a1479705e2 Fixed typo 2025-01-13 17:49:38 +01:00
Jkorf 175e23f110 Updated to version 8.6.1 2025-01-09 16:25:11 +01:00
Jkorf 9b7019ded2 Removed websocket Error callback when exception is expected 2025-01-09 16:23:34 +01:00
Jkorf 7904aa9ba7 Fixed websocket connection getting stuck after a ping frame timeout, removed unnecessary type restraints on RestApiClient.SendAsync methods 2025-01-09 16:18:13 +01:00
Jkorf 3fe6db589f Updated to version 8.6.0 2025-01-07 13:25:50 +01:00
Jkorf 625dccbbe4 Added ExchangeType enum, some small improvements 2025-01-07 13:22:16 +01:00
Jkorf e650771d16 Added response headers parameter to RestApiClient.TryParseError method, added check for ServerRateLimitError on the result 2025-01-07 10:19:37 +01:00
Jkorf 3dad28b19d Added IFeeRestClient to service registration 2025-01-07 08:59:51 +01:00
Jkorf 2b9fda985e Add support for passing weight to apply to an individual ratelimit guard 2025-01-07 08:35:06 +01:00
JKorf ff8759409b Use Convert.ToHexString if available 2025-01-06 21:38:42 +01:00
JKorf 0d9627c13f Changed socket no data reconnect message to LogLevel Warning 2024-12-23 20:03:56 +01:00
Jkorf 0179fd7e2a Fixed workflow automated tests 2024-12-23 14:43:23 +01:00
Jkorf b8d0b0cf95 Workflow fix 2024-12-23 14:36:18 +01:00
76 changed files with 746 additions and 225 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: 8.0.x
dotnet-version: 9.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
@@ -5,6 +5,7 @@ namespace CryptoExchange.Net.Attributes
/// <summary>
/// Map a enum entry to string values
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class MapAttribute : Attribute
{
/// <summary>
@@ -403,10 +403,14 @@ namespace CryptoExchange.Net.Authentication
/// <returns></returns>
protected static string BytesToHexString(byte[] buff)
{
#if NET9_0_OR_GREATER
return Convert.ToHexString(buff);
#else
var result = string.Empty;
foreach (var t in buff)
result += t.ToString("X2");
return result;
#endif
}
/// <summary>
@@ -439,16 +443,26 @@ namespace CryptoExchange.Net.Authentication
return DateTimeConverter.ConvertToMilliseconds(GetTimestamp(apiClient)).Value.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Get millisecond timestamp as a long including the time sync offset from the api client
/// </summary>
/// <param name="apiClient"></param>
/// <returns></returns>
protected long GetMillisecondTimestampLong(RestApiClient apiClient)
{
return DateTimeConverter.ConvertToMilliseconds(GetTimestamp(apiClient)).Value;
}
/// <summary>
/// Return the serialized request body
/// </summary>
/// <param name="serializer"></param>
/// <param name="parameters"></param>
/// <returns></returns>
protected string GetSerializedBody(IMessageSerializer serializer, IDictionary<string, object> parameters)
protected static string GetSerializedBody(IMessageSerializer serializer, IDictionary<string, object> parameters)
{
if (parameters.Count == 1 && parameters.ContainsKey(Constants.BodyPlaceHolderKey))
return serializer.Serialize(parameters[Constants.BodyPlaceHolderKey]);
if (parameters.Count == 1 && parameters.TryGetValue(Constants.BodyPlaceHolderKey, out object? value))
return serializer.Serialize(value);
else
return serializer.Serialize(parameters);
}
+2 -4
View File
@@ -38,9 +38,7 @@ namespace CryptoExchange.Net.Clients
/// </summary>
public bool OutputOriginalData { get; }
/// <summary>
/// Whether or not API credentials have been configured for this client. Does not check the credentials are actually valid.
/// </summary>
/// <inheritdoc />
public bool Authenticated => ApiOptions.ApiCredentials != null || ClientOptions.ApiCredentials != null;
/// <summary>
@@ -57,7 +55,7 @@ namespace CryptoExchange.Net.Clients
/// ctor
/// </summary>
/// <param name="logger">Logger</param>
/// <param name="outputOriginalData">Should data from this client include the orginal data in the call result</param>
/// <param name="outputOriginalData">Should data from this client include the original data in the call result</param>
/// <param name="baseAddress">Base address for this API client</param>
/// <param name="apiCredentials">Api credentials</param>
/// <param name="clientOptions">Client options</param>
+1 -1
View File
@@ -49,7 +49,7 @@ namespace CryptoExchange.Net.Clients
/// </summary>
protected internal ILogger _logger;
private object _versionLock = new object();
private readonly object _versionLock = new object();
private Version _exchangeVersion;
/// <summary>
@@ -93,6 +93,7 @@ namespace CryptoExchange.Net.Clients
{
tasks.Add(client.ReconnectAsync());
}
await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false);
}
@@ -106,6 +107,7 @@ namespace CryptoExchange.Net.Clients
{
result.AppendLine(client.GetSubscriptionsState());
}
return result.ToString();
}
@@ -120,6 +122,7 @@ namespace CryptoExchange.Net.Clients
{
result.Add(client.GetState());
}
return result;
}
}
@@ -9,7 +9,7 @@ namespace CryptoExchange.Net.Clients
/// </summary>
public class CryptoBaseClient : IDisposable
{
private Dictionary<Type, object> _serviceCache = new Dictionary<Type, object>();
private readonly Dictionary<Type, object> _serviceCache = new Dictionary<Type, object>();
/// <summary>
/// Service provider
+36 -17
View File
@@ -89,7 +89,7 @@ namespace CryptoExchange.Net.Clients
/// <summary>
/// Memory cache
/// </summary>
private static MemoryCache _cache = new MemoryCache();
private readonly static MemoryCache _cache = new MemoryCache();
/// <summary>
/// ctor
@@ -154,6 +154,7 @@ namespace CryptoExchange.Net.Clients
/// <param name="cancellationToken">Cancellation token</param>
/// <param name="additionalHeaders">Additional headers for this request</param>
/// <param name="weight">Override the request weight for this request definition, for example when the weight depends on the parameters</param>
/// <param name="weightSingleLimiter">Specify the weight to apply to the individual rate limit guard for this request</param>
/// <returns></returns>
protected virtual Task<WebCallResult<T>> SendAsync<T>(
string baseAddress,
@@ -161,7 +162,8 @@ namespace CryptoExchange.Net.Clients
ParameterCollection? parameters,
CancellationToken cancellationToken,
Dictionary<string, string>? additionalHeaders = null,
int? weight = null) where T : class
int? weight = null,
int? weightSingleLimiter = null)
{
var parameterPosition = definition.ParameterPosition ?? ParameterPositions[definition.Method];
return SendAsync<T>(
@@ -171,7 +173,8 @@ namespace CryptoExchange.Net.Clients
parameterPosition == HttpMethodParameterPosition.InBody ? parameters : null,
cancellationToken,
additionalHeaders,
weight);
weight,
weightSingleLimiter);
}
/// <summary>
@@ -185,6 +188,7 @@ namespace CryptoExchange.Net.Clients
/// <param name="cancellationToken">Cancellation token</param>
/// <param name="additionalHeaders">Additional headers for this request</param>
/// <param name="weight">Override the request weight for this request definition, for example when the weight depends on the parameters</param>
/// <param name="weightSingleLimiter">Specify the weight to apply to the individual rate limit guard for this request</param>
/// <returns></returns>
protected virtual async Task<WebCallResult<T>> SendAsync<T>(
string baseAddress,
@@ -193,7 +197,8 @@ namespace CryptoExchange.Net.Clients
ParameterCollection? bodyParameters,
CancellationToken cancellationToken,
Dictionary<string, string>? additionalHeaders = null,
int? weight = null) where T : class
int? weight = null,
int? weightSingleLimiter = null)
{
string? cacheKey = null;
if (ShouldCache(definition))
@@ -217,7 +222,7 @@ namespace CryptoExchange.Net.Clients
currentTry++;
var requestId = ExchangeHelpers.NextId();
var prepareResult = await PrepareAsync(requestId, baseAddress, definition, cancellationToken, additionalHeaders, weight).ConfigureAwait(false);
var prepareResult = await PrepareAsync(requestId, baseAddress, definition, cancellationToken, additionalHeaders, weight, weightSingleLimiter).ConfigureAwait(false);
if (!prepareResult)
return new WebCallResult<T>(prepareResult.Error!);
@@ -258,6 +263,7 @@ namespace CryptoExchange.Net.Clients
/// <param name="cancellationToken">Cancellation token</param>
/// <param name="additionalHeaders">Additional headers for this request</param>
/// <param name="weight">Override the request weight for this request</param>
/// <param name="weightSingleLimiter">Specify the weight to apply to the individual rate limit guard for this request</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
protected virtual async Task<CallResult> PrepareAsync(
@@ -266,10 +272,9 @@ namespace CryptoExchange.Net.Clients
RequestDefinition definition,
CancellationToken cancellationToken,
Dictionary<string, string>? additionalHeaders = null,
int? weight = null)
int? weight = null,
int? weightSingleLimiter = null)
{
var requestWeight = weight ?? definition.Weight;
// Time sync
if (definition.Authenticated)
{
@@ -295,6 +300,7 @@ namespace CryptoExchange.Net.Clients
}
// Rate limiting
var requestWeight = weight ?? definition.Weight;
if (requestWeight != 0)
{
if (definition.RateLimitGate == null)
@@ -316,7 +322,8 @@ namespace CryptoExchange.Net.Clients
if (ClientOptions.RateLimiterEnabled)
{
var limitResult = await definition.RateLimitGate.ProcessSingleAsync(_logger, requestId, definition.LimitGuard, RateLimitItemType.Request, definition, baseAddress, AuthenticationProvider?._credentials.Key, ClientOptions.RateLimitingBehaviour, cancellationToken).ConfigureAwait(false);
var singleRequestWeight = weightSingleLimiter ?? 1;
var limitResult = await definition.RateLimitGate.ProcessSingleAsync(_logger, requestId, definition.LimitGuard, RateLimitItemType.Request, definition, baseAddress, AuthenticationProvider?._credentials.Key, singleRequestWeight, ClientOptions.RateLimitingBehaviour, cancellationToken).ConfigureAwait(false);
if (!limitResult)
return new CallResult(limitResult.Error!);
}
@@ -617,7 +624,7 @@ namespace CryptoExchange.Net.Clients
paramString = $" with request body '{request.Content}'";
var headers = request.GetHeaders();
if (headers.Any())
if (headers.Count != 0)
paramString += " with headers " + string.Join(", ", headers.Select(h => h.Key + $"=[{string.Join(",", h.Value)}]"));
TotalRequestsMade++;
@@ -693,10 +700,21 @@ namespace CryptoExchange.Net.Clients
}
// Json response received
var parsedError = TryParseError(accessor);
var parsedError = TryParseError(response.ResponseHeaders, accessor);
if (parsedError != null)
{
if (parsedError is ServerRateLimitError rateError)
{
if (rateError.RetryAfter != null && gate != null && ClientOptions.RateLimiterEnabled)
{
_logger.RestApiRateLimitPauseUntil(request.RequestId, rateError.RetryAfter.Value);
await gate.SetRetryAfterGuardAsync(rateError.RetryAfter.Value).ConfigureAwait(false);
}
}
// Success status code, but TryParseError determined it was an error response
return new WebCallResult<T>(response.StatusCode, response.ResponseHeaders, sw.Elapsed, responseLength, OutputOriginalData ? accessor.GetOriginalString() : null, request.RequestId, request.Uri.ToString(), request.Content, request.Method, request.GetHeaders(), ResultDataSource.Server, default, parsedError);
}
var deserializeResult = accessor.Deserialize<T>();
return new WebCallResult<T>(response.StatusCode, response.ResponseHeaders, sw.Elapsed, responseLength, OutputOriginalData ? accessor.GetOriginalString() : null, request.RequestId, request.Uri.ToString(), request.Content, request.Method, request.GetHeaders(), ResultDataSource.Server, deserializeResult.Data, deserializeResult.Error);
@@ -730,12 +748,13 @@ namespace CryptoExchange.Net.Clients
/// <summary>
/// Can be used to parse an error even though response status indicates success. Some apis always return 200 OK, even though there is an error.
/// When setting manualParseError to true this method will be called for each response to be able to check if the response is an error or not.
/// This method will be called for each response to be able to check if the response is an error or not.
/// If the response is an error this method should return the parsed error, else it should return null
/// </summary>
/// <param name="accessor">Data accessor</param>
/// <param name="responseHeaders">The response headers</param>
/// <returns>Null if not an error, Error otherwise</returns>
protected virtual ServerError? TryParseError(IMessageAccessor accessor) => null;
protected virtual Error? TryParseError(IEnumerable<KeyValuePair<string, IEnumerable<string>>> responseHeaders, IMessageAccessor accessor) => null;
/// <summary>
/// Can be used to indicate that a request should be retried. Defaults to false. Make sure to retry a max number of times (based on the the tries parameter) or the request will retry forever.
@@ -752,7 +771,7 @@ namespace CryptoExchange.Net.Clients
// Only retry once
return false;
if ((int?)callResult.ResponseStatusCode == 429
if (callResult.Error is ServerRateLimitError
&& ClientOptions.RateLimiterEnabled
&& ClientOptions.RateLimitingBehaviour != RateLimitingBehaviour.Fail
&& gate != null)
@@ -807,7 +826,7 @@ namespace CryptoExchange.Net.Clients
if (parameterPosition == HttpMethodParameterPosition.InUri)
{
foreach (var parameter in parameters)
uri = uri.AddQueryParmeter(parameter.Key, parameter.Value.ToString()!);
uri = uri.AddQueryParameter(parameter.Key, parameter.Value.ToString()!);
}
var headers = new Dictionary<string, string>();
@@ -889,8 +908,8 @@ namespace CryptoExchange.Net.Clients
{
// Write the parameters as json in the body
string stringData;
if (parameters.Count == 1 && parameters.ContainsKey(Constants.BodyPlaceHolderKey))
stringData = CreateSerializer().Serialize(parameters[Constants.BodyPlaceHolderKey]);
if (parameters.Count == 1 && parameters.TryGetValue(Constants.BodyPlaceHolderKey, out object? value))
stringData = CreateSerializer().Serialize(value);
else
stringData = CreateSerializer().Serialize(parameters);
request.SetContent(stringData, contentType);
@@ -82,7 +82,7 @@ namespace CryptoExchange.Net.Clients
{
get
{
if (!socketConnections.Any())
if (socketConnections.IsEmpty)
return 0;
return socketConnections.Sum(s => s.Value.IncomingKbps);
@@ -97,7 +97,7 @@ namespace CryptoExchange.Net.Clients
{
get
{
if (!socketConnections.Any())
if (socketConnections.IsEmpty)
return 0;
return socketConnections.Sum(s => s.Value.UserSubscriptionCount);
@@ -510,7 +510,7 @@ namespace CryptoExchange.Net.Clients
if (connection != null)
{
if (connection.UserSubscriptionCount < ClientOptions.SocketSubscriptionsCombineTarget || socketConnections.Count >= (ApiOptions.MaxSocketConnections ?? ClientOptions.MaxSocketConnections) && socketConnections.All(s => s.Value.UserSubscriptionCount >= ClientOptions.SocketSubscriptionsCombineTarget))
if (connection.UserSubscriptionCount < ClientOptions.SocketSubscriptionsCombineTarget || (socketConnections.Count >= (ApiOptions.MaxSocketConnections ?? ClientOptions.MaxSocketConnections) && socketConnections.All(s => s.Value.UserSubscriptionCount >= ClientOptions.SocketSubscriptionsCombineTarget)))
// Use existing socket if it has less than target connections OR it has the least connections and we can't make new
return new CallResult<SocketConnection>(connection);
}
@@ -598,7 +598,7 @@ namespace CryptoExchange.Net.Clients
KeepAliveInterval = KeepAliveInterval,
ReconnectInterval = ClientOptions.ReconnectInterval,
RateLimiter = ClientOptions.RateLimiterEnabled ? RateLimiter : null,
RateLimitingBehaviour = ClientOptions.RateLimitingBehaviour,
RateLimitingBehavior = ClientOptions.RateLimitingBehaviour,
Proxy = ClientOptions.Proxy,
Timeout = ApiOptions.SocketNoDataTimeout ?? ClientOptions.SocketNoDataTimeout
};
@@ -718,7 +718,7 @@ namespace CryptoExchange.Net.Clients
base.SetOptions(options);
if ((!previousProxyIsSet && options.Proxy == null)
|| !socketConnections.Any())
|| socketConnections.IsEmpty)
{
return;
}
@@ -3,7 +3,7 @@
/// <summary>
/// Node accessor
/// </summary>
public struct NodeAccessor
public readonly struct NodeAccessor
{
/// <summary>
/// Index
@@ -6,9 +6,9 @@ namespace CryptoExchange.Net.Converters.MessageParsing
/// <summary>
/// Message access definition
/// </summary>
public struct MessagePath : IEnumerable<NodeAccessor>
public readonly struct MessagePath : IEnumerable<NodeAccessor>
{
private List<NodeAccessor> _path;
private readonly List<NodeAccessor> _path;
internal void Add(NodeAccessor node)
{
@@ -87,8 +87,12 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
if (prop.JsonConverterType == null && IsSimple(prop.PropertyInfo.PropertyType))
{
if (prop.PropertyInfo.PropertyType == typeof(string))
if (prop.TargetType == typeof(string))
writer.WriteStringValue(Convert.ToString(objValue, CultureInfo.InvariantCulture));
else if(prop.TargetType.IsEnum)
writer.WriteStringValue(EnumConverter.GetString(objValue));
else if (prop.TargetType == typeof(bool))
writer.WriteBooleanValue((bool)objValue);
else
writer.WriteRawValue(Convert.ToString(objValue, CultureInfo.InvariantCulture)!);
}
@@ -187,12 +191,12 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
_converterOptionsCache.TryAdd(attribute.JsonConverterType, newOptions);
}
value = JsonDocument.ParseValue(ref reader).Deserialize(targetType, newOptions);
value = JsonDocument.ParseValue(ref reader).Deserialize(attribute.PropertyInfo.PropertyType, newOptions);
}
else if (attribute.DefaultDeserialization)
{
// Use default deserialization
value = JsonDocument.ParseValue(ref reader).Deserialize(targetType, options);
value = JsonDocument.ParseValue(ref reader).Deserialize(attribute.PropertyInfo.PropertyType, SerializerOptions.WithConverters);
}
else
{
@@ -47,7 +47,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
if (reader.TokenType is JsonTokenType.Number)
{
var longValue = reader.GetDouble();
if (longValue == 0 || longValue == -1)
if (longValue == 0 || longValue < 0)
return default;
return ParseFromDouble(longValue);
@@ -172,6 +172,13 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
return true;
}
if (objectType.IsDefined(typeof(FlagsAttribute)))
{
var intValue = int.Parse(value);
result = Enum.ToObject(objectType, intValue);
return true;
}
try
{
// If no explicit mapping is found try to parse string
@@ -20,8 +20,8 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
/// </summary>
protected JsonDocument? _document;
private static JsonSerializerOptions _serializerOptions = SerializerOptions.WithConverters;
private JsonSerializerOptions? _customSerializerOptions;
private static readonly JsonSerializerOptions _serializerOptions = SerializerOptions.WithConverters;
private readonly JsonSerializerOptions? _customSerializerOptions;
/// <inheritdoc />
public bool IsJson { get; set; }
@@ -148,6 +148,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
return value.Value.Deserialize<T>(_customSerializerOptions ?? _serializerOptions);
}
catch { }
return default;
}
@@ -359,7 +360,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
/// <inheritdoc />
public override string GetOriginalString() =>
// Netstandard 2.0 doesn't support GetString from a ReadonlySpan<byte>, so use ToArray there instead
// NetStandard 2.0 doesn't support GetString from a ReadonlySpan<byte>, so use ToArray there instead
#if NETSTANDARD2_0
Encoding.UTF8.GetString(_bytes.ToArray());
#else
+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>8.5.0</PackageVersion>
<AssemblyVersion>8.5.0</AssemblyVersion>
<FileVersion>8.5.0</FileVersion>
<PackageVersion>8.8.0</PackageVersion>
<AssemblyVersion>8.8.0</AssemblyVersion>
<FileVersion>8.8.0</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</PackageTags>
<RepositoryType>git</RepositoryType>
+2 -1
View File
@@ -160,7 +160,7 @@ namespace CryptoExchange.Net
}
/// <summary>
/// Generate a new unique id. The id is staticly stored so it is guarenteed to be unique
/// Generate a new unique id. The id is statically stored so it is guaranteed to be unique
/// </summary>
/// <returns></returns>
public static int NextId() => Interlocked.Increment(ref _lastId);
@@ -261,6 +261,7 @@ namespace CryptoExchange.Net
if (price != null)
{
adjustedPrice = AdjustValueStep(0, decimal.MaxValue, symbol.PriceStep, RoundingType.Down, price.Value);
adjustedPrice = symbol.PriceSignificantFigures.HasValue ? RoundToSignificantDigits(adjustedPrice.Value, symbol.PriceSignificantFigures.Value, RoundingType.Closest) : adjustedPrice;
adjustedPrice = symbol.PriceDecimals.HasValue ? RoundDown(price.Value, symbol.PriceDecimals.Value) : adjustedPrice;
if (adjustedPrice != 0 && adjustedPrice * quantity < symbol.MinNotionalValue)
{
+6 -1
View File
@@ -111,6 +111,7 @@ namespace CryptoExchange.Net
formData.Add(kvp.Key, string.Format(CultureInfo.InvariantCulture, "{0}", kvp.Value));
}
}
return formData.ToString()!;
}
@@ -286,6 +287,7 @@ namespace CryptoExchange.Net
httpValueCollection.Add(parameter.Key, parameter.Value.ToString());
}
}
uriBuilder.Query = httpValueCollection.ToString();
return uriBuilder.Uri;
}
@@ -333,6 +335,7 @@ namespace CryptoExchange.Net
httpValueCollection.Add(parameter.Key, parameter.Value.ToString());
}
}
uriBuilder.Query = httpValueCollection.ToString();
return uriBuilder.Uri;
}
@@ -344,7 +347,7 @@ namespace CryptoExchange.Net
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Uri AddQueryParmeter(this Uri uri, string name, string value)
public static Uri AddQueryParameter(this Uri uri, string name, string value)
{
var httpValueCollection = HttpUtility.ParseQueryString(uri.Query);
@@ -435,6 +438,8 @@ namespace CryptoExchange.Net
services.AddTransient(x => (IWithdrawalRestClient)client(x)!);
if (typeof(IWithdrawRestClient).IsAssignableFrom(typeof(T)))
services.AddTransient(x => (IWithdrawRestClient)client(x)!);
if (typeof(IFeeRestClient).IsAssignableFrom(typeof(T)))
services.AddTransient(x => (IFeeRestClient)client(x)!);
if (typeof(ISpotOrderRestClient).IsAssignableFrom(typeof(T)))
services.AddTransient(x => (ISpotOrderRestClient)client(x)!);
@@ -16,6 +16,11 @@ namespace CryptoExchange.Net.Interfaces
/// </summary>
string BaseAddress { get; }
/// <summary>
/// Whether or not API credentials have been configured for this client. Does not check the credentials are actually valid.
/// </summary>
bool Authenticated { get; }
/// <summary>
/// Format a base and quote asset to an exchange accepted symbol
/// </summary>
@@ -36,7 +41,7 @@ namespace CryptoExchange.Net.Interfaces
/// <summary>
/// Set new options. Note that when using a proxy this should be provided in the options even when already set before or it will be reset.
/// </summary>
/// <typeparam name="T">Api crentials type</typeparam>
/// <typeparam name="T">Api credentials type</typeparam>
/// <param name="options">Options to set</param>
void SetOptions<T>(UpdateOptions<T> options) where T : ApiCredentials;
}
@@ -19,7 +19,7 @@ namespace CryptoExchange.Net.Interfaces
/// </summary>
int CurrentSubscriptions { get; }
/// <summary>
/// Incoming data kpbs
/// Incoming data Kbps
/// </summary>
double IncomingKbps { get; }
/// <summary>
@@ -105,7 +105,7 @@ namespace CryptoExchange.Net.Interfaces
Task StopAsync();
/// <summary>
/// Get the average price that a market order would fill at at the current order book state. This is no guarentee that an order of that quantity would actually be filled
/// Get the average price that a market order would fill at at the current order book state. This is no guarantee that an order of that quantity would actually be filled
/// at that price since between this calculation and the order placement the book might have changed.
/// </summary>
/// <param name="quantity">The quantity in base asset to fill</param>
@@ -115,7 +115,7 @@ namespace CryptoExchange.Net.Interfaces
/// <summary>
/// Get the amount of base asset which can be traded with the quote quantity when placing a market order at at the current order book state.
/// This is no guarentee that an order of that quantity would actually be fill the quantity returned by this since between this calculation and the order placement the book might have changed.
/// This is no guarantee that an order of that quantity would actually be fill the quantity returned by this since between this calculation and the order placement the book might have changed.
/// </summary>
/// <param name="quoteQuantity">The quantity in quote asset looking to trade</param>
/// <param name="type">The type</param>
+1 -1
View File
@@ -47,7 +47,7 @@ namespace CryptoExchange.Net.Interfaces
/// </summary>
event Func<Task> OnReconnected;
/// <summary>
/// Get reconntion url
/// Get reconnection url
/// </summary>
Func<Task<Uri?>>? GetReconnectionUrl { get; set; }
+8 -8
View File
@@ -10,9 +10,9 @@ namespace CryptoExchange.Net
public static class LibraryHelpers
{
/// <summary>
/// Client order id seperator
/// Client order id separator
/// </summary>
public const string ClientOrderIdSeperator = "JK";
public const string ClientOrderIdSeparator = "JK";
/// <summary>
/// Apply broker id to a client order id
@@ -20,25 +20,25 @@ namespace CryptoExchange.Net
/// <param name="clientOrderId"></param>
/// <param name="brokerId"></param>
/// <param name="maxLength"></param>
/// <param name="allowValueAdjustement"></param>
/// <param name="allowValueAdjustment"></param>
/// <returns></returns>
public static string ApplyBrokerId(string? clientOrderId, string brokerId, int maxLength, bool allowValueAdjustement)
public static string ApplyBrokerId(string? clientOrderId, string brokerId, int maxLength, bool allowValueAdjustment)
{
var reservedLength = brokerId.Length + ClientOrderIdSeperator.Length;
var reservedLength = brokerId.Length + ClientOrderIdSeparator.Length;
if ((clientOrderId?.Length + reservedLength) > maxLength)
return clientOrderId!;
if (!string.IsNullOrEmpty(clientOrderId))
{
if (allowValueAdjustement)
clientOrderId = brokerId + ClientOrderIdSeperator + clientOrderId;
if (allowValueAdjustment)
clientOrderId = brokerId + ClientOrderIdSeparator + clientOrderId;
return clientOrderId!;
}
else
{
clientOrderId = ExchangeHelpers.AppendRandomString(brokerId + ClientOrderIdSeperator, maxLength);
clientOrderId = ExchangeHelpers.AppendRandomString(brokerId + ClientOrderIdSeparator, maxLength);
}
return clientOrderId;
@@ -33,8 +33,9 @@ namespace CryptoExchange.Net.Logging.Extensions
private static readonly Action<ILogger, int, Exception?> _receiveLoopStoppedWithException;
private static readonly Action<ILogger, int, Exception?> _receiveLoopFinished;
private static readonly Action<ILogger, int, TimeSpan?, Exception?> _startingTaskForNoDataReceivedCheck;
private static readonly Action<ILogger, int, TimeSpan?, Exception?> _noDataReceiveTimoutReconnect;
private static readonly Action<ILogger, int, TimeSpan?, Exception?> _noDataReceiveTimeoutReconnect;
private static readonly Action<ILogger, int, string, string, Exception?> _socketProcessingStateChanged;
private static readonly Action<ILogger, int, Exception?> _socketPingTimeout;
static CryptoExchangeWebSocketClientLoggingExtension()
{
@@ -168,8 +169,8 @@ namespace CryptoExchange.Net.Logging.Extensions
new EventId(1026, "StartingTaskForNoDataReceivedCheck"),
"[Sckt {SocketId}] starting task checking for no data received for {Timeout}");
_noDataReceiveTimoutReconnect = LoggerMessage.Define<int, TimeSpan?>(
LogLevel.Debug,
_noDataReceiveTimeoutReconnect = LoggerMessage.Define<int, TimeSpan?>(
LogLevel.Warning,
new EventId(1027, "NoDataReceiveTimeoutReconnect"),
"[Sckt {SocketId}] no data received for {Timeout}, reconnecting socket");
@@ -180,9 +181,14 @@ namespace CryptoExchange.Net.Logging.Extensions
_socketProcessingStateChanged = LoggerMessage.Define<int, string, string>(
LogLevel.Trace,
new EventId(1028, "SocketProcessingStateChanged"),
new EventId(1029, "SocketProcessingStateChanged"),
"[Sckt {Id}] processing state change: {PreviousState} -> {NewState}");
_socketPingTimeout = LoggerMessage.Define<int>(
LogLevel.Warning,
new EventId(1030, "SocketPingTimeout"),
"[Sckt {Id}] ping frame timeout; reconnecting socket");
}
public static void SocketConnecting(
@@ -350,7 +356,7 @@ namespace CryptoExchange.Net.Logging.Extensions
public static void SocketNoDataReceiveTimoutReconnect(
this ILogger logger, int socketId, TimeSpan? timeSpan)
{
_noDataReceiveTimoutReconnect(logger, socketId, timeSpan, null);
_noDataReceiveTimeoutReconnect(logger, socketId, timeSpan, null);
}
public static void SocketProcessingStateChanged(
@@ -358,5 +364,11 @@ namespace CryptoExchange.Net.Logging.Extensions
{
_socketProcessingStateChanged(logger, socketId, prevState, newState, null);
}
public static void SocketPingTimeout(
this ILogger logger, int socketId)
{
_socketPingTimeout(logger, socketId, null);
}
}
}
@@ -22,7 +22,6 @@ namespace CryptoExchange.Net.Logging.Extensions
private static readonly Action<ILogger, string, Exception?> _restApiCacheHit;
private static readonly Action<ILogger, string, Exception?> _restApiCacheNotHit;
static RestApiClientLoggingExtensions()
{
_restApiErrorReceived = LoggerMessage.Define<int?, int?, long, string?>(
@@ -37,7 +36,7 @@ namespace CryptoExchange.Net.Logging.Extensions
_restApiFailedToSyncTime = LoggerMessage.Define<int, string>(
LogLevel.Debug,
new EventId(4002, "RestApifailedToSyncTime"),
new EventId(4002, "RestApiFailedToSyncTime"),
"[Req {RequestId}] Failed to sync time, aborting request: {ErrorMessage}");
_restApiNoApiCredentials = LoggerMessage.Define<int, string>(
@@ -10,7 +10,7 @@ namespace CryptoExchange.Net.Logging.Extensions
private static readonly Action<ILogger, int, bool, Exception?> _activityPaused;
private static readonly Action<ILogger, int, Sockets.SocketConnection.SocketStatus, Sockets.SocketConnection.SocketStatus, Exception?> _socketStatusChanged;
private static readonly Action<ILogger, int, string?, Exception?> _failedReconnectProcessing;
private static readonly Action<ILogger, int, Exception?> _unkownExceptionWhileProcessingReconnection;
private static readonly Action<ILogger, int, Exception?> _unknownExceptionWhileProcessingReconnection;
private static readonly Action<ILogger, int, WebSocketError, string?, Exception?> _webSocketErrorCodeAndDetails;
private static readonly Action<ILogger, int, string?, Exception?> _webSocketError;
private static readonly Action<ILogger, int, int, Exception?> _messageSentNotPending;
@@ -28,7 +28,7 @@ namespace CryptoExchange.Net.Logging.Extensions
private static readonly Action<ILogger, int, Exception?> _closingNoMoreSubscriptions;
private static readonly Action<ILogger, int, int, int, Exception?> _addingNewSubscription;
private static readonly Action<ILogger, int, Exception?> _nothingToResubscribeCloseConnection;
private static readonly Action<ILogger, int, Exception?> _failedAuthenticationDisconnectAndRecoonect;
private static readonly Action<ILogger, int, Exception?> _failedAuthenticationDisconnectAndReconnect;
private static readonly Action<ILogger, int, Exception?> _authenticationSucceeded;
private static readonly Action<ILogger, int, string?, Exception?> _failedRequestRevitalization;
private static readonly Action<ILogger, int, Exception?> _allSubscriptionResubscribed;
@@ -55,15 +55,15 @@ namespace CryptoExchange.Net.Logging.Extensions
new EventId(2002, "FailedReconnectProcessing"),
"[Sckt {SocketId}] failed reconnect processing: {ErrorMessage}, reconnecting again");
_unkownExceptionWhileProcessingReconnection = LoggerMessage.Define<int>(
_unknownExceptionWhileProcessingReconnection = LoggerMessage.Define<int>(
LogLevel.Warning,
new EventId(2003, "UnkownExceptionWhileProcessingReconnection"),
new EventId(2003, "UnknownExceptionWhileProcessingReconnection"),
"[Sckt {SocketId}] Unknown exception while processing reconnection, reconnecting again");
_webSocketErrorCodeAndDetails = LoggerMessage.Define<int, WebSocketError, string?>(
LogLevel.Warning,
new EventId(2004, "WebSocketErrorCode"),
"[Sckt {SocketId}] error: Websocket error code {WebSocketErrorCdoe}, details: {Details}");
"[Sckt {SocketId}] error: Websocket error code {WebSocketErrorCode}, details: {Details}");
_webSocketError = LoggerMessage.Define<int, string?>(
LogLevel.Warning,
@@ -145,7 +145,7 @@ namespace CryptoExchange.Net.Logging.Extensions
new EventId(2020, "NothingToResubscribe"),
"[Sckt {SocketId}] nothing to resubscribe, closing connection");
_failedAuthenticationDisconnectAndRecoonect = LoggerMessage.Define<int>(
_failedAuthenticationDisconnectAndReconnect = LoggerMessage.Define<int>(
LogLevel.Warning,
new EventId(2021, "FailedAuthentication"),
"[Sckt {SocketId}] authentication failed on reconnected socket. Disconnecting and reconnecting");
@@ -183,7 +183,7 @@ namespace CryptoExchange.Net.Logging.Extensions
_sendingData = LoggerMessage.Define<int, int, string>(
LogLevel.Trace,
new EventId(2028, "SendingData"),
"[Sckt {SocketId}] [Req {RequestId}] sending messsage: {Data}");
"[Sckt {SocketId}] [Req {RequestId}] sending message: {Data}");
_receivedMessageNotMatchedToAnyListener = LoggerMessage.Define<int, string, string>(
LogLevel.Warning,
@@ -206,9 +206,9 @@ namespace CryptoExchange.Net.Logging.Extensions
_failedReconnectProcessing(logger, socketId, error, null);
}
public static void UnkownExceptionWhileProcessingReconnection(this ILogger logger, int socketId, Exception e)
public static void UnknownExceptionWhileProcessingReconnection(this ILogger logger, int socketId, Exception e)
{
_unkownExceptionWhileProcessingReconnection(logger, socketId, e);
_unknownExceptionWhileProcessingReconnection(logger, socketId, e);
}
public static void WebSocketErrorCodeAndDetails(this ILogger logger, int socketId, WebSocketError error, string? details, Exception e)
@@ -285,7 +285,7 @@ namespace CryptoExchange.Net.Logging.Extensions
}
public static void FailedAuthenticationDisconnectAndRecoonect(this ILogger logger, int socketId)
{
_failedAuthenticationDisconnectAndRecoonect(logger, socketId, null);
_failedAuthenticationDisconnectAndReconnect(logger, socketId, null);
}
public static void AuthenticationSucceeded(this ILogger logger, int socketId)
{
@@ -62,7 +62,6 @@ namespace CryptoExchange.Net.Logging.Extensions
new EventId(5005, "OrderBookStopping"),
"{Api} order book {Symbol} stopping");
_orderBookStopped = LoggerMessage.Define<string, string>(
LogLevel.Trace,
new EventId(5006, "OrderBookStopped"),
@@ -97,7 +97,6 @@ namespace CryptoExchange.Net.Logging.Extensions
new EventId(6012, "KlineTrackerConnectionRestored"),
"Kline tracker for {Symbol} successfully resynchronized");
_tradeTrackerStatusChanged = LoggerMessage.Define<string, SyncStatus, SyncStatus>(
LogLevel.Debug,
new EventId(6013, "KlineTrackerStatusChanged"),
+1 -1
View File
@@ -89,7 +89,7 @@ namespace CryptoExchange.Net.Objects
/// <summary>
/// Create a new error result
/// </summary>
/// <param name="error">The erro rto return</param>
/// <param name="error">The error to return</param>
public CallResult(Error error) : this(default, null, error) { }
/// <summary>
+19 -3
View File
@@ -1,4 +1,6 @@
namespace CryptoExchange.Net.Objects
using CryptoExchange.Net.Attributes;
namespace CryptoExchange.Net.Objects
{
/// <summary>
/// What to do when a request would exceed the rate limit
@@ -92,7 +94,7 @@
/// <summary>
/// Disposed
/// </summary>
Diposed
Disposed
}
/// <summary>
@@ -215,7 +217,7 @@
/// </summary>
FixedDelay,
/// <summary>
/// Backof policy of 2^`reconnectAttempt`, where `reconnectAttempt` has a max value of 5
/// Backoff policy of 2^`reconnectAttempt`, where `reconnectAttempt` has a max value of 5
/// </summary>
ExponentialBackoff
}
@@ -235,4 +237,18 @@
Cache
}
/// <summary>
/// Type of exchange
/// </summary>
public enum ExchangeType
{
/// <summary>
/// Centralized
/// </summary>
CEX,
/// <summary>
/// Decentralized
/// </summary>
DEX
}
}
@@ -55,7 +55,7 @@ namespace CryptoExchange.Net.Objects.Options
{
/// <summary>
/// Trade environment. Contains info about URL's to use to connect to the API. To swap environment select another environment for
/// the exhange's environment list or create a custom environment using either `[Exchange]Environment.CreateCustom()` or `[Exchange]Environment.[Environment]`, for example `KucoinEnvironment.TestNet` or `BinanceEnvironment.Live`
/// the exchange's environment list or create a custom environment using either `[Exchange]Environment.CreateCustom()` or `[Exchange]Environment.[Environment]`, for example `KucoinEnvironment.TestNet` or `BinanceEnvironment.Live`
/// </summary>
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public TEnvironment Environment { get; set; }
@@ -25,8 +25,7 @@ namespace CryptoExchange.Net.Objects
/// </summary>
public bool Authenticated { get; set; }
// Formating
// Formatting
/// <summary>
/// The body format for this request
@@ -58,9 +58,38 @@ namespace CryptoExchange.Net.Objects
HttpMethodParameterPosition? parameterPosition = null,
ArrayParametersSerialization? arraySerialization = null,
bool? preventCaching = null)
=> GetOrCreate(method + path, method, path, rateLimitGate, weight, authenticated, limitGuard, requestBodyFormat, parameterPosition, arraySerialization, preventCaching);
/// <summary>
/// Get a definition if it is already in the cache or create a new definition and add it to the cache
/// </summary>
/// <param name="identifier">Request identifier</param>
/// <param name="method">The HttpMethod</param>
/// <param name="path">Endpoint path</param>
/// <param name="rateLimitGate">The rate limit gate</param>
/// <param name="limitGuard">The rate limit guard for this specific endpoint</param>
/// <param name="weight">Request weight</param>
/// <param name="authenticated">Endpoint is authenticated</param>
/// <param name="requestBodyFormat">Request body format</param>
/// <param name="parameterPosition">Parameter position</param>
/// <param name="arraySerialization">Array serialization type</param>
/// <param name="preventCaching">Prevent request caching</param>
/// <returns></returns>
public RequestDefinition GetOrCreate(
string identifier,
HttpMethod method,
string path,
IRateLimitGate? rateLimitGate,
int weight,
bool authenticated,
IRateLimitGuard? limitGuard = null,
RequestBodyFormat? requestBodyFormat = null,
HttpMethodParameterPosition? parameterPosition = null,
ArrayParametersSerialization? arraySerialization = null,
bool? preventCaching = null)
{
if (!_definitions.TryGetValue(method + path, out var def))
if (!_definitions.TryGetValue(identifier, out var def))
{
def = new RequestDefinition(path, method)
{
@@ -73,7 +102,7 @@ namespace CryptoExchange.Net.Objects
ParameterPosition = parameterPosition,
PreventCaching = preventCaching ?? false
};
_definitions.TryAdd(method + path, def);
_definitions.TryAdd(identifier, def);
}
return def;
+36 -11
View File
@@ -12,7 +12,12 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <summary>
/// The timestamp the data was received
/// </summary>
public DateTime Timestamp { get; set; }
public DateTime ReceiveTime { get; set; }
/// <summary>
/// The timestamp of the data as specified by the server. Note that the server time and client time might not be 100% in sync so this value might not be fully comparable to local time.
/// </summary>
public DateTime? DataTime { get; set; }
/// <summary>
/// The stream producing the update
@@ -42,29 +47,32 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <summary>
/// ctor
/// </summary>
public DataEvent(T data, string? streamId, string? symbol, string? originalData, DateTime timestamp, SocketUpdateType? updateType)
public DataEvent(T data, string? streamId, string? symbol, string? originalData, DateTime receiveTimestamp, SocketUpdateType? updateType)
{
Data = data;
StreamId = streamId;
Symbol = symbol;
OriginalData = originalData;
Timestamp = timestamp;
ReceiveTime = receiveTimestamp;
UpdateType = updateType;
}
/// <summary>
/// Create a new DataEvent with data in the from of type K based on the current DataEvent. Topic, OriginalData and Timestamp will be copied over
/// Create a new DataEvent with data in the from of type K based on the current DataEvent. Topic, OriginalData and ReceivedTimestamp will be copied over
/// </summary>
/// <typeparam name="K">The type of the new data</typeparam>
/// <param name="data">The new data</param>
/// <returns></returns>
public DataEvent<K> As<K>(K data)
{
return new DataEvent<K>(data, StreamId, Symbol, OriginalData, Timestamp, UpdateType);
return new DataEvent<K>(data, StreamId, Symbol, OriginalData, ReceiveTime, UpdateType)
{
DataTime = DataTime
};
}
/// <summary>
/// Create a new DataEvent with data in the from of type K based on the current DataEvent. OriginalData and Timestamp will be copied over
/// Create a new DataEvent with data in the from of type K based on the current DataEvent. OriginalData and ReceivedTimestamp will be copied over
/// </summary>
/// <typeparam name="K">The type of the new data</typeparam>
/// <param name="data">The new data</param>
@@ -72,11 +80,14 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <returns></returns>
public DataEvent<K> As<K>(K data, string? symbol)
{
return new DataEvent<K>(data, StreamId, symbol, OriginalData, Timestamp, UpdateType);
return new DataEvent<K>(data, StreamId, symbol, OriginalData, ReceiveTime, UpdateType)
{
DataTime = DataTime
};
}
/// <summary>
/// Create a new DataEvent with data in the from of type K based on the current DataEvent. OriginalData and Timestamp will be copied over
/// Create a new DataEvent with data in the from of type K based on the current DataEvent. OriginalData and ReceivedTimestamp will be copied over
/// </summary>
/// <typeparam name="K">The type of the new data</typeparam>
/// <param name="data">The new data</param>
@@ -86,7 +97,10 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <returns></returns>
public DataEvent<K> As<K>(K data, string streamId, string? symbol, SocketUpdateType updateType)
{
return new DataEvent<K>(data, streamId, symbol, OriginalData, Timestamp, updateType);
return new DataEvent<K>(data, streamId, symbol, OriginalData, ReceiveTime, updateType)
{
DataTime = DataTime
};
}
/// <summary>
@@ -98,10 +112,12 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <returns></returns>
public ExchangeEvent<K> AsExchangeEvent<K>(string exchange, K data)
{
return new ExchangeEvent<K>(exchange, this.As<K>(data));
return new ExchangeEvent<K>(exchange, this.As<K>(data))
{
DataTime = DataTime
};
}
/// <summary>
/// Specify the symbol
/// </summary>
@@ -135,6 +151,15 @@ namespace CryptoExchange.Net.Objects.Sockets
return this;
}
/// <summary>
/// Specify the data timestamp
/// </summary>
public DataEvent<T> WithDataTimestamp(DateTime? timestamp)
{
DataTime = timestamp;
return this;
}
/// <summary>
/// Create a CallResult from this DataEvent
/// </summary>
@@ -41,7 +41,7 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <summary>
/// Event when the connection is restored. Timespan parameter indicates the time the socket has been offline for before reconnecting.
/// Note that when the executing code is suspended and resumed at a later period (for example, a laptop going to sleep) the disconnect time will be incorrect as the diconnect
/// Note that when the executing code is suspended and resumed at a later period (for example, a laptop going to sleep) the disconnect time will be incorrect as the disconnect
/// will only be detected after resuming the code, so the initial disconnect time is lost. Use the timespan only for informational purposes.
/// </summary>
public event Action<TimeSpan> ConnectionRestored
@@ -41,7 +41,7 @@ namespace CryptoExchange.Net.Objects.Sockets
public ApiProxy? Proxy { get; set; }
/// <summary>
/// The maximum time of no data received before considering the connection lost and closting/reconnecting the socket
/// The maximum time of no data received before considering the connection lost and closing/reconnecting the socket
/// </summary>
public TimeSpan? Timeout { get; set; }
@@ -57,7 +57,7 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <summary>
/// What to do when rate limit is reached
/// </summary>
public RateLimitingBehaviour RateLimitingBehaviour { get; set; }
public RateLimitingBehaviour RateLimitingBehavior { get; set; }
/// <summary>
/// Encoding for sending/receiving data
+2 -2
View File
@@ -82,12 +82,12 @@ namespace CryptoExchange.Net.Objects
TimeSyncState.LastSyncTime = DateTime.UtcNow;
if (offset.TotalMilliseconds > 0 && offset.TotalMilliseconds < 500)
{
Logger.Log(LogLevel.Information, $"{TimeSyncState.ApiName} Time offset within limits, set offset to 0ms");
Logger.Log(LogLevel.Information, "{TimeSyncState.ApiName} Time offset within limits, set offset to 0ms", TimeSyncState.ApiName);
TimeSyncState.TimeOffset = TimeSpan.Zero;
}
else
{
Logger.Log(LogLevel.Information, $"{TimeSyncState.ApiName} Time offset set to {Math.Round(offset.TotalMilliseconds)}ms");
Logger.Log(LogLevel.Information, "{TimeSyncState.ApiName} Time offset set to {Offset}ms", TimeSyncState.ApiName, Math.Round(offset.TotalMilliseconds));
TimeSyncState.TimeOffset = offset;
}
}
@@ -17,7 +17,7 @@
/// <summary>
/// Trade environment. Contains info about URL's to use to connect to the API. To swap environment select another environment for
/// the echange's environment list or create a custom environment using either `[Exchange]Environment.CreateCustom()` or `[Exchange]Environment.[Environment]`, for example `KucoinEnvironment.TestNet` or `BinanceEnvironment.Live`
/// the exchange's environment list or create a custom environment using either `[Exchange]Environment.CreateCustom()` or `[Exchange]Environment.[Environment]`, for example `KucoinEnvironment.TestNet` or `BinanceEnvironment.Live`
/// </summary>
public class TradeEnvironment
{
@@ -74,8 +74,7 @@ namespace CryptoExchange.Net.OrderBook
/// <summary>
/// Whether levels should be strictly enforced. For example, when an order book has 25 levels and a new update comes in which pushes
/// the current level 25 ask out of the top 25, should the curent the level 26 entry be removed from the book or does the
/// server handle this
/// the current level 25 ask out of the top 25, should the level 26 entry be removed from the book or does the server handle this
/// </summary>
protected bool _strictLevels;
@@ -250,6 +249,7 @@ namespace CryptoExchange.Net.OrderBook
// Clear any previous messages
while (_processQueue.TryDequeue(out _)) { }
_processBuffer.Clear();
_bookSet = false;
@@ -407,7 +407,7 @@ namespace CryptoExchange.Net.OrderBook
/// <summary>
/// Set the initial data for the order book. Typically the snapshot which was requested from the Rest API, or the first snapshot
/// received from a socket subcription
/// received from a socket subscription
/// </summary>
/// <param name="orderBookSequenceNumber">The last update sequence number until which the snapshot is in sync</param>
/// <param name="askList">List of asks</param>
@@ -618,6 +618,7 @@ namespace CryptoExchange.Net.OrderBook
var bid = book.bids.Count() > i ? book.bids.ElementAt(i): null;
stringBuilder.AppendLine($"[{ask?.Quantity.ToString(CultureInfo.InvariantCulture),14}] {ask?.Price.ToString(CultureInfo.InvariantCulture),14} | {bid?.Price.ToString(CultureInfo.InvariantCulture),-14} [{bid?.Quantity.ToString(CultureInfo.InvariantCulture),-14}]");
}
return stringBuilder.ToString();
}
@@ -636,6 +637,7 @@ namespace CryptoExchange.Net.OrderBook
_queueEvent.Set();
// Clear queue
while (_processQueue.TryDequeue(out _)) { }
_processBuffer.Clear();
_bookSet = false;
DoReset();
@@ -732,7 +734,7 @@ namespace CryptoExchange.Net.OrderBook
var (prevBestBid, prevBestAsk) = BestOffers;
ProcessRangeUpdates(item.StartUpdateId, item.EndUpdateId, item.Bids, item.Asks);
if (!_asks.Any() || !_bids.Any())
if (_asks.Count == 0 || _bids.Count == 0)
return;
if (_asks.First().Key < _bids.First().Key)
@@ -32,9 +32,9 @@ namespace CryptoExchange.Net.RateLimiting.Guards
private readonly IEnumerable<IGuardFilter> _filters;
private readonly Dictionary<string, IWindowTracker> _trackers;
private RateLimitWindowType _windowType;
private double? _decayRate;
private int? _connectionWeight;
private readonly RateLimitWindowType _windowType;
private readonly double? _decayRate;
private readonly int? _connectionWeight;
private readonly Func<RequestDefinition, string, string?, string> _keySelector;
/// <inheritdoc />
@@ -68,8 +68,9 @@ namespace CryptoExchange.Net.RateLimiting.Interfaces
/// <param name="baseAddress">The host address</param>
/// <param name="apiKey">The API key</param>
/// <param name="behaviour">Behaviour when rate limit is hit</param>
/// <param name="requestWeight">The weight to apply to the limit guard</param>
/// <param name="ct">Cancelation token</param>
/// <returns>Error if RateLimitingBehaviour is Fail and rate limit is hit</returns>
Task<CallResult> ProcessSingleAsync(ILogger logger, int itemId, IRateLimitGuard guard, RateLimitItemType type, RequestDefinition definition, string baseAddress, string? apiKey, RateLimitingBehaviour behaviour, CancellationToken ct);
Task<CallResult> ProcessSingleAsync(ILogger logger, int itemId, IRateLimitGuard guard, RateLimitItemType type, RequestDefinition definition, string baseAddress, string? apiKey, int requestWeight, RateLimitingBehaviour behaviour, CancellationToken ct);
}
}
@@ -69,6 +69,7 @@ namespace CryptoExchange.Net.RateLimiting
RequestDefinition definition,
string host,
string? apiKey,
int requestWeight,
RateLimitingBehaviour rateLimitingBehaviour,
CancellationToken ct)
{
@@ -77,7 +78,7 @@ namespace CryptoExchange.Net.RateLimiting
_waitingCount++;
try
{
return await CheckGuardsAsync(new IRateLimitGuard[] { guard }, logger, itemId, type, definition, host, apiKey, 1, rateLimitingBehaviour, ct).ConfigureAwait(false);
return await CheckGuardsAsync(new IRateLimitGuard[] { guard }, logger, itemId, type, definition, host, apiKey, requestWeight, rateLimitingBehaviour, ct).ConfigureAwait(false);
}
catch (TaskCanceledException)
{
@@ -38,7 +38,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers
if (Current == 0)
{
throw new Exception("Request limit reached without any prior request. " +
$"This request can never execute with the current rate limiter. Request weight: {weight}, Ratelimit: {Limit}");
$"This request can never execute with the current rate limiter. Request weight: {weight}, RateLimit: {Limit}");
}
// Determine the time to wait before this weight can be applied without going over the rate limit
@@ -45,7 +45,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers
if (Current == 0)
{
throw new Exception("Request limit reached without any prior request. " +
$"This request can never execute with the current rate limiter. Request weight: {weight}, Ratelimit: {Limit}");
$"This request can never execute with the current rate limiter. Request weight: {weight}, RateLimit: {Limit}");
}
// Determine the time to wait before this weight can be applied without going over the rate limit
@@ -41,7 +41,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers
if (Current == 0)
{
throw new Exception("Request limit reached without any prior request. " +
$"This request can never execute with the current rate limiter. Request weight: {weight}, Ratelimit: {Limit}");
$"This request can never execute with the current rate limiter. Request weight: {weight}, RateLimit: {Limit}");
}
// Determine the time to wait before this weight can be applied without going over the rate limit
@@ -40,7 +40,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers
if (Current == 0)
{
throw new Exception("Request limit reached without any prior request. " +
$"This request can never execute with the current rate limiter. Request weight: {weight}, Ratelimit: {Limit}");
$"This request can never execute with the current rate limiter. Request weight: {weight}, RateLimit: {Limit}");
}
// Determine the time to wait before this weight can be applied without going over the rate limit
@@ -102,7 +102,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers
}
throw new Exception("Request not possible to execute with current rate limit guard. " +
$" Request weight: {requestWeight}, Ratelimit: {Limit}");
$" Request weight: {requestWeight}, RateLimit: {Limit}");
}
}
}
@@ -37,7 +37,7 @@ namespace CryptoExchange.Net.Requests
_httpClient = CreateClient(proxy, requestTimeout);
}
private HttpClient CreateClient(ApiProxy? proxy, TimeSpan requestTimeout)
private static HttpClient CreateClient(ApiProxy? proxy, TimeSpan requestTimeout)
{
var handler = new HttpClientHandler();
try
@@ -46,6 +46,7 @@ namespace CryptoExchange.Net.Requests
handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
}
catch (PlatformNotSupportedException) { }
catch (NotImplementedException) { } // Mono runtime throws NotImplementedException
if (proxy != null)
{
@@ -5,6 +5,14 @@
/// </summary>
public enum SharedKlineInterval
{
/// <summary>
/// 1 min
/// </summary>
OneMinute = 60,
/// <summary>
/// 3 min
/// </summary>
ThreeMinutes = 60 * 3,
/// <summary>
/// 5 min
/// </summary>
@@ -14,10 +22,34 @@
/// </summary>
FifteenMinutes = 60 * 15,
/// <summary>
/// Thirty minutes
/// </summary>
ThirtyMinutes = 60 * 30,
/// <summary>
/// 1 hour
/// </summary>
OneHour = 60 * 60,
/// <summary>
/// 2 hours
/// </summary>
TwoHours = 60 * 60 * 2,
/// <summary>
/// 4 hours
/// </summary>
FourHours = 60 * 60 * 4,
/// <summary>
/// 6 hours
/// </summary>
SixHours = 60 * 60 * 6,
/// <summary>
/// 8 hours
/// </summary>
EightHours = 60 * 60 * 8,
/// <summary>
/// 12 hours
/// </summary>
TwelveHours = 60 * 60 * 12,
/// <summary>
/// 1 day
/// </summary>
OneDay = 60 * 60 * 24,
@@ -21,9 +21,10 @@ namespace CryptoExchange.Net.SharedApis
evnt.StreamId,
evnt.Symbol,
evnt.OriginalData,
evnt.Timestamp,
evnt.ReceiveTime,
evnt.UpdateType)
{
DataTime = evnt.DataTime;
Exchange = exchange;
}
@@ -10,7 +10,7 @@ namespace CryptoExchange.Net.SharedApis
public class ExchangeParameters
{
private readonly List<ExchangeParameter> _parameters;
private static List<ExchangeParameter> _staticParameters = new List<ExchangeParameter>();
private readonly static List<ExchangeParameter> _staticParameters = new List<ExchangeParameter>();
/// <summary>
/// ctor
@@ -132,7 +132,6 @@ namespace CryptoExchange.Net.SharedApis
NextPageToken = nextPageToken;
}
/// <summary>
/// Copy the ExchangeWebResult to a new data type
/// </summary>
@@ -31,9 +31,17 @@ namespace CryptoExchange.Net.SharedApis
{
SupportIntervals = new[]
{
SharedKlineInterval.OneMinute,
SharedKlineInterval.ThreeMinutes,
SharedKlineInterval.FiveMinutes,
SharedKlineInterval.FifteenMinutes,
SharedKlineInterval.ThirtyMinutes,
SharedKlineInterval.OneHour,
SharedKlineInterval.TwoHours,
SharedKlineInterval.FourHours,
SharedKlineInterval.SixHours,
SharedKlineInterval.EightHours,
SharedKlineInterval.TwelveHours,
SharedKlineInterval.OneDay,
SharedKlineInterval.OneWeek,
SharedKlineInterval.OneMonth
@@ -22,10 +22,17 @@ namespace CryptoExchange.Net.SharedApis
{
SupportIntervals = new[]
{
SharedKlineInterval.OneMinute,
SharedKlineInterval.ThreeMinutes,
SharedKlineInterval.FiveMinutes,
SharedKlineInterval.FifteenMinutes,
SharedKlineInterval.ThirtyMinutes,
SharedKlineInterval.OneHour,
SharedKlineInterval.FifteenMinutes,
SharedKlineInterval.TwoHours,
SharedKlineInterval.FourHours,
SharedKlineInterval.SixHours,
SharedKlineInterval.EightHours,
SharedKlineInterval.TwelveHours,
SharedKlineInterval.OneDay,
SharedKlineInterval.OneWeek,
SharedKlineInterval.OneMonth
@@ -46,6 +46,10 @@
/// </summary>
public int? PriceDecimals { get; set; }
/// <summary>
/// The max amount of significant figures to use for price. For example with value of 5 these values are valid: 0.00001, 0.12300, 123.53, 12345, but this is not: 12345.1
/// </summary>
public int? PriceSignificantFigures { get; set; }
/// <summary>
/// Whether the symbol is currently available for trading
/// </summary>
public bool Trading { get; set; }
@@ -1,12 +1,13 @@
using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// A symbol representation based on a base and quote asset
/// </summary>
public class SharedSymbol
public record SharedSymbol
{
/// <summary>
/// The base asset of the symbol
@@ -46,14 +46,14 @@ namespace CryptoExchange.Net.Sockets
private bool _disposed;
private ProcessState _processState;
private DateTime _lastReconnectTime;
private string _baseAddress;
private readonly string _baseAddress;
private int _reconnectAttempt;
private const int _receiveBufferSize = 1048576;
private const int _sendBufferSize = 4096;
/// <summary>
/// Received messages, the size and the timstamp
/// Received messages, the size and the timestamp
/// </summary>
protected readonly List<ReceiveItem> _receivedMessages;
@@ -96,7 +96,7 @@ namespace CryptoExchange.Net.Sockets
{
UpdateReceivedMessages();
if (!_receivedMessages.Any())
if (_receivedMessages.Count == 0)
return 0;
return Math.Round(_receivedMessages.Sum(v => v.Bytes) / 1000d / 3d);
@@ -219,7 +219,7 @@ namespace CryptoExchange.Net.Sockets
if (Parameters.RateLimiter != null)
{
var definition = new RequestDefinition(Uri.AbsolutePath, HttpMethod.Get) { ConnectionId = Id };
var limitResult = await Parameters.RateLimiter.ProcessAsync(_logger, Id, RateLimitItemType.Connection, definition, _baseAddress, null, 1, Parameters.RateLimitingBehaviour, _ctsSource.Token).ConfigureAwait(false);
var limitResult = await Parameters.RateLimiter.ProcessAsync(_logger, Id, RateLimitItemType.Connection, definition, _baseAddress, null, 1, Parameters.RateLimitingBehavior, _ctsSource.Token).ConfigureAwait(false);
if (!limitResult)
return new CallResult(new ClientRateLimitError("Connection limit reached"));
}
@@ -296,7 +296,7 @@ namespace CryptoExchange.Net.Sockets
await (OnReconnecting?.Invoke() ?? Task.CompletedTask).ConfigureAwait(false);
}
// Delay here to prevent very repid looping when a connection to the server is accepted and immediately disconnected
// Delay here to prevent very rapid looping when a connection to the server is accepted and immediately disconnected
var initialDelay = GetReconnectDelay();
await Task.Delay(initialDelay).ConfigureAwait(false);
@@ -491,7 +491,7 @@ namespace CryptoExchange.Net.Sockets
{
try
{
if (!_sendBuffer.Any())
if (_sendBuffer.IsEmpty)
await _sendEvent.WaitAsync(ct: _ctsSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
@@ -508,7 +508,7 @@ namespace CryptoExchange.Net.Sockets
{
try
{
var limitResult = await Parameters.RateLimiter.ProcessAsync(_logger, data.Id, RateLimitItemType.Request, requestDefinition, _baseAddress, null, data.Weight, Parameters.RateLimitingBehaviour, _ctsSource.Token).ConfigureAwait(false);
var limitResult = await Parameters.RateLimiter.ProcessAsync(_logger, data.Id, RateLimitItemType.Request, requestDefinition, _baseAddress, null, data.Weight, Parameters.RateLimitingBehavior, _ctsSource.Token).ConfigureAwait(false);
if (!limitResult)
{
await (OnRequestRateLimited?.Invoke(data.Id) ?? Task.CompletedTask).ConfigureAwait(false);
@@ -587,15 +587,27 @@ namespace CryptoExchange.Net.Sockets
lock (_receivedMessagesLock)
_receivedMessages.Add(new ReceiveItem(DateTime.UtcNow, receiveResult.Count));
}
catch (OperationCanceledException)
catch (OperationCanceledException ex)
{
if (ex.InnerException?.InnerException?.Message.Equals("The WebSocket didn't receive a Pong frame in response to a Ping frame within the configured KeepAliveTimeout.") == true)
{
// Specific case that the websocket connection got closed because of a ping frame timeout
// Unfortunately doesn't seem to be a nicer way to catch
_logger.SocketPingTimeout(Id);
}
if (_closeTask?.IsCompleted != false)
_closeTask = CloseInternalAsync();
// canceled
break;
}
catch (Exception wse)
{
// Connection closed unexpectedly
await (OnError?.Invoke(wse) ?? Task.CompletedTask).ConfigureAwait(false);
if (!_ctsSource.Token.IsCancellationRequested && !_stopRequested)
// Connection closed unexpectedly
await (OnError?.Invoke(wse) ?? Task.CompletedTask).ConfigureAwait(false);
if (_closeTask?.IsCompleted != false)
_closeTask = CloseInternalAsync();
break;
@@ -667,11 +679,11 @@ namespace CryptoExchange.Net.Sockets
if (multiPartMessage)
{
// When the connection gets interupted we might not have received a full message
// When the connection gets interrupted we might not have received a full message
if (receiveResult?.EndOfMessage == true)
{
_logger.SocketReassembledMessage(Id, multipartStream!.Length);
// Get the underlying buffer of the memorystream holding the written data and delimit it (GetBuffer return the full array, not only the written part)
// Get the underlying buffer of the memory stream holding the written data and delimit it (GetBuffer return the full array, not only the written part)
await ProcessData(receiveResult.MessageType, new ReadOnlyMemory<byte>(multipartStream.GetBuffer(), 0, (int)multipartStream.Length)).ConfigureAwait(false);
}
else
@@ -698,7 +710,7 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Proccess a stream message
/// Process a stream message
/// </summary>
/// <param name="type"></param>
/// <param name="data"></param>
@@ -730,6 +742,7 @@ namespace CryptoExchange.Net.Sockets
_ = ReconnectAsync().ConfigureAwait(false);
return;
}
try
{
await Task.Delay(500, _ctsSource.Token).ConfigureAwait(false);
@@ -143,7 +143,7 @@ namespace CryptoExchange.Net.Sockets
public DateTime? DisconnectTime { get; set; }
/// <summary>
/// Tag for identificaion
/// Tag for identification
/// </summary>
public string Tag { get; set; }
@@ -214,7 +214,7 @@ namespace CryptoExchange.Net.Sockets
private readonly IByteMessageAccessor _accessor;
/// <summary>
/// The task that is sending periodic data on the websocket. Can be used for sending Ping messages every x seconds or similair. Not necesarry.
/// The task that is sending periodic data on the websocket. Can be used for sending Ping messages every x seconds or similar. Not necessary.
/// </summary>
protected Task? periodicTask;
@@ -286,7 +286,7 @@ namespace CryptoExchange.Net.Sockets
foreach (var query in _listeners.OfType<Query>().ToList())
{
query.Fail(new WebError("Connection interupted"));
query.Fail(new WebError("Connection interrupted"));
_listeners.Remove(query);
}
}
@@ -311,7 +311,7 @@ namespace CryptoExchange.Net.Sockets
foreach (var query in _listeners.OfType<Query>().ToList())
{
query.Fail(new WebError("Connection interupted"));
query.Fail(new WebError("Connection interrupted"));
_listeners.Remove(query);
}
}
@@ -340,7 +340,7 @@ namespace CryptoExchange.Net.Sockets
{
foreach (var query in _listeners.OfType<Query>().ToList())
{
query.Fail(new WebError("Connection interupted"));
query.Fail(new WebError("Connection interrupted"));
_listeners.Remove(query);
}
}
@@ -369,7 +369,7 @@ namespace CryptoExchange.Net.Sockets
}
catch(Exception ex)
{
_logger.UnkownExceptionWhileProcessingReconnection(SocketId, ex);
_logger.UnknownExceptionWhileProcessingReconnection(SocketId, ex);
_ = _socket.ReconnectAsync().ConfigureAwait(false);
}
});
@@ -392,7 +392,7 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Handler for whenever a request is rate limited and rate limit behaviour is set to fail
/// Handler for whenever a request is rate limited and rate limit behavior is set to fail
/// </summary>
/// <param name="requestId"></param>
/// <returns></returns>
@@ -172,7 +172,7 @@ namespace CryptoExchange.Net.Testing.Comparers
throw new Exception($"{method}: Property `{propertyName}` has no value while input json `{propName}` has value {propValue}");
}
if (propertyValue == default && (propValue.Type == JTokenType.Null || string.IsNullOrEmpty(propValue.ToString())) || propValue.ToString() == "0")
if ((propertyValue == default && (propValue.Type == JTokenType.Null || string.IsNullOrEmpty(propValue.ToString()))) || propValue.ToString() == "0")
return;
if (propertyValue!.GetType().GetInterfaces().Contains(typeof(IDictionary)))
@@ -69,11 +69,11 @@ namespace CryptoExchange.Net.Testing.Comparers
}
else if (jsonObject!.Type == JTokenType.Array)
{
var jObjs = (JArray)jsonObject;
var jArray = (JArray)jsonObject;
if (resultData is IEnumerable list)
{
var enumerator = list.GetEnumerator();
foreach (var jObj in jObjs)
foreach (var jObj in jArray)
{
if (!enumerator.MoveNext())
{
@@ -105,7 +105,7 @@ namespace CryptoExchange.Net.Testing.Comparers
int i = 0;
foreach (var item in jObj.Children())
{
var arrayProp = resultProps.Where(p => p.Item2 != null).SingleOrDefault(p => p.Item2!.Index == i).p;
var arrayProp = resultProps.Where(p => p.Item2 != null).FirstOrDefault(p => p.Item2!.Index == i).p;
if (arrayProp != null)
CheckPropertyValue(method, item, arrayProp.GetValue(resultObj), arrayProp.PropertyType, arrayProp.Name, "Array index " + i, ignoreProperties!);
i++;
@@ -123,7 +123,7 @@ namespace CryptoExchange.Net.Testing.Comparers
{
var resultProps = resultData.GetType().GetProperties().Select(p => (p, p.GetCustomAttributes(typeof(ArrayPropertyAttribute), true).Cast<ArrayPropertyAttribute>().SingleOrDefault()));
int i = 0;
foreach (var item in jObjs.Children())
foreach (var item in jArray.Children())
{
var arrayProp = resultProps.Where(p => p.Item2 != null).SingleOrDefault(p => p.Item2!.Index == i).p;
if (arrayProp != null)
@@ -196,7 +196,7 @@ namespace CryptoExchange.Net.Testing.Comparers
throw new Exception($"{method}: Property `{propertyName}` has no value while input json `{propName}` has value {propValue}");
}
if (propertyValue == default && (propValue.Type == JTokenType.Null || string.IsNullOrEmpty(propValue.ToString())) || propValue.ToString() == "0")
if ((propertyValue == default && (propValue.Type == JTokenType.Null || string.IsNullOrEmpty(propValue.ToString()))) || propValue.ToString() == "0")
return;
if (propertyValue!.GetType().GetInterfaces().Contains(typeof(IDictionary)))
@@ -227,10 +227,10 @@ namespace CryptoExchange.Net.Testing.Comparers
if (propValue.Type != JTokenType.Array)
return;
var jObjs = (JArray)propValue;
var jArray = (JArray)propValue;
var list = (IEnumerable)propertyValue;
var enumerator = list.GetEnumerator();
foreach (JToken jtoken in jObjs)
foreach (JToken jToken in jArray)
{
var moved = enumerator.MoveNext();
if (!moved)
@@ -241,9 +241,9 @@ namespace CryptoExchange.Net.Testing.Comparers
// Custom converter for the type, skip
continue;
if (jtoken.Type == JTokenType.Object)
if (jToken.Type == JTokenType.Object)
{
foreach (var subProp in ((JObject)jtoken).Properties())
foreach (var subProp in ((JObject)jToken).Properties())
{
if (ignoreProperties?.Contains(subProp.Name) == true)
continue;
@@ -251,7 +251,7 @@ namespace CryptoExchange.Net.Testing.Comparers
CheckObject(method, subProp, enumerator.Current, ignoreProperties);
}
}
else if (jtoken.Type == JTokenType.Array)
else if (jToken.Type == JTokenType.Array)
{
var resultObj = enumerator.Current;
var resultProps = resultObj.GetType().GetProperties().Select(p => (p, p.GetCustomAttributes(typeof(ArrayPropertyAttribute), true).Cast<ArrayPropertyAttribute>().SingleOrDefault()));
@@ -262,11 +262,11 @@ namespace CryptoExchange.Net.Testing.Comparers
continue;
int i = 0;
foreach (var item in jtoken.Children())
foreach (var item in jToken.Children())
{
var arrayProp = resultProps.Where(p => p.Item2 != null).SingleOrDefault(p => p.Item2!.Index == i).p;
var arrayProp = resultProps.Where(p => p.Item2 != null).FirstOrDefault(p => p.Item2!.Index == i).p;
if (arrayProp != null)
CheckPropertyValue(method, item, arrayProp.GetValue(resultObj), propertyType, arrayProp.Name, "Array index " + i, ignoreProperties);
CheckPropertyValue(method, item, arrayProp.GetValue(resultObj), arrayProp.PropertyType, arrayProp.Name, "Array index " + i, ignoreProperties);
i++;
}
@@ -274,10 +274,10 @@ namespace CryptoExchange.Net.Testing.Comparers
else
{
var value = enumerator.Current;
if (value == default && ((JValue)jtoken).Type != JTokenType.Null)
throw new Exception($"{method}: Property `{propertyName}` has no value while input json `{propName}` has value {jtoken}");
if (value == default && ((JValue)jToken).Type != JTokenType.Null)
throw new Exception($"{method}: Property `{propertyName}` has no value while input json `{propName}` has value {jToken}");
CheckValues(method, propertyName!, propertyType, (JValue)jtoken, value!);
CheckValues(method, propertyName!, propertyType, (JValue)jToken, value!);
}
}
}
@@ -298,11 +298,11 @@ namespace CryptoExchange.Net.Testing.Comparers
}
else if (propValue.Type == JTokenType.Array)
{
var jObjs = (JArray)propValue;
var jArray = (JArray)propValue;
if (propertyValue is IEnumerable list)
{
var enumerator = list.GetEnumerator();
foreach (var jObj in jObjs)
foreach (var jObj in jArray)
{
if (!enumerator.MoveNext())
{
@@ -348,9 +348,9 @@ namespace CryptoExchange.Net.Testing.Comparers
{
var resultProps = propertyValue.GetType().GetProperties().Select(p => (p, p.GetCustomAttributes(typeof(ArrayPropertyAttribute), true).Cast<ArrayPropertyAttribute>().SingleOrDefault()));
int i = 0;
foreach (var item in jObjs.Children())
foreach (var item in jArray.Children())
{
var arrayProp = resultProps.Where(p => p.Item2 != null).SingleOrDefault(p => p.Item2!.Index == i).p;
var arrayProp = resultProps.Where(p => p.Item2 != null).FirstOrDefault(p => p.Item2!.Index == i).p;
if (arrayProp != null)
CheckPropertyValue(method, item, arrayProp.GetValue(propertyValue), arrayProp.PropertyType, arrayProp.Name, "Array index " + i, ignoreProperties!);
i++;
@@ -11,7 +11,7 @@ namespace CryptoExchange.Net.Testing
/// Base class for executing REST API integration tests
/// </summary>
/// <typeparam name="TClient">Client type</typeparam>
public abstract class RestIntergrationTest<TClient>
public abstract class RestIntegrationTest<TClient>
{
/// <summary>
/// Get a client instance
@@ -113,7 +113,6 @@ namespace CryptoExchange.Net.Testing
if (lastMessage == null)
throw new Exception($"{name} expected to {line} to be send to server but did not receive anything");
var lastMessageJson = JToken.Parse(lastMessage);
var expectedJson = JToken.Parse(line.Substring(2));
foreach(var item in expectedJson)
@@ -133,7 +132,9 @@ namespace CryptoExchange.Net.Testing
overrideValue = lastMessageJson[prop.Name]?.Value<decimal>().ToString();
}
else if (lastMessageJson[prop.Name]?.Value<string>() != val.ToString() && ignoreProperties?.Contains(prop.Name) != true)
{
throw new Exception($"{name} Expected {prop.Name} to be {val}, but was {lastMessageJson[prop.Name]?.Value<string>()}");
}
}
// TODO check objects and arrays
+14 -8
View File
@@ -150,9 +150,9 @@ namespace CryptoExchange.Net.Testing
/// </summary>
/// <typeparam name="TClient"></typeparam>
/// <exception cref="Exception"></exception>
public static void CheckForMissingRestInterfaces<TClient>()
public static void CheckForMissingRestInterfaces<TClient>(string[]? excludeInterfaces = null)
{
CheckForMissingInterfaces(typeof(TClient), typeof(Task));
CheckForMissingInterfaces(typeof(TClient), typeof(Task), excludeInterfaces);
}
/// <summary>
@@ -160,26 +160,32 @@ namespace CryptoExchange.Net.Testing
/// </summary>
/// <typeparam name="TClient"></typeparam>
/// <exception cref="Exception"></exception>
public static void CheckForMissingSocketInterfaces<TClient>()
public static void CheckForMissingSocketInterfaces<TClient>(string[]? excludeInterfaces = null)
{
CheckForMissingInterfaces(typeof(TClient), typeof(Task<CallResult<UpdateSubscription>>));
CheckForMissingInterfaces(typeof(TClient), typeof(Task<CallResult<UpdateSubscription>>), excludeInterfaces);
}
private static void CheckForMissingInterfaces(Type clientType, Type implementationTypes)
private static void CheckForMissingInterfaces(Type clientType, Type implementationTypes, string[]? excludeInterfaces = null)
{
var assembly = Assembly.GetAssembly(clientType);
var interfaceType = clientType.GetInterface("I" + clientType.Name);
var clientInterfaces = assembly!.GetTypes().Where(t => t.Name.StartsWith("I" + clientType.Name) && !t.Name.EndsWith("Shared"));
var clientInterfaces = assembly!.GetTypes()
.Where(t => t.Name.StartsWith("I" + clientType.Name)
&& !t.Name.EndsWith("Shared")
&& (excludeInterfaces?.Contains(t.Name) != true));
foreach (var clientInterface in clientInterfaces)
{
var implementations = assembly.GetTypes().Where(t => clientInterface.IsAssignableFrom(t) && t != clientInterface);
var implementations = assembly.GetTypes().Where(t => clientInterface.IsAssignableFrom(t) && !t.IsInterface && t != clientInterface);
foreach (var implementation in implementations)
{
int methods = 0;
foreach (var method in implementation.GetMethods().Where(m => implementationTypes.IsAssignableFrom(m.ReturnType)))
{
var interfaceMethod = clientInterface.GetMethod(method.Name, method.GetParameters().Select(p => p.ParameterType).ToArray()) ?? throw new Exception($"Missing interface for method {method.Name} in {implementation.Name} implementing interface {clientInterface.Name}");
var interfaceMethod =
clientInterface.GetMethod(method.Name, method.GetParameters().Select(p => p.ParameterType).ToArray())
?? clientInterface.GetInterfaces().Select(x => x.GetMethod(method.Name, method.GetParameters().Select(p => p.ParameterType).ToArray())).FirstOrDefault()
?? throw new Exception($"Missing interface for method {method.Name} in {implementation.Name} implementing interface {clientInterface.Name}");
methods++;
}
@@ -94,7 +94,7 @@ namespace CryptoExchange.Net.Trackers.Klines
IEnumerable<SharedKline> GetData(DateTime? fromTimestamp = null, DateTime? toTimestamp = null);
/// <summary>
/// Get statitistics on the klines
/// Get statistics on the klines
/// </summary>
/// <param name="fromTimestamp">Start timestamp to get the data from, defaults to tracked data start time</param>
/// <param name="toTimestamp">End timestamp to get the data until, defaults to current time</param>
@@ -90,7 +90,7 @@ namespace CryptoExchange.Net.Trackers.Trades
IEnumerable<SharedTrade> GetData(DateTime? fromTimestamp = null, DateTime? toTimestamp = null);
/// <summary>
/// Get statitistics on the trades
/// Get statistics on the trades
/// </summary>
/// <param name="fromTimestamp">Start timestamp to get the data from, defaults to tracked data start time</param>
/// <param name="toTimestamp">End timestamp to get the data until, defaults to current time</param>
@@ -163,7 +163,7 @@ namespace CryptoExchange.Net.Trackers.Trades
Period = period;
}
private TradesStats GetStats(IEnumerable<SharedTrade> trades)
private static TradesStats GetStats(IEnumerable<SharedTrade> trades)
{
if (!trades.Any())
return new TradesStats();
@@ -350,7 +350,7 @@ namespace CryptoExchange.Net.Trackers.Trades
_data.Add(item);
}
if (_data.Any())
if (_data.Count != 0)
_firstTimestamp = _data.Min(v => v.Timestamp);
ApplyWindow(false);
@@ -431,7 +431,6 @@ namespace CryptoExchange.Net.Trackers.Trades
SetSyncStatus();
}
private void HandleConnectionLost()
{
_logger.TradeTrackerConnectionLost(SymbolName);
@@ -47,7 +47,7 @@ namespace CryptoExchange.Net.Trackers.Trades
public bool Complete { get; set; }
/// <summary>
/// Compare 2 stat snapshots to eachother
/// Compare 2 stat snapshots to each other
/// </summary>
public TradesCompare CompareTo(TradesStats otherStats)
{
+19 -17
View File
@@ -5,23 +5,25 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Binance.Net" Version="10.9.0" />
<PackageReference Include="Bitfinex.Net" Version="7.10.0" />
<PackageReference Include="BitMart.Net" Version="1.7.0" />
<PackageReference Include="Bybit.Net" Version="3.16.0" />
<PackageReference Include="CoinEx.Net" Version="7.9.0" />
<PackageReference Include="CryptoCom.Net" Version="1.2.0" />
<PackageReference Include="GateIo.Net" Version="1.12.0" />
<PackageReference Include="JK.BingX.Net" Version="1.14.0" />
<PackageReference Include="JK.Bitget.Net" Version="1.13.0" />
<PackageReference Include="JK.Mexc.Net" Version="1.11.0" />
<PackageReference Include="JK.OKX.Net" Version="2.8.0" />
<PackageReference Include="JKorf.Coinbase.Net" Version="1.4.0" />
<PackageReference Include="JKorf.HTX.Net" Version="6.4.0" />
<PackageReference Include="KrakenExchange.Net" Version="5.2.0" />
<PackageReference Include="Kucoin.Net" Version="5.18.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="WhiteBit.Net" Version="1.0.0" />
<PackageReference Include="Binance.Net" Version="10.16.2" />
<PackageReference Include="Bitfinex.Net" Version="8.0.2" />
<PackageReference Include="BitMart.Net" Version="1.12.2" />
<PackageReference Include="Bybit.Net" Version="4.0.2" />
<PackageReference Include="CoinEx.Net" Version="7.14.0" />
<PackageReference Include="CryptoCom.Net" Version="1.5.1" />
<PackageReference Include="GateIo.Net" Version="1.18.0" />
<PackageReference Include="HyperLiquid.Net" Version="1.0.1" />
<PackageReference Include="JK.BingX.Net" Version="1.20.1" />
<PackageReference Include="JK.Bitget.Net" Version="1.20.0" />
<PackageReference Include="JK.Mexc.Net" Version="2.0.0" />
<PackageReference Include="JK.OKX.Net" Version="2.14.2" />
<PackageReference Include="JKorf.BitMEX.Net" Version="1.0.0" />
<PackageReference Include="JKorf.Coinbase.Net" Version="1.7.2" />
<PackageReference Include="JKorf.HTX.Net" Version="6.8.2" />
<PackageReference Include="KrakenExchange.Net" Version="5.6.0" />
<PackageReference Include="Kucoin.Net" Version="5.23.5" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageReference Include="WhiteBit.Net" Version="1.3.2" />
</ItemGroup>
</Project>
+17 -3
View File
@@ -2,14 +2,16 @@
@inject IBinanceRestClient binanceClient
@inject IBingXRestClient bingXClient
@inject IBitfinexRestClient bitfinexClient
@inject IBitMartRestClient bitmartClient
@inject IBitgetRestClient bitgetClient
@inject IBitMartRestClient bitmartClient
@inject IBitMEXRestClient bitmexClient
@inject IBybitRestClient bybitClient
@inject ICoinbaseRestClient coinbaseClient
@inject ICoinExRestClient coinexClient
@inject ICryptoComRestClient cryptocomClient
@inject IGateIoRestClient gateioClient
@inject IHTXRestClient huobiClient
@inject IHTXRestClient htxClient
@inject IHyperLiquidRestClient hyperLiquidClient
@inject IKrakenRestClient krakenClient
@inject IKucoinRestClient kucoinClient
@inject IMexcRestClient mexcClient
@@ -32,12 +34,14 @@
var bitfinexTask = bitfinexClient.SpotApi.ExchangeData.GetTickerAsync("tBTCUSD");
var bitgetTask = bitgetClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT_SPBL");
var bitmartTask = bitmartClient.SpotApi.ExchangeData.GetTickerAsync("BTC_USDT");
var bitmexTask = bitmexClient.ExchangeApi.ExchangeData.GetSymbolsAsync("XBT_USDT");
var bybitTask = bybitClient.V5Api.ExchangeData.GetSpotTickersAsync("BTCUSDT");
var coinbaseTask = coinbaseClient.AdvancedTradeApi.ExchangeData.GetSymbolAsync("BTC-USDT");
var coinexTask = coinexClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT");
var cryptocomTask = cryptocomClient.ExchangeApi.ExchangeData.GetTickersAsync("BTC_USDT");
var gateioTask = gateioClient.SpotApi.ExchangeData.GetTickersAsync("BTC_USDT");
var htxTask = huobiClient.SpotApi.ExchangeData.GetTickerAsync("btcusdt");
var htxTask = htxClient.SpotApi.ExchangeData.GetTickerAsync("btcusdt");
var hyperLiquidTask = hyperLiquidClient.FuturesApi.ExchangeData.GetExchangeInfoAndTickersAsync(); // HyperLiquid does not have BTC spot trading
var krakenTask = krakenClient.SpotApi.ExchangeData.GetTickerAsync("XBTUSD");
var kucoinTask = kucoinClient.SpotApi.ExchangeData.GetTickerAsync("BTC-USDT");
var mexcTask = mexcClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT");
@@ -61,6 +65,9 @@
if (bitmartTask.Result.Success)
_prices.Add("BitMart", bitgetTask.Result.Data.ClosePrice);
if (bitmexTask.Result.Success)
_prices.Add("BitMEX", bitmexTask.Result.Data.First().LastPrice);
if (bybitTask.Result.Success)
_prices.Add("Bybit", bybitTask.Result.Data.List.First().LastPrice);
@@ -79,6 +86,13 @@
if (htxTask.Result.Success)
_prices.Add("HTX", htxTask.Result.Data.ClosePrice ?? 0);
if (hyperLiquidTask.Result.Success)
{
// HyperLiquid API doesn't offer an endpoint to filter for a specific ticker, so we have to filter client side
var tickers = hyperLiquidTask.Result.Data.Tickers;
_prices.Add("HyperLiquid", tickers.Single(x => x.Symbol == "BTC").MidPrice ?? 9);
}
if (krakenTask.Result.Success)
_prices.Add("Kraken", krakenTask.Result.Data.First().Value.LastTrade.Price);
+8 -3
View File
@@ -4,12 +4,14 @@
@inject IBitfinexSocketClient bitfinexSocketClient
@inject IBitgetSocketClient bitgetSocketClient
@inject IBitMartSocketClient bitmartSocketClient
@inject IBitMEXSocketClient bitmexSocketClient
@inject IBybitSocketClient bybitSocketClient
@inject ICoinbaseSocketClient coinbaseSocketClient
@inject ICoinExSocketClient coinExSocketClient
@inject ICryptoComSocketClient cryptocomSocketClient
@inject IGateIoSocketClient gateioSocketClient
@inject IHTXSocketClient htxSocketClient
@inject IHyperLiquidSocketClient hyperLiquidSocketClient
@inject IKrakenSocketClient krakenSocketClient
@inject IKucoinSocketClient kucoinSocketClient
@inject IMexcSocketClient mexcSocketClient
@@ -40,13 +42,16 @@
bitfinexSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("tETHBTC", data => UpdateData("Bitfinex", data.Data.LastPrice)),
bitgetSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETHBTC", data => UpdateData("Bitget", data.Data.LastPrice)),
bitmartSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH_BTC", data => UpdateData("BitMart", data.Data.LastPrice)),
bitmexSocketClient.ExchangeApi.SubscribeToSymbolUpdatesAsync("ETH_XBT", data => UpdateData("BitMEX", data.Data.LastPrice ?? 0)),
bybitSocketClient.V5SpotApi.SubscribeToTickerUpdatesAsync("ETHBTC", data => UpdateData("Bybit", data.Data.LastPrice)),
coinExSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETHBTC", data => UpdateData("CoinEx", data.Data.LastPrice)),
coinbaseSocketClient.AdvancedTradeApi.SubscribeToTickerUpdatesAsync("ETH-BTC", data => UpdateData("Coinbase", data.Data.LastPrice)),
coinExSocketClient.SpotApiV2.SubscribeToTickerUpdatesAsync(["ETHBTC"], data => UpdateData("CoinEx", data.Data.First().LastPrice)),
coinbaseSocketClient.AdvancedTradeApi.SubscribeToTickerUpdatesAsync("ETH-BTC", data => UpdateData("Coinbase", data.Data.LastPrice ?? 0)),
cryptocomSocketClient.ExchangeApi.SubscribeToTickerUpdatesAsync("ETH_BTC", data => UpdateData("CryptoCom", data.Data.LastPrice ?? 0)),
gateioSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH_BTC", data => UpdateData("GateIo", data.Data.LastPrice)),
htxSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ethbtc", data => UpdateData("HTX", data.Data.ClosePrice ?? 0)),
krakenSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH/XBT", data => UpdateData("Kraken", data.Data.LastPrice)),
// HyperLiquid doesn't support the ETH/BTC pair
//hyperLiquidSocketClient.SpotApi.SubscribeToSymbolUpdatesAsync("ETH", data => UpdateData("HyperLiquid", data.Data.MidPrice ?? 0)),
krakenSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH/BTC", data => UpdateData("Kraken", data.Data.LastPrice)),
kucoinSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH-BTC", data => UpdateData("Kucoin", data.Data.LastPrice ?? 0)),
mexcSocketClient.SpotApi.SubscribeToMiniTickerUpdatesAsync("ETHBTC", data => UpdateData("Mexc", data.Data.LastPrice)),
okxSocketClient.UnifiedApi.ExchangeData.SubscribeToTickerUpdatesAsync("ETH-BTC", data => UpdateData("OKX", data.Data.LastPrice ?? 0)),
@@ -6,6 +6,7 @@
@using Bitfinex.Net.Interfaces
@using Bitget.Net.Interfaces;
@using BitMart.Net.Interfaces;
@using BitMEX.Net.Interfaces;
@using Bybit.Net.Interfaces
@using CoinEx.Net.Interfaces
@using Coinbase.Net.Interfaces
@@ -13,6 +14,7 @@
@using CryptoCom.Net.Interfaces
@using GateIo.Net.Interfaces
@using HTX.Net.Interfaces
@using HyperLiquid.Net.Interfaces
@using Kraken.Net.Interfaces
@using Kucoin.Net.Clients
@using Kucoin.Net.Interfaces
@@ -24,12 +26,14 @@
@inject IBitfinexOrderBookFactory bitfinexFactory
@inject IBitgetOrderBookFactory bitgetFactory
@inject IBitMartOrderBookFactory bitmartFactory
@inject IBitMEXOrderBookFactory bitmexFactory
@inject IBybitOrderBookFactory bybitFactory
@inject ICoinbaseOrderBookFactory coinbaseFactory
@inject ICoinExOrderBookFactory coinExFactory
@inject ICryptoComOrderBookFactory cryptocomFactory
@inject IGateIoOrderBookFactory gateioFactory
@inject IHTXOrderBookFactory htxFactory
@inject IHyperLiquidOrderBookFactory hyperLiquidFactory
@inject IKrakenOrderBookFactory krakenFactory
@inject IKucoinOrderBookFactory kucoinFactory
@inject IMexcOrderBookFactory mexcFactory
@@ -73,12 +77,15 @@
{ "Bitfinex", bitfinexFactory.Create("tETHBTC") },
{ "Bitget", bitgetFactory.CreateSpot("ETHBTC") },
{ "BitMart", bitmartFactory.CreateSpot("ETH_BTC", null) },
{ "BitMEX", bitmexFactory.Create("ETH_XBT") },
{ "Bybit", bybitFactory.Create("ETHBTC", Bybit.Net.Enums.Category.Spot) },
{ "Coinbase", coinbaseFactory.Create("ETH-BTC", null) },
{ "CoinEx", coinExFactory.CreateSpot("ETHBTC") },
{ "CryptoCom", cryptocomFactory.Create("ETH_BTC") },
{ "GateIo", gateioFactory.CreateSpot("ETH_BTC") },
{ "HTX", htxFactory.CreateSpot("ethbtc") },
// HyperLiquid does not support the ETH/BTC pair
//{ "HyperLiquid", hyperLiquidFactory.Create("ETH/BTC") },
{ "Kraken", krakenFactory.CreateSpot("ETH/BTC") },
{ "Kucoin", kucoinFactory.CreateSpot("ETH-BTC") },
{ "Mexc", mexcFactory.CreateSpot("ETHBTC") },
+24 -17
View File
@@ -5,6 +5,7 @@
@using BingX.Net.Interfaces
@using Bitfinex.Net.Interfaces
@using Bitget.Net.Interfaces;
@using BitMEX.Net.Interfaces;
@using BitMart.Net.Interfaces;
@using Bybit.Net.Interfaces
@using CoinEx.Net.Interfaces
@@ -15,6 +16,7 @@
@using CryptoExchange.Net.Trackers.Trades
@using GateIo.Net.Interfaces
@using HTX.Net.Interfaces
@using HyperLiquid.Net.Interfaces
@using Kraken.Net.Interfaces
@using Kucoin.Net.Clients
@using Kucoin.Net.Interfaces
@@ -26,12 +28,14 @@
@inject IBitfinexTrackerFactory bitfinexFactory
@inject IBitgetTrackerFactory bitgetFactory
@inject IBitMartTrackerFactory bitmartFactory
@inject IBitMEXTrackerFactory bitmexFactory
@inject IBybitTrackerFactory bybitFactory
@inject ICoinbaseTrackerFactory coinbaseFactory
@inject ICoinExTrackerFactory coinExFactory
@inject ICryptoComTrackerFactory cryptocomFactory
@inject IGateIoTrackerFactory gateioFactory
@inject IHTXTrackerFactory htxFactory
@inject IHyperLiquidTrackerFactory hyperLiquidFactory
@inject IKrakenTrackerFactory krakenFactory
@inject IKucoinTrackerFactory kucoinFactory
@inject IMexcTrackerFactory mexcFactory
@@ -59,26 +63,29 @@
protected override async Task OnInitializedAsync()
{
var symbol = new SharedSymbol(TradingMode.Spot, "BTC", "USDT");
var usdtSymbol = new SharedSymbol(TradingMode.Spot, "BTC", "USDT");
_trackers = new List<ITradeTracker>
{
{ binanceFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bingXFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bitfinexFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bitgetFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bitmartFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ bybitFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ coinbaseFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ coinExFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ cryptocomFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ gateioFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ htxFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ krakenFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ kucoinFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ mexcFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ okxFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ whitebitFactory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5)) },
{ binanceFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ bingXFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ bitfinexFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ bitgetFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ bitmartFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ bitmexFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ bybitFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ coinbaseFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ coinExFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ cryptocomFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ gateioFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ htxFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
// HyperLiquid doesn't support spot pair, but does have a futures BTC/USDC pair
{ hyperLiquidFactory.CreateTradeTracker(new SharedSymbol(TradingMode.PerpetualLinear, "BTC", "USDC"), period: TimeSpan.FromMinutes(5)) },
{ krakenFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ kucoinFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ mexcFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ okxFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
{ whitebitFactory.CreateTradeTracker(usdtSymbol, period: TimeSpan.FromMinutes(5)) },
};
await Task.WhenAll(_trackers.Select(b => b.StartAsync()));
+2
View File
@@ -40,11 +40,13 @@ namespace BlazorClient
services.AddBitfinex();
services.AddBitget();
services.AddBitMart();
services.AddBitMEX();
services.AddBybit();
services.AddCoinbase();
services.AddCoinEx();
services.AddCryptoCom();
services.AddGateIo();
services.AddHyperLiquid();
services.AddHTX();
services.AddKraken();
services.AddKucoin();
+2
View File
@@ -13,12 +13,14 @@
@using Bitfinex.Net.Interfaces.Clients;
@using Bitget.Net.Interfaces.Clients;
@using BitMart.Net.Interfaces.Clients;
@using BitMEX.Net.Interfaces.Clients;
@using Bybit.Net.Interfaces.Clients;
@using Coinbase.Net.Interfaces.Clients;
@using CoinEx.Net.Interfaces.Clients;
@using CryptoCom.Net.Interfaces.Clients;
@using GateIo.Net.Interfaces.Clients;
@using HTX.Net.Interfaces.Clients;
@using HyperLiquid.Net.Interfaces.Clients;
@using Kraken.Net.Interfaces.Clients;
@using Kucoin.Net.Interfaces.Clients;
@using Mexc.Net.Interfaces.Clients;
+41
View File
@@ -17,6 +17,7 @@ The following API's are directly supported. Note that there are 3rd party implem
|Bitfinex|[JKorf/Bitfinex.Net](https://github.com/JKorf/Bitfinex.Net)|[![Nuget version](https://img.shields.io/nuget/v/Bitfinex.net.svg?style=flat-square)](https://www.nuget.org/packages/Bitfinex.Net)|
|Bitget|[JKorf/Bitget.Net](https://github.com/JKorf/Bitget.Net)|[![Nuget version](https://img.shields.io/nuget/v/JK.Bitget.net.svg?style=flat-square)](https://www.nuget.org/packages/JK.Bitget.Net)|
|BitMart|[JKorf/BitMart.Net](https://github.com/JKorf/BitMart.Net)|[![Nuget version](https://img.shields.io/nuget/v/BitMart.net.svg?style=flat-square)](https://www.nuget.org/packages/BitMart.Net)|
|BitMEX|[JKorf/BitMEX.Net](https://github.com/JKorf/BitMEX.Net)|[![Nuget version](https://img.shields.io/nuget/v/JKorf.BitMEX.net.svg?style=flat-square)](https://www.nuget.org/packages/JKorf.BitMEX.Net)|
|Bybit|[JKorf/Bybit.Net](https://github.com/JKorf/Bybit.Net)|[![Nuget version](https://img.shields.io/nuget/v/Bybit.net.svg?style=flat-square)](https://www.nuget.org/packages/Bybit.Net)|
|Coinbase|[JKorf/Coinbase.Net](https://github.com/JKorf/Coinbase.Net)|[![Nuget version](https://img.shields.io/nuget/v/JKorf.Coinbase.Net.svg?style=flat-square)](https://www.nuget.org/packages/JKorf.Coinbase.Net)|
|CoinEx|[JKorf/CoinEx.Net](https://github.com/JKorf/CoinEx.Net)|[![Nuget version](https://img.shields.io/nuget/v/CoinEx.net.svg?style=flat-square)](https://www.nuget.org/packages/CoinEx.Net)|
@@ -24,6 +25,7 @@ The following API's are directly supported. Note that there are 3rd party implem
|Crypto.com|[JKorf/CryptoCom.Net](https://github.com/JKorf/CryptoCom.Net)|[![Nuget version](https://img.shields.io/nuget/v/CryptoCom.net.svg?style=flat-square)](https://www.nuget.org/packages/CryptoCom.Net)|
|Gate.io|[JKorf/GateIo.Net](https://github.com/JKorf/GateIo.Net)|[![Nuget version](https://img.shields.io/nuget/v/GateIo.net.svg?style=flat-square)](https://www.nuget.org/packages/GateIo.Net)|
|HTX|[JKorf/HTX.Net](https://github.com/JKorf/HTX.Net)|[![Nuget version](https://img.shields.io/nuget/v/JKorf.HTX.net.svg?style=flat-square)](https://www.nuget.org/packages/JKorf.HTX.Net)|
|HyperLiquid|[JKorf/HyperLiquid.Net](https://github.com/JKorf/HyperLiquid.Net)|[![Nuget version](https://img.shields.io/nuget/v/HyperLiquid.Net.svg?style=flat-square)](https://www.nuget.org/packages/HyperLiquid.Net)|
|Kraken|[JKorf/Kraken.Net](https://github.com/JKorf/Kraken.Net)|[![Nuget version](https://img.shields.io/nuget/v/KrakenExchange.net.svg?style=flat-square)](https://www.nuget.org/packages/KrakenExchange.Net)|
|Kucoin|[JKorf/Kucoin.Net](https://github.com/JKorf/Kucoin.Net)|[![Nuget version](https://img.shields.io/nuget/v/Kucoin.net.svg?style=flat-square)](https://www.nuget.org/packages/Kucoin.Net)|
|Mexc|[JKorf/Mexc.Net](https://github.com/JKorf/Mexc.Net)|[![Nuget version](https://img.shields.io/nuget/v/JK.Mexc.net.svg?style=flat-square)](https://www.nuget.org/packages/JK.Mexc.Net)|
@@ -50,6 +52,7 @@ When creating an account on new exchanges please consider using a referral link
|CoinEx|[https://www.coinex.com/register?refer_code=hd6gn](https://www.coinex.com/register?refer_code=hd6gn)|
|Crypto.com|[https://crypto.com/exch/26ge92xbkn](https://crypto.com/exch/26ge92xbkn)|
|HTX|[https://www.htx.com/invite/en-us/1f?invite_code=fxp9](https://www.htx.com/invite/en-us/1f?invite_code=fxp9)|
|HyperLiquid|[https://app.hyperliquid.xyz/join/JKORF](https://app.hyperliquid.xyz/join/JKORF)|
|Kucoin|[https://www.kucoin.com/r/rf/QBS4FPED](https://www.kucoin.com/r/rf/QBS4FPED)|
|OKX|[https://okx.com/join/48046699](https://okx.com/join/48046699)|
|WhiteBit|[https://whitebit.com/referral/a8e59b59-186c-4662-824c-3095248e0edf](https://whitebit.com/referral/a8e59b59-186c-4662-824c-3095248e0edf)|
@@ -66,6 +69,44 @@ 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 8.8.0 - 10 Feb 2025
* Split DataEvent.Timestamp in DataEvent.ReceivedTime and DataEvent.DataTime
* Added SharedKlineInterval enum values
* Fixed some typos
* Version 8.7.4 - 08 Feb 2025
* Fixed exception when creating rest client for mono runtime
* Version 8.7.3 - 05 Feb 2025
* Added handling of negative number DateTime deserialization to default
* Updated SharedSymbol from class to record
* Fixed issue with serialization of nullable types in System.Text.Json ArrayConverter
* Fix for unnecessary error message in logging when closing websocket connection
* Version 8.7.2 - 27 Jan 2025
* Some small fixes in the System.Text.Json ArrayConverter
* Added support for Flags enum deserialization in System.Text.Json EnumConverter
* Version 8.7.1 - 24 Jan 2025
* Added Authenticated property to IBaseApiClient interface to check if a client was provided API credentials
* Version 8.7.0 - 21 Jan 2025
* Added GetMillisecondTimestampLong helper method to AuthenticationProvider
* Added PriceSignificationFigures to SharedSpotSymbol model
* Version 8.6.1 - 09 Jan 2025
* Fixed websocket connection getting stuck after a ping frame timeout
* Removed websocket Error callback when exception is expected
* Removed unnecessary type restraints on RestApiClient.SendAsync methods
* Version 8.6.0 - 07 Jan 2025
* Added support for passing weight to apply to an individual ratelimit guard
* Added IFeeRestClient to service registration
* Added response headers parameter to RestApiClient.TryParseError method
* Added check for ServerRateLimitError on RestApiClient.TryParseError response
* Added ExchangeType Enum
* Some small improvements
* Version 8.5.0 - 23 Dec 2024
* Added SetOptions method to update client settings
* Added SocketConnection parameter to PeriodicQuery callback
+231 -2
View File
@@ -151,6 +151,7 @@
<tr><td>Bitfinex</td><td><a href="https://github.com/JKorf/Bitfinex.Net">JKorf/Bitfinex.Net</a></td><td><a href="https://www.nuget.org/packages/Bitfinex.Net" target="_blank"><img src="https://img.shields.io/nuget/v/Bitfinex.net.svg?style=flat-square" /></a></td></tr>
<tr><td>Bitget</td><td><a href="https://github.com/JKorf/Bitget.Net">JKorf/Bitget.Net</a></td><td><a href="https://www.nuget.org/packages/JK.Bitget.Net" target="_blank"><img src="https://img.shields.io/nuget/v/JK.Bitget.net.svg?style=flat-square" /></a></td></tr>
<tr><td>BitMart</td><td><a href="https://github.com/JKorf/BitMart.Net">JKorf/BitMart.Net</a></td><td><a href="https://www.nuget.org/packages/BitMart.Net" target="_blank"><img src="https://img.shields.io/nuget/v/BitMart.net.svg?style=flat-square" /></a></td></tr>
<tr><td>BitMEX</td><td><a href="https://github.com/JKorf/BitMEX.Net">JKorf/BitMEX.Net</a></td><td><a href="https://www.nuget.org/packages/JKorf.BitMEX.Net" target="_blank"><img src="https://img.shields.io/nuget/v/JKorf.BitMEX.net.svg?style=flat-square" /></a></td></tr>
<tr><td>Bybit</td><td><a href="https://github.com/JKorf/Bybit.Net">JKorf/Bybit.Net</a></td><td><a href="https://www.nuget.org/packages/Bybit.Net" target="_blank"><img src="https://img.shields.io/nuget/v/Bybit.net.svg?style=flat-square" /></a></td></tr>
<tr><td>Coinbase</td><td><a href="https://github.com/JKorf/Coinbase.Net">JKorf/Coinbase.Net</a></td><td><a href="https://www.nuget.org/packages/JKorf.Coinbase.Net" target="_blank"><img src="https://img.shields.io/nuget/v/JKorf.Coinbase.net.svg?style=flat-square" /></a></td></tr>
<tr><td>CoinEx</td><td><a href="https://github.com/JKorf/CoinEx.Net">JKorf/CoinEx.Net</a></td><td><a href="https://www.nuget.org/packages/CoinEx.Net" target="_blank"><img src="https://img.shields.io/nuget/v/CoinEx.net.svg?style=flat-square" /></a></td></tr>
@@ -158,6 +159,7 @@
<tr><td>Crypto.com</td><td><a href="https://github.com/JKorf/CryptoCom.Net">JKorf/CryptoCom.Net</a></td><td><a href="https://www.nuget.org/packages/CryptoCom.Net" target="_blank"><img src="https://img.shields.io/nuget/v/CryptoCom.net.svg?style=flat-square" /></a></td></tr>
<tr><td>Gate.io</td><td><a href="https://github.com/JKorf/GateIo.Net">JKorf/GateIo.Net</a></td><td><a href="https://www.nuget.org/packages/GateIo.Net" target="_blank"><img src="https://img.shields.io/nuget/v/GateIo.net.svg?style=flat-square" /></a></td></tr>
<tr><td>HTX</td><td><a href="https://github.com/JKorf/HTX.Net">JKorf/HTX.Net</a></td><td><a href="https://www.nuget.org/packages/JKorf.HTX.Net" target="_blank"><img src="https://img.shields.io/nuget/v/JKorf.HTX.net.svg?style=flat-square" /></a></td></tr>
<tr><td>HyperLiquid</td><td><a href="https://github.com/JKorf/HyperLiquid.Net">JKorf/HyperLiquid.Net</a></td><td><a href="https://www.nuget.org/packages/HyperLiquid.Net" target="_blank"><img src="https://img.shields.io/nuget/v/HyperLiquid.net.svg?style=flat-square" /></a></td></tr>
<tr><td>Kraken</td><td><a href="https://github.com/JKorf/Kraken.Net">JKorf/Kraken.Net</a></td><td><a href="https://www.nuget.org/packages/KrakenExchange.Net" target="_blank"><img src="https://img.shields.io/nuget/v/KrakenExchange.net.svg?style=flat-square" /></a></td></tr>
<tr><td>Kucoin</td><td><a href="https://github.com/JKorf/Kucoin.Net">JKorf/Kucoin.Net</a></td><td><a href="https://www.nuget.org/packages/Kucoin.Net" target="_blank"><img src="https://img.shields.io/nuget/v/Kucoin.net.svg?style=flat-square" /></a></td></tr>
<tr><td>Mexc</td><td><a href="https://github.com/JKorf/Mexc.Net">JKorf/Mexc.Net</a></td><td><a href="https://www.nuget.org/packages/JK.Mexc.Net" target="_blank"><img src="https://img.shields.io/nuget/v/JK.Mexc.net.svg?style=flat-square" /></a></td></tr>
@@ -197,13 +199,14 @@
<b>Referral</b>
<p>When creating an account on new exchanges please consider using a referral link from below to support development</p>
<table>
<tr><td>Exchange</td><td>Link</td></tr>
<table class="table table-bordered">
<tr><th>Exchange</th><th>Link</th></tr>
<tr><td>Bybit</td><td>https://partner.bybit.com/b/jkorf</td></tr>
<tr><td>Coinbase</td><td>https://advanced.coinbase.com/join/T6H54H8</td></tr>
<tr><td>CoinEx</td><td>https://www.coinex.com/register?refer_code=hd6gn</td></tr>
<tr><td>Crypto.com</td><td>https://crypto.com/exch/26ge92xbkn</td></tr>
<tr><td>HTX</td><td>https://www.htx.com/invite/en-us/1f?invite_code=fxp9</td></tr>
<tr><td>HyperLiquid</td><td>https://app.hyperliquid.xyz/join/JKORF</td></tr>
<tr><td>Kucoin</td><td>https://www.kucoin.com/r/rf/QBS4FPED</td></tr>
<tr><td>OKX</td><td>https://okx.com/join/48046699</td></tr>
<tr><td>WhiteBit</td><td>https://whitebit.com/referral/a8e59b59-186c-4662-824c-3095248e0edf</td></tr>
@@ -280,6 +283,9 @@
<li class="nav-item" role="presentation">
<a class="nav-link" id="install-htx-tab" data-toggle="tab" href="#install-htx" role="tab" aria-controls="install-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="install-hyperliquid-tab" data-toggle="tab" href="#install-hyperliquid" role="tab" aria-controls="install-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="install-kraken-tab" data-toggle="tab" href="#install-kraken" role="tab" aria-controls="install-kraken" aria-selected="false">Kraken</a>
</li>
@@ -345,6 +351,9 @@
<div class="tab-pane fade" id="install-htx" role="tabpanel" aria-labelledby="install-htx-tab">
<pre><code>dotnet add package JKorf.HTX.Net</code></pre>
</div>
<div class="tab-pane fade" id="install-hyperliquid" role="tabpanel" aria-labelledby="install-hyperliquid-tab">
<pre><code>dotnet add package HyperLiquid.Net</code></pre>
</div>
<div class="tab-pane fade" id="install-kraken" role="tabpanel" aria-labelledby="install-kraken-tab">
<pre><code>dotnet add package KrakenExchange.Net</code></pre>
<img src="assets/images/KrakenInstall.png" />
@@ -420,6 +429,9 @@
<li class="nav-item" role="presentation">
<a class="nav-link" id="di-htx-tab" data-toggle="tab" href="#di-htx" role="tab" aria-controls="di-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="di-hyperliquid-tab" data-toggle="tab" href="#di-hyperliquid" role="tab" aria-controls="di-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="di-kraken-tab" data-toggle="tab" href="#di-kraken" role="tab" aria-controls="di-kraken" aria-selected="false">Kraken</a>
</li>
@@ -478,6 +490,9 @@
</div>
<div class="tab-pane fade" id="di-htx" role="tabpanel" aria-labelledby="di-htx-tab">
<pre><code>builder.Services.AddHTX();</code></pre>
</div>
<div class="tab-pane fade" id="di-hyperliquid" role="tabpanel" aria-labelledby="di-hyperliquid-tab">
<pre><code>builder.Services.AddHyperLiquid();</code></pre>
</div>
<div class="tab-pane fade" id="di-kraken" role="tabpanel" aria-labelledby="di-kraken-tab">
<pre><code>builder.Services.AddKraken();</code></pre>
@@ -542,6 +557,9 @@
<li class="nav-item" role="presentation">
<a class="nav-link" id="interfaces-htx-tab" data-toggle="tab" href="#interfaces-htx" role="tab" aria-controls="interfaces-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="interfaces-hyperliquid-tab" data-toggle="tab" href="#interfaces-hyperliquid" role="tab" aria-controls="interfaces-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="interfaces-kraken-tab" data-toggle="tab" href="#interfaces-kraken" role="tab" aria-controls="interfaces-kraken" aria-selected="false">Kraken</a>
</li>
@@ -975,6 +993,39 @@
</tr>
</table>
</div>
<div class="tab-pane fade" id="interfaces-hyperliquid" role="tabpanel" aria-labelledby="interfaces-hyperliquid-tab">
<table class="table table-bordered">
<tr><th>Interface</th><th>Description</th></tr>
<tr>
<td><code>IHyperLiquidRestClient</code></td>
<td>The client for accessing the HyperLiquid REST API</td>
</tr>
<tr>
<td><code>IHyperLiquidSocketClient</code></td>
<td>The client for accessing the HyperLiquid Websocket API</td>
</tr>
<tr>
<td><code>IHyperLiquidOrderBookFactory</code></td>
<td>A factory for creating SymbolOrderBook instances for the HyperLiquid API</td>
</tr>
<tr>
<td><code>IHyperLiquidTrackerFactory</code></td>
<td>A factory for creating kline and trade Tracker instances for the HyperLiquid API</td>
</tr>
<tr>
<td><code>ICryptoRestClient</code></td>
<td>An aggregating client from which multiple different library REST clients can be accessed</td>
</tr>
<tr>
<td><code>ICryptoSocketClient</code></td>
<td>An aggregating client from which multiple different library Websocket clients can be accessed</td>
</tr>
<tr>
<td><code>ISharedClient</code></td>
<td>Various interfaces deriving from ISharedClient which can be used for common functionality</td>
</tr>
</table>
</div>
<div class="tab-pane fade" id="interfaces-kraken" role="tabpanel" aria-labelledby="interfaces-kraken-tab">
<table class="table table-bordered">
<tr><th>Interface</th><th>Description</th></tr>
@@ -1237,6 +1288,9 @@
<li class="nav-item" role="presentation">
<a class="nav-link" id="rest-htx-tab" data-toggle="tab" href="#rest-htx" role="tab" aria-controls="rest-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="rest-hyperliquid-tab" data-toggle="tab" href="#rest-hyperliquid" role="tab" aria-controls="rest-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="rest-kraken-tab" data-toggle="tab" href="#rest-kraken" role="tab" aria-controls="rest-kraken" aria-selected="false">Kraken</a>
</li>
@@ -1409,6 +1463,18 @@ if (!tickersResult.Success)
// Handle error, tickersResult.Error contains more information
}
else
{
// Handle data, tickersResult.Data will contain the actual data
}</code></pre>
</div>
<div class="tab-pane fade" id="rest-hyperliquid" role="tabpanel" aria-labelledby="rest-hyperliquid-tab">
<pre><code>var client = new HyperLiquidRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetExchangeInfoAndTickersAsync();
if (!tickersResult.Success)
{
// Handle error, tickersResult.Error contains more information
}
else
{
// Handle data, tickersResult.Data will contain the actual data
}</code></pre>
@@ -1595,6 +1661,9 @@ else
<li class="nav-item" role="presentation">
<a class="nav-link" id="socket-htx-tab" data-toggle="tab" href="#socket-htx" role="tab" aria-controls="socket-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="socket-hyperliquid-tab" data-toggle="tab" href="#socket-hyperliquid" role="tab" aria-controls="socket-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="socket-kraken-tab" data-toggle="tab" href="#socket-kraken" role="tab" aria-controls="socket-kraken" aria-selected="false">Kraken</a>
</li>
@@ -1745,6 +1814,17 @@ if (!subscribeResult.Success)
{
// Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler</code></pre>
</div>
<div class="tab-pane fade" id="socket-hyperliquid" role="tabpanel" aria-labelledby="socket-hyperliquid-tab">
<pre><code>var client = new HyperLiquidSocketClient();
var subscribeResult = await client.SpotApi.SubscribeToSymbolUpdatesAsync("HYPE/USDC", update => {
// Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
// Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler</code></pre>
</div>
<div class="tab-pane fade" id="socket-kraken" role="tabpanel" aria-labelledby="socket-kraken-tab">
@@ -1999,6 +2079,9 @@ var binanceTriggered = CheckForTrigger(lastBinanceTicker);</code></pre>
<li class="nav-item" role="presentation">
<a class="nav-link" id="shared-htx-tab" data-toggle="tab" href="#shared-htx" role="tab" aria-controls="shared-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="shared-hyperliquid-tab" data-toggle="tab" href="#shared-hyperliquid" role="tab" aria-controls="shared-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="shared-kraken-tab" data-toggle="tab" href="#shared-kraken" role="tab" aria-controls="shared-kraken" aria-selected="false">Kraken</a>
</li>
@@ -2152,6 +2235,19 @@ var usdFuturesSharedRestClient = htxRestClient.UsdtFuturesApi.SharedClient;
// USDT Futures API common functionality socket client
var usdFuturesSharedSocketClient = htxSocketClient.UsdtFuturesApi.SharedClient;</code></pre>
</div>
<div class="tab-pane fade" id="shared-hyperliquid" role="tabpanel" aria-labelledby="shared-hyperliquid-tab">
<pre><code>// Spot API common functionality rest client
var spotSharedRestClients = hyperliquidRestClient.SpotApi.SharedClient;
// Spot API common functionality socket client
var spotSharedSocketClient = hyperliquidSocketClient.SpotApi.SharedClient;
// Perpetual Futures API common functionality rest client
var futuresSharedRestClient = hyperliquidRestClient.FuturesApi.SharedClient;
// Perpetual Futures API common functionality socket client
var futuresSharedSocketClient = hyperliquidSocketClient.FuturesApi.SharedClient;</code></pre>
</div>
<div class="tab-pane fade" id="shared-kraken" role="tabpanel" aria-labelledby="shared-kraken-tab">
<pre><code>// Spot API common functionality rest client
@@ -2485,6 +2581,9 @@ options.ApiCredentials = new ApiCredentials("YOUR PUBLIC KEY", "YOUR PRIVATE KEY
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-htx-tab" data-toggle="tab" href="#options-htx" role="tab" aria-controls="options-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-hyperliquid-tab" data-toggle="tab" href="#options-hyperliquid" role="tab" aria-controls="options-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-kraken-tab" data-toggle="tab" href="#options-kraken" role="tab" aria-controls="options-kraken" aria-selected="false">Kraken</a>
</li>
@@ -2656,6 +2755,18 @@ builder.Services.AddGateIo(builder.Configuration.GetSection("GateIo"));</code></
// see https://github.com/JKorf/CryptoExchange.Net/tree/master/Examples/example-config.json for an example configuration
builder.Services.AddHTX(builder.Configuration.GetSection("HTX"));</code></pre>
</div>
<div class="tab-pane fade" id="options-hyperliquid" role="tabpanel" aria-labelledby="options-hyperliquid-tab">
<pre><code>builder.Services.AddHyperLiquid(
options => {
options.Rest.RequestTimeout = TimeSpan.FromSeconds(30);
options.Socket.RequestTimeout = TimeSpan.FromSeconds(5);
});
// OR
// see https://github.com/JKorf/CryptoExchange.Net/tree/master/Examples/example-config.json for an example configuration
builder.Services.AddHyperLiquid(builder.Configuration.GetSection("HyperLiquid"));</code></pre>
</div>
<div class="tab-pane fade" id="options-kraken" role="tabpanel" aria-labelledby="options-kraken-tab">
<pre><code>builder.Services.AddKraken(
@@ -2775,6 +2886,9 @@ builder.Services.AddXT(builder.Configuration.GetSection("XT"));</code></pre>
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-htx-tab" data-toggle="tab" href="#options-constr-htx" role="tab" aria-controls="options-constr-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-hyperliquid-tab" data-toggle="tab" href="#options-constr-hyperliquid" role="tab" aria-controls="options-constr-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-kraken-tab" data-toggle="tab" href="#options-constr-kraken" role="tab" aria-controls="options-constr-kraken" aria-selected="false">Kraken</a>
</li>
@@ -2869,6 +2983,12 @@ builder.Services.AddXT(builder.Configuration.GetSection("XT"));</code></pre>
</div>
<div class="tab-pane fade" id="options-constr-htx" role="tabpanel" aria-labelledby="options-htx-tab">
<pre><code>var client = new HTXRestClient(opts =>
{
opts.RequestTimeout = TimeSpan.FromSeconds(30);
});</code></pre>
</div>
<div class="tab-pane fade" id="options-constr-hyperliquid" role="tabpanel" aria-labelledby="options-hyperliquid-tab">
<pre><code>var client = new HyperLiquidRestClient(opts =>
{
opts.RequestTimeout = TimeSpan.FromSeconds(30);
});</code></pre>
@@ -2952,6 +3072,9 @@ builder.Services.AddXT(builder.Configuration.GetSection("XT"));</code></pre>
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-htx-tab" data-toggle="tab" href="#options-default-htx" role="tab" aria-controls="options-default-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-hyperliquid-tab" data-toggle="tab" href="#options-default-hyperliquid" role="tab" aria-controls="options-default-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="options-kraken-tab" data-toggle="tab" href="#options-default-kraken" role="tab" aria-controls="options-default-kraken" aria-selected="false">Kraken</a>
</li>
@@ -3055,6 +3178,13 @@ var client = new GateIoRestClient();</code></pre>
options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new HTXRestClient();</code></pre>
</div>
<div class="tab-pane fade" id="options-default-hyperliquid" role="tabpanel" aria-labelledby="options-hyperliquid-tab">
<pre><code>HyperLiquidRestClient.SetDefaultOptions(options =>
{
options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new HyperLiquidRestClient();</code></pre>
</div>
<div class="tab-pane fade" id="options-default-kraken" role="tabpanel" aria-labelledby="options-kraken-tab">
<pre><code>KrakenRestClient.SetDefaultOptions(options =>
@@ -3317,6 +3447,9 @@ var client = new XTRestClient();</code></pre>
<li class="nav-item" role="presentation">
<a class="nav-link" id="book-htx-tab" data-toggle="tab" href="#book-htx" role="tab" aria-controls="book-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="book-hyperliquid-tab" data-toggle="tab" href="#book-hyperliquid" role="tab" aria-controls="book-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="book-kraken-tab" data-toggle="tab" href="#book-kraken" role="tab" aria-controls="book-kraken" aria-selected="false">Kraken</a>
</li>
@@ -3490,6 +3623,19 @@ if (!startResult.Success)
}
// Book has successfully started and synchronized
// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
</code></pre>
</div>
<div class="tab-pane fade" id="book-hyperliquid" role="tabpanel" aria-labelledby="book-hyperliquid-tab">
<pre><code>var book = new HyperLiquidSymbolOrderBook("HYPE/USDC");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
// Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized
// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
</code></pre>
@@ -3726,6 +3872,9 @@ foreach (var book in books.Where(b => b.Status == OrderBookStatus.Synced))
<li class="nav-item" role="presentation">
<a class="nav-link" id="tracker-htx-tab" data-toggle="tab" href="#tracker-htx" role="tab" aria-controls="tracker-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="tracker-hyperliquid-tab" data-toggle="tab" href="#tracker-hyperliquid" role="tab" aria-controls="tracker-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="tracker-kraken-tab" data-toggle="tab" href="#tracker-kraken" role="tab" aria-controls="tracker-kraken" aria-selected="false">Kraken</a>
</li>
@@ -3983,6 +4132,26 @@ if (!startResult.Success)
// Tracker has successfully started
// Note that it might not be fully synced yet, check tracker.Status for this.
// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await tracker.StopAsync();
</code></pre>
</div>
<div class="tab-pane fade" id="tracker-hyperliquid" role="tabpanel" aria-labelledby="tracker-hyperliquid-tab">
<pre><code>// Either create a new factory or inject the IHyperLiquidTrackerFactory interface
var factory = new HyperLiquidTrackerFactory();
var symbol = new SharedSymbol(TradingMode.Spot, "HYPE", "USDC");
// Create a tracker for HYPE/USDC keeping track of trades in the last 5 minutes
var tracker = factory.CreateTradeTracker(symbol, period: TimeSpan.FromMinutes(5));
var startResult = await tracker.StartAsync();
if (!startResult.Success)
{
// Handle error, error info available in startResult.Error
}
// Tracker has successfully started
// Note that it might not be fully synced yet, check tracker.Status for this.
// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await tracker.StopAsync();
</code></pre>
@@ -4441,6 +4610,9 @@ var binanceClient = new BinanceRestClient(new HttpClient(), logFactory, options
<li class="nav-item" role="presentation">
<a class="nav-link" id="limit-htx-tab" data-toggle="tab" href="#limit-htx" role="tab" aria-controls="limit-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="limit-hyperliquid-tab" data-toggle="tab" href="#limit-hyperliquid" role="tab" aria-controls="limit-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="limit-kraken-tab" data-toggle="tab" href="#limit-kraken" role="tab" aria-controls="limit-kraken" aria-selected="false">Kraken</a>
</li>
@@ -4583,6 +4755,20 @@ var binanceClient = new BinanceRestClient(new HttpClient(), logFactory, options
<p>To be notified of when a rate limit is hit the static <code>HTXExchange.RateLimiter</code> exposes an event which triggers when a rate limit is reached</p>
<pre><code>HTXExchange.RateLimiter.RateLimitTriggered += (rateLimitEvent) => Console.WriteLine("Limit triggered: " + rateLimitEvent);
</code></pre>
</div>
<div class="tab-pane fade" id="limit-hyperliquid" role="tabpanel" aria-labelledby="limit-hyperliquid-tab">
<pre><code>services.AddHyperLiquid(x =>
x.RatelimiterEnabled = true;
x.RateLimitingBehaviour = RateLimitingBehaviour.Wait;
}, x =>
{
x.RatelimiterEnabled = true;
x.RateLimitingBehaviour = RateLimitingBehaviour.Wait;
});</code></pre>
<p>To be notified of when a rate limit is hit the static <code>HyperLiquidExchange.RateLimiter</code> exposes an event which triggers when a rate limit is reached</p>
<pre><code>HyperLiquidExchange.RateLimiter.RateLimitTriggered += (rateLimitEvent) => Console.WriteLine("Limit triggered: " + rateLimitEvent);
</code></pre>
</div>
<div class="tab-pane fade" id="limit-kraken" role="tabpanel" aria-labelledby="limit-kraken-tab">
@@ -4760,6 +4946,9 @@ var responseSource = result.DataSource;</code></pre>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-symbols-htx-tab" data-toggle="tab" href="#example-symbols-htx" role="tab" aria-controls="example-symbols-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-symbols-hyperliquid-tab" data-toggle="tab" href="#example-symbols-hyperliquid" role="tab" aria-controls="example-symbols-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-symbols-kraken-tab" data-toggle="tab" href="#example-symbols-kraken" role="tab" aria-controls="example-symbols-kraken" aria-selected="false">Kraken</a>
</li>
@@ -4823,6 +5012,9 @@ await exchangeRestClient.GetSpotSymbolsAsync(new GetSymbolsRequest(), ["Binance"
</div>
<div class="tab-pane fade" id="example-symbols-htx" role="tabpanel" aria-labelledby="example-symbols-htx-tab">
<pre><code>await htxClient.SpotApi.ExchangeData.GetSymbolsAsync();</code></pre>
</div>
<div class="tab-pane fade" id="example-symbols-hyperliquid" role="tabpanel" aria-labelledby="example-symbols-hyperliquid-tab">
<pre><code>await hyperLiquidClient.SpotApi.ExchangeData.GetExchangeInfoAsync();</code></pre>
</div>
<div class="tab-pane fade" id="example-symbols-kraken" role="tabpanel" aria-labelledby="example-symbols-kraken-tab">
<pre><code>await krakenClient.SpotApi.ExchangeData.GetSymbolsAsync();</code></pre>
@@ -4896,6 +5088,9 @@ await exchangeRestClient.GetSpotSymbolsAsync(new GetSymbolsRequest(), ["Binance"
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-ticker-htx-tab" data-toggle="tab" href="#example-ticker-htx" role="tab" aria-controls="example-ticker-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-ticker-hyperliquid-tab" data-toggle="tab" href="#example-ticker-hyperliquid" role="tab" aria-controls="example-ticker-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-ticker-kraken-tab" data-toggle="tab" href="#example-ticker-kraken" role="tab" aria-controls="example-ticker-kraken" aria-selected="false">Kraken</a>
</li>
@@ -4961,6 +5156,11 @@ await coinbaseClient.AdvancedTradeApi.ExchangeData.GetSymbolAsync("BTC-USDT");</
</div>
<div class="tab-pane fade" id="example-ticker-htx" role="tabpanel" aria-labelledby="example-ticker-htx-tab">
<pre><code>await htxClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT");</code></pre>
</div>
<div class="tab-pane fade" id="example-ticker-hyperliquid" role="tabpanel" aria-labelledby="example-ticker-hyperliquid-tab">
<pre><code>// HyperLiquid API doesn't offer a symbol filter, so we have to filter client side
var tickersResult = await hyperLiquidClient.SpotApi.ExchangeData.GetExchangeInfoAndTickersAsync();
var ticker = tickersResult.Data.Tickers.Single(x => x.Symbol == "HYPE/USDC");</code></pre>
</div>
<div class="tab-pane fade" id="example-ticker-kraken" role="tabpanel" aria-labelledby="example-ticker-kraken-tab">
<pre><code>await krakenClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT");</code></pre>
@@ -5036,6 +5236,9 @@ var ticker = tickersResult.Data.Single(x => x.Symbol == "BTC_USDT");</code></pre
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-balances-htx-tab" data-toggle="tab" href="#example-balances-htx" role="tab" aria-controls="example-balances-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-balances-hyperliquid-tab" data-toggle="tab" href="#example-balances-hyperliquid" role="tab" aria-controls="example-balances-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-balances-kraken-tab" data-toggle="tab" href="#example-balances-kraken" role="tab" aria-controls="example-balances-kraken" aria-selected="false">Kraken</a>
</li>
@@ -5103,6 +5306,9 @@ var accounts = await htxClient.SpotApi.Account.GetAccountsAsync();
var account = accounts.Data.Single(a => a.Type == AccountType.Spot);
var result = await htxClient.SpotApi.Account.GetBalancesAsync();</code></pre>
</div>
<div class="tab-pane fade" id="example-balances-hyperliquid" role="tabpanel" aria-labelledby="example-balances-hyperliquid-tab">
<pre><code>await hyperLiquidClient.SpotApi.Account.GetBalancesAsync();</code></pre>
</div>
<div class="tab-pane fade" id="example-balances-kraken" role="tabpanel" aria-labelledby="example-balances-kraken-tab">
<pre><code>await krakenClient.SpotApi.Account.GetBalancesAsync();</code></pre>
@@ -5176,6 +5382,9 @@ var result = await htxClient.SpotApi.Account.GetBalancesAsync();</code></pre>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-place-htx-tab" data-toggle="tab" href="#example-place-htx" role="tab" aria-controls="example-place-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-place-hyperliquid-tab" data-toggle="tab" href="#example-place-hyperliquid" role="tab" aria-controls="example-place-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-place-kraken-tab" data-toggle="tab" href="#example-place-kraken" role="tab" aria-controls="example-place-kraken" aria-selected="false">Kraken</a>
</li>
@@ -5241,6 +5450,10 @@ var accounts = await htxClient.SpotApi.Account.GetAccountsAsync();
var account = accounts.Data.Single(a => a.Type == AccountType.Spot);
var result = await htxClient.SpotApi.Trading.PlaceOrderAsync(account.Id, "BTCUSDT", OrderSide.Buy, OrderType.Limit, 0.1m, price: 50000);</code></pre>
</div>
<div class="tab-pane fade" id="example-place-hyperliquid" role="tabpanel" aria-labelledby="example-place-hyperliquid-tab">
<pre><code>// BTC not support on HyperLiquid Spot trading, example uses HYPE/USDC Pair
await hyperLiquidClient.SpotApi.Trading.PlaceOrderAsync("HYPE/USDC",OrderSide.Buy, OrderType.Limit, 1m, 20);</code></pre>
</div>
<div class="tab-pane fade" id="example-place-kraken" role="tabpanel" aria-labelledby="example-place-kraken-tab">
<pre><code>await krakenClient.SpotApi.Trading.PlaceOrderAsync("BTCUSDT",OrderSide.Buy, OrderType.Limit, 0.1m, 50000);</code></pre>
@@ -5314,6 +5527,9 @@ var result = await htxClient.SpotApi.Trading.PlaceOrderAsync(account.Id, "BTCUSD
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-stream-ticker-htx-tab" data-toggle="tab" href="#example-stream-ticker-htx" role="tab" aria-controls="example-stream-ticker-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-stream-ticker-hyperliquid-tab" data-toggle="tab" href="#example-stream-ticker-hyperliquid" role="tab" aria-controls="example-stream-ticker-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-stream-ticker-kraken-tab" data-toggle="tab" href="#example-stream-ticker-kraken" role="tab" aria-controls="example-stream-ticker-kraken" aria-selected="false">Kraken</a>
</li>
@@ -5400,6 +5616,11 @@ await exchangeSocketClient.SubscribeToTickerUpdatesAsync(new SubscribeTickerRequ
<div class="tab-pane fade" id="example-stream-ticker-gateio" role="tabpanel" aria-labelledby="example-stream-ticker-gateio-tab">
<pre><code>await gateioSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH_USDT", data => {
// Handle update
});</code></pre>
</div>
<div class="tab-pane fade" id="example-stream-ticker-hyperliquid" role="tabpanel" aria-labelledby="example-stream-ticker-hyperliquid-tab">
<pre><code>await hyperLiquidSocketClient.SpotApi.SubscribeToSymbolUpdatesAsync("HYPE/USDC", data => {
// Handle update
});</code></pre>
</div>
<div class="tab-pane fade" id="example-stream-ticker-htx" role="tabpanel" aria-labelledby="example-stream-ticker-htx-tab">
@@ -5494,6 +5715,9 @@ await exchangeSocketClient.SubscribeToTickerUpdatesAsync(new SubscribeTickerRequ
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-stream-order-htx-tab" data-toggle="tab" href="#example-stream-order-htx" role="tab" aria-controls="example-stream-order-htx" aria-selected="false">HTX</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-stream-order-hyperliquid-tab" data-toggle="tab" href="#example-stream-order-hyperliquid" role="tab" aria-controls="example-stream-order-hyperliquid" aria-selected="false">HyperLiquid</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="example-stream-order-kraken-tab" data-toggle="tab" href="#example-stream-order-kraken" role="tab" aria-controls="example-stream-order-kraken" aria-selected="false">Kraken</a>
</li>
@@ -5621,6 +5845,11 @@ _ = Task.Run(async () => {
<div class="tab-pane fade" id="example-stream-order-htx" role="tabpanel" aria-labelledby="example-stream-order-htx-tab">
<pre><code>await htxSocketClient.SpotApi.SubscribeToOrderUpdatesAsync(onOrderMatched: data => {
// Handle update
});</code></pre>
</div>
<div class="tab-pane fade" id="example-stream-order-hyperliquid" role="tabpanel" aria-labelledby="example-stream-order-hyperliquid-tab">
<pre><code>await hyperLiquidSocketClient.SpotApi.SubscribeToOrderUpdatesAsync(null, data => {
// Handle update
});</code></pre>
</div>
<div class="tab-pane fade" id="example-stream-order-kraken" role="tabpanel" aria-labelledby="example-stream-order-kraken-tab">