1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-10-15 15:40:52 +00:00
Files
CryptoExchange.Net/CryptoExchange.Net/SharedApis/Models/Options/Endpoints/EndpointOptions.cs
T
Jan Korf e823114623 CryptoExchange V12 (#281)
* Result types:
  * (Web)CallResult types are replaced by HttpResult, WebSocketResult and QueryResult with the same logic
  * Updated result types to record type
  * Result creation can be done with (Http/WebSocket/Query)Result.Ok(..) and .Fail(..)
  * Removed implicit result type conversion to bool, `if (result)` no longer works, instead use `if (result.Success)`
  * Replaced CallResult.SuccessResult with CallResult.Ok()
  * Fixed result object nullability hinting, for example Data might be null if Success isn't checked for true

* Parameters & serialization:
  * Added support for `enabled` and `disabled` strings to bool converter
  * Removed ParameterCollection type, has been replaced by Parameters type
  * Removed ArraySerialization, OrderParameters and ParameterOrderComparer properties from RestApiClient, moved to ParameterSerializationsSettings
  * Updated RestRequestConfiguration in AuthenticationProvider.ProcessRequest to contain the full RequestDefinition instead of copied fields	

* Clients:
  * Updated Api client constructor logging parameter from ILogger to ILoggerFactory? 
  * Added Api client constructor exchange name parameter
  * Added ToString overrides on base API types
  * Added Exchange property on BaseApiClient
  * Added ApiCredentials property on IRestApiClient and ISocketApiClient interfaces
  * Updated ILogger source from client name to topic specific client name
  * Removed logging from client creation
  * Fixed BaseRestClient SetApiCredentials not marked as virtual

* Rest:
  * Added BaseAddress to RequestDefinition object
  * Updated RestApiClient AuthenticationProvider logic from private to protected and virtual
  * Removed RestApiClient.SendAsync baseAddress parameter removed
  * Removed RestApiClient.SendAsync without type parameter

* WebSocket:
  * Updated MessageRouting definition into CreateForEvent for subscriptions and CreateForQuery for queries
  * Improved Query type safety with CeateForQuery which allows second parameter for specifying the result type
  * Renamed MessageRouter.CreateWithoutHandler to CreateVoid
  * Updated SocketApiClient.GetSocketConnection to check connection uri instead of Tag for finding compatible connections
  * Removed unused UnhandledMessageExpected property SocketApiClient
  * Fixed issue in SocketApiClient.GetSocketConnection causing requests to always wait the full max 10 seconds when there was a reconnecting socket
	
* Shared APIs:
  * Updated Option definitions to always require the exchange name as first parameter
  * Added missing dedicated option types
  * Added Discover method on ISharedClient interface, returning info on supported capabilities and operations
  * Added SharedRequest GetParamValue helper method accepting multiple parameter names
  * Added ResetStaticExchangeParameters method on ExchangeParameters
  * Added Status property to SharedWithdrawal model
  * Added TradingModes property to SharedBalance model
  * Updated ExchangeSymbolCache to support multiple environments and additional key separation
  * Updated Shared ExchangeParameters parameter names to be case insensitive
  * Updated code comments
  * Replaced ExchangeResult with ExchangeCallResult type
  * Removed AsExchangeResult/ExchangeWebResult
  * Removed TradingMode from the response model, only maintained on models where it makes sense
  * Removed IListenKey support, listen keys now rely on internal management with TokenManager

* Rate limiting:
  * Fixed websocket connection attempts counting towards rate limit even when server could not be reached
  * Removed host from rate limit methods, now part of the already provided RequestDefinition
  * Added amount parameter to RateLimit Reset method to allow partially resetting the limit

* Added TokenManager implementation for automatic listenkey/token management
* Added UserClientProvider base class
* Added async streaming on UserDataTracker items with StreamUpdatesAsync
* Added cancellation token support to UserDataTracker starting
* Added Unit type for non-result types
* Added ServerError constructor taking ErrorType and message to make it easier to create
* Added SupportedEnvironments property to PlatformInfo
* Updated SymbolOrderBook DoResyncAsync to return CallResult instead of CallResult<bool> which was redundant
* Various small performance improvements
2026-06-29 10:38:09 +02:00

205 lines
8.5 KiB
C#

using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Options for an exchange endpoint
/// </summary>
public abstract class EndpointOptions
{
/// <summary>
/// Required exchange-specific parameters. These can be provided via the `exchangeParameters` property of the request object.
/// </summary>
public List<ParameterDescription> RequiredExchangeParameters { get; set; } = new List<ParameterDescription>();
/// <summary>
/// Optional exchange-specific parameters. These can be provided via the `exchangeParameters` property of the request object.
/// </summary>
public List<ParameterDescription> OptionalExchangeParameters { get; set; } = new List<ParameterDescription>();
/// <summary>
/// Exchange
/// </summary>
public string Exchange { get; set; }
/// <summary>
/// Endpoint name
/// </summary>
public string EndpointName { get; set; }
/// <summary>
/// Exchange specific additional info
/// </summary>
public string? RequestNotes { get; set; }
/// <summary>
/// Whether the call requires authentication
/// </summary>
public bool NeedsAuthentication { get; set; }
/// <summary>
/// Whether the call is supported. If false the exchange API does not support this operation.
/// </summary>
public bool Supported { get; set; } = true;
/// <summary>
/// ctor
/// </summary>
public EndpointOptions(string exchange, string endpointName, bool needAuthentication)
{
Exchange = exchange;
EndpointName = endpointName;
NeedsAuthentication = needAuthentication;
}
/// <summary>
/// Validate a request
/// </summary>
/// <param name="exchangeParameters">Provided exchange parameters</param>
/// <param name="tradingMode">Request trading mode</param>
/// <param name="supportedTradingModes">Supported trading modes</param>
/// <returns></returns>
public virtual Error? ValidateRequest(ExchangeParameters? exchangeParameters, TradingMode? tradingMode, TradingMode[] supportedTradingModes)
{
if (!Supported)
return ArgumentError.Invalid("Endpoint", $"Endpoint {Exchange} {EndpointName} is not supported by the API");
if (tradingMode != null && !supportedTradingModes.Contains(tradingMode.Value))
return ArgumentError.Invalid("TradingMode", $"TradingMode.{tradingMode} is not supported, supported types: {string.Join(", ", supportedTradingModes)}");
foreach (var param in RequiredExchangeParameters)
{
if (param.Names!.All(x => ExchangeParameters.HasValue(exchangeParameters, Exchange, x, param.ValueType) != true))
return ArgumentError.Invalid(string.Join("/", param.Names!), $"One of exchange parameters `{string.Join(", ", param.Names!)}` for exchange `{Exchange}` should be provided. Example: {param.ExampleValue}");
}
return null;
}
}
/// <summary>
/// Options for an exchange endpoint
/// </summary>
/// <typeparam name="TRequest">Type of data</typeparam>
#if NET5_0_OR_GREATER
public class EndpointOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] TRequest> : EndpointOptions
where TRequest : SharedRequest
#else
public abstract class EndpointOptions<TRequest> : EndpointOptions
where TRequest : SharedRequest
#endif
{
/// <summary>
/// ctor
/// </summary>
public EndpointOptions(string exchange, bool needsAuthentication, string requestName) : base(exchange, requestName, needsAuthentication)
{
}
}
/// <summary>
/// Options for an exchange endpoint
/// </summary>
/// <typeparam name="TRequest">Type of data</typeparam>
/// <typeparam name="TClient">Type of the client</typeparam>
#if NET5_0_OR_GREATER
public abstract class EndpointOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] TRequest, TClient> : EndpointOptions <TRequest>
where TRequest : SharedRequest
where TClient : ISharedClient
#else
public abstract class EndpointOptions<TRequest, TClient> : EndpointOptions<TRequest>
where TRequest : SharedRequest
where TClient : ISharedClient
#endif
{
private static PropertyInfo[] _requestProperties = typeof(TRequest).GetProperties();
/// <summary>
/// Required optional parameters in the request. These can be provided via the `exchangeParameters` property of the request object.
/// </summary>
public List<ParameterDescription> RequiredOptionalParameters { get; set; } = new List<ParameterDescription>();
/// <summary>
/// Whether this accepts multiple symbols (Only applicable to request requiring symbol parameters)
/// </summary>
public bool SupportsMultipleSymbols { get; set; } = false;
/// <summary>
/// The max number of symbols which can be passed in a call (Only applicable to request requiring symbol parameters)
/// </summary>
public int? MaxSymbolCount { get; set; }
/// <summary>
/// ctor
/// </summary>
public EndpointOptions(string exchange, bool needsAuthentication, string requestName) : base(exchange, needsAuthentication, requestName)
{
}
/// <summary>
/// Validate a request
/// </summary>
/// <param name="request">The request</param>
/// <param name="client">Containing client</param>
/// <returns></returns>
public virtual Error? ValidateRequest(TRequest request, TClient client)
{
if (NeedsAuthentication && !client.Authenticated)
return new NoApiCredentialsError();
foreach (var param in RequiredOptionalParameters)
{
if (param.Names!.All(x => _requestProperties.Single(p => p.Name == x).GetValue(request, null) == null))
return ArgumentError.Invalid(string.Join("/", param.Names!), $"One of optional parameters `{string.Join(", ", param.Names!)}` for exchange `{Exchange}` should be provided. Example: {param.ExampleValue}");
}
if (request is SharedSymbolRequest symbolsRequest)
{
if (symbolsRequest.Symbols != null)
{
if (!SupportsMultipleSymbols)
return ArgumentError.Invalid(nameof(SharedSymbolRequest.Symbols), $"Only a single symbol parameter is allowed, multiple symbols are not supported");
if (symbolsRequest.Symbols.Length > MaxSymbolCount)
return ArgumentError.Invalid(nameof(SharedSymbolRequest.Symbols), $"Max number of symbols is {MaxSymbolCount} but {symbolsRequest.Symbols.Length} were passed");
}
}
return ValidateRequest(request.ExchangeParameters, request.TradingMode, client.SupportedTradingModes);
}
/// <inheritdoc />
public override string ToString()
{
if (!Supported)
return $"{Exchange} {EndpointName} NOT SUPPORTED";
var sb = new StringBuilder();
sb.AppendLine($"{Exchange} {EndpointName}");
sb.AppendLine($"Needs authentication: {NeedsAuthentication}");
if (!string.IsNullOrEmpty(RequestNotes))
sb.AppendLine(RequestNotes);
if (RequiredOptionalParameters.Any())
{
sb.AppendLine($"Required optional parameters:");
foreach(var param in RequiredOptionalParameters)
sb.AppendLine($" {param}");
}
if (RequiredExchangeParameters.Any())
{
sb.AppendLine($"Required exchange specific parameters:");
foreach (var param in RequiredExchangeParameters)
sb.AppendLine($" {param}");
}
if (OptionalExchangeParameters.Any())
{
sb.AppendLine($"Optional exchange specific parameters:");
foreach (var param in OptionalExchangeParameters)
sb.AppendLine($" {param}");
}
return sb.ToString();
}
}
}