1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-08-11 16:32:57 +00:00

Compare commits

...

3 Commits

Author SHA1 Message Date
JKorf 73764970b0 . 2025-08-25 19:11:50 +02:00
JKorf 9ba29035b2 Merge branch 'master' into feature/code-analyzis 2025-08-25 17:37:46 +02:00
JKorf 4c953e2c87 wip 2025-08-24 21:58:52 +02:00
355 changed files with 23441 additions and 23799 deletions
@@ -5,6 +5,10 @@
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<None Include="..\CryptoExchange.Net\.editorconfig" Link=".editorconfig" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"></PackageReference>
<PackageReference Include="Moq" Version="4.20.72" />
@@ -1,132 +0,0 @@
//using System;
//using System.IO;
//using System.Net.WebSockets;
//using System.Security.Authentication;
//using System.Text;
//using System.Threading.Tasks;
//using CryptoExchange.Net.Interfaces;
//using CryptoExchange.Net.Objects;
//namespace CryptoExchange.Net.UnitTests.TestImplementations
//{
// public class TestSocket: IWebsocket
// {
// public bool CanConnect { get; set; }
// public bool Connected { get; set; }
// public event Func<Task> OnClose;
//#pragma warning disable 0067
// public event Func<Task> OnReconnected;
// public event Func<Task> OnReconnecting;
// public event Func<int, Task> OnRequestRateLimited;
//#pragma warning restore 0067
// public event Func<int, Task> OnRequestSent;
// public event Func<WebSocketMessageType, ReadOnlyMemory<byte>, Task> OnStreamMessage;
// public event Func<Exception, Task> OnError;
// public event Func<Task> OnOpen;
// public Func<Task<Uri>> GetReconnectionUrl { get; set; }
// public int Id { get; }
// public bool ShouldReconnect { get; set; }
// public TimeSpan Timeout { get; set; }
// public Func<string, string> DataInterpreterString { get; set; }
// public Func<byte[], string> DataInterpreterBytes { get; set; }
// public DateTime? DisconnectTime { get; set; }
// public string Url { get; }
// public bool IsClosed => !Connected;
// public bool IsOpen => Connected;
// public bool PingConnection { get; set; }
// public TimeSpan PingInterval { get; set; }
// public SslProtocols SSLProtocols { get; set; }
// public Encoding Encoding { get; set; }
// public int ConnectCalls { get; private set; }
// public bool Reconnecting { get; set; }
// public string Origin { get; set; }
// public int? RatelimitPerSecond { get; set; }
// public double IncomingKbps => throw new NotImplementedException();
// public Uri Uri => new Uri("");
// public TimeSpan KeepAliveInterval { get; set; }
// public static int lastId = 0;
// public static object lastIdLock = new object();
// public TestSocket()
// {
// lock (lastIdLock)
// {
// Id = lastId + 1;
// lastId++;
// }
// }
// public Task<CallResult> ConnectAsync()
// {
// Connected = CanConnect;
// ConnectCalls++;
// if (CanConnect)
// InvokeOpen();
// return Task.FromResult(CanConnect ? new CallResult(null) : new CallResult(new CantConnectError()));
// }
// public bool Send(int requestId, string data, int weight)
// {
// if(!Connected)
// throw new Exception("Socket not connected");
// OnRequestSent?.Invoke(requestId);
// return true;
// }
// public void Reset()
// {
// }
// public Task CloseAsync()
// {
// Connected = false;
// DisconnectTime = DateTime.UtcNow;
// OnClose?.Invoke();
// return Task.FromResult(0);
// }
// public void SetProxy(string host, int port)
// {
// throw new NotImplementedException();
// }
// public void Dispose()
// {
// }
// public void InvokeClose()
// {
// Connected = false;
// DisconnectTime = DateTime.UtcNow;
// Reconnecting = true;
// OnClose?.Invoke();
// }
// public void InvokeOpen()
// {
// OnOpen?.Invoke();
// }
// public void InvokeMessage(string data)
// {
// OnStreamMessage?.Invoke(WebSocketMessageType.Text, new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(data))).Wait();
// }
// public void SetProxy(ApiProxy proxy)
// {
// throw new NotImplementedException();
// }
// public void InvokeError(Exception error)
// {
// OnError?.Invoke(error);
// }
// public Task ReconnectAsync() => Task.CompletedTask;
// }
//}
+183
View File
@@ -0,0 +1,183 @@
root = true
[*]
# Indentation and spacing
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
charset = utf-8
max_line_length = 140
insert_final_newline = true
# ReSharper code style properties
resharper_csharp_keep_existing_embedded_arrangement = false
resharper_csharp_place_accessorholder_attribute_on_same_line = false
resharper_csharp_wrap_after_declaration_lpar = true
resharper_csharp_wrap_parameters_style = chop_if_long
resharper_csharp_blank_lines_around_single_line_auto_property = 1
resharper_csharp_keep_blank_lines_in_declarations = 1
resharper_trailing_comma_in_multiline_lists = true
[*.cs]
indent_size = 4
# Code style conventions
dotnet_style_predefined_type_for_member_access = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_object_initializer = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_expression_bodied_methods = true:suggestion
csharp_style_namespace_declarations = file_scoped:warning
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
csharp_prefer_braces = when_multiline:warning
# Analyzer preferences
dotnet_diagnostic.CA2007.severity = warning # Call ConfigureAwait on the awaited Task.
dotnet_code_quality.CA2007.exclude_async_void_methods = true
dotnet_code_quality.CA2007.output_kind = DynamicallyLinkedLibrary
dotnet_diagnostic.CA1000.severity = none # Do not declare static members on generic types
dotnet_diagnostic.CA1051.severity = none # Do not declare visible instance fields
dotnet_diagnostic.CA1510.severity = none # Use ArgumentNullException throw helper
dotnet_diagnostic.CA1720.severity = none # Identifiers should not contain type names
dotnet_diagnostic.CA1716.severity = none # Identifiers should not match keywords
dotnet_diagnostic.CA1835.severity = none # Use ArgumentNullException throw helper
dotnet_diagnostic.CA1846.severity = none # Prefer AsSpan over Substring
dotnet_diagnostic.CA1848.severity = none # Use the LoggerMessage delegates
dotnet_diagnostic.CA1850.severity = none # Prefer static HashData method over ComputeHash
dotnet_diagnostic.CA1866.severity = none # Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char
dotnet_diagnostic.CA2201.severity = none # Do not raise reserved exception types
dotnet_diagnostic.CA2208.severity = none # Do not raise reserved exception types
dotnet_diagnostic.IDE0005.severity = warning # Using directive is unnecessary
[*.xml]
ij_xml_space_inside_empty_tag = true
[*.cs]
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = warning
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.private_or_internal_field_should_be_fields_start_with__.severity = warning
dotnet_naming_rule.private_or_internal_field_should_be_fields_start_with__.symbols = private_or_internal_field
dotnet_naming_rule.private_or_internal_field_should_be_fields_start_with__.style = fields_start_with__
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field
dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private, private_protected
dotnet_naming_symbols.private_or_internal_field.required_modifiers =
# Naming styles
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.fields_start_with__.required_prefix = _
dotnet_naming_style.fields_start_with__.required_suffix =
dotnet_naming_style.fields_start_with__.word_separator =
dotnet_naming_style.fields_start_with__.capitalization = camel_case
csharp_indent_labels = one_less_than_current
csharp_using_directive_placement = outside_namespace:suggestion
csharp_prefer_simple_using_statement = true:suggestion
csharp_style_prefer_method_group_conversion = true:silent
csharp_style_prefer_top_level_statements = true:silent
csharp_style_prefer_primary_constructors = true:suggestion
csharp_prefer_system_threading_lock = true:suggestion
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = true:suggestion
csharp_style_expression_bodied_indexers = true:suggestion
csharp_style_expression_bodied_accessors = true:suggestion
csharp_style_expression_bodied_lambdas = true:silent
csharp_style_expression_bodied_local_functions = true:silent
[*.vb]
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
[*.{cs,vb}]
#### Naming styles ####
# Naming rules
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
# Naming styles
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_style_operator_placement_when_wrapping = beginning_of_line
tab_width = 4
end_of_line = crlf
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
+4 -5
View File
@@ -1,6 +1,5 @@
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("CryptoExchange.Net.UnitTests")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("CryptoExchange.Net.UnitTests")]
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit { }
}
namespace System.Runtime.CompilerServices;
internal static class IsExternalInit { }
@@ -1,12 +1,11 @@
using System;
using System;
namespace CryptoExchange.Net.Attributes
namespace CryptoExchange.Net.Attributes;
/// <summary>
/// Used for conversion in ArrayConverter
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class JsonConversionAttribute: Attribute
{
/// <summary>
/// Used for conversion in ArrayConverter
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class JsonConversionAttribute: Attribute
{
}
}
@@ -1,13 +1,13 @@
using System;
using System;
namespace CryptoExchange.Net.Attributes
namespace CryptoExchange.Net.Attributes;
/// <summary>
/// Map a enum entry to string values
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class MapAttribute : Attribute
{
/// <summary>
/// Map a enum entry to string values
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class MapAttribute : Attribute
{
/// <summary>
/// Values mapping to the enum entry
/// </summary>
@@ -21,5 +21,4 @@ namespace CryptoExchange.Net.Attributes
{
Values = maps;
}
}
}
@@ -1,15 +1,12 @@
using System;
using System.IO;
using CryptoExchange.Net.Converters.SystemTextJson;
using CryptoExchange.Net.Converters.MessageParsing;
using System;
namespace CryptoExchange.Net.Authentication
namespace CryptoExchange.Net.Authentication;
/// <summary>
/// Api credentials, used to sign requests accessing private endpoints
/// </summary>
public class ApiCredentials
{
/// <summary>
/// Api credentials, used to sign requests accessing private endpoints
/// </summary>
public class ApiCredentials
{
/// <summary>
/// The api key / label to authenticate requests
/// </summary>
@@ -56,5 +53,4 @@ namespace CryptoExchange.Net.Authentication
{
return new ApiCredentials(Key, Secret, Pass, CredentialType);
}
}
}
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Authentication
namespace CryptoExchange.Net.Authentication;
/// <summary>
/// Credentials type
/// </summary>
public enum ApiCredentialsType
{
/// <summary>
/// Credentials type
/// </summary>
public enum ApiCredentialsType
{
/// <summary>
/// Hmac keys credentials
/// </summary>
@@ -17,5 +17,4 @@
/// Rsa keys credentials in pem/base64 format. Only available for .NetStandard 2.1 and up, use xml format for lower.
/// </summary>
RsaPem
}
}
@@ -1,21 +1,20 @@
using CryptoExchange.Net.Clients;
using CryptoExchange.Net.Clients;
using CryptoExchange.Net.Converters.SystemTextJson;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
namespace CryptoExchange.Net.Authentication
namespace CryptoExchange.Net.Authentication;
/// <summary>
/// Base class for authentication providers
/// </summary>
public abstract class AuthenticationProvider
{
/// <summary>
/// Base class for authentication providers
/// </summary>
public abstract class AuthenticationProvider
{
internal IAuthTimeProvider TimeProvider { get; set; } = new AuthTimeProvider();
/// <summary>
@@ -209,7 +208,9 @@ namespace CryptoExchange.Net.Authentication
/// <returns></returns>
protected static string SignMD5(string data, SignOutputType? outputType = null)
{
#pragma warning disable CA5351
using var encryptor = MD5.Create();
#pragma warning restore CA5351
var resultBytes = encryptor.ComputeHash(Encoding.UTF8.GetBytes(data));
return outputType == SignOutputType.Base64 ? BytesToBase64String(resultBytes) : BytesToHexString(resultBytes);
}
@@ -222,7 +223,9 @@ namespace CryptoExchange.Net.Authentication
/// <returns></returns>
protected static string SignMD5(byte[] data, SignOutputType? outputType = null)
{
#pragma warning disable CA5351
using var encryptor = MD5.Create();
#pragma warning restore CA5351
var resultBytes = encryptor.ComputeHash(data);
return outputType == SignOutputType.Base64 ? BytesToBase64String(resultBytes) : BytesToHexString(resultBytes);
}
@@ -234,7 +237,9 @@ namespace CryptoExchange.Net.Authentication
/// <returns></returns>
protected static byte[] SignMD5Bytes(string data)
{
#pragma warning disable CA5351
using var encryptor = MD5.Create();
#pragma warning restore CA5351
return encryptor.ComputeHash(Encoding.UTF8.GetBytes(data));
}
@@ -454,13 +459,17 @@ namespace CryptoExchange.Net.Authentication
else
return stringSerializer.Serialize(parameters);
}
}
}
/// <inheritdoc />
public abstract class AuthenticationProvider<TApiCredentials> : AuthenticationProvider where TApiCredentials : ApiCredentials
{
/// <inheritdoc />
public abstract class AuthenticationProvider<TApiCredentials> : AuthenticationProvider where TApiCredentials : ApiCredentials
{
/// <inheritdoc />
#pragma warning disable IDE1006 // Naming Styles
#pragma warning disable CA1707 // Naming Styles
protected new TApiCredentials _credentials => (TApiCredentials)base._credentials;
#pragma warning restore IDE1006 // Naming Styles
#pragma warning restore CA1707 // Naming Styles
/// <summary>
/// ctor
@@ -469,5 +478,4 @@ namespace CryptoExchange.Net.Authentication
protected AuthenticationProvider(TApiCredentials credentials) : base(credentials)
{
}
}
}
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Authentication
namespace CryptoExchange.Net.Authentication;
/// <summary>
/// Output string type
/// </summary>
public enum SignOutputType
{
/// <summary>
/// Output string type
/// </summary>
public enum SignOutputType
{
/// <summary>
/// Hex string
/// </summary>
@@ -13,5 +13,4 @@
/// Base64 string
/// </summary>
Base64
}
}
+4 -5
View File
@@ -1,11 +1,11 @@
using System;
using System;
using System.Collections.Concurrent;
using System.Linq;
namespace CryptoExchange.Net.Caching
namespace CryptoExchange.Net.Caching;
internal class MemoryCache
{
internal class MemoryCache
{
private readonly ConcurrentDictionary<string, CacheItem> _cache = new ConcurrentDictionary<string, CacheItem>();
private readonly object _lock = new object();
@@ -49,5 +49,4 @@ namespace CryptoExchange.Net.Caching
Value = value;
}
}
}
}
+16 -10
View File
@@ -1,20 +1,18 @@
using System;
using System.Collections.Generic;
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects.Errors;
using CryptoExchange.Net.Objects.Options;
using CryptoExchange.Net.SharedApis;
using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <summary>
/// Base API for all API clients
/// </summary>
public abstract class BaseApiClient : IDisposable, IBaseApiClient
{
/// <summary>
/// Base API for all API clients
/// </summary>
public abstract class BaseApiClient : IDisposable, IBaseApiClient
{
/// <summary>
/// Logger
/// </summary>
@@ -126,9 +124,17 @@ namespace CryptoExchange.Net.Clients
/// <summary>
/// Dispose
/// </summary>
public virtual void Dispose()
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose
/// </summary>
public virtual void Dispose(bool disposing)
{
_disposing = true;
}
}
}
+23 -11
View File
@@ -1,17 +1,16 @@
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Objects.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Collections.Generic;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <summary>
/// The base for all clients, websocket client and rest client
/// </summary>
public abstract class BaseClient : IDisposable
{
/// <summary>
/// The base for all clients, websocket client and rest client
/// </summary>
public abstract class BaseClient : IDisposable
{
/// <summary>
/// Version of the CryptoExchange.Net base library
/// </summary>
@@ -80,7 +79,7 @@ namespace CryptoExchange.Net.Clients
throw new ArgumentNullException(nameof(options));
ClientOptions = options;
_logger.Log(LogLevel.Trace, $"Client configuration: {options}, CryptoExchange.Net: v{CryptoExchangeLibVersion}, {Exchange}.Net: v{ExchangeLibVersion}");
_logger.Log(LogLevel.Trace, "Client configuration: {Options}, CryptoExchange.Net: v{CryptoExchangeVersion}, {Exchange}.Net: v{ExchangeVersion}", options, CryptoExchangeLibVersion, Exchange, ExchangeLibVersion);
}
/// <summary>
@@ -102,7 +101,7 @@ namespace CryptoExchange.Net.Clients
if (ClientOptions == null)
throw new InvalidOperationException("Client should have called Initialize before adding API clients");
_logger.Log(LogLevel.Trace, $" {apiClient.GetType().Name}, base address: {apiClient.BaseAddress}");
_logger.Log(LogLevel.Trace, " {ApiClient}, base address: {BaseAddress}", apiClient.GetType().Name, apiClient.BaseAddress);
ApiClients.Add(apiClient);
return apiClient;
}
@@ -120,11 +119,24 @@ namespace CryptoExchange.Net.Clients
/// <summary>
/// Dispose
/// </summary>
public virtual void Dispose()
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose
/// </summary>
public virtual void Dispose(bool disposing)
{
if (disposing)
{
_logger.Log(LogLevel.Debug, "Disposing client");
foreach (var client in ApiClients)
client.Dispose();
}
}
}
+6 -7
View File
@@ -3,13 +3,13 @@ using CryptoExchange.Net.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <summary>
/// Base rest client
/// </summary>
public abstract class BaseRestClient : BaseClient, IRestClient
{
/// <summary>
/// Base rest client
/// </summary>
public abstract class BaseRestClient : BaseClient, IRestClient
{
/// <inheritdoc />
public int TotalRequestsMade => ApiClients.OfType<RestApiClient>().Sum(s => s.TotalRequestsMade);
@@ -22,5 +22,4 @@ namespace CryptoExchange.Net.Clients
{
_logger = loggerFactory?.CreateLogger(name + ".RestClient") ?? NullLoggerFactory.Instance.CreateLogger(name);
}
}
}
@@ -1,22 +1,21 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Logging.Extensions;
using CryptoExchange.Net.Objects.Sockets;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <summary>
/// Base for socket client implementations
/// </summary>
public abstract class BaseSocketClient : BaseClient, ISocketClient
{
/// <summary>
/// Base for socket client implementations
/// </summary>
public abstract class BaseSocketClient : BaseClient, ISocketClient
{
#region fields
/// <summary>
@@ -128,5 +127,4 @@ namespace CryptoExchange.Net.Clients
return result;
}
}
}
+19 -8
View File
@@ -1,14 +1,14 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <summary>
/// Base crypto client
/// </summary>
public class CryptoBaseClient : IDisposable
{
/// <summary>
/// Base crypto client
/// </summary>
public class CryptoBaseClient : IDisposable
{
private readonly Dictionary<Type, object> _serviceCache = new Dictionary<Type, object>();
/// <summary>
@@ -59,9 +59,20 @@ namespace CryptoExchange.Net.Clients
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
public void Dispose(bool disposing)
{
if (disposing)
{
_serviceCache.Clear();
}
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
@@ -1,14 +1,11 @@
using CryptoExchange.Net.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using CryptoExchange.Net.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <inheritdoc />
public class CryptoRestClient : CryptoBaseClient, ICryptoRestClient
{
/// <inheritdoc />
public class CryptoRestClient : CryptoBaseClient, ICryptoRestClient
{
/// <summary>
/// ctor
/// </summary>
@@ -23,5 +20,4 @@ namespace CryptoExchange.Net.Clients
public CryptoRestClient(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
}
}
@@ -1,11 +1,11 @@
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Interfaces;
using System;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <inheritdoc />
public class CryptoSocketClient : CryptoBaseClient, ICryptoSocketClient
{
/// <inheritdoc />
public class CryptoSocketClient : CryptoBaseClient, ICryptoSocketClient
{
/// <summary>
/// ctor
/// </summary>
@@ -20,5 +20,4 @@ namespace CryptoExchange.Net.Clients
public CryptoSocketClient(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
}
}
+7 -8
View File
@@ -18,13 +18,13 @@ using CryptoExchange.Net.RateLimiting.Interfaces;
using CryptoExchange.Net.Requests;
using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <summary>
/// Base rest API client for interacting with a REST API
/// </summary>
public abstract class RestApiClient : BaseApiClient, IRestApiClient
{
/// <summary>
/// Base rest API client for interacting with a REST API
/// </summary>
public abstract class RestApiClient : BaseApiClient, IRestApiClient
{
/// <inheritdoc />
public IRequestFactory RequestFactory { get; set; } = new RequestFactory();
@@ -637,7 +637,7 @@ namespace CryptoExchange.Net.Clients
{
// Handle retry after header
var retryAfterHeader = responseHeaders.SingleOrDefault(r => r.Key.Equals("Retry-After", StringComparison.InvariantCultureIgnoreCase));
if (retryAfterHeader.Value?.Any() != true)
if (!(retryAfterHeader.Value.Length > 0))
return new ServerRateLimitError();
var value = retryAfterHeader.Value.First();
@@ -724,5 +724,4 @@ namespace CryptoExchange.Net.Clients
=> ClientOptions.CachingEnabled
&& definition.Method == HttpMethod.Get
&& !definition.PreventCaching;
}
}
+26 -12
View File
@@ -17,13 +17,13 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Clients
namespace CryptoExchange.Net.Clients;
/// <summary>
/// Base socket API client for interaction with a websocket API
/// </summary>
public abstract class SocketApiClient : BaseApiClient, ISocketApiClient
{
/// <summary>
/// Base socket API client for interaction with a websocket API
/// </summary>
public abstract class SocketApiClient : BaseApiClient, ISocketApiClient
{
#region Fields
/// <inheritdoc/>
public IWebsocketFactory SocketFactory { get; set; } = new WebsocketFactory();
@@ -86,7 +86,7 @@ namespace CryptoExchange.Net.Clients
/// <summary>
/// Whether to continue processing and forward unparsable messages to handlers
/// </summary>
protected internal bool ProcessUnparsableMessages { get; set; } = false;
protected internal bool ProcessUnparsableMessages { get; set; }
/// <inheritdoc />
public double IncomingKbps
@@ -340,7 +340,13 @@ namespace CryptoExchange.Net.Clients
SocketConnection socketConnection;
var released = false;
await semaphoreSlim.WaitAsync().ConfigureAwait(false);
try
{
await semaphoreSlim.WaitAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
try
{
var socketResult = await GetSocketConnection(url, query.Authenticated, true).ConfigureAwait(false);
@@ -395,7 +401,13 @@ namespace CryptoExchange.Net.Clients
return connectResult;
if (ClientOptions.DelayAfterConnect != TimeSpan.Zero)
await Task.Delay(ClientOptions.DelayAfterConnect).ConfigureAwait(false);
{
try
{
await Task.Delay(ClientOptions.DelayAfterConnect, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
}
if (!authenticated || socket.Authenticated)
return CallResult.SuccessResult;
@@ -827,8 +839,11 @@ namespace CryptoExchange.Net.Clients
/// <summary>
/// Dispose the client
/// </summary>
public override void Dispose()
public override void Dispose(bool disposing)
{
if (disposing)
return;
_disposing = true;
var tasks = new List<Task>();
{
@@ -843,7 +858,7 @@ namespace CryptoExchange.Net.Clients
}
semaphoreSlim?.Dispose();
base.Dispose();
base.Dispose(disposing);
}
/// <summary>
@@ -861,5 +876,4 @@ namespace CryptoExchange.Net.Clients
/// <param name="data"></param>
/// <returns></returns>
public virtual ReadOnlyMemory<byte> PreprocessStreamMessage(SocketConnection connection, WebSocketMessageType type, ReadOnlyMemory<byte> data) => data;
}
}
@@ -1,13 +1,13 @@
using System;
using System;
namespace CryptoExchange.Net.Converters
namespace CryptoExchange.Net.Converters;
/// <summary>
/// Mark property as an index in the array
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ArrayPropertyAttribute : Attribute
{
/// <summary>
/// Mark property as an index in the array
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ArrayPropertyAttribute : Attribute
{
/// <summary>
/// The index in the array
/// </summary>
@@ -21,5 +21,4 @@ namespace CryptoExchange.Net.Converters
{
Index = index;
}
}
}
@@ -1,16 +1,14 @@
using System;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters
namespace CryptoExchange.Net.Converters;
/// <summary>
/// Caching for JsonSerializerContext instances
/// </summary>
public static class JsonSerializerContextCache
{
/// <summary>
/// Caching for JsonSerializerContext instances
/// </summary>
public static class JsonSerializerContextCache
{
private static ConcurrentDictionary<Type, JsonSerializerContext> _cache = new ConcurrentDictionary<Type, JsonSerializerContext>();
/// <summary>
@@ -27,5 +25,4 @@ namespace CryptoExchange.Net.Converters
_cache[contextType] = instance;
return instance;
}
}
}
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Converters.MessageParsing
namespace CryptoExchange.Net.Converters.MessageParsing;
/// <summary>
/// Node accessor
/// </summary>
public readonly struct NodeAccessor
{
/// <summary>
/// Node accessor
/// </summary>
public readonly struct NodeAccessor
{
/// <summary>
/// Index
/// </summary>
@@ -45,5 +45,4 @@
/// </summary>
/// <returns></returns>
public static NodeAccessor PropertyName() { return new NodeAccessor(null, null, 2); }
}
}
@@ -1,13 +1,13 @@
using System.Collections;
using System.Collections;
using System.Collections.Generic;
namespace CryptoExchange.Net.Converters.MessageParsing
namespace CryptoExchange.Net.Converters.MessageParsing;
/// <summary>
/// Message access definition
/// </summary>
public readonly struct MessagePath : IEnumerable<NodeAccessor>
{
/// <summary>
/// Message access definition
/// </summary>
public readonly struct MessagePath : IEnumerable<NodeAccessor>
{
private readonly List<NodeAccessor> _path;
internal void Add(NodeAccessor node)
@@ -46,5 +46,4 @@ namespace CryptoExchange.Net.Converters.MessageParsing
{
return GetEnumerator();
}
}
}
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Converters.MessageParsing
namespace CryptoExchange.Net.Converters.MessageParsing;
/// <summary>
/// Message path extension methods
/// </summary>
public static class MessagePathExtension
{
/// <summary>
/// Message path extension methods
/// </summary>
public static class MessagePathExtension
{
/// <summary>
/// Add a string node accessor
/// </summary>
@@ -39,5 +39,4 @@
path.Add(NodeAccessor.Int(index));
return path;
}
}
}
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Converters.MessageParsing
namespace CryptoExchange.Net.Converters.MessageParsing;
/// <summary>
/// Message node type
/// </summary>
public enum NodeType
{
/// <summary>
/// Message node type
/// </summary>
public enum NodeType
{
/// <summary>
/// Array node
/// </summary>
@@ -17,5 +17,4 @@
/// Value node
/// </summary>
Value
}
}
@@ -1,28 +1,27 @@
using System;
using System.Collections.Concurrent;
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using System.Text.Json;
using CryptoExchange.Net.Attributes;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Diagnostics;
namespace CryptoExchange.Net.Converters.SystemTextJson
{
/// <summary>
/// Converter for arrays to objects. Can deserialize data like [0.1, 0.2, "test"] to an object. Mapping is done by marking the class with [JsonConverter(typeof(ArrayConverter))] and the properties
/// with [ArrayProperty(x)] where x is the index of the property in the array
/// </summary>
#if NET5_0_OR_GREATER
public class ArrayConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T> : JsonConverter<T> where T : new()
#else
public class ArrayConverter<T> : JsonConverter<T> where T : new()
using System.Diagnostics.CodeAnalysis;
#endif
{
using System.Threading;
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Converter for arrays to objects. Can deserialize data like [0.1, 0.2, "test"] to an object. Mapping is done by marking the class with [JsonConverter(typeof(ArrayConverter))] and the properties
/// with [ArrayProperty(x)] where x is the index of the property in the array
/// </summary>
#if NET5_0_OR_GREATER
public class ArrayConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T> : JsonConverter<T> where T : new()
#else
public class ArrayConverter<T> : JsonConverter<T> where T : new()
#endif
{
private static readonly Lazy<List<ArrayPropertyInfo>> _typePropertyInfo = new Lazy<List<ArrayPropertyInfo>>(CacheTypeAttributes, LazyThreadSafetyMode.PublicationOnly);
/// <inheritdoc />
@@ -228,7 +227,6 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
public JsonConverter? JsonConverter { get; set; }
public bool DefaultDeserialization { get; set; }
public Type TargetType { get; set; } = null!;
public JsonSerializerOptions? JsonSerializerOptions { get; set; } = null;
}
public JsonSerializerOptions? JsonSerializerOptions { get; set; }
}
}
@@ -1,15 +1,15 @@
using System;
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Decimal converter that handles overflowing decimal values (by setting it to decimal.MaxValue)
/// </summary>
public class BigDecimalConverter : JsonConverter<decimal>
{
/// <summary>
/// Decimal converter that handles overflowing decimal values (by setting it to decimal.MaxValue)
/// </summary>
public class BigDecimalConverter : JsonConverter<decimal>
{
/// <inheritdoc />
public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
@@ -42,5 +42,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
{
writer.WriteNumberValue(value);
}
}
}
@@ -1,16 +1,16 @@
using System;
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Bool converter
/// </summary>
public class BoolConverter : JsonConverterFactory
{
/// <summary>
/// Bool converter
/// </summary>
public class BoolConverter : JsonConverterFactory
{
/// <inheritdoc />
public override bool CanConvert(Type typeToConvert)
{
@@ -28,7 +28,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> (T)((object?)ReadBool(ref reader, typeToConvert, options) ?? default(T))!;
public bool? ReadBool(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
public static bool? ReadBool(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.True)
return true;
@@ -80,5 +80,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
}
}
}
}
@@ -1,23 +1,23 @@
using System;
using System.Collections.Generic;
using System;
#if NET5_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
{
/// <summary>
/// Converter for comma separated enum values
/// </summary>
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Converter for comma separated enum values
/// </summary>
#if NET5_0_OR_GREATER
public class CommaSplitEnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] T> : JsonConverter<T[]> where T : struct, Enum
public class CommaSplitEnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] T> : JsonConverter<T[]> where T : struct, Enum
#else
public class CommaSplitEnumConverter<T> : JsonConverter<T[]> where T : struct, Enum
public class CommaSplitEnumConverter<T> : JsonConverter<T[]> where T : struct, Enum
#endif
{
{
/// <inheritdoc />
public override T[]? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
@@ -33,5 +33,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
{
writer.WriteStringValue(string.Join(",", value.Select(x => EnumConverter.GetString(x))));
}
}
}
@@ -1,17 +1,17 @@
using System;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Date time converter
/// </summary>
public class DateTimeConverter : JsonConverterFactory
{
/// <summary>
/// Date time converter
/// </summary>
public class DateTimeConverter : JsonConverterFactory
{
private static readonly DateTime _epoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private const long _ticksPerSecond = TimeSpan.TicksPerMillisecond * 1000;
private const double _ticksPerMicrosecond = TimeSpan.TicksPerMillisecond / 1000d;
@@ -34,7 +34,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> (T)((object?)ReadDateTime(ref reader, typeToConvert, options) ?? default(T))!;
private DateTime? ReadDateTime(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
private static DateTime? ReadDateTime(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
@@ -238,5 +238,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
/// <returns></returns>
[return: NotNullIfNotNull("time")]
public static long? ConvertToNanoseconds(DateTime? time) => time == null ? null : (long)Math.Round((time.Value - _epoch).Ticks / _ticksPerNanosecond);
}
}
@@ -1,15 +1,14 @@
using System;
using System.Globalization;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Decimal converter
/// </summary>
public class DecimalConverter : JsonConverter<decimal?>
{
/// <summary>
/// Decimal converter
/// </summary>
public class DecimalConverter : JsonConverter<decimal?>
{
/// <inheritdoc />
public override decimal? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
@@ -41,5 +40,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
else
writer.WriteNumberValue(value.Value);
}
}
}
@@ -1,15 +1,15 @@
using System;
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Converter for serializing decimal values as string
/// </summary>
public class DecimalStringWriterConverter : JsonConverter<decimal>
{
/// <summary>
/// Converter for serializing decimal values as string
/// </summary>
public class DecimalStringWriterConverter : JsonConverter<decimal>
{
/// <inheritdoc />
public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
@@ -19,5 +19,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture) ?? null);
}
}
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Attributes;
using CryptoExchange.Net.Attributes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -9,13 +9,13 @@ using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Static EnumConverter methods
/// </summary>
public static class EnumConverter
{
/// <summary>
/// Static EnumConverter methods
/// </summary>
public static class EnumConverter
{
/// <summary>
/// Get the enum value from a string
/// </summary>
@@ -52,20 +52,20 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
public static string? GetString<T>(T? enumValue) where T : struct, Enum
#endif
=> EnumConverter<T>.GetString(enumValue);
}
}
/// <summary>
/// Converter for enum values. Enums entries should be noted with a MapAttribute to map the enum value to a string value
/// </summary>
/// <summary>
/// Converter for enum values. Enums entries should be noted with a MapAttribute to map the enum value to a string value
/// </summary>
#if NET5_0_OR_GREATER
public class EnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] T>
public class EnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] T>
#else
public class EnumConverter<T>
public class EnumConverter<T>
#endif
: JsonConverter<T>, INullableConverterFactory where T : struct, Enum
{
private static List<KeyValuePair<T, string>>? _mapping = null;
private NullableEnumConverter? _nullableEnumConverter = null;
{
private static List<KeyValuePair<T, string>>? _mapping;
private NullableEnumConverter? _nullableEnumConverter;
private static ConcurrentBag<string> _unknownValuesWarned = new ConcurrentBag<string>();
@@ -79,7 +79,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
}
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return _enumConverter.ReadNullable(ref reader, typeToConvert, options, out var isEmptyString, out var warn);
return EnumConverter<T>.ReadNullable(ref reader, typeToConvert, options, out var isEmptyString, out var warn);
}
public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
@@ -122,7 +122,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
}
}
private T? ReadNullable(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, out bool isEmptyString, out bool warn)
private static T? ReadNullable(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, out bool isEmptyString, out bool warn)
{
isEmptyString = false;
warn = false;
@@ -285,5 +285,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
_nullableEnumConverter ??= new NullableEnumConverter(this);
return _nullableEnumConverter;
}
}
}
@@ -1,15 +1,14 @@
using System;
using System.Globalization;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Converter for serializing enum values as int
/// </summary>
public class EnumIntWriterConverter<T> : JsonConverter<T> where T: struct, Enum
{
/// <summary>
/// Converter for serializing enum values as int
/// </summary>
public class EnumIntWriterConverter<T> : JsonConverter<T> where T: struct, Enum
{
/// <inheritdoc />
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
@@ -19,5 +18,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
=> writer.WriteNumberValue((int)(object)value);
}
}
@@ -1,9 +1,8 @@
using System.Text.Json.Serialization;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
internal interface INullableConverterFactory
{
internal interface INullableConverterFactory
{
JsonConverter CreateNullableConverter();
}
}
@@ -1,15 +1,15 @@
using System;
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Int converter
/// </summary>
public class IntConverter : JsonConverter<int?>
{
/// <summary>
/// Int converter
/// </summary>
public class IntConverter : JsonConverter<int?>
{
/// <inheritdoc />
public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
@@ -36,5 +36,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
else
writer.WriteNumberValue(value.Value);
}
}
}
@@ -1,15 +1,15 @@
using System;
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Int converter
/// </summary>
public class LongConverter : JsonConverter<long?>
{
/// <summary>
/// Int converter
/// </summary>
public class LongConverter : JsonConverter<long?>
{
/// <inheritdoc />
public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
@@ -36,5 +36,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
else
writer.WriteNumberValue(value.Value);
}
}
}
@@ -1,14 +1,12 @@
using System;
using System.Collections.Generic;
using System.Text;
using System;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
internal class NullableEnumConverterFactory : JsonConverterFactory
{
internal class NullableEnumConverterFactory : JsonConverterFactory
{
private readonly IJsonTypeInfoResolver _jsonTypeInfoResolver;
private static readonly JsonSerializerOptions _options = new JsonSerializerOptions();
@@ -39,5 +37,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
return nullConverterFactory.CreateNullableConverter();
}
}
}
@@ -1,14 +1,14 @@
using System;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Read string or number as string
/// </summary>
public class NumberStringConverter : JsonConverter<string?>
{
/// <summary>
/// Read string or number as string
/// </summary>
public class NumberStringConverter : JsonConverter<string?>
{
/// <inheritdoc />
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
@@ -38,5 +38,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
{
writer.WriteStringValue(value);
}
}
}
@@ -1,15 +1,17 @@
using System;
using System;
using System.Text.Json.Serialization;
using System.Text.Json;
#if NET5_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Converter for values which contain a nested json value
/// </summary>
public class ObjectStringConverter<T> : JsonConverter<T>
{
/// <summary>
/// Converter for values which contain a nested json value
/// </summary>
public class ObjectStringConverter<T> : JsonConverter<T>
{
/// <inheritdoc />
#if NET5_0_OR_GREATER
[UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL3050:RequiresUnreferencedCode", Justification = "JsonSerializerOptions provided here has TypeInfoResolver set")]
@@ -24,7 +26,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
if (string.IsNullOrEmpty(value))
return default;
return (T?)JsonDocument.Parse(value!).Deserialize(typeof(T), options);
return JsonDocument.Parse(value!).Deserialize<T>(options);
}
/// <inheritdoc />
@@ -39,5 +41,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
writer.WriteStringValue(JsonSerializer.Serialize(value, options));
}
}
}
@@ -1,15 +1,15 @@
using System;
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Replace a value on a string property
/// </summary>
public abstract class ReplaceConverter : JsonConverter<string>
{
/// <summary>
/// Replace a value on a string property
/// </summary>
public abstract class ReplaceConverter : JsonConverter<string>
{
private readonly (string ValueToReplace, string ValueToReplaceWith)[] _replacementSets;
/// <summary>
@@ -19,7 +19,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
{
_replacementSets = replaceSets.Select(x =>
{
var split = x.Split(new string[] { "->" }, StringSplitOptions.None);
var split = x.Split(["->"], StringSplitOptions.None);
if (split.Length != 2)
throw new ArgumentException("Invalid replacement config");
return (split[0], split[1]);
@@ -37,5 +37,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) => writer.WriteStringValue(value);
}
}
@@ -1,15 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;
using System;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Attribute to mark a model as json serializable. Used for AOT compilation.
/// </summary>
[AttributeUsage(System.AttributeTargets.Class | AttributeTargets.Enum | System.AttributeTargets.Interface)]
public class SerializationModelAttribute : Attribute
{
/// <summary>
/// Attribute to mark a model as json serializable. Used for AOT compilation.
/// </summary>
[AttributeUsage(System.AttributeTargets.Class | AttributeTargets.Enum | System.AttributeTargets.Interface)]
public class SerializationModelAttribute : Attribute
{
/// <summary>
/// ctor
/// </summary>
@@ -19,5 +17,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
/// </summary>
/// <param name="type"></param>
public SerializationModelAttribute(Type type) { }
}
}
@@ -1,14 +1,14 @@
using System.Collections.Concurrent;
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// Serializer options
/// </summary>
public static class SerializerOptions
{
/// <summary>
/// Serializer options
/// </summary>
public static class SerializerOptions
{
private static readonly ConcurrentDictionary<JsonSerializerContext, JsonSerializerOptions> _cache = new ConcurrentDictionary<JsonSerializerContext, JsonSerializerOptions>();
/// <summary>
@@ -43,5 +43,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
return options;
}
}
}
@@ -1,17 +1,15 @@
using CryptoExchange.Net.SharedApis;
using CryptoExchange.Net.SharedApis;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
{
internal class SharedQuantityConverter : SharedQuantityReferenceConverter<SharedQuantity> { }
internal class SharedOrderQuantityConverter : SharedQuantityReferenceConverter<SharedOrderQuantity> { }
namespace CryptoExchange.Net.Converters.SystemTextJson;
internal class SharedQuantityReferenceConverter<T> : JsonConverter<T> where T: SharedQuantityReference, new()
{
internal class SharedQuantityConverter : SharedQuantityReferenceConverter<SharedQuantity> { }
internal class SharedOrderQuantityConverter : SharedQuantityReferenceConverter<SharedOrderQuantity> { }
internal class SharedQuantityReferenceConverter<T> : JsonConverter<T> where T: SharedQuantityReference, new()
{
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray)
@@ -56,5 +54,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
writer.WriteNumberValue(value.QuantityInContracts.Value);
writer.WriteEndArray();
}
}
}
@@ -1,14 +1,12 @@
using CryptoExchange.Net.SharedApis;
using CryptoExchange.Net.SharedApis;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
internal class SharedSymbolConverter : JsonConverter<SharedSymbol>
{
internal class SharedSymbolConverter : JsonConverter<SharedSymbol>
{
public override SharedSymbol? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray)
@@ -42,5 +40,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
writer.WriteStringValue(value.DeliverTime?.ToString());
writer.WriteEndArray();
}
}
}
@@ -1,21 +1,22 @@
using CryptoExchange.Net.Converters.MessageParsing;
using CryptoExchange.Net.Converters.MessageParsing;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
#if NET5_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <summary>
/// System.Text.Json message accessor
/// </summary>
public abstract class SystemTextJsonMessageAccessor : IMessageAccessor
{
/// <summary>
/// System.Text.Json message accessor
/// </summary>
public abstract class SystemTextJsonMessageAccessor : IMessageAccessor
{
/// <summary>
/// The JsonDocument loaded
/// </summary>
@@ -235,13 +236,15 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
/// <inheritdoc />
public abstract void Clear();
}
}
/// <summary>
/// System.Text.Json stream message accessor
/// </summary>
public class SystemTextJsonStreamMessageAccessor : SystemTextJsonMessageAccessor, IStreamMessageAccessor
{
/// <summary>
/// System.Text.Json stream message accessor
/// </summary>
#pragma warning disable CA1001 // Types that own disposable fields should be disposable
public class SystemTextJsonStreamMessageAccessor : SystemTextJsonMessageAccessor, IStreamMessageAccessor
#pragma warning restore CA1001 // Types that own disposable fields should be disposable
{
private Stream? _stream;
/// <inheritdoc />
@@ -308,13 +311,13 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
_document = null;
}
}
}
/// <summary>
/// System.Text.Json byte message accessor
/// </summary>
public class SystemTextJsonByteMessageAccessor : SystemTextJsonMessageAccessor, IByteMessageAccessor
{
/// <summary>
/// System.Text.Json byte message accessor
/// </summary>
public class SystemTextJsonByteMessageAccessor : SystemTextJsonMessageAccessor, IByteMessageAccessor
{
private ReadOnlyMemory<byte> _bytes;
/// <summary>
@@ -370,5 +373,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
_document?.Dispose();
_document = null;
}
}
}
@@ -1,14 +1,14 @@
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Interfaces;
#if NET5_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace CryptoExchange.Net.Converters.SystemTextJson
namespace CryptoExchange.Net.Converters.SystemTextJson;
/// <inheritdoc />
public class SystemTextJsonMessageSerializer : IStringMessageSerializer
{
/// <inheritdoc />
public class SystemTextJsonMessageSerializer : IStringMessageSerializer
{
private readonly JsonSerializerOptions _options;
/// <summary>
@@ -25,5 +25,4 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
[UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL3050:RequiresUnreferencedCode", Justification = "Everything referenced in the loaded assembly is manually preserved, so it's safe")]
#endif
public string Serialize<T>(T message) => JsonSerializer.Serialize(message, _options);
}
}
@@ -24,6 +24,7 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
</PropertyGroup>
<ItemGroup>
<None Include="C:\Projects\CryptoExchange.Net\CryptoExchange.Net\.editorconfig" />
<None Include="Icon\icon.png" Pack="true" PackagePath="\" />
<None Include="..\README.md" Pack="true" PackagePath="\" />
</ItemGroup>
@@ -40,6 +41,12 @@
<PropertyGroup>
<DocumentationFile>CryptoExchange.Net.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>Recommended</AnalysisMode>
<AnalysisModeGlobalization>None</AnalysisModeGlobalization>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ConfigureAwaitChecker.Analyzer" Version="5.0.0.1">
<PrivateAssets>all</PrivateAssets>
@@ -58,4 +65,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Http" Version="9.0.6" />
</ItemGroup>
<ItemGroup>
<EditorConfigFiles Remove="C:\Projects\CryptoExchange.Net\CryptoExchange.Net\.editorconfig" />
</ItemGroup>
</Project>
+14 -13
View File
@@ -1,20 +1,22 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.SharedApis;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
#if NETSTANDARD2_1_OR_GREATER || NET9_0_OR_GREATER
using System.Security.Cryptography;
#endif
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net
namespace CryptoExchange.Net;
/// <summary>
/// General helpers functions
/// </summary>
public static class ExchangeHelpers
{
/// <summary>
/// General helpers functions
/// </summary>
public static class ExchangeHelpers
{
private const string _allowedRandomChars = "ABCDEFGHIJKLMONOPQRSTUVWXYZabcdefghijklmonopqrstuvwxyz0123456789";
private const string _allowedRandomHexChars = "0123456789ABCDEF";
@@ -287,16 +289,16 @@ namespace CryptoExchange.Net
/// <summary>
/// Execute multiple requests to retrieve multiple pages of the result set
/// </summary>
/// <typeparam name="T">Type of the client</typeparam>
/// <typeparam name="U">Type of the request</typeparam>
/// <typeparam name="TResult">Type of the client</typeparam>
/// <typeparam name="TRequest">Type of the request</typeparam>
/// <param name="paginatedFunc">The func to execute with each request</param>
/// <param name="request">The request parameters</param>
/// <param name="ct">Cancellation token</param>
/// <returns></returns>
public static async IAsyncEnumerable<ExchangeWebResult<T[]>> ExecutePages<T, U>(Func<U, INextPageToken?, CancellationToken, Task<ExchangeWebResult<T[]>>> paginatedFunc, U request, [EnumeratorCancellation]CancellationToken ct = default)
public static async IAsyncEnumerable<ExchangeWebResult<TResult[]>> ExecutePages<TResult, TRequest>(Func<TRequest, INextPageToken?, CancellationToken, Task<ExchangeWebResult<TResult[]>>> paginatedFunc, TRequest request, [EnumeratorCancellation]CancellationToken ct = default)
{
var result = new List<T>();
ExchangeWebResult<T[]> batch;
var result = new List<TResult>();
ExchangeWebResult<TResult[]> batch;
INextPageToken? nextPageToken = null;
while (true)
{
@@ -385,5 +387,4 @@ namespace CryptoExchange.Net
// Unknown decimal format, return null
return null;
}
}
}
+7 -9
View File
@@ -1,17 +1,16 @@
using CryptoExchange.Net.SharedApis;
using CryptoExchange.Net.SharedApis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CryptoExchange.Net
namespace CryptoExchange.Net;
/// <summary>
/// Cache for symbol parsing
/// </summary>
public static class ExchangeSymbolCache
{
/// <summary>
/// Cache for symbol parsing
/// </summary>
public static class ExchangeSymbolCache
{
private static ConcurrentDictionary<string, ExchangeInfo> _symbolInfos = new ConcurrentDictionary<string, ExchangeInfo>();
/// <summary>
@@ -66,5 +65,4 @@ namespace CryptoExchange.Net
Symbols = symbols;
}
}
}
}
+7 -11
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
@@ -10,17 +10,14 @@ using CryptoExchange.Net.Objects;
using System.Globalization;
using Microsoft.Extensions.DependencyInjection;
using CryptoExchange.Net.SharedApis;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CryptoExchange.Net
namespace CryptoExchange.Net;
/// <summary>
/// Helper methods
/// </summary>
public static class ExtensionMethods
{
/// <summary>
/// Helper methods
/// </summary>
public static class ExtensionMethods
{
/// <summary>
/// Add a parameter
/// </summary>
@@ -519,6 +516,5 @@ namespace CryptoExchange.Net
return services;
}
}
}
@@ -1,16 +1,15 @@
using System;
using System;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Time provider
/// </summary>
internal interface IAuthTimeProvider
{
/// <summary>
/// Time provider
/// </summary>
internal interface IAuthTimeProvider
{
/// <summary>
/// Get current time
/// </summary>
/// <returns></returns>
DateTime GetTime();
}
}
@@ -1,16 +1,15 @@
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Objects.Options;
using CryptoExchange.Net.SharedApis;
using System;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Base api client
/// </summary>
public interface IBaseApiClient
{
/// <summary>
/// Base api client
/// </summary>
public interface IBaseApiClient
{
/// <summary>
/// Base address
/// </summary>
@@ -44,5 +43,4 @@ namespace CryptoExchange.Net.Interfaces
/// <typeparam name="T">Api credentials type</typeparam>
/// <param name="options">Options to set</param>
void SetOptions<T>(UpdateOptions<T> options) where T : ApiCredentials;
}
}
@@ -1,17 +1,16 @@
using System;
using System;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Client for accessing REST API's for different exchanges
/// </summary>
public interface ICryptoRestClient
{
/// <summary>
/// Client for accessing REST API's for different exchanges
/// </summary>
public interface ICryptoRestClient
{
/// <summary>
/// Try get
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T TryGet<T>(Func<T> createFunc);
}
}
@@ -1,17 +1,16 @@
using System;
using System;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Client for accessing Websocket API's for different exchanges
/// </summary>
public interface ICryptoSocketClient
{
/// <summary>
/// Client for accessing Websocket API's for different exchanges
/// </summary>
public interface ICryptoSocketClient
{
/// <summary>
/// Try get a client by type for the service collection
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T TryGet<T>(Func<T> createFunc);
}
}
@@ -1,18 +1,19 @@
using CryptoExchange.Net.Converters.MessageParsing;
using CryptoExchange.Net.Converters.MessageParsing;
using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
#if NET5_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
using System.IO;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Message accessor
/// </summary>
public interface IMessageAccessor
{
/// <summary>
/// Message accessor
/// </summary>
public interface IMessageAccessor
{
/// <summary>
/// Is this a valid message
/// </summary>
@@ -81,30 +82,29 @@ namespace CryptoExchange.Net.Interfaces
/// </summary>
/// <returns></returns>
string GetOriginalString();
}
}
/// <summary>
/// Stream message accessor
/// </summary>
public interface IStreamMessageAccessor : IMessageAccessor
{
/// <summary>
/// Stream message accessor
/// </summary>
public interface IStreamMessageAccessor : IMessageAccessor
{
/// <summary>
/// Load a stream message
/// </summary>
/// <param name="stream"></param>
/// <param name="bufferStream"></param>
Task<CallResult> Read(Stream stream, bool bufferStream);
}
}
/// <summary>
/// Byte message accessor
/// </summary>
public interface IByteMessageAccessor : IMessageAccessor
{
/// <summary>
/// Byte message accessor
/// </summary>
public interface IByteMessageAccessor : IMessageAccessor
{
/// <summary>
/// Load a data message
/// </summary>
/// <param name="data"></param>
CallResult Read(ReadOnlyMemory<byte> data);
}
}
@@ -1,17 +1,16 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects.Sockets;
using CryptoExchange.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Message processor
/// </summary>
public interface IMessageProcessor
{
/// <summary>
/// Message processor
/// </summary>
public interface IMessageProcessor
{
/// <summary>
/// Id of the processor
/// </summary>
@@ -31,5 +30,4 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="type"></param>
/// <returns></returns>
CallResult<object> Deserialize(IMessageAccessor accessor, Type type);
}
}
@@ -1,37 +1,34 @@
using System.Diagnostics.CodeAnalysis;
namespace CryptoExchange.Net.Interfaces;
namespace CryptoExchange.Net.Interfaces
/// <summary>
/// Serializer interface
/// </summary>
public interface IMessageSerializer
{
/// <summary>
/// Serializer interface
/// </summary>
public interface IMessageSerializer
{
}
}
/// <summary>
/// Serialize to byte array
/// </summary>
public interface IByteMessageSerializer: IMessageSerializer
{
/// <summary>
/// Serialize to byte array
/// </summary>
public interface IByteMessageSerializer: IMessageSerializer
{
/// <summary>
/// Serialize an object to a string
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
byte[] Serialize<T>(T message);
}
}
/// <summary>
/// Serialize to string
/// </summary>
public interface IStringMessageSerializer: IMessageSerializer
{
/// <summary>
/// Serialize to string
/// </summary>
public interface IStringMessageSerializer: IMessageSerializer
{
/// <summary>
/// Serialize an object to a string
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
string Serialize<T>(T message);
}
}
@@ -1,14 +1,13 @@
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// A provider for a nonce value used when signing requests
/// </summary>
public interface INonceProvider
{
/// <summary>
/// A provider for a nonce value used when signing requests
/// </summary>
public interface INonceProvider
{
/// <summary>
/// Get nonce value. Nonce value should be unique and incremental for each call
/// </summary>
/// <returns>Nonce value</returns>
long GetNonce();
}
}
@@ -1,14 +1,14 @@
using CryptoExchange.Net.Objects.Options;
using CryptoExchange.Net.Objects.Options;
using CryptoExchange.Net.SharedApis;
using System;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Factory for ISymbolOrderBook instances
/// </summary>
public interface IOrderBookFactory<TOptions> where TOptions : OrderBookOptions
{
/// <summary>
/// Factory for ISymbolOrderBook instances
/// </summary>
public interface IOrderBookFactory<TOptions> where TOptions : OrderBookOptions
{
/// <summary>
/// Create a new order book by symbol name
/// </summary>
@@ -31,5 +31,4 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="options">Options for the order book</param>
/// <returns></returns>
public ISymbolOrderBook Create(SharedSymbol symbol, Action<TOptions>? options = null);
}
}
@@ -4,13 +4,13 @@ using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Rate limiter interface
/// </summary>
public interface IRateLimiter
{
/// <summary>
/// Rate limiter interface
/// </summary>
public interface IRateLimiter
{
/// <summary>
/// Limit a request based on previous requests made
/// </summary>
@@ -24,5 +24,4 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="ct">Cancellation token to cancel waiting</param>
/// <returns>The time in milliseconds spend waiting</returns>
Task<CallResult<int>> LimitRequestAsync(ILogger log, string endpoint, HttpMethod method, bool signed, string? apiKey, RateLimitingBehaviour limitBehaviour, int requestWeight, CancellationToken ct);
}
}
+7 -8
View File
@@ -1,16 +1,16 @@
using System;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Request interface
/// </summary>
public interface IRequest
{
/// <summary>
/// Request interface
/// </summary>
public interface IRequest
{
/// <summary>
/// Accept header
/// </summary>
@@ -62,5 +62,4 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IResponse> GetResponseAsync(CancellationToken cancellationToken);
}
}
@@ -1,14 +1,14 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects;
using System;
using System.Net.Http;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Request factory interface
/// </summary>
public interface IRequestFactory
{
/// <summary>
/// Request factory interface
/// </summary>
public interface IRequestFactory
{
/// <summary>
/// Create a request for an uri
/// </summary>
@@ -32,5 +32,4 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="proxy">Proxy to use</param>
/// <param name="requestTimeout">Request timeout to use</param>
void UpdateSettings(ApiProxy? proxy, TimeSpan requestTimeout);
}
}
+7 -8
View File
@@ -1,15 +1,15 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Response object interface
/// </summary>
public interface IResponse
{
/// <summary>
/// Response object interface
/// </summary>
public interface IResponse
{
/// <summary>
/// The response status code
/// </summary>
@@ -40,5 +40,4 @@ namespace CryptoExchange.Net.Interfaces
/// Close the response
/// </summary>
void Close();
}
}
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Base rest API client
/// </summary>
public interface IRestApiClient : IBaseApiClient
{
/// <summary>
/// Base rest API client
/// </summary>
public interface IRestApiClient : IBaseApiClient
{
/// <summary>
/// The factory for creating requests. Used for unit testing
/// </summary>
@@ -14,5 +14,4 @@
/// Total amount of requests made with this API client
/// </summary>
int TotalRequestsMade { get; set; }
}
}
+7 -8
View File
@@ -1,13 +1,13 @@
using System;
using System;
using CryptoExchange.Net.Objects.Options;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Base class for rest API implementations
/// </summary>
public interface IRestClient: IDisposable
{
/// <summary>
/// Base class for rest API implementations
/// </summary>
public interface IRestClient: IDisposable
{
/// <summary>
/// The options provided for this client
/// </summary>
@@ -22,5 +22,4 @@ namespace CryptoExchange.Net.Interfaces
/// The exchange name
/// </summary>
string Exchange { get; }
}
}
@@ -1,15 +1,15 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects.Options;
using CryptoExchange.Net.Objects.Sockets;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Socket API client
/// </summary>
public interface ISocketApiClient: IBaseApiClient
{
/// <summary>
/// Socket API client
/// </summary>
public interface ISocketApiClient: IBaseApiClient
{
/// <summary>
/// The current amount of socket connections on the API client
/// </summary>
@@ -66,5 +66,4 @@ namespace CryptoExchange.Net.Interfaces
/// </summary>
/// <returns></returns>
Task<CallResult> PrepareConnectionsAsync();
}
}
@@ -1,15 +1,15 @@
using System;
using System;
using System.Threading.Tasks;
using CryptoExchange.Net.Objects.Options;
using CryptoExchange.Net.Objects.Sockets;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Base class for socket API implementations
/// </summary>
public interface ISocketClient: IDisposable
{
/// <summary>
/// Base class for socket API implementations
/// </summary>
public interface ISocketClient: IDisposable
{
/// <summary>
/// The exchange name
/// </summary>
@@ -54,5 +54,4 @@ namespace CryptoExchange.Net.Interfaces
/// </summary>
/// <returns></returns>
Task UnsubscribeAllAsync();
}
}
@@ -1,16 +1,15 @@
using System;
using System.Collections.Generic;
using System;
using System.Threading;
using System.Threading.Tasks;
using CryptoExchange.Net.Objects;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Interface for order book
/// </summary>
public interface ISymbolOrderBook
{
/// <summary>
/// Interface for order book
/// </summary>
public interface ISymbolOrderBook
{
/// <summary>
/// The exchange the book is for
/// </summary>
@@ -127,5 +126,4 @@ namespace CryptoExchange.Net.Interfaces
/// </summary>
/// <returns></returns>
string ToString(int rows);
}
}
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Interface for order book entries
/// </summary>
public interface ISymbolOrderBookEntry
{
/// <summary>
/// Interface for order book entries
/// </summary>
public interface ISymbolOrderBookEntry
{
/// <summary>
/// The quantity of the entry
/// </summary>
@@ -13,16 +13,15 @@
/// The price of the entry
/// </summary>
decimal Price { get; set; }
}
}
/// <summary>
/// Interface for order book entries
/// </summary>
public interface ISymbolOrderSequencedBookEntry: ISymbolOrderBookEntry
{
/// <summary>
/// Interface for order book entries
/// </summary>
public interface ISymbolOrderSequencedBookEntry: ISymbolOrderBookEntry
{
/// <summary>
/// Sequence of the update
/// </summary>
long Sequence { get; set; }
}
}
+7 -8
View File
@@ -1,16 +1,16 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects;
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Websocket connection interface
/// </summary>
public interface IWebsocket: IDisposable
{
/// <summary>
/// Websocket connection interface
/// </summary>
public interface IWebsocket: IDisposable
{
/// <summary>
/// Websocket closed event
/// </summary>
@@ -106,5 +106,4 @@ namespace CryptoExchange.Net.Interfaces
/// Update proxy setting
/// </summary>
void UpdateProxy(ApiProxy? proxy);
}
}
@@ -1,13 +1,13 @@
using CryptoExchange.Net.Objects.Sockets;
using CryptoExchange.Net.Objects.Sockets;
using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Interfaces
namespace CryptoExchange.Net.Interfaces;
/// <summary>
/// Websocket factory interface
/// </summary>
public interface IWebsocketFactory
{
/// <summary>
/// Websocket factory interface
/// </summary>
public interface IWebsocketFactory
{
/// <summary>
/// Create a websocket for an url
/// </summary>
@@ -15,5 +15,4 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="parameters">The parameters to use for the connection</param>
/// <returns></returns>
IWebsocket CreateWebsocket(ILogger logger, WebSocketParameters parameters);
}
}
+5 -10
View File
@@ -1,14 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace CryptoExchange.Net;
namespace CryptoExchange.Net
/// <summary>
/// Helpers for client libraries
/// </summary>
public static class LibraryHelpers
{
/// <summary>
/// Helpers for client libraries
/// </summary>
public static class LibraryHelpers
{
/// <summary>
/// Client order id separator
/// </summary>
@@ -43,5 +39,4 @@ namespace CryptoExchange.Net
return clientOrderId;
}
}
}
@@ -1,11 +1,11 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using System;
namespace CryptoExchange.Net.Logging.Extensions
{
namespace CryptoExchange.Net.Logging.Extensions;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class CryptoExchangeWebSocketClientLoggingExtension
{
public static class CryptoExchangeWebSocketClientLoggingExtension
{
private static readonly Action<ILogger, int, Exception?> _connecting;
private static readonly Action<ILogger, int, string, Exception?> _connectionFailed;
private static readonly Action<ILogger, int, Exception?> _connectingCanceled;
@@ -383,5 +383,4 @@ namespace CryptoExchange.Net.Logging.Extensions
{
_connectingCanceled(logger, socketId, null);
}
}
}
@@ -1,11 +1,11 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using System;
namespace CryptoExchange.Net.Logging.Extensions
{
namespace CryptoExchange.Net.Logging.Extensions;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class RateLimitGateLoggingExtensions
{
public static class RateLimitGateLoggingExtensions
{
private static readonly Action<ILogger, int, string, string, string, Exception?> _rateLimitRequestFailed;
private static readonly Action<ILogger, int, string, string, Exception?> _rateLimitConnectionFailed;
private static readonly Action<ILogger, int, string, TimeSpan, string, string, Exception?> _rateLimitDelayingRequest;
@@ -75,5 +75,4 @@ namespace CryptoExchange.Net.Logging.Extensions
{
_rateLimitAppliedRequest(logger, requestIdId, path, guard, limit, current, null);
}
}
}
@@ -1,14 +1,14 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Net.Http;
namespace CryptoExchange.Net.Logging.Extensions
{
namespace CryptoExchange.Net.Logging.Extensions;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class RestApiClientLoggingExtensions
{
public static class RestApiClientLoggingExtensions
{
private static readonly Action<ILogger, int?, int?, long, string?, string?, Exception?> _restApiErrorReceived;
private static readonly Action<ILogger, int?, int?, long, string?, Exception?> _restApiResponseReceived;
private static readonly Action<ILogger, int, string, Exception?> _restApiFailedToSyncTime;
@@ -155,5 +155,4 @@ namespace CryptoExchange.Net.Logging.Extensions
{
_restApiCancellationRequested(logger, requestId, null);
}
}
}
@@ -1,11 +1,11 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using System;
namespace CryptoExchange.Net.Logging.Extensions
{
namespace CryptoExchange.Net.Logging.Extensions;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class SocketApiClientLoggingExtension
{
public static class SocketApiClientLoggingExtension
{
private static readonly Action<ILogger, int, Exception?> _failedToAddSubscriptionRetryOnDifferentConnection;
private static readonly Action<ILogger, int, Exception?> _hasBeenPausedCantSubscribeAtThisMoment;
private static readonly Action<ILogger, int, string?, Exception?> _failedToSubscribe;
@@ -196,5 +196,4 @@ namespace CryptoExchange.Net.Logging.Extensions
{
_addingRetryAfterGuard(logger, retryAfter, null);
}
}
}
@@ -1,12 +1,12 @@
using System;
using System;
using System.Net.WebSockets;
using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Logging.Extensions
{
namespace CryptoExchange.Net.Logging.Extensions;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class SocketConnectionLoggingExtension
{
public static class SocketConnectionLoggingExtension
{
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;
@@ -345,5 +345,4 @@ namespace CryptoExchange.Net.Logging.Extensions
{
_sendingByteData(logger, socketId, requestId, length, null);
}
}
}
@@ -1,13 +1,13 @@
using System;
using System;
using CryptoExchange.Net.Objects;
using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Logging.Extensions
{
namespace CryptoExchange.Net.Logging.Extensions;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class SymbolOrderBookLoggingExtensions
{
public static class SymbolOrderBookLoggingExtensions
{
private static readonly Action<ILogger, string, string, OrderBookStatus, OrderBookStatus, Exception?> _orderBookStatusChanged;
private static readonly Action<ILogger, string, string, Exception?> _orderBookStarting;
private static readonly Action<ILogger, string, string, Exception?> _orderBookStoppedStarting;
@@ -233,5 +233,4 @@ namespace CryptoExchange.Net.Logging.Extensions
{
_orderBookOutOfSyncChecksum(logger, api, symbol, null);
}
}
}
@@ -1,13 +1,13 @@
using System;
using System;
using CryptoExchange.Net.Objects;
using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Logging.Extensions
{
namespace CryptoExchange.Net.Logging.Extensions;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public static class TrackerLoggingExtensions
{
public static class TrackerLoggingExtensions
{
private static readonly Action<ILogger, string, SyncStatus, SyncStatus, Exception?> _klineTrackerStatusChanged;
private static readonly Action<ILogger, string, Exception?> _klineTrackerStarting;
private static readonly Action<ILogger, string, string, Exception?> _klineTrackerStartFailed;
@@ -287,5 +287,4 @@ namespace CryptoExchange.Net.Logging.Extensions
{
_tradeTrackerConnectionRestored(logger, symbol, null);
}
}
}
+6 -7
View File
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Objects
namespace CryptoExchange.Net.Objects;
/// <summary>
/// Proxy info
/// </summary>
public class ApiProxy
{
/// <summary>
/// Proxy info
/// </summary>
public class ApiProxy
{
/// <summary>
/// The host address of the proxy
/// </summary>
@@ -38,5 +38,4 @@
Login = login;
Password = password;
}
}
}
+5 -10
View File
@@ -1,14 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace CryptoExchange.Net.Objects;
namespace CryptoExchange.Net.Objects
/// <summary>
/// An alias used by the exchange for an asset commonly known by another name
/// </summary>
public class AssetAlias
{
/// <summary>
/// An alias used by the exchange for an asset commonly known by another name
/// </summary>
public class AssetAlias
{
/// <summary>
/// The name of the asset on the exchange
/// </summary>
@@ -26,5 +22,4 @@ namespace CryptoExchange.Net.Objects
ExchangeAssetName = exchangeName;
CommonAssetName = commonName;
}
}
}
@@ -1,15 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CryptoExchange.Net.Objects
namespace CryptoExchange.Net.Objects;
/// <summary>
/// Exchange configuration for asset aliases
/// </summary>
public class AssetAliasConfiguration
{
/// <summary>
/// Exchange configuration for asset aliases
/// </summary>
public class AssetAliasConfiguration
{
/// <summary>
/// Defined aliases
/// </summary>
@@ -30,5 +27,4 @@ namespace CryptoExchange.Net.Objects
/// </summary>
public string ExchangeToCommonName(string exchangeName) => !AutoConvertEnabled ? exchangeName : Aliases.SingleOrDefault(x => x.ExchangeAssetName == exchangeName)?.CommonAssetName ?? exchangeName;
}
}
@@ -1,17 +1,17 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Objects
namespace CryptoExchange.Net.Objects;
/// <summary>
/// Async auto reset based on Stephen Toub`s implementation
/// https://devblogs.microsoft.com/pfxteam/building-async-coordination-primitives-part-2-asyncautoresetevent/
/// </summary>
public class AsyncResetEvent : IDisposable
{
/// <summary>
/// Async auto reset based on Stephen Toub`s implementation
/// https://devblogs.microsoft.com/pfxteam/building-async-coordination-primitives-part-2-asyncautoresetevent/
/// </summary>
public class AsyncResetEvent : IDisposable
{
private static readonly Task<bool> _completed = Task.FromResult(true);
private Queue<TaskCompletionSource<bool>> _waits = new Queue<TaskCompletionSource<bool>>();
private bool _signaled;
@@ -106,15 +106,28 @@ namespace CryptoExchange.Net.Objects
toRelease.TrySetResult(true);
}
else if (!_signaled)
{
_signaled = true;
}
}
}
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose(bool disposing)
{
if (disposing)
{
_waits.Clear();
}
@@ -1,10 +1,9 @@
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Interfaces;
using System;
namespace CryptoExchange.Net.Objects
namespace CryptoExchange.Net.Objects;
internal class AuthTimeProvider : IAuthTimeProvider
{
internal class AuthTimeProvider : IAuthTimeProvider
{
public DateTime GetTime() => DateTime.UtcNow;
}
}
@@ -1,13 +1,13 @@
using System;
using System;
using System.Collections.Generic;
namespace CryptoExchange.Net.Objects
namespace CryptoExchange.Net.Objects;
/// <summary>
/// Comparer for byte order
/// </summary>
public class ByteOrderComparer : IComparer<byte[]>
{
/// <summary>
/// Comparer for byte order
/// </summary>
public class ByteOrderComparer : IComparer<byte[]>
{
/// <summary>
/// Compare function
/// </summary>
@@ -54,5 +54,4 @@ namespace CryptoExchange.Net.Objects
// Compare lengths.
return x.Length < y.Length ? -1 : 1;
}
}
}
+66 -67
View File
@@ -1,4 +1,4 @@
using CryptoExchange.Net.SharedApis;
using CryptoExchange.Net.SharedApis;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -6,13 +6,13 @@ using System.Net;
using System.Net.Http;
using System.Text;
namespace CryptoExchange.Net.Objects
namespace CryptoExchange.Net.Objects;
/// <summary>
/// The result of an operation
/// </summary>
public class CallResult
{
/// <summary>
/// The result of an operation
/// </summary>
public class CallResult
{
/// <summary>
/// Static success result
/// </summary>
@@ -51,14 +51,14 @@ namespace CryptoExchange.Net.Objects
{
return Success ? $"Success" : $"Error: {Error}";
}
}
}
/// <summary>
/// The result of an operation
/// </summary>
/// <typeparam name="T"></typeparam>
public class CallResult<T>: CallResult
{
/// <summary>
/// The result of an operation
/// </summary>
/// <typeparam name="T"></typeparam>
public class CallResult<T>: CallResult
{
/// <summary>
/// The data returned by the call, only available when Success = true
/// </summary>
@@ -140,12 +140,12 @@ namespace CryptoExchange.Net.Objects
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="data">The data of the new type</param>
/// <returns></returns>
public CallResult<K> As<K>([AllowNull] K data)
public CallResult<TNew> As<TNew>([AllowNull] TNew data)
{
return new CallResult<K>(data, OriginalData, Error);
return new CallResult<TNew>(data, OriginalData, Error);
}
/// <summary>
@@ -169,24 +169,24 @@ namespace CryptoExchange.Net.Objects
/// <summary>
/// Copy the CallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="data">The data</param>
/// <param name="error">The error returned</param>
/// <returns></returns>
public CallResult<K> AsErrorWithData<K>(Error error, K data)
public CallResult<TNew> AsErrorWithData<TNew>(Error error, TNew data)
{
return new CallResult<K>(data, OriginalData, error);
return new CallResult<TNew>(data, OriginalData, error);
}
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="error">The error to return</param>
/// <returns></returns>
public CallResult<K> AsError<K>(Error error)
public CallResult<TNew> AsError<TNew>(Error error)
{
return new CallResult<K>(default, OriginalData, error);
return new CallResult<TNew>(default, OriginalData, error);
}
/// <inheritdoc />
@@ -194,13 +194,13 @@ namespace CryptoExchange.Net.Objects
{
return Success ? $"Success" : $"Error: {Error}";
}
}
}
/// <summary>
/// The result of a request
/// </summary>
public class WebCallResult : CallResult
{
/// <summary>
/// The result of a request
/// </summary>
public class WebCallResult : CallResult
{
/// <summary>
/// The request http method
/// </summary>
@@ -292,49 +292,49 @@ namespace CryptoExchange.Net.Objects
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="data">The data of the new type</param>
/// <returns></returns>
public WebCallResult<K> As<K>([AllowNull] K data)
public WebCallResult<TNew> As<TNew>([AllowNull] TNew data)
{
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, 0, null, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, ResultDataSource.Server, data, Error);
return new WebCallResult<TNew>(ResponseStatusCode, ResponseHeaders, ResponseTime, 0, null, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, ResultDataSource.Server, data, Error);
}
/// <summary>
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="exchange">The exchange</param>
/// <param name="tradeMode">Trade mode the result applies to</param>
/// <param name="data">The data</param>
/// <returns></returns>
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode tradeMode, [AllowNull] K data)
public ExchangeWebResult<TNew> AsExchangeResult<TNew>(string exchange, TradingMode tradeMode, [AllowNull] TNew data)
{
return new ExchangeWebResult<K>(exchange, tradeMode, this.As<K>(data));
return new ExchangeWebResult<TNew>(exchange, tradeMode, this.As<TNew>(data));
}
/// <summary>
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="exchange">The exchange</param>
/// <param name="tradeModes">Trade modes the result applies to</param>
/// <param name="data">The data</param>
/// <returns></returns>
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode[]? tradeModes, [AllowNull] K data)
public ExchangeWebResult<TNew> AsExchangeResult<TNew>(string exchange, TradingMode[]? tradeModes, [AllowNull] TNew data)
{
return new ExchangeWebResult<K>(exchange, tradeModes, this.As<K>(data));
return new ExchangeWebResult<TNew>(exchange, tradeModes, this.As<TNew>(data));
}
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="error">The error returned</param>
/// <returns></returns>
public WebCallResult<K> AsError<K>(Error error)
public WebCallResult<TNew> AsError<TNew>(Error error)
{
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, 0, null, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, ResultDataSource.Server, default, error);
return new WebCallResult<TNew>(ResponseStatusCode, ResponseHeaders, ResponseTime, 0, null, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, ResultDataSource.Server, default, error);
}
/// <inheritdoc />
@@ -342,14 +342,14 @@ namespace CryptoExchange.Net.Objects
{
return (Success ? $"Success" : $"Error: {Error}") + $" in {ResponseTime}";
}
}
}
/// <summary>
/// The result of a request
/// </summary>
/// <typeparam name="T"></typeparam>
public class WebCallResult<T>: CallResult<T>
{
/// <summary>
/// The result of a request
/// </summary>
/// <typeparam name="T"></typeparam>
public class WebCallResult<T>: CallResult<T>
{
/// <summary>
/// The request http method
/// </summary>
@@ -470,35 +470,35 @@ namespace CryptoExchange.Net.Objects
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="data">The data of the new type</param>
/// <returns></returns>
public new WebCallResult<K> As<K>([AllowNull] K data)
public new WebCallResult<TNew> As<TNew>([AllowNull] TNew data)
{
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, data, Error);
return new WebCallResult<TNew>(ResponseStatusCode, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, data, Error);
}
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="error">The error returned</param>
/// <returns></returns>
public new WebCallResult<K> AsError<K>(Error error)
public new WebCallResult<TNew> AsError<TNew>(Error error)
{
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, default, error);
return new WebCallResult<TNew>(ResponseStatusCode, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, default, error);
}
/// <summary>
/// Copy the WebCallResult to a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="data">The data</param>
/// <param name="error">The error returned</param>
/// <returns></returns>
public new WebCallResult<K> AsErrorWithData<K>(Error error, K data)
public new WebCallResult<TNew> AsErrorWithData<TNew>(Error error, TNew data)
{
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, data, error);
return new WebCallResult<TNew>(ResponseStatusCode, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, data, error);
}
/// <summary>
@@ -526,41 +526,41 @@ namespace CryptoExchange.Net.Objects
/// <summary>
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="exchange">The exchange</param>
/// <param name="tradeMode">Trade mode the result applies to</param>
/// <param name="data">Data</param>
/// <param name="nextPageToken">Next page token</param>
/// <returns></returns>
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode tradeMode, [AllowNull] K data, INextPageToken? nextPageToken = null)
public ExchangeWebResult<TNew> AsExchangeResult<TNew>(string exchange, TradingMode tradeMode, [AllowNull] TNew data, INextPageToken? nextPageToken = null)
{
return new ExchangeWebResult<K>(exchange, tradeMode, As<K>(data), nextPageToken);
return new ExchangeWebResult<TNew>(exchange, tradeMode, As<TNew>(data), nextPageToken);
}
/// <summary>
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="exchange">The exchange</param>
/// <param name="tradeModes">Trade modes the result applies to</param>
/// <param name="data">Data</param>
/// <param name="nextPageToken">Next page token</param>
/// <returns></returns>
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode[]? tradeModes, [AllowNull] K data, INextPageToken? nextPageToken = null)
public ExchangeWebResult<TNew> AsExchangeResult<TNew>(string exchange, TradingMode[]? tradeModes, [AllowNull] TNew data, INextPageToken? nextPageToken = null)
{
return new ExchangeWebResult<K>(exchange, tradeModes, As<K>(data), nextPageToken);
return new ExchangeWebResult<TNew>(exchange, tradeModes, As<TNew>(data), nextPageToken);
}
/// <summary>
/// Copy the WebCallResult to an ExchangeWebResult with a specific error
/// </summary>
/// <typeparam name="K">The new type</typeparam>
/// <typeparam name="TNew">The new type</typeparam>
/// <param name="exchange">The exchange</param>
/// <param name="error">The error returned</param>
/// <returns></returns>
public ExchangeWebResult<K> AsExchangeError<K>(string exchange, Error error)
public ExchangeWebResult<TNew> AsExchangeError<TNew>(string exchange, Error error)
{
return new ExchangeWebResult<K>(exchange, null, AsError<K>(error));
return new ExchangeWebResult<TNew>(exchange, null, AsError<TNew>(error));
}
/// <summary>
@@ -584,5 +584,4 @@ namespace CryptoExchange.Net.Objects
return sb.ToString();
}
}
}
+6 -7
View File
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Objects
namespace CryptoExchange.Net.Objects;
/// <summary>
/// Constants
/// </summary>
public class Constants
{
/// <summary>
/// Constants
/// </summary>
public class Constants
{
/// <summary>
/// Json content type header
/// </summary>
@@ -17,5 +17,4 @@
/// Placeholder key for when request body should be set to the value of this KVP
/// </summary>
public const string BodyPlaceHolderKey = "_BODY_";
}
}
+83 -87
View File
@@ -1,12 +1,10 @@
using CryptoExchange.Net.Attributes;
namespace CryptoExchange.Net.Objects;
namespace CryptoExchange.Net.Objects
/// <summary>
/// What to do when a request would exceed the rate limit
/// </summary>
public enum RateLimitingBehaviour
{
/// <summary>
/// What to do when a request would exceed the rate limit
/// </summary>
public enum RateLimitingBehaviour
{
/// <summary>
/// Fail the request
/// </summary>
@@ -15,13 +13,13 @@ namespace CryptoExchange.Net.Objects
/// Wait till the request can be send
/// </summary>
Wait
}
}
/// <summary>
/// What to do when a request would exceed the rate limit
/// </summary>
public enum RateLimitWindowType
{
/// <summary>
/// What to do when a request would exceed the rate limit
/// </summary>
public enum RateLimitWindowType
{
/// <summary>
/// A sliding window
/// </summary>
@@ -38,13 +36,13 @@ namespace CryptoExchange.Net.Objects
/// Decaying window
/// </summary>
Decay
}
}
/// <summary>
/// Where the parameters for a HttpMethod should be added in a request
/// </summary>
public enum HttpMethodParameterPosition
{
/// <summary>
/// Where the parameters for a HttpMethod should be added in a request
/// </summary>
public enum HttpMethodParameterPosition
{
/// <summary>
/// Parameters in body
/// </summary>
@@ -53,13 +51,13 @@ namespace CryptoExchange.Net.Objects
/// Parameters in url
/// </summary>
InUri
}
}
/// <summary>
/// The format of the request body
/// </summary>
public enum RequestBodyFormat
{
/// <summary>
/// The format of the request body
/// </summary>
public enum RequestBodyFormat
{
/// <summary>
/// Form data
/// </summary>
@@ -68,13 +66,13 @@ namespace CryptoExchange.Net.Objects
/// Json
/// </summary>
Json
}
}
/// <summary>
/// Tracker sync status
/// </summary>
public enum SyncStatus
{
/// <summary>
/// Tracker sync status
/// </summary>
public enum SyncStatus
{
/// <summary>
/// Not connected
/// </summary>
@@ -95,13 +93,13 @@ namespace CryptoExchange.Net.Objects
/// Disposed
/// </summary>
Disposed
}
}
/// <summary>
/// Status of the order book
/// </summary>
public enum OrderBookStatus
{
/// <summary>
/// Status of the order book
/// </summary>
public enum OrderBookStatus
{
/// <summary>
/// Not connected
/// </summary>
@@ -130,13 +128,13 @@ namespace CryptoExchange.Net.Objects
/// Disposed
/// </summary>
Disposed
}
}
/// <summary>
/// Order book entry type
/// </summary>
public enum OrderBookEntryType
{
/// <summary>
/// Order book entry type
/// </summary>
public enum OrderBookEntryType
{
/// <summary>
/// Ask
/// </summary>
@@ -145,14 +143,14 @@ namespace CryptoExchange.Net.Objects
/// Bid
/// </summary>
Bid
}
}
/// <summary>
/// Define how array parameters should be send
/// </summary>
public enum ArrayParametersSerialization
/// <summary>
/// Define how array parameters should be send
/// </summary>
public enum ArrayParametersSerialization
#pragma warning disable CS1570 // XML comment has badly formed XML
{
{
/// <summary>
/// Send as key=value1&key=value2
/// </summary>
@@ -167,13 +165,13 @@ namespace CryptoExchange.Net.Objects
/// </summary>
JsonArray
#pragma warning restore CS1570 // XML comment has badly formed XML
}
}
/// <summary>
/// How to round
/// </summary>
public enum RoundingType
{
/// <summary>
/// How to round
/// </summary>
public enum RoundingType
{
/// <summary>
/// Round down (flooring)
/// </summary>
@@ -186,13 +184,13 @@ namespace CryptoExchange.Net.Objects
/// Round up (ceil)
/// </summary>
Up
}
}
/// <summary>
/// Type of the update
/// </summary>
public enum SocketUpdateType
{
/// <summary>
/// Type of the update
/// </summary>
public enum SocketUpdateType
{
/// <summary>
/// A update
/// </summary>
@@ -201,13 +199,13 @@ namespace CryptoExchange.Net.Objects
/// A snapshot, generally send at the start of the connection
/// </summary>
Snapshot
}
}
/// <summary>
/// Reconnect policy
/// </summary>
public enum ReconnectPolicy
{
/// <summary>
/// Reconnect policy
/// </summary>
public enum ReconnectPolicy
{
/// <summary>
/// Reconnect is disabled
/// </summary>
@@ -220,13 +218,13 @@ namespace CryptoExchange.Net.Objects
/// Backoff policy of 2^`reconnectAttempt`, where `reconnectAttempt` has a max value of 5
/// </summary>
ExponentialBackoff
}
}
/// <summary>
/// The data source of the result
/// </summary>
public enum ResultDataSource
{
/// <summary>
/// The data source of the result
/// </summary>
public enum ResultDataSource
{
/// <summary>
/// From server
/// </summary>
@@ -235,13 +233,13 @@ namespace CryptoExchange.Net.Objects
/// From cache
/// </summary>
Cache
}
}
/// <summary>
/// Type of exchange
/// </summary>
public enum ExchangeType
{
/// <summary>
/// Type of exchange
/// </summary>
public enum ExchangeType
{
/// <summary>
/// Centralized
/// </summary>
@@ -250,13 +248,13 @@ namespace CryptoExchange.Net.Objects
/// Decentralized
/// </summary>
DEX
}
}
/// <summary>
/// Timeout behavior for queries
/// </summary>
public enum TimeoutBehavior
{
/// <summary>
/// Timeout behavior for queries
/// </summary>
public enum TimeoutBehavior
{
/// <summary>
/// Fail the request
/// </summary>
@@ -265,6 +263,4 @@ namespace CryptoExchange.Net.Objects
/// Mark the query as successful
/// </summary>
Succeed
}
}
+102 -104
View File
@@ -1,14 +1,13 @@
using CryptoExchange.Net.Objects.Errors;
using CryptoExchange.Net.Objects.Errors;
using System;
namespace CryptoExchange.Net.Objects
{
/// <summary>
/// Base class for errors
/// </summary>
public abstract class Error
{
namespace CryptoExchange.Net.Objects;
/// <summary>
/// Base class for errors
/// </summary>
public abstract class Error
{
private int? _code;
/// <summary>
/// The int error code the server returned; or the http status code int value if there was no error code.<br />
@@ -81,60 +80,60 @@ namespace CryptoExchange.Net.Objects
{
return ErrorCode != null ? $"[{GetType().Name}.{ErrorType}] {ErrorCode}: {Message ?? ErrorDescription}" : $"[{GetType().Name}.{ErrorType}] {Message ?? ErrorDescription}";
}
}
}
/// <summary>
/// Cant reach server error
/// </summary>
public class CantConnectError : Error
{
/// <summary>
/// Cant reach server error
/// </summary>
public class CantConnectError : Error
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.UnableToConnect, false, "Can't connect to the server");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.UnableToConnect, false, "Can't connect to the server");
/// <summary>
/// ctor
/// </summary>
public CantConnectError() : base(null, _errorInfo, null) { }
public CantConnectError() : base(null, errorInfo, null) { }
/// <summary>
/// ctor
/// </summary>
public CantConnectError(Exception? exception) : base(null, _errorInfo, exception) { }
public CantConnectError(Exception? exception) : base(null, errorInfo, exception) { }
/// <summary>
/// ctor
/// </summary>
protected CantConnectError(ErrorInfo info, Exception? exception) : base(null, info, exception) { }
}
}
/// <summary>
/// No api credentials provided while trying to access a private endpoint
/// </summary>
public class NoApiCredentialsError : Error
{
/// <summary>
/// No api credentials provided while trying to access a private endpoint
/// </summary>
public class NoApiCredentialsError : Error
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.MissingCredentials, false, "No credentials provided for private endpoint");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.MissingCredentials, false, "No credentials provided for private endpoint");
/// <summary>
/// ctor
/// </summary>
public NoApiCredentialsError() : base(null, _errorInfo, null) { }
public NoApiCredentialsError() : base(null, errorInfo, null) { }
/// <summary>
/// ctor
/// </summary>
protected NoApiCredentialsError(ErrorInfo info, Exception? exception) : base(null, info, exception) { }
}
}
/// <summary>
/// Error returned by the server
/// </summary>
public class ServerError : Error
{
/// <summary>
/// Error returned by the server
/// </summary>
public class ServerError : Error
{
/// <summary>
/// ctor
/// </summary>
@@ -151,91 +150,91 @@ namespace CryptoExchange.Net.Objects
/// ctor
/// </summary>
public ServerError(string errorCode, ErrorInfo errorInfo, Exception? exception = null) : base(errorCode, errorInfo, exception) { }
}
}
/// <summary>
/// Web error returned by the server
/// </summary>
public class WebError : Error
{
/// <summary>
/// Web error returned by the server
/// </summary>
public class WebError : Error
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.NetworkError, true, "Failed to complete the request to the server due to a network error");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.NetworkError, true, "Failed to complete the request to the server due to a network error");
/// <summary>
/// ctor
/// </summary>
public WebError(string? message = null, Exception? exception = null) : base(null, _errorInfo with { Message = (message?.Length > 0 ? _errorInfo.Message + ": " + message : _errorInfo.Message) }, exception) { }
}
public WebError(string? message = null, Exception? exception = null) : base(null, errorInfo with { Message = (message?.Length > 0 ? errorInfo.Message + ": " + message : errorInfo.Message) }, exception) { }
}
/// <summary>
/// Timeout error waiting for a response from the server
/// </summary>
public class TimeoutError : Error
{
/// <summary>
/// Timeout error waiting for a response from the server
/// </summary>
public class TimeoutError : Error
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.Timeout, false, "Failed to receive a response from the server in time");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.Timeout, false, "Failed to receive a response from the server in time");
/// <summary>
/// ctor
/// </summary>
public TimeoutError(string? message = null, Exception? exception = null) : base(null, _errorInfo with { Message = (message?.Length > 0 ? _errorInfo.Message + ": " + message : _errorInfo.Message) }, exception) { }
}
public TimeoutError(string? message = null, Exception? exception = null) : base(null, errorInfo with { Message = (message?.Length > 0 ? errorInfo.Message + ": " + message : errorInfo.Message) }, exception) { }
}
/// <summary>
/// Error while deserializing data
/// </summary>
public class DeserializeError : Error
{
/// <summary>
/// Error while deserializing data
/// </summary>
public class DeserializeError : Error
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.DeserializationFailed, false, "Failed to deserialize data");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.DeserializationFailed, false, "Failed to deserialize data");
/// <summary>
/// ctor
/// </summary>
public DeserializeError(string? message = null, Exception? exception = null) : base(null, _errorInfo with { Message = (message?.Length > 0 ? _errorInfo.Message + ": " + message : _errorInfo.Message) }, exception) { }
}
public DeserializeError(string? message = null, Exception? exception = null) : base(null, errorInfo with { Message = (message?.Length > 0 ? errorInfo.Message + ": " + message : errorInfo.Message) }, exception) { }
}
/// <summary>
/// An invalid parameter has been provided
/// </summary>
public class ArgumentError : Error
{
/// <summary>
/// An invalid parameter has been provided
/// </summary>
public class ArgumentError : Error
{
/// <summary>
/// Default error info for missing parameter
/// </summary>
protected static readonly ErrorInfo _missingInfo = new ErrorInfo(ErrorType.MissingParameter, false, "Missing parameter");
protected static readonly ErrorInfo missingInfo = new ErrorInfo(ErrorType.MissingParameter, false, "Missing parameter");
/// <summary>
/// Default error info for invalid parameter
/// </summary>
protected static readonly ErrorInfo _invalidInfo = new ErrorInfo(ErrorType.InvalidParameter, false, "Invalid parameter");
protected static readonly ErrorInfo invalidInfo = new ErrorInfo(ErrorType.InvalidParameter, false, "Invalid parameter");
/// <summary>
/// ctor
/// </summary>
public static ArgumentError Missing(string parameterName, string? message = null) => new ArgumentError(_missingInfo with { Message = message == null ? $"{_missingInfo.Message} '{parameterName}'" : $"{_missingInfo.Message} '{parameterName}': {message}" }, null);
public static ArgumentError Missing(string parameterName, string? message = null) => new ArgumentError(missingInfo with { Message = message == null ? $"{missingInfo.Message} '{parameterName}'" : $"{missingInfo.Message} '{parameterName}': {message}" }, null);
/// <summary>
/// ctor
/// </summary>
public static ArgumentError Invalid(string parameterName, string message) => new ArgumentError(_invalidInfo with { Message = $"{_invalidInfo.Message} '{parameterName}': {message}" }, null);
public static ArgumentError Invalid(string parameterName, string message) => new ArgumentError(invalidInfo with { Message = $"{invalidInfo.Message} '{parameterName}': {message}" }, null);
/// <summary>
/// ctor
/// </summary>
protected ArgumentError(ErrorInfo info, Exception? exception) : base(null, info, exception) { }
}
}
/// <summary>
/// Rate limit exceeded (client side)
/// </summary>
public abstract class BaseRateLimitError : Error
{
/// <summary>
/// Rate limit exceeded (client side)
/// </summary>
public abstract class BaseRateLimitError : Error
{
/// <summary>
/// When the request can be retried
/// </summary>
@@ -245,89 +244,88 @@ namespace CryptoExchange.Net.Objects
/// ctor
/// </summary>
protected BaseRateLimitError(ErrorInfo errorInfo, Exception? exception) : base(null, errorInfo, exception) { }
}
}
/// <summary>
/// Rate limit exceeded (client side)
/// </summary>
public class ClientRateLimitError : BaseRateLimitError
{
/// <summary>
/// Rate limit exceeded (client side)
/// </summary>
public class ClientRateLimitError : BaseRateLimitError
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.RateLimitRequest, false, "Client rate limit exceeded");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.RateLimitRequest, false, "Client rate limit exceeded");
/// <summary>
/// ctor
/// </summary>
public ClientRateLimitError(string? message = null, Exception? exception = null) : base(_errorInfo with { Message = (message?.Length > 0 ? _errorInfo.Message + ": " + message : _errorInfo.Message) }, exception) { }
public ClientRateLimitError(string? message = null, Exception? exception = null) : base(errorInfo with { Message = (message?.Length > 0 ? errorInfo.Message + ": " + message : errorInfo.Message) }, exception) { }
/// <summary>
/// ctor
/// </summary>
protected ClientRateLimitError(ErrorInfo info, Exception? exception) : base(info, exception) { }
}
}
/// <summary>
/// Rate limit exceeded (server side)
/// </summary>
public class ServerRateLimitError : BaseRateLimitError
{
/// <summary>
/// Rate limit exceeded (server side)
/// </summary>
public class ServerRateLimitError : BaseRateLimitError
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.RateLimitRequest, false, "Server rate limit exceeded");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.RateLimitRequest, false, "Server rate limit exceeded");
/// <summary>
/// ctor
/// </summary>
public ServerRateLimitError(string? message = null, Exception? exception = null) : base(_errorInfo with { Message = (message?.Length > 0 ? _errorInfo.Message + ": " + message : _errorInfo.Message) }, exception) { }
public ServerRateLimitError(string? message = null, Exception? exception = null) : base(errorInfo with { Message = (message?.Length > 0 ? errorInfo.Message + ": " + message : errorInfo.Message) }, exception) { }
/// <summary>
/// ctor
/// </summary>
protected ServerRateLimitError(ErrorInfo info, Exception? exception) : base(info, exception) { }
}
}
/// <summary>
/// Cancellation requested
/// </summary>
public class CancellationRequestedError : Error
{
/// <summary>
/// Cancellation requested
/// </summary>
public class CancellationRequestedError : Error
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.CancellationRequested, false, "Cancellation requested");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.CancellationRequested, false, "Cancellation requested");
/// <summary>
/// ctor
/// </summary>
public CancellationRequestedError(Exception? exception = null) : base(null, _errorInfo, null) { }
public CancellationRequestedError(Exception? exception = null) : base(null, errorInfo, null) { }
/// <summary>
/// ctor
/// </summary>
protected CancellationRequestedError(ErrorInfo info, Exception? exception) : base(null, info, exception) { }
}
}
/// <summary>
/// Invalid operation requested
/// </summary>
public class InvalidOperationError : Error
{
/// <summary>
/// Invalid operation requested
/// </summary>
public class InvalidOperationError : Error
{
/// <summary>
/// Default error info
/// </summary>
protected static readonly ErrorInfo _errorInfo = new ErrorInfo(ErrorType.InvalidOperation, false, "Operation invalid");
protected static readonly ErrorInfo errorInfo = new ErrorInfo(ErrorType.InvalidOperation, false, "Operation invalid");
/// <summary>
/// ctor
/// </summary>
public InvalidOperationError(string message) : base(null, _errorInfo with { Message = message }, null) { }
public InvalidOperationError(string message) : base(null, errorInfo with { Message = message }, null) { }
/// <summary>
/// ctor
/// </summary>
protected InvalidOperationError(ErrorInfo info, Exception? exception) : base(null, info, exception) { }
}
}
@@ -1,14 +1,12 @@
using System;
using System.Collections.Generic;
using System.Text;
using System;
namespace CryptoExchange.Net.Objects.Errors
namespace CryptoExchange.Net.Objects.Errors;
/// <summary>
/// Error evaluator
/// </summary>
public class ErrorEvaluator
{
/// <summary>
/// Error evaluator
/// </summary>
public class ErrorEvaluator
{
/// <summary>
/// Error code
/// </summary>
@@ -36,5 +34,4 @@ namespace CryptoExchange.Net.Objects.Errors
ErrorCodes = errorCodes;
ErrorTypeEvaluator = errorTypeEvaluator;
}
}
}
@@ -1,12 +1,10 @@
using System;
namespace CryptoExchange.Net.Objects.Errors;
namespace CryptoExchange.Net.Objects.Errors
/// <summary>
/// Error info
/// </summary>
public record ErrorInfo
{
/// <summary>
/// Error info
/// </summary>
public record ErrorInfo
{
/// <summary>
/// Unknown error info
/// </summary>
@@ -54,5 +52,4 @@ namespace CryptoExchange.Net.Objects.Errors
IsTransient = isTransient;
ErrorDescription = description;
}
}
}
@@ -1,15 +1,13 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CryptoExchange.Net.Objects.Errors
namespace CryptoExchange.Net.Objects.Errors;
/// <summary>
/// Error mapping collection
/// </summary>
public class ErrorMapping
{
/// <summary>
/// Error mapping collection
/// </summary>
public class ErrorMapping
{
private Dictionary<string, ErrorEvaluator> _evaluators = new Dictionary<string, ErrorEvaluator>();
private Dictionary<string, ErrorInfo> _directMapping = new Dictionary<string, ErrorInfo>();
@@ -20,7 +18,7 @@ namespace CryptoExchange.Net.Objects.Errors
{
foreach (var item in errorMappings)
{
if (!item.ErrorCodes.Any())
if (item.ErrorCodes.Length == 0)
throw new Exception("Error codes can't be null in error mapping");
foreach(var code in item.ErrorCodes!)
@@ -50,5 +48,4 @@ namespace CryptoExchange.Net.Objects.Errors
return ErrorInfo.Unknown with { Message = message };
}
}
}
+5 -10
View File
@@ -1,14 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace CryptoExchange.Net.Objects.Errors;
namespace CryptoExchange.Net.Objects.Errors
/// <summary>
/// Type of error
/// </summary>
public enum ErrorType
{
/// <summary>
/// Type of error
/// </summary>
public enum ErrorType
{
#region Library errors
/// <summary>
@@ -158,5 +154,4 @@ namespace CryptoExchange.Net.Objects.Errors
RiskError
#endregion
}
}
@@ -1,12 +1,12 @@
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Authentication;
namespace CryptoExchange.Net.Objects.Options
namespace CryptoExchange.Net.Objects.Options;
/// <summary>
/// Options for API usage
/// </summary>
public class ApiOptions
{
/// <summary>
/// Options for API usage
/// </summary>
public class ApiOptions
{
/// <summary>
/// If true, the CallResult and DataEvent objects will also include the originally received json data in the OriginalData property
/// </summary>
@@ -16,5 +16,4 @@ namespace CryptoExchange.Net.Objects.Options
/// The api credentials used for signing requests to this API. Overrides API credentials provided in the client options
/// </summary>
public ApiCredentials? ApiCredentials { get; set; }
}
}
@@ -1,13 +1,13 @@
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Authentication;
using System;
namespace CryptoExchange.Net.Objects.Options
namespace CryptoExchange.Net.Objects.Options;
/// <summary>
/// Exchange options
/// </summary>
public class ExchangeOptions
{
/// <summary>
/// Exchange options
/// </summary>
public class ExchangeOptions
{
/// <summary>
/// Proxy settings
/// </summary>
@@ -16,7 +16,7 @@ namespace CryptoExchange.Net.Objects.Options
/// <summary>
/// If true, the CallResult and DataEvent objects will also include the originally received json data in the OriginalData property
/// </summary>
public bool OutputOriginalData { get; set; } = false;
public bool OutputOriginalData { get; set; }
/// <summary>
/// The max time a request is allowed to take
@@ -42,5 +42,4 @@ namespace CryptoExchange.Net.Objects.Options
{
return $"RequestTimeout: {RequestTimeout}, Proxy: {(Proxy == null ? "-" : "set")}, ApiCredentials: {(ApiCredentials == null ? "-" : "set")}";
}
}
}
@@ -1,21 +1,21 @@
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Authentication;
using Microsoft.Extensions.DependencyInjection;
namespace CryptoExchange.Net.Objects.Options
{
/// <summary>
/// Library options
/// </summary>
/// <typeparam name="TRestOptions"></typeparam>
/// <typeparam name="TSocketOptions"></typeparam>
/// <typeparam name="TApiCredentials"></typeparam>
/// <typeparam name="TEnvironment"></typeparam>
public class LibraryOptions<TRestOptions, TSocketOptions, TApiCredentials, TEnvironment>
namespace CryptoExchange.Net.Objects.Options;
/// <summary>
/// Library options
/// </summary>
/// <typeparam name="TRestOptions"></typeparam>
/// <typeparam name="TSocketOptions"></typeparam>
/// <typeparam name="TApiCredentials"></typeparam>
/// <typeparam name="TEnvironment"></typeparam>
public class LibraryOptions<TRestOptions, TSocketOptions, TApiCredentials, TEnvironment>
where TRestOptions: RestExchangeOptions, new()
where TSocketOptions: SocketExchangeOptions, new()
where TApiCredentials: ApiCredentials
where TEnvironment: TradeEnvironment
{
{
/// <summary>
/// Rest client options
/// </summary>
@@ -54,5 +54,4 @@ namespace CryptoExchange.Net.Objects.Options
return targetOptions;
}
}
}
@@ -1,10 +1,10 @@
namespace CryptoExchange.Net.Objects.Options
namespace CryptoExchange.Net.Objects.Options;
/// <summary>
/// Base for order book options
/// </summary>
public class OrderBookOptions
{
/// <summary>
/// Base for order book options
/// </summary>
public class OrderBookOptions
{
/// <summary>
/// Whether or not checksum validation is enabled. Default is true, disabling will ignore checksum messages.
/// </summary>
@@ -22,5 +22,4 @@
ChecksumValidationEnabled = ChecksumValidationEnabled,
};
}
}
}
@@ -1,13 +1,13 @@
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Authentication;
using System;
namespace CryptoExchange.Net.Objects.Options
namespace CryptoExchange.Net.Objects.Options;
/// <summary>
/// Http api options
/// </summary>
public class RestApiOptions : ApiOptions
{
/// <summary>
/// Http api options
/// </summary>
public class RestApiOptions : ApiOptions
{
/// <summary>
/// Whether or not to automatically sync the local time with the server time
/// </summary>
@@ -29,14 +29,14 @@ namespace CryptoExchange.Net.Objects.Options
item.TimestampRecalculationInterval = TimestampRecalculationInterval;
return item;
}
}
}
/// <summary>
/// Http API options
/// </summary>
/// <typeparam name="TApiCredentials"></typeparam>
public class RestApiOptions<TApiCredentials>: RestApiOptions where TApiCredentials: ApiCredentials
{
/// <summary>
/// Http API options
/// </summary>
/// <typeparam name="TApiCredentials"></typeparam>
public class RestApiOptions<TApiCredentials>: RestApiOptions where TApiCredentials: ApiCredentials
{
/// <summary>
/// The api credentials used for signing requests to this API.
/// </summary>
@@ -45,5 +45,4 @@ namespace CryptoExchange.Net.Objects.Options
get => (TApiCredentials?)base.ApiCredentials;
set => base.ApiCredentials = value;
}
}
}

Some files were not shown because too many files have changed in this diff Show More