using System;
using CryptoExchange.Net.Interfaces.Clients;
using CryptoExchange.Net.Objects.Errors;
using CryptoExchange.Net.Objects.Options;
using CryptoExchange.Net.SharedApis;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace CryptoExchange.Net.Clients
{
///
/// Base API for all API clients
///
public abstract class BaseApiClient : IDisposable, IBaseApiClient
{
///
/// Client name
///
protected string? _clientName;
///
/// Logger
///
protected ILogger _logger;
///
/// If we are disposing
///
protected bool _disposed;
///
/// Whether a proxy is configured
///
protected bool _proxyConfigured;
///
/// Name of the client
///
protected internal string ClientName
{
get
{
if (_clientName != null)
return _clientName;
_clientName = GetType().Name;
return _clientName;
}
}
///
/// The name of the exchange this client is for
///
public string Exchange { get; }
///
/// The environment this client communicates to
///
public string BaseAddress { get; }
///
/// Output the original string data along with the deserialized object
///
public bool OutputOriginalData { get; }
///
/// Api options
///
public ApiOptions ApiOptions { get; }
///
/// Client Options
///
public ExchangeOptions ClientOptions { get; }
///
/// Mapping of a response code to known error types
///
protected internal virtual ErrorMapping ErrorMapping { get; } = new ErrorMapping([]);
///
/// ctor
///
/// Logger factory
/// The exchange name
/// Should data from this client include the original data in the call result
/// Base address for this API client
/// Client options
/// Api options
protected BaseApiClient(
ILoggerFactory? loggerFactory,
string exchange,
bool outputOriginalData,
string baseAddress,
ExchangeOptions clientOptions,
ApiOptions apiOptions)
{
var loggerName = ClientName.StartsWith(exchange, StringComparison.OrdinalIgnoreCase)
? exchange + "." + ClientName.Substring(exchange.Length).TrimStart('.')
: exchange + "." + ClientName;
_logger = loggerFactory?.CreateLogger(loggerName) ?? NullLogger.Instance;
Exchange = exchange;
ClientOptions = clientOptions;
ApiOptions = apiOptions;
OutputOriginalData = outputOriginalData;
BaseAddress = baseAddress;
_proxyConfigured = ClientOptions.Proxy != null;
}
///
public abstract string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverDate = null);
///
/// Get error info for a response code
///
public ErrorInfo GetErrorInfo(int code, string? message = null) => GetErrorInfo(code.ToString(), message);
///
/// Get error info for a response code
///
public ErrorInfo GetErrorInfo(string code, string? message = null) => ErrorMapping.GetErrorInfo(code.ToString(), message);
///
/// Dispose
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Dispose
///
protected virtual void Dispose(bool disposing)
{
_disposed = true;
}
}
}