1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-10-04 18:33:39 +00:00

Compare commits

..

51 Commits

Author SHA1 Message Date
Jkorf c1af97dd4a Updated to version 12.5.0 2026-08-21 10:21:54 +02:00
Jkorf ecfe3cf392 Added ISpotOrderManagementSocketClient and IFuturesOrderManagementSocketClient for placing/canceling orders via websocket 2026-08-21 09:56:56 +02:00
Jkorf ac1e9cf2ab Added Description property to EndpointOptions classes. Updated client info string representation, added additional validation for Spot endpoints 2026-08-21 09:55:53 +02:00
Jkorf 4987e6be70 Added WithCalculatedQuantities to SharedQuantity to retrieve a copy with calculated quantities 2026-08-21 09:52:54 +02:00
Jkorf 9100c0d7f3 Added UpperPriceLimitPerecentage, LowerPriceLimitPercentage, MakerFeePercentage and TakerFeePercentage to SharedSpotSymbol model 2026-08-21 09:52:29 +02:00
Jkorf 5b1ae30e4b Updated SharedId value to be nullable 2026-08-21 09:52:00 +02:00
Jkorf 36a06e8a9a Added UpperFundingCap, LowerFundingCap to SharedFuturesSymbol model 2026-08-21 09:51:43 +02:00
Jkorf e7eb559074 Updated remaining quantity/volumes to SharedOrderQuantity model in Shared APIs, added QuantityType to SharedOrderBook, added auto calculated quote quantity where for SharedOrderQuantity where it makes sense 2026-08-21 09:51:17 +02:00
Jkorf 79e2efec70 Added IQueryResult interface to QueryResult, moved OriginalData to the base class 2026-08-21 09:48:57 +02:00
Jkorf c8c6d14329 Split UserClientProvider into base class with RestClient and derived class also containing SocketClient 2026-08-21 09:47:19 +02:00
Jkorf b8bd30a09d Added UsePublicConnectionForAuth property to SocketApiClient 2026-08-21 09:44:30 +02:00
Jkorf c2b58ab19a Removed unnecessary log from token manager 2026-08-21 09:43:57 +02:00
Jkorf 90a031c595 Added support for order polling where Shared order implementation doesn't support time filtering to UserDataTracker implementations 2026-08-17 14:17:43 +02:00
Jkorf 860d753ad6 Update README.md 2026-08-07 09:09:51 +02:00
Jkorf e16c91792c Added LBank reference 2026-08-06 10:29:02 +02:00
Jkorf a3d95da9fa Updated examples 2026-08-06 10:26:39 +02:00
JKorf 907399b878 Added ManualUpdateSubscription and UpdateSubscription additional constructor to allow producing websocket events without actual connection 2026-08-05 21:31:59 +02:00
JKorf 9eab0d967e Merge branch 'master' of https://github.com/JKorf/CryptoExchange.Net 2026-08-05 17:53:51 +02:00
JKorf 0dee68e8ae Fixed timing issue in test 2026-08-05 17:53:43 +02:00
Jkorf d838d3377f Updated logging unhandled websocket message 2026-08-05 13:13:48 +02:00
Jkorf 2141ad9061 Fixed incorrect check test output 2026-07-29 13:05:42 +02:00
Jkorf 9be8798ccf Updated to version 12.4.0 2026-07-28 12:45:36 +02:00
Jkorf 4803ed91cd Updated SharedTrade to use SharedOrderQuantity for quantities 2026-07-28 11:47:59 +02:00
Jkorf 20bddd5c37 Updated SharedFuturesTicker, SharedSpotTicker and SharedKline to use SharedOrderQuantity for volumes. Added AveragePrice property to SharedQuantity model 2026-07-28 09:05:48 +02:00
Jkorf 0e75ddb3d0 Updated json deserialization error for empty response 2026-07-24 15:42:37 +02:00
Jkorf 0e5b46002c Added DebuggerDisplay Result objects 2026-07-24 15:42:11 +02:00
Jkorf 8f7c71f9ce Add Pionex reference 2026-07-24 15:40:56 +02:00
Jkorf 73377fbb87 Updated to version 12.3.0 2026-07-23 13:47:24 +02:00
Jkorf 3a00d6371a Updated some Shared errors 2026-07-23 13:17:08 +02:00
Jkorf caf6d36bcd Extracted ConnectionCanBeUsedFor method in SocketApiClient for easier custom logic implementation 2026-07-23 13:16:59 +02:00
Jkorf e078a373da Remove duplicate warnings from testing output 2026-07-21 16:39:30 +02:00
Jkorf 007743f5a1 Added calculation of AveragePrice on Shared order models if data is available and AveragePrice is not set 2026-07-21 11:35:59 +02:00
Jkorf d06f891cee Updated to version 12.2.0 2026-07-20 14:02:03 +02:00
Jkorf 8dcbb687f5 Fixed warning 2026-07-20 13:45:32 +02:00
Jan Korf fcb36f7ee0 Shared asset and symbol types
Added SpotSymbolCatalog to Shared ISpotSymbolRestClient interface
Added FuturesSymbolCatalog to Shared IFuturesSymbolRestClient interface
Added BaseAssetType, BaseAssetSubType, QuoteAssetType and QuoteAssetSubType to GetSymbolsRequest model
Added DisplayName to SharedSpotSymbol and SharedFuturesSymbol models
Added BaseAssetType, BaseAssetSubType, QuoteAssetType and QuoteAssetSubType to SharedSpotSymbol and SharedFuturesSymbol models
Added IsStableCoin, IsCommodity and IsEquity helper methods to LibraryHelpers
2026-07-20 13:40:58 +02:00
nils2525 3cffd67518 Fixed socket individual subscription target calculation (#282)
* Fixed socket individual subscription target calculation

* Fixed socket selection when the least-loaded connection has reached its individual subscription limit
2026-07-20 09:24:01 +02:00
Jkorf ecd00ea707 Added DebuggerDisplay attributes to Shared models 2026-07-14 09:59:02 +02:00
JKorf 38a7b981ce Updated to version 12.1.1 2026-07-11 15:34:31 +02:00
JKorf c41cc3c4c7 Added timestamp deserialization support for yyyy-MM-dd HH:mm:ss.ffffff+00:00:00 2026-07-11 15:19:02 +02:00
Jkorf 4accc8039b Updated to version 12.1.0 2026-07-09 15:06:09 +02:00
Jkorf 87c86ec0c0 Fixed nullability operator on Parameters.AddCommaSeperated 2026-07-09 08:35:39 +02:00
Jkorf d9850da282 Added ExchangeParameters parameter to KlineTracker, TradeTracker and ITrackerFactory methods 2026-07-08 12:00:26 +02:00
Jkorf c4a8b02054 Updated some testing logic 2026-07-02 14:09:55 +02:00
Jkorf 34b7258496 Updated to version 12.0.2 2026-07-01 13:19:57 +02:00
Jkorf 69099922c9 Updated test validation to output a list of issues instead of throwing on the first 2026-07-01 13:16:06 +02:00
Jkorf 64c1cd5fa8 Updated RestIntegrationTest to output missing properties in a list so the running test can output them as warning instead of error 2026-07-01 09:42:55 +02:00
JKorf 936ac6640b Cleanup 2026-06-30 19:22:54 +02:00
Jkorf 68ad9ae114 Fixed warnings in tests 2026-06-30 15:25:08 +02:00
Jkorf 6238c17471 Added skills hub reference 2026-06-30 15:01:54 +02:00
Jkorf 52e6fbfe47 Updated examples 2026-06-30 12:55:20 +02:00
Jkorf 4129622d71 Added Lighter ref 2026-06-29 16:07:25 +02:00
659 changed files with 2864 additions and 117650 deletions
+17 -1
View File
@@ -30,6 +30,22 @@ var ticker = await binance.GetSpotTickerAsync(new GetTickerRequest(symbol));
`SharedSymbol(TradingMode.Spot, "BTC", "USDT")` is portable. Each library translates to its native format internally. Don't pass raw strings like `"BTCUSDT"` to shared methods. `SharedSymbol(TradingMode.Spot, "BTC", "USDT")` is portable. Each library translates to its native format internally. Don't pass raw strings like `"BTCUSDT"` to shared methods.
## Symbol metadata and catalogs
In 12.2.0, `SharedSpotSymbol` and `SharedFuturesSymbol` include `DisplayName` and base/quote asset classification through `SharedAssetType` (`Crypto`, `Fiat`, `TradFi`) and `SharedAssetSubType` (`StableCoin`, `Equity`, `Commodity`). Pass the matching base/quote filters to `GetSymbolsRequest` when discovery should return only a class of markets.
After calling `GetSpotSymbolsAsync`, `ISpotSymbolRestClient.SpotSymbolCatalog` maps asset and symbol names to shared metadata. `IFuturesSymbolRestClient.FuturesSymbolCatalog` works the same way after `GetFuturesSymbolsAsync`. Treat either property as unavailable before its corresponding request has populated the cache.
When implementing an exchange library, use `LibraryHelpers.IsStableCoin`, `IsCommodity`, and `IsEquity` only as best-effort classifiers and supply exchange-specific additions where needed.
## Shared market-data quantities
In 12.4.0, use `SharedOrderQuantity`-valued `Volumes` on shared spot/futures tickers and klines, and `Quantities` on shared trades. The scalar `Volume`, `QuoteVolume`, and `Quantity` members are obsolete.
## WebSocket order commands
In 12.5.0, `ISpotOrderManagementSocketClient` and `IFuturesOrderManagementSocketClient` optionally provide place/cancel order commands over WebSocket. Their methods return `QueryResult<SharedId>`, not `WebSocketResult<UpdateSubscription>`. Check whether the exchange implements the interface.
## Result pattern ## Result pattern
REST methods return `HttpResult<T>` and websocket subscription methods return `WebSocketResult<UpdateSubscription>`. Always check `.Success`. `.Exchange` property identifies which exchange responded — useful for logging. REST methods return `HttpResult<T>` and websocket subscription methods return `WebSocketResult<UpdateSubscription>`. Always check `.Success`. `.Exchange` property identifies which exchange responded — useful for logging.
@@ -37,7 +53,7 @@ REST methods return `HttpResult<T>` and websocket subscription methods return `W
## Available shared interfaces ## Available shared interfaces
- REST tickers/symbols/orderbook/klines/trades, orders (spot/futures, regular/trigger/TP-SL), balances, positions, fees, deposits/withdrawals, transfers - REST tickers/symbols/orderbook/klines/trades, orders (spot/futures, regular/trigger/TP-SL), balances, positions, fees, deposits/withdrawals, transfers
- WebSocket tickers, book tickers, order book, trades, klines, user data - WebSocket tickers, book tickers, order book, trades, klines, user data, and optional spot/futures order management
Each exchange documents which it implements. Not every exchange supports every operation. Each exchange documents which it implements. Not every exchange supports every operation.
+15 -1
View File
@@ -24,6 +24,20 @@ var ticker = await binance.GetSpotTickerAsync(new GetTickerRequest(symbol));
Same code works on every exchange that implements the interface. Use `Task.WhenAll` for concurrent multi-exchange calls. Same code works on every exchange that implements the interface. Use `Task.WhenAll` for concurrent multi-exchange calls.
## Shared symbol metadata
CryptoExchange.Net 12.2.0 classifies the base and quote sides of `SharedSpotSymbol` and `SharedFuturesSymbol` with `SharedAssetType` (`Crypto`, `Fiat`, `TradFi`) and optional `SharedAssetSubType` (`StableCoin`, `Equity`, `Commodity`). The models also expose `DisplayName`. Use the corresponding base/quote fields on `GetSymbolsRequest` to filter symbol discovery.
`ISpotSymbolRestClient.SpotSymbolCatalog` is populated by `GetSpotSymbolsAsync`; `IFuturesSymbolRestClient.FuturesSymbolCatalog` is populated by `GetFuturesSymbolsAsync`. Do not assume a catalog is available before that request. For exchange-library implementations, `LibraryHelpers.IsStableCoin`, `IsCommodity`, and `IsEquity` offer best-effort classification and can be extended with exchange-specific values.
## Shared market-data quantities
CryptoExchange.Net 12.4.0 uses `SharedOrderQuantity` for market-data quantities. Prefer `Volumes` on `SharedSpotTicker`, `SharedFuturesTicker`, and `SharedKline`, and `Quantities` on `SharedTrade`; the scalar `Volume`, `QuoteVolume`, and `Quantity` members are obsolete.
## WebSocket order commands
CryptoExchange.Net 12.5.0 adds optional `ISpotOrderManagementSocketClient` and `IFuturesOrderManagementSocketClient` interfaces for placing and canceling orders over WebSocket. These command methods return `QueryResult<SharedId>` rather than a subscription result. Check exchange support before relying on either interface.
## Single-exchange code uses the exchange's own client ## Single-exchange code uses the exchange's own client
For Binance-only code, use `BinanceRestClient` directly (see Binance.Net repo `AGENTS.md`). SharedApis is for portability — use it when you need that. For Binance-only code, use `BinanceRestClient` directly (see Binance.Net repo `AGENTS.md`). SharedApis is for portability — use it when you need that.
@@ -35,7 +49,7 @@ REST methods return `HttpResult<T>` and websocket subscription methods return `W
## Available shared interfaces ## Available shared interfaces
REST: tickers, symbols, orderbook, klines, trades, orders (spot/futures, trigger, TP-SL), balances, positions, fees, deposits/withdrawals, transfers. REST: tickers, symbols, orderbook, klines, trades, orders (spot/futures, trigger, TP-SL), balances, positions, fees, deposits/withdrawals, transfers.
WebSocket: tickers, book tickers, orderbook, trades, klines, user data. WebSocket: tickers, book tickers, orderbook, trades, klines, user data, and optional spot/futures order management.
Each exchange library implements a subset. Check exchange docs for support matrix. Each exchange library implements a subset. Check exchange docs for support matrix.
+27
View File
@@ -67,6 +67,32 @@ var btcusdtPerp = new SharedSymbol(TradingMode.PerpetualLinear, "BTC", "USDT");
For exchanges that use exotic asset names, see the AssetAliases configuration. For exchanges that use exotic asset names, see the AssetAliases configuration.
## Symbol Metadata and Asset Classification
Since CryptoExchange.Net 12.2.0, shared symbol responses describe both sides of a market with `BaseAssetType`, `BaseAssetSubType`, `QuoteAssetType`, and `QuoteAssetSubType`. `SharedAssetType` distinguishes `Crypto`, `Fiat`, and `TradFi`; `SharedAssetSubType` distinguishes `StableCoin`, `Equity`, and `Commodity`. `SharedSpotSymbol` and `SharedFuturesSymbol` also expose `DisplayName`.
The same fields on `GetSymbolsRequest` filter spot or futures symbol discovery:
```csharp
var request = new GetSymbolsRequest(
baseAssetType: SharedAssetType.Crypto,
quoteAssetSubType: SharedAssetSubType.StableCoin);
var result = await symbolClient.GetSpotSymbolsAsync(request);
```
After calling `GetSpotSymbolsAsync` or `GetFuturesSymbolsAsync`, use the client's `SpotSymbolCatalog` or `FuturesSymbolCatalog` to look up normalized asset and symbol metadata by name. The catalog is unavailable until the corresponding symbol request has populated the cache.
For exchange-library implementations, `LibraryHelpers.IsStableCoin`, `IsCommodity`, and `IsEquity` provide best-effort classification of known assets and accept exchange-specific additions. These helpers are heuristics, not an exhaustive source of truth.
## Shared Market-Data Quantities
Since CryptoExchange.Net 12.4.0, shared market-data models use `SharedOrderQuantity` so base-asset, quote-asset, and contract quantities remain explicit. Read `SharedSpotTicker.Volumes`, `SharedFuturesTicker.Volumes`, and `SharedKline.Volumes`; read `SharedTrade.Quantities`. The former scalar `Volume`, `QuoteVolume`, and `Quantity` members are obsolete.
## WebSocket Order Management
Since CryptoExchange.Net 12.5.0, exchanges can implement `ISpotOrderManagementSocketClient` and `IFuturesOrderManagementSocketClient` to place and cancel orders over WebSocket. These are command interfaces, not subscription interfaces: `Place*OrderAsync` and `Cancel*OrderAsync` return `QueryResult<SharedId>`. Check exchange support before using them.
## Available Shared Interfaces ## Available Shared Interfaces
**REST:** **REST:**
@@ -80,6 +106,7 @@ For exchanges that use exotic asset names, see the AssetAliases configuration.
- `ITickerSocketClient`, `IBookTickerSocketClient` - `ITickerSocketClient`, `IBookTickerSocketClient`
- `IOrderBookSocketClient`, `ITradeSocketClient`, `IKlineSocketClient` - `IOrderBookSocketClient`, `ITradeSocketClient`, `IKlineSocketClient`
- `IUserTradeSocketClient`, `ISpotOrderSocketClient`, `IFuturesOrderSocketClient`, `IPositionSocketClient`, `IBalanceSocketClient` - `IUserTradeSocketClient`, `ISpotOrderSocketClient`, `IFuturesOrderSocketClient`, `IPositionSocketClient`, `IBalanceSocketClient`
- Order commands: `ISpotOrderManagementSocketClient`, `IFuturesOrderManagementSocketClient`
Each exchange documents which interfaces it implements (some exchanges don't support every operation). Each exchange documents which interfaces it implements (some exchanges don't support every operation).
@@ -91,28 +91,25 @@ namespace CryptoExchange.Net.UnitTests
var evnt = new AsyncResetEvent(false, true); var evnt = new AsyncResetEvent(false, true);
var waiters = new List<Task<bool>>(); var waiters = new List<Task<bool>>();
for(var i = 0; i < 10; i++) for (var i = 0; i < 10; i++)
{ {
waiters.Add(evnt.WaitAsync()); waiters.Add(evnt.WaitAsync());
} }
List<bool>? results = null; var remaining = waiters.ToList();
var resultsWaiter = Task.Run(async () =>
{
await Task.WhenAll(waiters);
results = waiters.Select(w => w.Result).ToList();
});
for(var i = 1; i <= 10; i++) for (var i = 0; i < 10; i++)
{ {
evnt.Set(); evnt.Set();
await Task.Delay(1); // Wait for the continuation.
Assert.That(10 - i == waiters.Count(w => w.Status != TaskStatus.RanToCompletion)); var completed = await Task.WhenAny(remaining);
Assert.That(await completed, Is.True);
remaining.Remove(completed);
Assert.That(remaining.Count(w => w.IsCompleted), Is.Zero);
} }
await resultsWaiter; Assert.That(remaining, Is.Empty);
Assert.That(10 == results?.Count(r => r));
} }
[Test] [Test]
@@ -138,6 +138,68 @@ namespace CryptoExchange.Net.UnitTests.ClientTests
Assert.That(socket2.Connected == false); Assert.That(socket2.Connected == false);
} }
[TestCase()]
public async Task BatchedSubscription_Should_NotExceedIndividualCombineTarget()
{
// arrange
var client = new TestSocketClient(options =>
{
options.SocketSubscriptionsCombineTarget = 10;
options.SocketIndividualSubscriptionCombineTarget = 10;
});
TestHelpers.ConfigureSocketClient(client, "wss://localhost");
// act
await client.ApiClient1.SubscribeToUpdatesAsync<TestObject>(x => { }, false, default, individualSubscriptionCount: 6);
TestHelpers.ConfigureSocketClient(client, "wss://localhost");
await client.ApiClient1.SubscribeToUpdatesAsync<TestObject>(x => { }, false, default, individualSubscriptionCount: 6);
// assert
Assert.That(client.ApiClient1._socketConnections.Count == 2);
Assert.That(client.ApiClient1._socketConnections.Values.All(connection => connection.Subscriptions.Sum(subscription => subscription.IndividualSubscriptionCount) <= 10));
}
[TestCase()]
public async Task BatchedSubscription_FullIndividualConnection_Should_NotPreventEligibleConnectionReuse()
{
// arrange
var client = new TestSocketClient(options =>
{
options.SocketSubscriptionsCombineTarget = 5;
options.SocketIndividualSubscriptionCombineTarget = 10;
});
TestHelpers.ConfigureSocketClient(client, "wss://localhost");
await client.ApiClient1.SubscribeToUpdatesAsync<TestObject>(x => { }, false, default);
await client.ApiClient1.SubscribeToUpdatesAsync<TestObject>(x => { }, false, default);
TestHelpers.ConfigureSocketClient(client, "wss://localhost");
await client.ApiClient1.SubscribeToUpdatesAsync<TestObject>(x => { }, false, default, individualSubscriptionCount: 10);
TestHelpers.ConfigureSocketClient(client, "wss://localhost");
// act
await client.ApiClient1.SubscribeToUpdatesAsync<TestObject>(x => { }, false, default);
// assert
Assert.That(
client.ApiClient1._socketConnections.Count,
Is.EqualTo(2),
"The eligible connection should be reused instead of opening a new connection after selecting a full individual-subscription connection");
var fullConnection = client.ApiClient1._socketConnections.Values
.Single(connection => connection.Subscriptions.Sum(subscription => subscription.IndividualSubscriptionCount) == 10);
Assert.That(
fullConnection.UserSubscriptionCount,
Is.EqualTo(1),
"The full connection should not receive the normal subscription");
var eligibleConnection = client.ApiClient1._socketConnections.Values.Single(connection => connection != fullConnection);
Assert.That(
eligibleConnection.UserSubscriptionCount,
Is.EqualTo(3),
"The existing eligible connection should receive the normal subscription");
}
[TestCase()] [TestCase()]
public async Task ErrorResponse_ShouldNot_ConfirmSubscription() public async Task ErrorResponse_ShouldNot_ConfirmSubscription()
{ {
@@ -31,7 +31,7 @@ namespace CryptoExchange.Net.UnitTests.ConverterTests
[TestCase(-1, false)] [TestCase(-1, false)]
public void TestBoolConverterInts(int value, bool? expected) public void TestBoolConverterInts(int value, bool? expected)
{ {
var val = value == null ? "null" : $"{value}"; var val = $"{value}";
var output = JsonSerializer.Deserialize<STJBoolObject>($"{{ \"Value\": {val} }}", SerializerOptions.WithConverters(new TestSerializerContext())); var output = JsonSerializer.Deserialize<STJBoolObject>($"{{ \"Value\": {val} }}", SerializerOptions.WithConverters(new TestSerializerContext()));
Assert.That(output!.Value == expected); Assert.That(output!.Value == expected);
} }
@@ -15,6 +15,7 @@ namespace CryptoExchange.Net.UnitTests.ConverterTests
[TestCase("1620777600000")] [TestCase("1620777600000")]
[TestCase("2021-05-12T00:00:00.000Z")] [TestCase("2021-05-12T00:00:00.000Z")]
[TestCase("2021-05-12T00:00:00.000000000Z")] [TestCase("2021-05-12T00:00:00.000000000Z")]
[TestCase("2021-05-12 00:00:00.000000+00:00:00")]
[TestCase("0.000000", true)] [TestCase("0.000000", true)]
[TestCase("0", true)] [TestCase("0", true)]
[TestCase("", true)] [TestCase("", true)]
@@ -36,9 +36,13 @@ namespace CryptoExchange.Net.UnitTests.Implementations
protected override TestAuthenticationProvider CreateAuthenticationProvider(TestCredentials credentials) => protected override TestAuthenticationProvider CreateAuthenticationProvider(TestCredentials credentials) =>
new TestAuthenticationProvider(credentials); new TestAuthenticationProvider(credentials);
public async Task<WebSocketResult<UpdateSubscription>> SubscribeToUpdatesAsync<T>(Action<DataEvent<T>> handler, bool subQuery, CancellationToken ct) public async Task<WebSocketResult<UpdateSubscription>> SubscribeToUpdatesAsync<T>(Action<DataEvent<T>> handler, bool subQuery, CancellationToken ct, int individualSubscriptionCount = 1)
{ {
return await base.SubscribeAsync(new TestSubscription<T>(_logger, handler, subQuery, false), ct); var subscription = new TestSubscription<T>(_logger, handler, subQuery, false)
{
IndividualSubscriptionCount = individualSubscriptionCount
};
return await base.SubscribeAsync(subscription, ct);
} }
} }
} }
@@ -0,0 +1,136 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Objects.Errors;
using CryptoExchange.Net.Objects.Sockets;
using CryptoExchange.Net.Sockets.Default;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CryptoExchange.Net.UnitTests
{
[TestFixture]
public class ManualUpdateSubscriptionTests
{
[Test]
public void Constructor_Should_CreateSubscribedVirtualSubscription()
{
var controller = new ManualUpdateSubscription(socketId: 12);
Assert.That(controller.Subscription.SocketId, Is.EqualTo(12));
Assert.That(controller.Subscription.Id, Is.GreaterThan(0));
Assert.That(controller.Subscription.SocketStatus, Is.EqualTo(SocketStatus.Connected));
Assert.That(controller.Subscription.SubscriptionStatus, Is.EqualTo(SubscriptionStatus.Subscribed));
Assert.That(controller.Subscription.LastReceiveTime, Is.Null);
}
[Test]
public void StateChanges_Should_BeVisibleOnSubscription()
{
var controller = new ManualUpdateSubscription();
var timestamp = new DateTime(2026, 8, 5, 12, 0, 0, DateTimeKind.Utc);
var statuses = new List<SubscriptionStatus>();
controller.Subscription.SubscriptionStatusChanged += statuses.Add;
controller.SetLastReceiveTime(timestamp);
controller.SetSocketStatus(SocketStatus.Reconnecting);
controller.SetSubscriptionStatus(SubscriptionStatus.Subscribing);
controller.SetSubscriptionStatus(SubscriptionStatus.Subscribed);
Assert.That(controller.Subscription.LastReceiveTime, Is.EqualTo(timestamp));
Assert.That(controller.Subscription.SocketStatus, Is.EqualTo(SocketStatus.Reconnecting));
Assert.That(controller.Subscription.SubscriptionStatus, Is.EqualTo(SubscriptionStatus.Subscribed));
Assert.That(statuses, Is.EqualTo(new[]
{
SubscriptionStatus.Subscribing,
SubscriptionStatus.Subscribed
}));
}
[Test]
public void LifecycleMethods_Should_InvokeSubscriptionEvents()
{
var controller = new ManualUpdateSubscription();
var error = new ServerError("Test error", ErrorInfo.Unknown);
var exception = new InvalidOperationException("Test exception");
var disconnectedPeriod = TimeSpan.FromMinutes(2);
var lost = 0;
var restored = TimeSpan.Zero;
Error? resubscribeError = null;
var paused = 0;
var unpaused = 0;
Exception? receivedException = null;
controller.Subscription.ConnectionLost += () => lost++;
controller.Subscription.ConnectionRestored += x => restored = x;
controller.Subscription.ResubscribingFailed += x => resubscribeError = x;
controller.Subscription.ActivityPaused += () => paused++;
controller.Subscription.ActivityUnpaused += () => unpaused++;
controller.Subscription.Exception += x => receivedException = x;
controller.InvokeConnectionLost();
controller.InvokeConnectionRestored(disconnectedPeriod);
controller.InvokeResubscribingFailed(error);
controller.InvokeActivityPaused();
controller.InvokeActivityUnpaused();
controller.InvokeException(exception);
Assert.That(lost, Is.EqualTo(1));
Assert.That(restored, Is.EqualTo(disconnectedPeriod));
Assert.That(resubscribeError, Is.SameAs(error));
Assert.That(paused, Is.EqualTo(1));
Assert.That(unpaused, Is.EqualTo(1));
Assert.That(receivedException, Is.SameAs(exception));
}
[Test]
public void InvokeConnectionClosed_Should_CloseAndOnlyInvokeOnce()
{
var controller = new ManualUpdateSubscription();
var closed = 0;
controller.Subscription.ConnectionClosed += () => closed++;
controller.InvokeConnectionClosed();
controller.InvokeConnectionClosed();
Assert.That(closed, Is.EqualTo(1));
Assert.That(controller.Subscription.SocketStatus, Is.EqualTo(SocketStatus.Closed));
Assert.That(controller.Subscription.SubscriptionStatus, Is.EqualTo(SubscriptionStatus.Closed));
}
[Test]
public async Task SubscriptionOperations_Should_InvokeCallbacks()
{
var closes = 0;
var reconnects = 0;
var resubscribes = 0;
var controller = new ManualUpdateSubscription(
closeAsync: () =>
{
closes++;
return Task.CompletedTask;
},
reconnectAsync: () =>
{
reconnects++;
return Task.CompletedTask;
},
resubscribeAsync: () =>
{
resubscribes++;
return Task.FromResult(CallResult.Ok());
});
await controller.Subscription.ReconnectAsync();
var resubscribeResult = await controller.Subscription.ResubscribeAsync();
await controller.Subscription.CloseAsync();
await controller.Subscription.CloseAsync();
Assert.That(reconnects, Is.EqualTo(1));
Assert.That(resubscribes, Is.EqualTo(1));
Assert.That(resubscribeResult.Success, Is.True);
Assert.That(closes, Is.EqualTo(1));
Assert.That(controller.Subscription.SubscriptionStatus, Is.EqualTo(SubscriptionStatus.Closed));
}
}
}
@@ -156,8 +156,9 @@ namespace CryptoExchange.Net.UnitTests.SocketRoutingTests
MessageRouter = messageRouter; MessageRouter = messageRouter;
} }
#pragma warning disable CS0067 // The event is never used, but it's required by the interface
public event Action? OnMessageRouterUpdated; public event Action? OnMessageRouterUpdated;
#pragma warning restore CS0067
public bool Handle(string typeIdentifier, string? topicFilter, SocketConnection socketConnection, DateTime receiveTime, string? originalData, object result) public bool Handle(string typeIdentifier, string? topicFilter, SocketConnection socketConnection, DateTime receiveTime, string? originalData, object result)
{ {
return true; return true;
+50 -33
View File
@@ -97,6 +97,11 @@ namespace CryptoExchange.Net.Clients
/// </summary> /// </summary>
protected bool AllowTopicsOnTheSameConnection { get; set; } = true; protected bool AllowTopicsOnTheSameConnection { get; set; } = true;
/// <summary>
/// Whether to allow usage of a current public WebSocket connection for an authenticated request
/// </summary>
protected bool UsePublicConnectionForAuth { get; set; } = false;
/// <inheritdoc /> /// <inheritdoc />
public double IncomingKbps public double IncomingKbps
{ {
@@ -625,6 +630,21 @@ namespace CryptoExchange.Net.Clients
return Task.FromResult(CallResult.Ok()); return Task.FromResult(CallResult.Ok());
} }
/// <summary>
/// Whether the connection can be used for a new subscription or query with the provided parameters
/// </summary>
/// <param name="connection">The connection to check</param>
/// <param name="address">The address set by the request</param>
/// <param name="authenticated">Whether the request needs an authenticated connection</param>
/// <param name="topic">Topic of the request</param>
/// <returns>True if connection can be used</returns>
protected virtual bool ConnectionCanBeUsedFor(SocketConnection connection, string address, bool authenticated, string? topic = null)
{
return connection.ConnectionUriString.Equals(address.TrimEnd('/'), StringComparison.Ordinal)
&& connection.ApiClient.ClientName.Equals(ClientName, StringComparison.Ordinal)
&& (AllowTopicsOnTheSameConnection || !connection.Topics.Contains(topic));
}
/// <summary> /// <summary>
/// Gets a connection for a new subscription or query. Can be an existing if there are open position or a new one. /// Gets a connection for a new subscription or query. Can be an existing if there are open position or a new one.
/// </summary> /// </summary>
@@ -643,10 +663,7 @@ namespace CryptoExchange.Net.Clients
string? topic = null, string? topic = null,
int individualSubscriptionCount = 1) int individualSubscriptionCount = 1)
{ {
var socketQuery = _socketConnections.Where(s => s.Value.ConnectionUriString.Equals(address.TrimEnd('/'), StringComparison.Ordinal) var socketQuery = _socketConnections.Where(s => ConnectionCanBeUsedFor(s.Value, address, authenticated, topic)).Select(x => x.Value); // Don't ToList this so the query is executed again when called
&& s.Value.ApiClient.ClientName.Equals(ClientName, StringComparison.Ordinal)
&& (AllowTopicsOnTheSameConnection || !s.Value.Topics.Contains(topic)))
.Select(x => x.Value); // Don't ToList this so the query is executed again when called
// If all current socket connections are reconnecting or resubscribing wait for that to finish as we can probably use the existing connection // If all current socket connections are reconnecting or resubscribing wait for that to finish as we can probably use the existing connection
var delayStart = DateTime.UtcNow; var delayStart = DateTime.UtcNow;
@@ -676,49 +693,32 @@ namespace CryptoExchange.Net.Clients
_logger.WaitedForReconnectingSocket((long)(DateTime.UtcNow - delayStart).TotalMilliseconds); _logger.WaitedForReconnectingSocket((long)(DateTime.UtcNow - delayStart).TotalMilliseconds);
socketQuery = socketQuery.Where(s => (s.Status == SocketStatus.None || s.Status == SocketStatus.Connected) socketQuery = socketQuery.Where(s => (s.Status == SocketStatus.None || s.Status == SocketStatus.Connected)
&& (s.Authenticated == authenticated || !authenticated) && (s.Authenticated == authenticated || !authenticated || UsePublicConnectionForAuth)
&& s.Connected).ToList(); && s.Connected).ToList();
SocketConnection? connection; bool maxConnectionsReached = _socketConnections.Count >= (ApiOptions.MaxSocketConnections ?? ClientOptions.MaxSocketConnections);
if (!dedicatedRequestConnection) SocketConnection? connection = null;
{ if (dedicatedRequestConnection)
connection = socketQuery
.Where(s => !s.DedicatedRequestConnection.IsDedicatedRequestConnection)
.OrderBy(s => s.UserSubscriptionCount)
.FirstOrDefault();
}
else
{ {
connection = socketQuery.Where(s => s.DedicatedRequestConnection.IsDedicatedRequestConnection).FirstOrDefault(); connection = socketQuery.Where(s => s.DedicatedRequestConnection.IsDedicatedRequestConnection).FirstOrDefault();
if (connection != null && !connection.DedicatedRequestConnection.Authenticated) if (connection != null && !connection.DedicatedRequestConnection.Authenticated)
// Mark dedicated request connection as authenticated if the request is authenticated // Mark dedicated request connection as authenticated if the request is authenticated
connection.DedicatedRequestConnection.Authenticated = authenticated; connection.DedicatedRequestConnection.Authenticated = authenticated;
}
if (connection == null) if (connection == null)
// Fall back to an existing connection if there is no dedicated request connection available {
connection = socketQuery.OrderBy(s => s.UserSubscriptionCount).FirstOrDefault(); // Use an eligible non-dedicated connection for subscriptions, or as fallback when no dedicated request connection is available
connection = socketQuery
.Where(s => !s.DedicatedRequestConnection.IsDedicatedRequestConnection)
.Where(s => IsConnectionEligible(s, individualSubscriptionCount, maxConnectionsReached))
.OrderBy(s => s.UserSubscriptionCount)
.FirstOrDefault();
} }
bool maxConnectionsReached = _socketConnections.Count >= (ApiOptions.MaxSocketConnections ?? ClientOptions.MaxSocketConnections);
if (connection != null) if (connection != null)
{
bool lessThanBatchSubCombineTarget = connection.UserSubscriptionCount < ClientOptions.SocketSubscriptionsCombineTarget;
bool lessThanIndividualSubCombineTarget = connection.Subscriptions.Sum(x => x.IndividualSubscriptionCount) < ClientOptions.SocketIndividualSubscriptionCombineTarget;
if ((lessThanBatchSubCombineTarget && lessThanIndividualSubCombineTarget)
|| maxConnectionsReached)
{
// Use existing socket if it has less than target connections OR it has the least connections and we can't make new
// If there is a max subscriptions per connection limit also only use existing if the new subscription doesn't go over the limit
if (MaxIndividualSubscriptionsPerConnection == null)
return CallResult.Ok(connection); return CallResult.Ok(connection);
var currentCount = connection.Subscriptions.Sum(x => x.IndividualSubscriptionCount);
if (currentCount + individualSubscriptionCount <= MaxIndividualSubscriptionsPerConnection)
return CallResult.Ok(connection);
}
}
if (maxConnectionsReached) if (maxConnectionsReached)
return CallResult.Fail<SocketConnection>(new InvalidOperationError("Max amount of socket connections reached")); return CallResult.Fail<SocketConnection>(new InvalidOperationError("Max amount of socket connections reached"));
@@ -784,6 +784,23 @@ namespace CryptoExchange.Net.Clients
return CallResult.Ok(socketConnection); return CallResult.Ok(socketConnection);
} }
private bool IsConnectionEligible(SocketConnection socketConnection, int individualSubscriptionCount, bool maxConnectionsReached)
{
var currentIndividualSubscriptionCount = socketConnection.Subscriptions.Sum(x => x.IndividualSubscriptionCount);
bool lessThanBatchSubCombineTarget = socketConnection.UserSubscriptionCount < ClientOptions.SocketSubscriptionsCombineTarget;
// Include the incoming batch so batched subscriptions cannot overshoot the configured socket target.
bool lessThanIndividualSubCombineTarget = currentIndividualSubscriptionCount + individualSubscriptionCount <= ClientOptions.SocketIndividualSubscriptionCombineTarget;
if ((!lessThanBatchSubCombineTarget || !lessThanIndividualSubCombineTarget)
&& !maxConnectionsReached)
{
return false;
}
return MaxIndividualSubscriptionsPerConnection == null
|| currentIndividualSubscriptionCount + individualSubscriptionCount <= MaxIndividualSubscriptionsPerConnection;
}
/// <summary> /// <summary>
/// Process an unhandled message /// Process an unhandled message
/// </summary> /// </summary>
+100 -60
View File
@@ -14,21 +14,19 @@ using System.Text;
namespace CryptoExchange.Net.Clients namespace CryptoExchange.Net.Clients
{ {
/// <inheritdoc /> /// <inheritdoc />
public abstract class UserClientProvider<TRestClient, TSocketClient, TRestOptions, TSocketOptions, TCredentials, TEnvironment> public abstract class UserClientProvider<TRestClient, TRestOptions, TCredentials, TEnvironment>
where TRestClient : IRestClient<TCredentials> where TRestClient : IRestClient<TCredentials>
where TSocketClient : ISocketClient<TCredentials>
where TRestOptions : RestExchangeOptions<TEnvironment, TCredentials>, new() where TRestOptions : RestExchangeOptions<TEnvironment, TCredentials>, new()
where TSocketOptions : SocketExchangeOptions<TEnvironment, TCredentials>, new()
where TCredentials : ApiCredentials where TCredentials : ApiCredentials
where TEnvironment : TradeEnvironment where TEnvironment : TradeEnvironment
{ {
private ConcurrentDictionary<string, TRestClient> _restClients = new ConcurrentDictionary<string, TRestClient>(); private ConcurrentDictionary<string, TRestClient> _restClients = new ConcurrentDictionary<string, TRestClient>();
private ConcurrentDictionary<string, TSocketClient> _socketClients = new ConcurrentDictionary<string, TSocketClient>();
private readonly IOptions<TRestOptions> _restOptions; private readonly IOptions<TRestOptions> _restOptions;
private readonly IOptions<TSocketOptions> _socketOptions;
private readonly HttpClient _httpClient; private readonly HttpClient _httpClient;
private readonly ILoggerFactory? _loggerFactory; /// <summary>
/// Logger factory
/// </summary>
protected readonly ILoggerFactory? _loggerFactory;
/// <inheritdoc /> /// <inheritdoc />
public abstract string ExchangeName { get; } public abstract string ExchangeName { get; }
@@ -39,17 +37,14 @@ namespace CryptoExchange.Net.Clients
public UserClientProvider( public UserClientProvider(
HttpClient? httpClient, HttpClient? httpClient,
ILoggerFactory? loggerFactory, ILoggerFactory? loggerFactory,
IOptions<TRestOptions> restOptions, IOptions<TRestOptions> restOptions)
IOptions<TSocketOptions> socketOptions)
{ {
_httpClient = httpClient ?? new HttpClient(); _httpClient = httpClient ?? new HttpClient();
_httpClient.Timeout = restOptions.Value.RequestTimeout; _httpClient.Timeout = restOptions.Value.RequestTimeout;
_loggerFactory = loggerFactory; _loggerFactory = loggerFactory;
_restOptions = restOptions; _restOptions = restOptions;
_socketOptions = socketOptions;
} }
private IOptions<TRestOptions> SetRestEnvironment(IOptions<TRestOptions> options, TEnvironment? environment) private IOptions<TRestOptions> SetRestEnvironment(IOptions<TRestOptions> options, TEnvironment? environment)
{ {
if (environment == null) if (environment == null)
@@ -61,22 +56,10 @@ namespace CryptoExchange.Net.Clients
return Options.Create(newRestClientOptions); return Options.Create(newRestClientOptions);
} }
private IOptions<TSocketOptions> SetSocketEnvironment(IOptions<TSocketOptions> options, TEnvironment? environment)
{
if (environment == null)
return options;
var newSocketClientOptions = new TSocketOptions();
options.Value.Set(newSocketClientOptions);
newSocketClientOptions.Environment = environment;
return Options.Create(newSocketClientOptions);
}
/// <inheritdoc /> /// <inheritdoc />
public void InitializeUserClient(string userIdentifier, TCredentials credentials, TEnvironment? environment = null) public virtual void InitializeUserClient(string userIdentifier, TCredentials credentials, TEnvironment? environment = null)
{ {
CreateRestClient(userIdentifier, credentials, environment); CreateRestClient(userIdentifier, credentials, environment);
CreateSocketClient(userIdentifier, credentials, environment);
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -88,15 +71,6 @@ namespace CryptoExchange.Net.Clients
return client; return client;
} }
/// <inheritdoc />
public TSocketClient GetSocketClient(string userIdentifier, TCredentials? credentials = null, TEnvironment? environment = null)
{
if (!_socketClients.TryGetValue(userIdentifier, out var client) || client.Disposed)
client = CreateSocketClient(userIdentifier, credentials, environment);
return client;
}
private TRestClient CreateRestClient(string userIdentifier, TCredentials? credentials, TEnvironment? environment) private TRestClient CreateRestClient(string userIdentifier, TCredentials? credentials, TEnvironment? environment)
{ {
var clientRestOptions = SetRestEnvironment(_restOptions, environment); var clientRestOptions = SetRestEnvironment(_restOptions, environment);
@@ -109,6 +83,94 @@ namespace CryptoExchange.Net.Clients
return client; return client;
} }
/// <summary>
/// Constructs a new instance of the rest client
/// </summary>
protected abstract TRestClient ConstructRestClient(
HttpClient client,
ILoggerFactory? loggerFactory,
IOptions<TRestOptions> options);
/// <inheritdoc />
public virtual void ClearUserClients(string userIdentifier)
{
_restClients.TryRemove(userIdentifier, out var restClient);
restClient?.Dispose();
}
/// <inheritdoc />
public virtual void Clear()
{
foreach (var client in _restClients.Values)
client.Dispose();
_restClients.Clear();
}
/// <summary>
/// Applies the provided options delegate to a new instance of the specified type.
/// </summary>
protected static T ApplyOptionsDelegate<T>(Action<T>? del) where T : new()
{
var opts = new T();
del?.Invoke(opts);
return opts;
}
}
/// <inheritdoc />
public abstract class UserClientProvider<TRestClient, TSocketClient, TRestOptions, TSocketOptions, TCredentials, TEnvironment>
: UserClientProvider<TRestClient, TRestOptions, TCredentials, TEnvironment>
where TRestClient : IRestClient<TCredentials>
where TSocketClient : ISocketClient<TCredentials>
where TRestOptions : RestExchangeOptions<TEnvironment, TCredentials>, new()
where TSocketOptions : SocketExchangeOptions<TEnvironment, TCredentials>, new()
where TCredentials : ApiCredentials
where TEnvironment : TradeEnvironment
{
private ConcurrentDictionary<string, TSocketClient> _socketClients = new ConcurrentDictionary<string, TSocketClient>();
private readonly IOptions<TSocketOptions> _socketOptions;
/// <summary>
/// ctor
/// </summary>
public UserClientProvider(
HttpClient? httpClient,
ILoggerFactory? loggerFactory,
IOptions<TRestOptions> restOptions,
IOptions<TSocketOptions> socketOptions)
: base(httpClient, loggerFactory, restOptions)
{
_socketOptions = socketOptions;
}
private IOptions<TSocketOptions> SetSocketEnvironment(IOptions<TSocketOptions> options, TEnvironment? environment)
{
if (environment == null)
return options;
var newSocketClientOptions = new TSocketOptions();
options.Value.Set(newSocketClientOptions);
newSocketClientOptions.Environment = environment;
return Options.Create(newSocketClientOptions);
}
/// <inheritdoc />
public override void InitializeUserClient(string userIdentifier, TCredentials credentials, TEnvironment? environment = null)
{
base.InitializeUserClient(userIdentifier, credentials, environment);
CreateSocketClient(userIdentifier, credentials, environment);
}
/// <inheritdoc />
public TSocketClient GetSocketClient(string userIdentifier, TCredentials? credentials = null, TEnvironment? environment = null)
{
if (!_socketClients.TryGetValue(userIdentifier, out var client) || client.Disposed)
client = CreateSocketClient(userIdentifier, credentials, environment);
return client;
}
private TSocketClient CreateSocketClient(string userIdentifier, TCredentials? credentials, TEnvironment? environment) private TSocketClient CreateSocketClient(string userIdentifier, TCredentials? credentials, TEnvironment? environment)
{ {
var clientSocketOptions = SetSocketEnvironment(_socketOptions, environment); var clientSocketOptions = SetSocketEnvironment(_socketOptions, environment);
@@ -121,15 +183,6 @@ namespace CryptoExchange.Net.Clients
return client; return client;
} }
/// <summary>
/// Constructs a new instance of the rest client
/// </summary>
protected abstract TRestClient ConstructRestClient(
HttpClient client,
ILoggerFactory? loggerFactory,
IOptions<TRestOptions> options);
/// <summary> /// <summary>
/// Constructs a new instance of the socket client /// Constructs a new instance of the socket client
/// </summary> /// </summary>
@@ -137,36 +190,23 @@ namespace CryptoExchange.Net.Clients
ILoggerFactory? loggerFactory, ILoggerFactory? loggerFactory,
IOptions<TSocketOptions> options); IOptions<TSocketOptions> options);
/// <inheritdoc /> /// <inheritdoc />
public void ClearUserClients(string userIdentifier) public override void ClearUserClients(string userIdentifier)
{ {
_restClients.TryRemove(userIdentifier, out var restClient); base.ClearUserClients(userIdentifier);
_socketClients.TryRemove(userIdentifier, out var socketClient); _socketClients.TryRemove(userIdentifier, out var socketClient);
restClient?.Dispose();
socketClient?.Dispose(); socketClient?.Dispose();
} }
/// <inheritdoc /> /// <inheritdoc />
public void Clear() public override void Clear()
{ {
foreach (var client in _restClients.Values) base.Clear();
client.Dispose();
_restClients.Clear();
foreach (var client in _socketClients.Values) foreach (var client in _socketClients.Values)
client.Dispose(); client.Dispose();
_socketClients.Clear(); _socketClients.Clear();
} }
/// <summary>
/// Applies the provided options delegate to a new instance of the specified type.
/// </summary>
protected static T ApplyOptionsDelegate<T>(Action<T>? del) where T : new()
{
var opts = new T();
del?.Invoke(opts);
return opts;
}
} }
} }
@@ -198,6 +198,9 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
return new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Utc); return new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Utc);
} }
if (stringValue.EndsWith("+00:00:00"))
return DateTime.Parse(stringValue.Substring(0, stringValue.Length - 9), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
return DateTime.Parse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); return DateTime.Parse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
} }
@@ -88,7 +88,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson.MessageHandlers
stream.Seek(0, SeekOrigin.Begin); stream.Seek(0, SeekOrigin.Begin);
var written = new StreamReader(stream).ReadBlock(dataSnippet, 0, _errorResponseSnippetLimit); var written = new StreamReader(stream).ReadBlock(dataSnippet, 0, _errorResponseSnippetLimit);
var data = new string(dataSnippet, 0, written); var data = new string(dataSnippet, 0, written);
errorMsg += $": {data}"; errorMsg += $": {(string.IsNullOrEmpty(data) ? "(empty)" : data)}";
if (data.Length == _errorResponseSnippetLimit) if (data.Length == _errorResponseSnippetLimit)
errorMsg += " (truncated)"; errorMsg += " (truncated)";
} }
+3 -3
View File
@@ -6,9 +6,9 @@
<PackageId>CryptoExchange.Net</PackageId> <PackageId>CryptoExchange.Net</PackageId>
<Authors>JKorf</Authors> <Authors>JKorf</Authors>
<Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description> <Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description>
<PackageVersion>12.0.1</PackageVersion> <PackageVersion>12.5.0</PackageVersion>
<AssemblyVersion>12.0.1</AssemblyVersion> <AssemblyVersion>12.5.0</AssemblyVersion>
<FileVersion>12.0.1</FileVersion> <FileVersion>12.5.0</FileVersion>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange;CryptoExchange.Net</PackageTags> <PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange;CryptoExchange.Net</PackageTags>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
+71 -10
View File
@@ -33,7 +33,7 @@ namespace CryptoExchange.Net
if (keyedCache != null && DateTime.UtcNow - keyedCache.UpdateTime < TimeSpan.FromMinutes(60)) if (keyedCache != null && DateTime.UtcNow - keyedCache.UpdateTime < TimeSpan.FromMinutes(60))
return; return;
exchangeInfo.Set(key, new ExchangeInfo(DateTime.UtcNow, updateData.ToDictionary(x => x.Name, x => x.SharedSymbol))); exchangeInfo.Set(key, new ExchangeInfo(DateTime.UtcNow, updateData.ToDictionary(x => x.Name, x => x)));
} }
/// <summary> /// <summary>
@@ -118,6 +118,22 @@ namespace CryptoExchange.Net
return exchangeInfo.ParseSymbol(key, symbolName); return exchangeInfo.ParseSymbol(key, symbolName);
} }
/// <summary>
/// Get a symbol catalog for a specific exchange(topic) and environment. Only available if <see cref="UpdateSymbolInfo(string, string, string?, SharedSpotSymbol[])"/> has been called previously.
/// </summary>
/// <param name="exchange">Exchange name</param>
/// <param name="topicId">Id for the provided data</param>
/// <param name="environmentName">Trade environment</param>
/// <param name="key">Additional data set identification key</param>
public static SharedSymbolCatalog? GetSymbolCatalog(string exchange, string topicId, string environmentName, string? key)
{
var id = topicId + environmentName;
if (!_symbolInfos.TryGetValue(id, out var exchangeInfo))
return null;
return exchangeInfo.GetSymbolCatalog(exchange, key);
}
class ExchangeKeyedCache class ExchangeKeyedCache
{ {
private ExchangeInfo? _noKeyCache; private ExchangeInfo? _noKeyCache;
@@ -163,7 +179,7 @@ namespace CryptoExchange.Net
public SharedSymbol? ParseSymbol(string? key, string symbolName) public SharedSymbol? ParseSymbol(string? key, string symbolName)
{ {
SharedSymbol? symbolInfo = null; SharedSpotSymbol? symbolInfo = null;
if (key == null) if (key == null)
{ {
if (_noKeyCache != null) if (_noKeyCache != null)
@@ -173,7 +189,7 @@ namespace CryptoExchange.Net
return new SharedSymbol(symbolInfo.TradingMode, symbolInfo.BaseAsset, symbolInfo.QuoteAsset, symbolName) return new SharedSymbol(symbolInfo.TradingMode, symbolInfo.BaseAsset, symbolInfo.QuoteAsset, symbolName)
{ {
DeliverTime = symbolInfo.DeliverTime DeliverTime = (symbolInfo as SharedFuturesSymbol)?.DeliveryTime
}; };
} }
@@ -183,7 +199,7 @@ namespace CryptoExchange.Net
{ {
return new SharedSymbol(symbolInfo.TradingMode, symbolInfo.BaseAsset, symbolInfo.QuoteAsset, symbolName) return new SharedSymbol(symbolInfo.TradingMode, symbolInfo.BaseAsset, symbolInfo.QuoteAsset, symbolName)
{ {
DeliverTime = symbolInfo.DeliverTime DeliverTime = (symbolInfo as SharedFuturesSymbol)?.DeliveryTime
}; };
} }
} }
@@ -199,7 +215,7 @@ namespace CryptoExchange.Net
{ {
return new SharedSymbol(symbolInfo.TradingMode, symbolInfo.BaseAsset, symbolInfo.QuoteAsset, symbolName) return new SharedSymbol(symbolInfo.TradingMode, symbolInfo.BaseAsset, symbolInfo.QuoteAsset, symbolName)
{ {
DeliverTime = symbolInfo.DeliverTime DeliverTime = (symbolInfo as SharedFuturesSymbol)?.DeliveryTime
}; };
} }
@@ -265,7 +281,7 @@ namespace CryptoExchange.Net
{ {
return _noKeyCache.Symbols return _noKeyCache.Symbols
.Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase)) .Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase))
.Select(x => x.Value) .Select(x => x.Value.SharedSymbol)
.ToArray(); .ToArray();
} }
@@ -274,7 +290,7 @@ namespace CryptoExchange.Net
{ {
result.AddRange(cache.Symbols result.AddRange(cache.Symbols
.Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase)) .Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase))
.Select(x => x.Value)); .Select(x => x.Value.SharedSymbol));
} }
return result.ToArray(); return result.ToArray();
@@ -286,18 +302,63 @@ namespace CryptoExchange.Net
return exchangeInfo.Symbols return exchangeInfo.Symbols
.Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase)) .Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase))
.Select(x => x.Value) .Select(x => x.Value.SharedSymbol)
.ToArray(); .ToArray();
} }
internal SharedSymbolCatalog? GetSymbolCatalog(string exchange, string? key)
{
IEnumerable<SharedSpotSymbol> cachedSymbols;
if (key == null)
{
if (_noKeyCache != null)
cachedSymbols = _noKeyCache.Symbols.Values;
else
cachedSymbols = _keyedCache.Values.SelectMany(x => x.Symbols.Values);
}
else
{
if (!_keyedCache.TryGetValue(key, out var exchangeInfo) || exchangeInfo == null)
return null;
cachedSymbols = exchangeInfo.Symbols.Values;
}
var assets = new Dictionary<string, SharedAssetInfo>();
var symbols = new Dictionary<string, SharedSpotSymbol>();
foreach (var symbol in cachedSymbols)
{
if (!assets.TryGetValue(symbol.BaseAsset, out var baseAssetInfo))
{
baseAssetInfo = new SharedAssetInfo(symbol.BaseAsset, symbol.BaseAssetType, symbol.BaseAssetSubType);
assets.Add(symbol.BaseAsset, baseAssetInfo);
}
if (!assets.TryGetValue(symbol.QuoteAsset, out var quoteAssetInfo))
{
quoteAssetInfo = new SharedAssetInfo(symbol.QuoteAsset, symbol.QuoteAssetType, symbol.QuoteAssetSubType);
assets.Add(symbol.QuoteAsset, quoteAssetInfo);
}
symbols.Add(symbol.Name, symbol);
}
return new SharedSymbolCatalog
{
Exchange = exchange,
Assets = assets,
Symbols = symbols
};
}
} }
class ExchangeInfo class ExchangeInfo
{ {
public DateTime UpdateTime { get; set; } public DateTime UpdateTime { get; set; }
public Dictionary<string, SharedSymbol> Symbols { get; set; } public Dictionary<string, SharedSpotSymbol> Symbols { get; set; }
public ExchangeInfo(DateTime updateTime, Dictionary<string, SharedSymbol> symbols) public ExchangeInfo(DateTime updateTime, Dictionary<string, SharedSpotSymbol> symbols)
{ {
UpdateTime = updateTime; UpdateTime = updateTime;
Symbols = symbols; Symbols = symbols;
+4
View File
@@ -461,11 +461,15 @@ namespace CryptoExchange.Net
if (typeof(ISpotOrderSocketClient).IsAssignableFrom(typeof(T))) if (typeof(ISpotOrderSocketClient).IsAssignableFrom(typeof(T)))
services.AddTransient(x => (ISpotOrderSocketClient)client(x)!); services.AddTransient(x => (ISpotOrderSocketClient)client(x)!);
if (typeof(ISpotOrderManagementSocketClient).IsAssignableFrom(typeof(T)))
services.AddTransient(x => (ISpotOrderManagementSocketClient)client(x)!);
if (typeof(IFuturesOrderSocketClient).IsAssignableFrom(typeof(T))) if (typeof(IFuturesOrderSocketClient).IsAssignableFrom(typeof(T)))
services.AddTransient(x => (IFuturesOrderSocketClient)client(x)!); services.AddTransient(x => (IFuturesOrderSocketClient)client(x)!);
if (typeof(IPositionSocketClient).IsAssignableFrom(typeof(T))) if (typeof(IPositionSocketClient).IsAssignableFrom(typeof(T)))
services.AddTransient(x => (IPositionSocketClient)client(x)!); services.AddTransient(x => (IPositionSocketClient)client(x)!);
if (typeof(IFuturesOrderManagementSocketClient).IsAssignableFrom(typeof(T)))
services.AddTransient(x => (IFuturesOrderManagementSocketClient)client(x)!);
return services; return services;
} }
@@ -24,8 +24,9 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="interval">Kline interval</param> /// <param name="interval">Kline interval</param>
/// <param name="limit">The max amount of klines to retain</param> /// <param name="limit">The max amount of klines to retain</param>
/// <param name="period">The max period the data should be retained</param> /// <param name="period">The max period the data should be retained</param>
/// <param name="exchangeParameters">Exchange parameters</param>
/// <returns></returns> /// <returns></returns>
IKlineTracker CreateKlineTracker(SharedSymbol symbol, SharedKlineInterval interval, int? limit = null, TimeSpan? period = null); IKlineTracker CreateKlineTracker(SharedSymbol symbol, SharedKlineInterval interval, int? limit = null, TimeSpan? period = null, ExchangeParameters? exchangeParameters = null);
/// <summary> /// <summary>
/// Whether the factory supports creating a TradeTracker instance for this symbol /// Whether the factory supports creating a TradeTracker instance for this symbol
@@ -39,7 +40,8 @@ namespace CryptoExchange.Net.Interfaces
/// <param name="symbol">The symbol</param> /// <param name="symbol">The symbol</param>
/// <param name="limit">The max amount of trades to retain</param> /// <param name="limit">The max amount of trades to retain</param>
/// <param name="period">The max period the data should be retained</param> /// <param name="period">The max period the data should be retained</param>
/// <param name="exchangeParameters">Exchange parameters</param>
/// <returns></returns> /// <returns></returns>
ITradeTracker CreateTradeTracker(SharedSymbol symbol, int? limit = null, TimeSpan? period = null); ITradeTracker CreateTradeTracker(SharedSymbol symbol, int? limit = null, TimeSpan? period = null, ExchangeParameters? exchangeParameters = null);
} }
} }
+118
View File
@@ -4,6 +4,8 @@ using CryptoExchange.Net.Objects.Options;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO.Pipelines;
using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
@@ -14,6 +16,61 @@ namespace CryptoExchange.Net
/// </summary> /// </summary>
public static class LibraryHelpers public static class LibraryHelpers
{ {
private static readonly HashSet<string> _stableCoins = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
// USD
"USDT", "USDC", "DAI", "FDUSD", "USDE", "TUSD", "USDP", "PYUSD", "GUSD",
"USDD", "LUSD", "USDJ", "SUSD", "ZUSD", "BUSD", "USTC", "USDX", "USDK",
"CUSD", "USD1", "USD0", "XUSD", "BFUSD", "USDS", "RLUSD", "OUSD", "USDH",
"APXUSD", "USDQ", "USDPT", "FIDD", "AUSD",
// EUR
"EURS", "EURC", "EURI", "EURT", "AGEUR", "CEUR", "AEUR", "EURQ", "EUROP",
// Other
"CNYT", // CNY
"CREAL", "BRL1", // BRL
"XSGD", // SGD
"GYEN", // JPY
"KGST", // KGS
"QCAD", // CAD
"TGBP", // GBP
"AUDX", // AUD
"MXNB", // MXN
};
private static readonly HashSet<string> _commodities = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
// Metals
"XAU", "XAUT", "XAG", "XPT", "XPD", "COPPER", "PAXG", "XNI", "XCU", "XAL", "GOLD", "SILVER",
// Energy
"BZ", "NATGAS", "NGAS", "CL", "XTI", "UKOIL", "USOIL", "BRENTOIL"
};
private static readonly HashSet<string> _stocks = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
// Top stocks, will need to update periodically
"AAAU", "AADR", "AAPL", "ACWI", "ACWX", "AGG", "AMD", "AMLP", "AMZN", "ARKF",
"ARKG", "ARKK", "ARKQ", "ARKW", "AVGO", "BA", "BABA", "BND", "BNDX", "BOTZ",
"CIBR", "COIN", "DIA", "DIVB", "DVY", "EEM", "EFA", "EFAV", "ESGU", "EWG",
"EWJ", "EWT", "EWU", "EWW", "EWY", "EWZ", "FDN", "FEZ", "GLDM", "GOOGL",
"HDV", "HOOD", "HYG", "IAU", "IBB", "ICLN", "IEFA", "IEMG", "IGSB", "IJH",
"IJR", "INTC", "ITOT", "IUSB", "IUSG", "IUSV", "IWM", "IWO", "IWR", "IYR",
"JETS", "JPM", "LIT", "MCHI", "META", "MGK", "MSTR", "MTUM", "MU", "NET",
"NFLX", "NOBL", "NVDA", "OIH", "ORCL", "PAVE", "PBW", "PLTR", "QQQ", "QQQM",
"SCHB", "SCHD", "SCHF", "SCHG", "SCHH", "SCHV", "SCHX", "SKHY", "SPCX", "SPCXD",
"SPLG", "SPY", "SPYG", "SPYV", "SQQQ", "TSLA", "TSM", "TQQQ", "USMV", "VBR",
"VCIT", "VCSH", "VEA", "VEU", "VGIT", "VGK", "VGT", "VHT", "VIG", "VNQ",
"VOO", "VOT", "VTI", "VTV", "VUG", "VXUS", "XBI", "XLC", "XLE", "XLF",
"XLI", "XLK", "XLP", "XLU", "XLV", "XLY", "CSCO", "UBER", "MRVL", "RKLB",
"COHR", "SOXL", "HD", "DIS", "CBRS", "V", "BRKB", "FLNC", "LLY", "COST",
"ARM", "BMNR", "NBIS", "ASML", "AAOI", "GLW", "SHLD", "BE", "QNTX", "IBM",
"AMAT", "NOK", "ASTS", "BBX", "SLX", "SKHYNIX", "SAMSUNG", "HYUNDAI", "NVO",
"IREN", "ONDS", "CRM" , "VRT", "ZEST", "BTW", "HPE", "AXTI", "BX", "CRWD",
"CRDO", "NOW", "ZM", "DKNG", "RIVN", "URNM", "EBAY", "ADBE", "UVXY", "RDW",
"CIEN","PANW", "WIN", "PAYP", "HIMS", "CRWV", "QCOM", "LITE", "DRAM", "ANTHROPIC",
"OPENAI", "USAR", "BILL", "SNDK", "NASDAQ100", "SPX500", "BSB", "CRCL", "STRC",
"MSFT", "WDC"
};
private static ILogger? _staticLogger; private static ILogger? _staticLogger;
/// <summary> /// <summary>
/// Static logger /// Static logger
@@ -105,6 +162,67 @@ namespace CryptoExchange.Net
return _defaultClientReferences.TryGetValue(key, out var id) ? id : throw new KeyNotFoundException($"{exchange} not found in configuration"); return _defaultClientReferences.TryGetValue(key, out var id) ? id : throw new KeyNotFoundException($"{exchange} not found in configuration");
} }
/// <summary>
/// Check whether an asset is a known stablecoin. Note that this is not definitive, only large known stocks are checked
/// </summary>
/// <param name="asset">Asset name</param>
/// <param name="additionalStableCoins">Additional stablecoin names for the specific exchange</param>
public static bool IsStableCoin(string asset, params HashSet<string> additionalStableCoins)
{
if (string.IsNullOrEmpty(asset))
return false;
return _stableCoins.Contains(asset) || (additionalStableCoins != null && additionalStableCoins.Contains(asset, StringComparer.OrdinalIgnoreCase));
}
/// <summary>
/// Check whether an asset is a known commodity. Note that this is not definitive, only large known stocks are checked
/// </summary>
/// <param name="asset">Asset name</param>
/// <param name="additionalCommodities">Additional commodity names for the specific exchange</param>
public static bool IsCommodity(string asset, params HashSet<string> additionalCommodities)
{
if (string.IsNullOrEmpty(asset))
return false;
return _commodities.Contains(asset) || (additionalCommodities != null && additionalCommodities.Contains(asset, StringComparer.OrdinalIgnoreCase));
}
/// <summary>
/// Check whether an asset is a known stock. Note that this is not definitive, only large known stocks are checked
/// </summary>
/// <param name="asset">Asset name</param>
/// <param name="additionalStocks">Additional stock names for the specific exchange</param>
public static bool IsEquity(string asset, params HashSet<string> additionalStocks)
=> IsEquity(asset, [], additionalStocks);
/// <summary>
/// Check whether an asset is a known stock.
/// </summary>
/// <param name="asset">Asset name</param>
/// <param name="potentialSuffixes">Suffixes to check, for example when `X` is a potential suffix both `TSLA` and `TSLAX` will be checked</param>
/// <param name="additionalStocks">Additional stock names for the specific exchange</param>
public static bool IsEquity(string asset, string[] potentialSuffixes, params HashSet<string> additionalStocks)
{
if (string.IsNullOrEmpty(asset))
return false;
if (_stocks.Contains(asset) || (additionalStocks != null && additionalStocks.Contains(asset, StringComparer.OrdinalIgnoreCase)))
return true;
foreach (var suffix in potentialSuffixes)
{
if (!asset.EndsWith(suffix))
continue;
var suffixAsset = asset.Substring(0, asset.Length - suffix.Length);
if (_stocks.Contains(suffixAsset) || (additionalStocks != null && additionalStocks.Contains(suffixAsset, StringComparer.OrdinalIgnoreCase)))
return true;
}
return false;
}
/// <summary> /// <summary>
/// Create a new HttpMessageHandler instance /// Create a new HttpMessageHandler instance
/// </summary> /// </summary>
@@ -180,7 +180,7 @@ namespace CryptoExchange.Net.Logging.Extensions
_receivedMessageNotMatchedToAnyListener = LoggerMessage.Define<int, string, string, string>( _receivedMessageNotMatchedToAnyListener = LoggerMessage.Define<int, string, string, string>(
LogLevel.Warning, LogLevel.Warning,
new EventId(2029, "ReceivedMessageNotMatchedToAnyListener"), new EventId(2029, "ReceivedMessageNotMatchedToAnyListener"),
"[Sckt {SocketId}] received message not matched to any listener. TypeIdentifier: {TypeIdentifier}, ListenId: {ListenId}, current listeners: [{ListenIds}]"); "[Sckt {SocketId}] received message not matched to any listener. TypeIdentifier: {TypeIdentifier}, TopicFilter: {ListenId}, registered TopicFilters for type: [{TopicFilters}]");
_failedToParse = LoggerMessage.Define<int, string>( _failedToParse = LoggerMessage.Define<int, string>(
LogLevel.Warning, LogLevel.Warning,
@@ -326,9 +326,9 @@ namespace CryptoExchange.Net.Logging.Extensions
_sendingData(logger, socketId, requestId, data, null); _sendingData(logger, socketId, requestId, data, null);
} }
public static void ReceivedMessageNotMatchedToAnyListener(this ILogger logger, int socketId, string typeIdentifier, string listenId, string listenIds) public static void ReceivedMessageNotMatchedToAnyListener(this ILogger logger, int socketId, string typeIdentifier, string topicFilter, string topicFilters)
{ {
_receivedMessageNotMatchedToAnyListener(logger, socketId, typeIdentifier, listenId, listenIds, null); _receivedMessageNotMatchedToAnyListener(logger, socketId, typeIdentifier, topicFilter, topicFilters, null);
} }
public static void SendingByteData(this ILogger logger, int socketId, int requestId, int length) public static void SendingByteData(this ILogger logger, int socketId, int requestId, int length)
+1 -1
View File
@@ -233,7 +233,7 @@ namespace CryptoExchange.Net.Objects
/// Add key as comma separated values /// Add key as comma separated values
/// </summary> /// </summary>
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
public void AddCommaSeparated<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] T>(string key, IEnumerable<T> values) public void AddCommaSeparated<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] T>(string key, IEnumerable<T>? values)
#else #else
public void AddCommaSeparated<T>(string key, IEnumerable<T>? values) public void AddCommaSeparated<T>(string key, IEnumerable<T>? values)
#endif #endif
@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Text; using System.Text;
@@ -8,8 +9,11 @@ namespace CryptoExchange.Net.Objects;
/// <summary> /// <summary>
/// Call result /// Call result
/// </summary> /// </summary>
[DebuggerDisplay("{DebugView,nq}")]
public record CallResult : ICallResult public record CallResult : ICallResult
{ {
private string DebugView => Success ? "Success" : $"Error: {Error}";
private static CallResult _successResult = new CallResult(); private static CallResult _successResult = new CallResult();
/// <inheritdoc /> /// <inheritdoc />
@@ -1,6 +1,7 @@
using CryptoExchange.Net.SharedApis; using CryptoExchange.Net.SharedApis;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
@@ -12,8 +13,11 @@ namespace CryptoExchange.Net.Objects;
/// <summary> /// <summary>
/// HTTP call result /// HTTP call result
/// </summary> /// </summary>
[DebuggerDisplay("{DebugView,nq}")]
public record HttpResult : IHttpResult public record HttpResult : IHttpResult
{ {
private string DebugView => $"[Req {RequestId}] " + (Success ? "Success" : $"Error: {Error}");
/// <summary> /// <summary>
/// Create a new success HTTP result /// Create a new success HTTP result
/// </summary> /// </summary>
@@ -251,8 +255,32 @@ public record HttpResult : IHttpResult
/// <inheritdoc /> /// <inheritdoc />
[DebuggerDisplay("{DebugView,nq}")]
public record HttpResult<T> : HttpResult, IHttpResult<T> public record HttpResult<T> : HttpResult, IHttpResult<T>
{ {
private string DebugView
{
get
{
var result = new StringBuilder($"[Req {RequestId}] " + (Success ? "Success" : $"Error: {Error}"));
if (Data != null)
{
result.Append(", ");
var typeName = typeof(T).Name;
if (Data is Array ar)
{
result.Append($"{ar.Length} {typeName.Substring(0, typeName.Length - 2)}");
}
else
{
result.Append(typeName);
}
}
return result.ToString();
}
}
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Text; using System.Text;
@@ -8,8 +9,11 @@ namespace CryptoExchange.Net.Objects;
/// <summary> /// <summary>
/// WebSocket call result /// WebSocket call result
/// </summary> /// </summary>
[DebuggerDisplay("{DebugView,nq}")]
public record WebSocketResult : IWebSocketResult public record WebSocketResult : IWebSocketResult
{ {
private string DebugView => $"[Sckt {ConnectionId}] " + (RequestId == null ? "" : $"[Req {RequestId}] ") + (Success ? "Success" : $"Error: {Error}");
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -183,7 +187,7 @@ public record WebSocketResult<T> : WebSocketResult, IWebSocketResult<T>
} }
/// <inheritdoc /> /// <inheritdoc />
public record QueryResult : WebSocketResult public record QueryResult : WebSocketResult, IQueryResult
{ {
/// <summary> /// <summary>
/// ctor /// ctor
@@ -208,6 +212,8 @@ public record QueryResult : WebSocketResult
Url = result.Url, Url = result.Url,
RequestId = result.RequestId, RequestId = result.RequestId,
ResponseTime = result.ResponseTime, ResponseTime = result.ResponseTime,
OriginalData = result.OriginalData,
RequestBody = result.RequestBody
}; };
/// <summary> /// <summary>
@@ -288,6 +294,9 @@ public record QueryResult : WebSocketResult
/// <inheritdoc /> /// <inheritdoc />
public string? RequestBody { get; init; } public string? RequestBody { get; init; }
/// <inheritdoc />
public string? OriginalData { get; init; }
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -314,7 +323,4 @@ public record QueryResult<T> : QueryResult, IQueryResult<T>
public new bool Success => Error == null; public new bool Success => Error == null;
/// <inheritdoc /> /// <inheritdoc />
public T? Data { get; set; } public T? Data { get; set; }
/// <inheritdoc />
public string? OriginalData { get; init; }
} }
@@ -0,0 +1,209 @@
using CryptoExchange.Net.Sockets;
using CryptoExchange.Net.Sockets.Default;
using CryptoExchange.Net.Sockets.Default.Routing;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Objects.Sockets
{
/// <summary>
/// Controller for an update subscription which isn't backed by a websocket connection. Can be used for testing.
/// </summary>
public class ManualUpdateSubscription
{
private readonly Func<Task> _closeAsync;
private readonly Func<Task> _reconnectAsync;
private readonly Func<Task<CallResult>> _resubscribeAsync;
private readonly ManualSubscription _manualSubscription;
private int _closedEventInvoked;
/// <summary>
/// The update subscription
/// </summary>
public UpdateSubscription Subscription { get; }
/// <summary>
/// The virtual socket id
/// </summary>
public int SocketId { get; }
/// <summary>
/// The last timestamp anything was received by the subscription
/// </summary>
public DateTime? LastReceiveTime { get; private set; }
/// <summary>
/// The current virtual websocket status
/// </summary>
public SocketStatus SocketStatus { get; private set; }
/// <summary>
/// Create a manually controlled update subscription
/// </summary>
/// <param name="socketId">The virtual socket id</param>
/// <param name="closeAsync">Callback when the subscription is closed</param>
/// <param name="reconnectAsync">Callback when a reconnect is requested</param>
/// <param name="resubscribeAsync">Callback when a resubscribe is requested</param>
public ManualUpdateSubscription(
int socketId = 0,
Func<Task>? closeAsync = null,
Func<Task>? reconnectAsync = null,
Func<Task<CallResult>>? resubscribeAsync = null)
{
SocketId = socketId;
SocketStatus = SocketStatus.Connected;
_closeAsync = closeAsync ?? (() => Task.CompletedTask);
_reconnectAsync = reconnectAsync ?? (() => Task.CompletedTask);
_resubscribeAsync = resubscribeAsync ?? (() => Task.FromResult(CallResult.Ok()));
_manualSubscription = new ManualSubscription();
_manualSubscription.Status = SubscriptionStatus.Subscribed;
Subscription = new UpdateSubscription(this, _manualSubscription);
}
/// <summary>
/// Set the last timestamp anything was received by the subscription
/// </summary>
/// <param name="timestamp">The receive timestamp</param>
public void SetLastReceiveTime(DateTime? timestamp)
{
LastReceiveTime = timestamp;
}
/// <summary>
/// Set the virtual websocket status
/// </summary>
/// <param name="status">The status</param>
public void SetSocketStatus(SocketStatus status)
{
SocketStatus = status;
}
/// <summary>
/// Set the subscription status
/// </summary>
/// <param name="status">The status</param>
public void SetSubscriptionStatus(SubscriptionStatus status)
{
_manualSubscription.Status = status;
}
/// <summary>
/// Invoke the connection lost event
/// </summary>
public void InvokeConnectionLost()
{
Subscription.HandleConnectionLostEvent();
}
/// <summary>
/// Invoke the connection restored event
/// </summary>
/// <param name="disconnectedPeriod">The period the connection was disconnected</param>
public void InvokeConnectionRestored(TimeSpan disconnectedPeriod)
{
Subscription.HandleConnectionRestoredEvent(disconnectedPeriod);
}
/// <summary>
/// Invoke the connection closed event
/// </summary>
public void InvokeConnectionClosed()
{
if (Interlocked.Exchange(ref _closedEventInvoked, 1) != 0)
return;
SocketStatus = SocketStatus.Closed;
_manualSubscription.Status = SubscriptionStatus.Closed;
Subscription.HandleConnectionClosedEvent();
}
/// <summary>
/// Invoke the resubscribing failed event
/// </summary>
/// <param name="error">The resubscribe error</param>
public void InvokeResubscribingFailed(Error error)
{
if (error == null)
throw new ArgumentNullException(nameof(error));
Subscription.HandleResubscribeFailedEvent(error);
}
/// <summary>
/// Invoke the activity paused event
/// </summary>
public void InvokeActivityPaused()
{
Subscription.HandlePausedEvent();
}
/// <summary>
/// Invoke the activity unpaused event
/// </summary>
public void InvokeActivityUnpaused()
{
Subscription.HandleUnpausedEvent();
}
/// <summary>
/// Invoke the exception event
/// </summary>
/// <param name="exception">The exception</param>
public void InvokeException(Exception exception)
{
if (exception == null)
throw new ArgumentNullException(nameof(exception));
_manualSubscription.InvokeExceptionHandler(exception);
}
internal async Task CloseAsync()
{
if (_manualSubscription.Status == SubscriptionStatus.Closed
|| _manualSubscription.Status == SubscriptionStatus.Closing)
return;
_manualSubscription.Status = SubscriptionStatus.Closing;
try
{
await _closeAsync().ConfigureAwait(false);
}
finally
{
_manualSubscription.Status = SubscriptionStatus.Closed;
}
}
internal Task ReconnectAsync()
{
return _reconnectAsync();
}
internal Task<CallResult> ResubscribeAsync()
{
return _resubscribeAsync();
}
private class ManualSubscription : Subscription
{
public ManualSubscription()
: base(NullLogger.Instance, false)
{
MessageRouter = MessageRouter.Create();
}
protected override Query? GetSubQuery(SocketConnection connection)
{
return null;
}
protected override Query? GetUnsubQuery(SocketConnection connection)
{
return null;
}
}
}
}
@@ -12,7 +12,8 @@ namespace CryptoExchange.Net.Objects.Sockets
/// </summary> /// </summary>
public class UpdateSubscription public class UpdateSubscription
{ {
private readonly SocketConnection _connection; private readonly SocketConnection? _connection;
private readonly ManualUpdateSubscription? _manualSubscription;
internal readonly Subscription _subscription; internal readonly Subscription _subscription;
#if NET9_0_OR_GREATER #if NET9_0_OR_GREATER
@@ -102,7 +103,7 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <summary> /// <summary>
/// The id of the socket /// The id of the socket
/// </summary> /// </summary>
public int SocketId => _connection.SocketId; public int SocketId => _connection?.SocketId ?? _manualSubscription!.SocketId;
/// <summary> /// <summary>
/// The id of the subscription /// The id of the subscription
@@ -112,12 +113,12 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <summary> /// <summary>
/// The last timestamp anything was received from the server /// The last timestamp anything was received from the server
/// </summary> /// </summary>
public DateTime? LastReceiveTime => _connection.LastReceiveTime; public DateTime? LastReceiveTime => _connection?.LastReceiveTime ?? _manualSubscription!.LastReceiveTime;
/// <summary> /// <summary>
/// The current websocket status /// The current websocket status
/// </summary> /// </summary>
public SocketStatus SocketStatus => _connection.Status; public SocketStatus SocketStatus => _connection?.Status ?? _manualSubscription!.SocketStatus;
/// <summary> /// <summary>
/// The current subscription status /// The current subscription status
@@ -143,6 +144,18 @@ namespace CryptoExchange.Net.Objects.Sockets
_subscription.StatusChanged += (x) => SubscriptionStatusChanged?.Invoke(x); _subscription.StatusChanged += (x) => SubscriptionStatusChanged?.Invoke(x);
} }
/// <summary>
/// ctor
/// </summary>
/// <param name="manualSubscription">The manual subscription for controlling events and data</param>
/// <param name="subscription">The subscription</param>
internal UpdateSubscription(ManualUpdateSubscription manualSubscription, Subscription subscription)
{
_manualSubscription = manualSubscription;
_subscription = subscription;
_subscription.StatusChanged += (x) => SubscriptionStatusChanged?.Invoke(x);
}
private void UnsubscribeConnectionEvents() private void UnsubscribeConnectionEvents()
{ {
lock (_eventLock) lock (_eventLock)
@@ -150,22 +163,26 @@ namespace CryptoExchange.Net.Objects.Sockets
if (!_connectionEventsSubscribed) if (!_connectionEventsSubscribed)
return; return;
if (_connection != null)
{
_connection.ConnectionClosed -= HandleConnectionClosedEvent; _connection.ConnectionClosed -= HandleConnectionClosedEvent;
_connection.ConnectionLost -= HandleConnectionLostEvent; _connection.ConnectionLost -= HandleConnectionLostEvent;
_connection.ConnectionRestored -= HandleConnectionRestoredEvent; _connection.ConnectionRestored -= HandleConnectionRestoredEvent;
_connection.ResubscribingFailed -= HandleResubscribeFailedEvent; _connection.ResubscribingFailed -= HandleResubscribeFailedEvent;
_connection.ActivityPaused -= HandlePausedEvent; _connection.ActivityPaused -= HandlePausedEvent;
_connection.ActivityUnpaused -= HandleUnpausedEvent; _connection.ActivityUnpaused -= HandleUnpausedEvent;
}
_connectionEventsSubscribed = false; _connectionEventsSubscribed = false;
} }
} }
private void HandleConnectionClosedEvent() internal void HandleConnectionClosedEvent()
{ {
UnsubscribeConnectionEvents(); UnsubscribeConnectionEvents();
// If we're not the subscription closing this connection don't bother emitting // If we're not the subscription closing this connection don't bother emitting
if (!_subscription.IsClosingConnection) if (_connection != null && !_subscription.IsClosingConnection)
return; return;
List<Action> handlers; List<Action> handlers;
@@ -176,7 +193,7 @@ namespace CryptoExchange.Net.Objects.Sockets
callback(); callback();
} }
private void HandleConnectionLostEvent() internal void HandleConnectionLostEvent()
{ {
if (!_subscription.Active) if (!_subscription.Active)
{ {
@@ -192,7 +209,7 @@ namespace CryptoExchange.Net.Objects.Sockets
callback(); callback();
} }
private void HandleConnectionRestoredEvent(TimeSpan period) internal void HandleConnectionRestoredEvent(TimeSpan period)
{ {
if (!_subscription.Active) if (!_subscription.Active)
{ {
@@ -208,7 +225,7 @@ namespace CryptoExchange.Net.Objects.Sockets
callback(period); callback(period);
} }
private void HandleResubscribeFailedEvent(Error error) internal void HandleResubscribeFailedEvent(Error error)
{ {
if (!_subscription.Active) if (!_subscription.Active)
{ {
@@ -224,7 +241,7 @@ namespace CryptoExchange.Net.Objects.Sockets
callback(error); callback(error);
} }
private void HandlePausedEvent() internal void HandlePausedEvent()
{ {
if (!_subscription.Active) if (!_subscription.Active)
{ {
@@ -240,7 +257,7 @@ namespace CryptoExchange.Net.Objects.Sockets
callback(); callback();
} }
private void HandleUnpausedEvent() internal void HandleUnpausedEvent()
{ {
if (!_subscription.Active) if (!_subscription.Active)
{ {
@@ -262,7 +279,10 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <returns></returns> /// <returns></returns>
public Task CloseAsync() public Task CloseAsync()
{ {
if (_connection != null)
return _connection.CloseAsync(_subscription); return _connection.CloseAsync(_subscription);
return _manualSubscription!.CloseAsync();
} }
/// <summary> /// <summary>
@@ -271,7 +291,10 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <returns></returns> /// <returns></returns>
public Task ReconnectAsync() public Task ReconnectAsync()
{ {
if (_connection != null)
return _connection.TriggerReconnectAsync(); return _connection.TriggerReconnectAsync();
return _manualSubscription!.ReconnectAsync();
} }
/// <summary> /// <summary>
@@ -279,8 +302,14 @@ namespace CryptoExchange.Net.Objects.Sockets
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
internal async Task UnsubscribeAsync() internal async Task UnsubscribeAsync()
{
if (_connection != null)
{ {
await _connection.UnsubscribeAsync(_subscription).ConfigureAwait(false); await _connection.UnsubscribeAsync(_subscription).ConfigureAwait(false);
return;
}
await _manualSubscription!.CloseAsync().ConfigureAwait(false);
} }
/// <summary> /// <summary>
@@ -289,7 +318,10 @@ namespace CryptoExchange.Net.Objects.Sockets
/// <returns></returns> /// <returns></returns>
internal async Task<CallResult> ResubscribeAsync() internal async Task<CallResult> ResubscribeAsync()
{ {
if (_connection != null)
return await _connection.ResubscribeAsync(_subscription).ConfigureAwait(false); return await _connection.ResubscribeAsync(_subscription).ConfigureAwait(false);
return await _manualSubscription!.ResubscribeAsync().ConfigureAwait(false);
} }
} }
} }
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Asset type
/// </summary>
public enum SharedAssetType
{
/// <summary>
/// Unknown or unspecified asset type
/// </summary>
Unspecified,
/// <summary>
/// Cryptocurrency asset type
/// </summary>
Crypto,
/// <summary>
/// Fiat currency asset type
/// </summary>
Fiat,
/// <summary>
/// Traditional finance asset type
/// </summary>
TradFi
}
/// <summary>
/// Asset sub type
/// </summary>
public enum SharedAssetSubType
{
// --- Crypto sub types ---
/// <summary>
/// Stable coin, can be for different fiat currencies
/// </summary>
StableCoin,
// --- TradFi sub types ---
/// <summary>
/// Equity, can be stocks, ETFs, or indices
/// </summary>
Equity,
/// <summary>
/// Commodity, can be oil, gas, metals, etc.
/// </summary>
Commodity
}
}
@@ -9,6 +9,11 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public interface IFuturesSymbolRestClient : ISharedClient public interface IFuturesSymbolRestClient : ISharedClient
{ {
/// <summary>
/// Get the futures symbol catalog. Only available if <see cref="GetFuturesSymbolsAsync(GetSymbolsRequest, CancellationToken)"/> has been called previously.
/// </summary>
SharedSymbolCatalog? FuturesSymbolCatalog { get; }
/// <summary> /// <summary>
/// Futures symbol request options.<br /> /// Futures symbol request options.<br />
/// Use <see cref="EndpointOptions.RequiredExchangeParameters"/> and <see cref="EndpointOptions.OptionalExchangeParameters"/> to check for required and optional parameters for the request. <br /> /// Use <see cref="EndpointOptions.RequiredExchangeParameters"/> and <see cref="EndpointOptions.OptionalExchangeParameters"/> to check for required and optional parameters for the request. <br />
@@ -44,7 +44,6 @@ namespace CryptoExchange.Net.SharedApis
PlaceSpotOrderOptions PlaceSpotOrderOptions { get; } PlaceSpotOrderOptions PlaceSpotOrderOptions { get; }
/// <summary> /// <summary>
/// Place a new spot order, see <see cref="PlaceSpotOrderOptions"/> for request options and exchange specific required/optional parameters. <br /> /// Place a new spot order, see <see cref="PlaceSpotOrderOptions"/> for request options and exchange specific required/optional parameters. <br />
/// The result is paginated, if there are more results to be retrieved, the `NextPageRequest` property of the result will contain the pagination request to be used for the next request to continue pagination.
/// </summary> /// </summary>
/// <param name="request">Request info</param> /// <param name="request">Request info</param>
/// <param name="ct">Cancellation token</param> /// <param name="ct">Cancellation token</param>
@@ -9,6 +9,11 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public interface ISpotSymbolRestClient : ISharedClient public interface ISpotSymbolRestClient : ISharedClient
{ {
/// <summary>
/// Get the spot symbol catalog. Only available if <see cref="GetSpotSymbolsAsync(GetSymbolsRequest, CancellationToken)"/> has been called previously.
/// </summary>
SharedSymbolCatalog? SpotSymbolCatalog { get; }
/// <summary> /// <summary>
/// Spot symbols request options.<br /> /// Spot symbols request options.<br />
/// Use <see cref="EndpointOptions.RequiredExchangeParameters"/> and <see cref="EndpointOptions.OptionalExchangeParameters"/> to check for required and optional parameters for the request. <br /> /// Use <see cref="EndpointOptions.RequiredExchangeParameters"/> and <see cref="EndpointOptions.OptionalExchangeParameters"/> to check for required and optional parameters for the request. <br />
@@ -0,0 +1,66 @@
using CryptoExchange.Net.Objects;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Client for placing and managing futures orders
/// </summary>
public interface IFuturesOrderManagementSocketClient : ISharedClient
{
/// <summary>
/// How the trading fee is deducted
/// </summary>
SharedFeeDeductionType FuturesFeeDeductionType { get; }
/// <summary>
/// How the asset is determined in which the trading fee is paid
/// </summary>
SharedFeeAssetType FuturesFeeAssetType { get; }
/// <summary>
/// Supported order types for futures orders
/// </summary>
SharedOrderType[] FuturesSupportedOrderTypes { get; }
/// <summary>
/// Supported time in force types for futures orders
/// </summary>
SharedTimeInForce[] FuturesSupportedTimeInForce { get; }
/// <summary>
/// Supported quantity types for futures orders
/// </summary>
SharedQuantitySupport FuturesSupportedOrderQuantity { get; }
/// <summary>
/// Generate a new random client order id
/// </summary>
/// <returns></returns>
string GenerateClientOrderId();
/// <summary>
/// Futures place order request options.<br />
/// Use <see cref="EndpointOptions.RequiredExchangeParameters"/> and <see cref="EndpointOptions.OptionalExchangeParameters"/> to check for required and optional parameters for the request. <br />
/// Exchange specific parameters can be added to the request via the `ExchangeParameters` property of the request object.
/// </summary>
PlaceFuturesOrderSocketOptions PlaceFuturesOrderOptions { get; }
/// <summary>
/// Place a new futures order, see <see cref="PlaceFuturesOrderOptions"/> for request options and exchange specific required/optional parameters. <br />
/// </summary>
/// <param name="request">Request info</param>
/// <param name="ct">Cancellation token</param>
Task<QueryResult<SharedId>> PlaceFuturesOrderAsync(PlaceFuturesOrderRequest request, CancellationToken ct = default);
/// <summary>
/// Futures cancel order request options.<br />
/// Use <see cref="EndpointOptions.RequiredExchangeParameters"/> and <see cref="EndpointOptions.OptionalExchangeParameters"/> to check for required and optional parameters for the request. <br />
/// Exchange specific parameters can be added to the request via the `ExchangeParameters` property of the request object.
/// </summary>
CancelFuturesOrderSocketOptions CancelFuturesOrderOptions { get; }
/// <summary>
/// Cancel a futures order, see <see cref="CancelFuturesOrderOptions"/> for request options and exchange specific required/optional parameters. <br />
/// </summary>
/// <param name="request">Request info</param>
/// <param name="ct">Cancellation token</param>
Task<QueryResult<SharedId>> CancelFuturesOrderAsync(CancelOrderRequest request, CancellationToken ct = default);
}
}
@@ -0,0 +1,66 @@
using CryptoExchange.Net.Objects;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Client for placing and managing spot orders
/// </summary>
public interface ISpotOrderManagementSocketClient : ISharedClient
{
/// <summary>
/// How the trading fee is deducted
/// </summary>
SharedFeeDeductionType SpotFeeDeductionType { get; }
/// <summary>
/// How the asset is determined in which the trading fee is paid
/// </summary>
SharedFeeAssetType SpotFeeAssetType { get; }
/// <summary>
/// Supported order types for spot orders
/// </summary>
SharedOrderType[] SpotSupportedOrderTypes { get; }
/// <summary>
/// Supported time in force types for placing spot orders
/// </summary>
SharedTimeInForce[] SpotSupportedTimeInForce { get; }
/// <summary>
/// Supported quantity types for placing spot orders
/// </summary>
SharedQuantitySupport SpotSupportedOrderQuantity { get; }
/// <summary>
/// Generate a new random client order id
/// </summary>
/// <returns></returns>
string GenerateClientOrderId();
/// <summary>
/// Spot place order request options.<br />
/// Use <see cref="EndpointOptions.RequiredExchangeParameters"/> and <see cref="EndpointOptions.OptionalExchangeParameters"/> to check for required and optional parameters for the request. <br />
/// Exchange specific parameters can be added to the request via the `ExchangeParameters` property of the request object.
/// </summary>
PlaceSpotOrderSocketOptions PlaceSpotOrderOptions { get; }
/// <summary>
/// Place a new spot order, see <see cref="PlaceSpotOrderOptions"/> for request options and exchange specific required/optional parameters. <br />
/// </summary>
/// <param name="request">Request info</param>
/// <param name="ct">Cancellation token</param>
Task<QueryResult<SharedId>> PlaceSpotOrderAsync(PlaceSpotOrderRequest request, CancellationToken ct = default);
/// <summary>
/// Spot cancel order request options.<br />
/// Use <see cref="EndpointOptions.RequiredExchangeParameters"/> and <see cref="EndpointOptions.OptionalExchangeParameters"/> to check for required and optional parameters for the request. <br />
/// Exchange specific parameters can be added to the request via the `ExchangeParameters` property of the request object.
/// </summary>
CancelSpotOrderSocketOptions CancelSpotOrderOptions { get; }
/// <summary>
/// Cancel a spot order, see <see cref="CancelSpotOrderOptions"/> for request options and exchange specific required/optional parameters. <br />
/// </summary>
/// <param name="request">Request info</param>
/// <param name="ct">Cancellation token</param>
Task<QueryResult<SharedId>> CancelSpotOrderAsync(CancelOrderRequest request, CancellationToken ct = default);
}
}
@@ -5,6 +5,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class CancelFuturesOrderByClientOrderIdOptions : EndpointOptions<CancelOrderRequest, IFuturesOrderClientIdRestClient> public class CancelFuturesOrderByClientOrderIdOptions : EndpointOptions<CancelOrderRequest, IFuturesOrderClientIdRestClient>
{ {
/// <inheritdoc />
public override string Description => "Cancel a futures order by its client order id";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class CancelFuturesOrderOptions : EndpointOptions<CancelOrderRequest, IFuturesOrderRestClient> public class CancelFuturesOrderOptions : EndpointOptions<CancelOrderRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Cancel a futures order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Options for canceling a futures order
/// </summary>
public class CancelFuturesOrderSocketOptions : EndpointOptions<CancelOrderRequest, IFuturesOrderManagementSocketClient>
{
/// <inheritdoc />
public override string Description => "Cancel a futures order over a socket connection";
/// <summary>
/// ctor
/// </summary>
public CancelFuturesOrderSocketOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(IFuturesOrderManagementSocketClient.CancelFuturesOrderAsync))
{
}
}
}
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class CancelFuturesTpSlOptions : EndpointOptions<CancelTpSlRequest, IFuturesTpSlRestClient> public class CancelFuturesTpSlOptions : EndpointOptions<CancelTpSlRequest, IFuturesTpSlRestClient>
{ {
/// <inheritdoc />
public override string Description => "Cancel a take profit or stop loss order for a futures position";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class CancelFuturesTriggerOrderOptions : EndpointOptions<CancelOrderRequest, IFuturesTriggerOrderRestClient> public class CancelFuturesTriggerOrderOptions : EndpointOptions<CancelOrderRequest, IFuturesTriggerOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Cancel a futures trigger order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class CancelSpotOrderByClientOrderIdOptions : EndpointOptions<CancelOrderRequest, ISpotOrderClientIdRestClient> public class CancelSpotOrderByClientOrderIdOptions : EndpointOptions<CancelOrderRequest, ISpotOrderClientIdRestClient>
{ {
/// <inheritdoc />
public override string Description => "Cancel a spot order by its client order id";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public CancelSpotOrderByClientOrderIdOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderClientIdRestClient.CancelSpotOrderByClientOrderIdAsync)) public CancelSpotOrderByClientOrderIdOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderClientIdRestClient.CancelSpotOrderByClientOrderIdAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(CancelOrderRequest request, ISpotOrderClientIdRestClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
return base.ValidateRequest(request, client);
}
} }
} }
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class CancelSpotOrderOptions : EndpointOptions<CancelOrderRequest, ISpotOrderRestClient> public class CancelSpotOrderOptions : EndpointOptions<CancelOrderRequest, ISpotOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Cancel a spot order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public CancelSpotOrderOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderRestClient.CancelSpotOrderAsync)) public CancelSpotOrderOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderRestClient.CancelSpotOrderAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(CancelOrderRequest request, ISpotOrderRestClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
return base.ValidateRequest(request, client);
}
} }
} }
@@ -0,0 +1,32 @@
using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
using System.Text;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Options for canceling a spot order
/// </summary>
public class CancelSpotOrderSocketOptions : EndpointOptions<CancelOrderRequest, ISpotOrderManagementSocketClient>
{
/// <inheritdoc />
public override string Description => "Cancel a spot order over a socket connection";
/// <summary>
/// ctor
/// </summary>
public CancelSpotOrderSocketOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderManagementSocketClient.CancelSpotOrderAsync))
{
}
/// <inheritdoc />
public override Error? ValidateRequest(CancelOrderRequest request, ISpotOrderManagementSocketClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
return base.ValidateRequest(request, client);
}
}
}
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class CancelSpotTriggerOrderOptions : EndpointOptions<CancelOrderRequest, ISpotTriggerOrderRestClient> public class CancelSpotTriggerOrderOptions : EndpointOptions<CancelOrderRequest, ISpotTriggerOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Cancel a spot trigger order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public CancelSpotTriggerOrderOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotTriggerOrderRestClient.CancelSpotTriggerOrderAsync)) public CancelSpotTriggerOrderOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotTriggerOrderRestClient.CancelSpotTriggerOrderAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(CancelOrderRequest request, ISpotTriggerOrderRestClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
return base.ValidateRequest(request, client);
}
} }
} }
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class ClosePositionOptions : EndpointOptions<ClosePositionRequest, IFuturesOrderRestClient> public class ClosePositionOptions : EndpointOptions<ClosePositionRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Close an open futures position";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -41,6 +41,10 @@ namespace CryptoExchange.Net.SharedApis
/// Whether the call is supported. If false the exchange API does not support this operation. /// Whether the call is supported. If false the exchange API does not support this operation.
/// </summary> /// </summary>
public bool Supported { get; set; } = true; public bool Supported { get; set; } = true;
/// <summary>
/// Description of the endpoint
/// </summary>
public abstract string Description { get; }
/// <summary> /// <summary>
/// ctor /// ctor
@@ -70,8 +74,13 @@ namespace CryptoExchange.Net.SharedApis
foreach (var param in RequiredExchangeParameters) foreach (var param in RequiredExchangeParameters)
{ {
if (param.Names!.All(x => ExchangeParameters.HasValue(exchangeParameters, Exchange, x, param.ValueType) != true)) if (param.Names!.All(x => ExchangeParameters.HasValue(exchangeParameters, Exchange, x, param.ValueType) != true))
{
if (param.Names.Length == 1)
return ArgumentError.Invalid(string.Join("/", param.Names!), $"Exchange parameter `{param.Names[0]}` for exchange `{Exchange}` should be provided. Example: {param.ExampleValue}");
else
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 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; return null;
} }
@@ -82,7 +91,7 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
/// <typeparam name="TRequest">Type of data</typeparam> /// <typeparam name="TRequest">Type of data</typeparam>
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
public class EndpointOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] TRequest> : EndpointOptions public abstract class EndpointOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] TRequest> : EndpointOptions
where TRequest : SharedRequest where TRequest : SharedRequest
#else #else
public abstract class EndpointOptions<TRequest> : EndpointOptions public abstract class EndpointOptions<TRequest> : EndpointOptions
@@ -149,8 +158,13 @@ namespace CryptoExchange.Net.SharedApis
foreach (var param in RequiredOptionalParameters) foreach (var param in RequiredOptionalParameters)
{ {
if (param.Names!.All(x => _requestProperties.Single(p => p.Name == x).GetValue(request, null) == null)) if (param.Names!.All(x => _requestProperties.Single(p => p.Name == x).GetValue(request, null) == null))
{
if (param.Names.Length == 1)
return ArgumentError.Invalid(string.Join("/", param.Names!), $"Optional parameter `{param.Names[0]}` for exchange `{Exchange}` should be provided. Example: {param.ExampleValue}");
else
return ArgumentError.Invalid(string.Join("/", param.Names!), $"One of optional parameters `{string.Join(", ", param.Names!)}` for exchange `{Exchange}` should be provided. Example: {param.ExampleValue}"); 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 (request is SharedSymbolRequest symbolsRequest)
{ {
@@ -171,32 +185,40 @@ namespace CryptoExchange.Net.SharedApis
/// <inheritdoc /> /// <inheritdoc />
public override string ToString() public override string ToString()
{ {
if (!Supported)
return $"{Exchange} {EndpointName} NOT SUPPORTED";
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.AppendLine($"{Exchange} {EndpointName}"); sb.AppendLine($"{EndpointName}");
sb.AppendLine($"Needs authentication: {NeedsAuthentication}"); if (!Supported)
{
sb.AppendLine(" NOT SUPPORTED");
return sb.ToString();
}
sb.AppendLine($"{Description}");
if (!string.IsNullOrEmpty(RequestNotes)) if (!string.IsNullOrEmpty(RequestNotes))
{
sb.Append(" Notes: ");
sb.AppendLine(RequestNotes); sb.AppendLine(RequestNotes);
}
if (RequiredOptionalParameters.Any()) if (RequiredOptionalParameters.Any())
{ {
sb.AppendLine($"Required optional parameters:"); sb.AppendLine($" Required optional parameters:");
foreach(var param in RequiredOptionalParameters) foreach(var param in RequiredOptionalParameters)
sb.AppendLine($" {param}"); sb.AppendLine($" {param}");
} }
if (RequiredExchangeParameters.Any()) if (RequiredExchangeParameters.Any())
{ {
sb.AppendLine($"Required exchange specific parameters:"); sb.AppendLine($" Required exchange specific parameters:");
foreach (var param in RequiredExchangeParameters) foreach (var param in RequiredExchangeParameters)
sb.AppendLine($" {param}"); sb.AppendLine($" {param}");
} }
if (OptionalExchangeParameters.Any()) if (OptionalExchangeParameters.Any())
{ {
sb.AppendLine($"Optional exchange specific parameters:"); sb.AppendLine($" Optional exchange specific parameters:");
foreach (var param in OptionalExchangeParameters) foreach (var param in OptionalExchangeParameters)
sb.AppendLine($" {param}"); sb.AppendLine($" {param}");
} }
sb.Append(" Needs authentication: ");
sb.AppendLine($"{NeedsAuthentication}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetAssetOptions : EndpointOptions<GetAssetRequest, IAssetsRestClient> public class GetAssetOptions : EndpointOptions<GetAssetRequest, IAssetsRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve basic info for a single asset and networks it supports for withdrawals/deposits";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetAssetsOptions : EndpointOptions<GetAssetsRequest, IAssetsRestClient> public class GetAssetsOptions : EndpointOptions<GetAssetsRequest, IAssetsRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve basic info for all assets and the networks they support for withdrawals/deposits";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System.Linq; using System.Linq;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
@@ -8,6 +8,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetBalancesOptions : EndpointOptions<GetBalancesRequest, IBalanceRestClient> public class GetBalancesOptions : EndpointOptions<GetBalancesRequest, IBalanceRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve account balances";
/// <summary> /// <summary>
/// Supported account types /// Supported account types
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetBookTickerOptions : EndpointOptions<GetBookTickerRequest, IBookTickerRestClient> public class GetBookTickerOptions : EndpointOptions<GetBookTickerRequest, IBookTickerRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve the best bid and ask price for a symbol";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetDepositAddressesOptions : EndpointOptions<GetDepositAddressesRequest, IDepositRestClient> public class GetDepositAddressesOptions : EndpointOptions<GetDepositAddressesRequest, IDepositRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve deposit addresses for an asset";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetDepositsOptions : PaginatedEndpointOptions<GetDepositsRequest, IDepositRestClient> public class GetDepositsOptions : PaginatedEndpointOptions<GetDepositsRequest, IDepositRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve deposit history";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFeeOptions : EndpointOptions<GetFeeRequest, IFeeRestClient> public class GetFeeOptions : EndpointOptions<GetFeeRequest, IFeeRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve trading fee information";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFundingRateHistoryOptions : PaginatedEndpointOptions<GetFundingRateHistoryRequest, IFundingRateRestClient> public class GetFundingRateHistoryOptions : PaginatedEndpointOptions<GetFundingRateHistoryRequest, IFundingRateRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve historical funding rates for a futures symbol";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesClosedOrdersOptions : PaginatedEndpointOptions<GetClosedOrdersRequest, IFuturesOrderRestClient> public class GetFuturesClosedOrdersOptions : PaginatedEndpointOptions<GetClosedOrdersRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve closed futures orders";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesOrderByClientOrderIdOptions : EndpointOptions<GetOrderRequest, IFuturesOrderClientIdRestClient> public class GetFuturesOrderByClientOrderIdOptions : EndpointOptions<GetOrderRequest, IFuturesOrderClientIdRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve a futures order by its client order id";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesOrderOptions : EndpointOptions<GetOrderRequest, IFuturesOrderRestClient> public class GetFuturesOrderOptions : EndpointOptions<GetOrderRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve a futures order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesOrderTradesOptions : EndpointOptions<GetOrderTradesRequest, IFuturesOrderRestClient> public class GetFuturesOrderTradesOptions : EndpointOptions<GetOrderTradesRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve trades for a futures order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,52 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesSymbolsOptions : EndpointOptions<GetSymbolsRequest, IFuturesSymbolRestClient> public class GetFuturesSymbolsOptions : EndpointOptions<GetSymbolsRequest, IFuturesSymbolRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve supported futures symbols and their trading rules";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public GetFuturesSymbolsOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(IFuturesSymbolRestClient.GetFuturesSymbolsAsync)) public GetFuturesSymbolsOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(IFuturesSymbolRestClient.GetFuturesSymbolsAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(GetSymbolsRequest request, IFuturesSymbolRestClient client)
{
if (request.BaseAssetType != null && request.BaseAssetSubType != null)
{
var error = ValidateAssetTypeCombination(request.BaseAssetType.Value, request.BaseAssetSubType.Value);
if (error != null)
return error;
}
if (request.QuoteAssetType != null && request.QuoteAssetSubType != null)
{
var error = ValidateAssetTypeCombination(request.QuoteAssetType.Value, request.QuoteAssetSubType.Value);
if (error != null)
return error;
}
return base.ValidateRequest(request, client);
}
private Error? ValidateAssetTypeCombination(SharedAssetType type, SharedAssetSubType subType)
{
if (type == SharedAssetType.Crypto
&& (subType == SharedAssetSubType.Commodity
|| (subType == SharedAssetSubType.Equity)))
{
return ArgumentError.Invalid(nameof(GetSymbolsRequest.BaseAssetSubType), $"Invalid combination of asset type filters: {type} and {subType}");
}
if (type == SharedAssetType.TradFi && subType == SharedAssetSubType.StableCoin)
return ArgumentError.Invalid(nameof(GetSymbolsRequest.BaseAssetSubType), $"Invalid combination of asset type filters: {type} and {subType}");
if (type == SharedAssetType.Fiat)
return ArgumentError.Invalid(nameof(GetSymbolsRequest.BaseAssetSubType), $"Invalid combination of asset type filters: {type} and {subType}");
return null;
}
} }
} }
@@ -1,4 +1,4 @@
using System.Text; using System.Text;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesTickerOptions : EndpointOptions<GetTickerRequest, IFuturesTickerRestClient> public class GetFuturesTickerOptions : EndpointOptions<GetTickerRequest, IFuturesTickerRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve price ticker information for a futures symbol";
/// <summary> /// <summary>
/// Type of ticker calculation /// Type of ticker calculation
/// </summary> /// </summary>
@@ -24,7 +27,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Ticker data calculation type: {TickerType}"); sb.AppendLine($" Ticker data calculation type: {TickerType}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using System.Text; using System.Text;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesTickersOptions : EndpointOptions<GetTickersRequest, IFuturesTickerRestClient> public class GetFuturesTickersOptions : EndpointOptions<GetTickersRequest, IFuturesTickerRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve price ticker information for all futures symbols";
/// <summary> /// <summary>
/// Type of ticker calculation /// Type of ticker calculation
/// </summary> /// </summary>
@@ -24,7 +27,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Ticker data calculation type: {TickerType}"); sb.AppendLine($" Ticker data calculation type: {TickerType}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesTriggerOrderOptions : EndpointOptions<GetOrderRequest, IFuturesTriggerOrderRestClient> public class GetFuturesTriggerOrderOptions : EndpointOptions<GetOrderRequest, IFuturesTriggerOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve a futures trigger order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetFuturesUserTradesOptions : PaginatedEndpointOptions<GetUserTradesRequest, IFuturesOrderRestClient> public class GetFuturesUserTradesOptions : PaginatedEndpointOptions<GetUserTradesRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve futures user trade history";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -10,6 +10,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetIndexPriceKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IIndexPriceKlineRestClient> public class GetIndexPriceKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IIndexPriceKlineRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve index price candlestick data";
/// <summary> /// <summary>
/// The supported kline intervals /// The supported kline intervals
/// </summary> /// </summary>
@@ -108,9 +111,9 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Supported SharedKlineInterval values: {string.Join(", ", SupportIntervals)}"); sb.AppendLine($" Supported intervals: {string.Join(", ", SupportIntervals)}");
if (MaxTotalDataPoints != null) if (MaxTotalDataPoints != null)
sb.AppendLine($"Max total data points available: {MaxTotalDataPoints}"); sb.AppendLine($" Max total data points available: {MaxTotalDataPoints}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -10,6 +10,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IKlineRestClient> public class GetKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IKlineRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve candlestick data for a symbol";
/// <summary> /// <summary>
/// The supported kline intervals /// The supported kline intervals
/// </summary> /// </summary>
@@ -108,9 +111,9 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Supported SharedKlineInterval values: {string.Join(", ", SupportIntervals)}"); sb.AppendLine($" Supported intervals: {string.Join(", ", SupportIntervals)}");
if (MaxTotalDataPoints != null) if (MaxTotalDataPoints != null)
sb.AppendLine($"Max total data points available: {MaxTotalDataPoints}"); sb.AppendLine($" Max total data points available: {MaxTotalDataPoints}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetLeverageOptions : EndpointOptions<GetLeverageRequest, ILeverageRestClient> public class GetLeverageOptions : EndpointOptions<GetLeverageRequest, ILeverageRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve the current leverage for a futures symbol";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -10,6 +10,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetMarkPriceKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IMarkPriceKlineRestClient> public class GetMarkPriceKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IMarkPriceKlineRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve mark price candlestick data";
/// <summary> /// <summary>
/// The supported kline intervals /// The supported kline intervals
/// </summary> /// </summary>
@@ -108,9 +111,9 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Supported SharedKlineInterval values: {string.Join(", ", SupportIntervals)}"); sb.AppendLine($" Supported intervals: {string.Join(", ", SupportIntervals)}");
if (MaxTotalDataPoints != null) if (MaxTotalDataPoints != null)
sb.AppendLine($"Max total data points available: {MaxTotalDataPoints}"); sb.AppendLine($" Max total data points available: {MaxTotalDataPoints}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetOpenFuturesOrdersOptions : EndpointOptions<GetOpenOrdersRequest, IFuturesOrderRestClient> public class GetOpenFuturesOrdersOptions : EndpointOptions<GetOpenOrdersRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve open futures orders";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetOpenInterestOptions : EndpointOptions<GetOpenInterestRequest, IOpenInterestRestClient> public class GetOpenInterestOptions : EndpointOptions<GetOpenInterestRequest, IOpenInterestRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve open interest for a futures symbol";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetOpenSpotOrdersOptions : EndpointOptions<GetOpenOrdersRequest, ISpotOrderRestClient> public class GetOpenSpotOrdersOptions : EndpointOptions<GetOpenOrdersRequest, ISpotOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve open spot orders";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -10,6 +10,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetOrderBookOptions : EndpointOptions<GetOrderBookRequest, IOrderBookRestClient> public class GetOrderBookOptions : EndpointOptions<GetOrderBookRequest, IOrderBookRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve the current order book for a symbol";
/// <summary> /// <summary>
/// Supported order book depths /// Supported order book depths
/// </summary> /// </summary>
@@ -65,7 +68,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Supported limit values: [{(SupportedLimits != null ? string.Join(", ", SupportedLimits) : $"{MinLimit}..{MaxLimit}")}]"); sb.AppendLine($" Supported limit values: [{(SupportedLimits != null ? string.Join(", ", SupportedLimits) : $"{MinLimit}..{MaxLimit}")}]");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetPositionHistoryOptions : PaginatedEndpointOptions<GetPositionHistoryRequest, IPositionHistoryRestClient> public class GetPositionHistoryOptions : PaginatedEndpointOptions<GetPositionHistoryRequest, IPositionHistoryRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve historical futures positions";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,10 +1,13 @@
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
/// <summary> /// <summary>
/// Options for requesting current position mode /// Options for requesting current position mode
/// </summary> /// </summary>
public class GetPositionModeOptions : EndpointOptions<GetPositionModeRequest, IPositionModeRestClient> public class GetPositionModeOptions : EndpointOptions<GetPositionModeRequest, IPositionModeRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve the current futures position mode";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetPositionsOptions : EndpointOptions<GetPositionsRequest, IFuturesOrderRestClient> public class GetPositionsOptions : EndpointOptions<GetPositionsRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve open futures positions";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System.Text; using System.Text;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
@@ -8,6 +8,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetRecentTradesOptions : EndpointOptions<GetRecentTradesRequest, IRecentTradeRestClient> public class GetRecentTradesOptions : EndpointOptions<GetRecentTradesRequest, IRecentTradeRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve recent public trades for a symbol";
/// <summary> /// <summary>
/// The max number of trades that can be requested /// The max number of trades that can be requested
/// </summary> /// </summary>
@@ -39,7 +42,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Max data points: {MaxLimit}"); sb.AppendLine($" Max data points: {MaxLimit}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotClosedOrdersOptions : PaginatedEndpointOptions<GetClosedOrdersRequest, ISpotOrderRestClient> public class GetSpotClosedOrdersOptions : PaginatedEndpointOptions<GetClosedOrdersRequest, ISpotOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve closed spot orders";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -20,6 +23,9 @@ namespace CryptoExchange.Net.SharedApis
/// <inheritdoc /> /// <inheritdoc />
public override Error? ValidateRequest(GetClosedOrdersRequest request, ISpotOrderRestClient client) public override Error? ValidateRequest(GetClosedOrdersRequest request, ISpotOrderRestClient client)
{ {
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
if (!SupportsAscending && request.Direction == DataDirection.Ascending) if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetClosedOrdersRequest.Direction), $"Ascending direction is not supported"); return ArgumentError.Invalid(nameof(GetClosedOrdersRequest.Direction), $"Ascending direction is not supported");
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotOrderByClientOrderIdOptions : EndpointOptions<GetOrderRequest, ISpotOrderClientIdRestClient> public class GetSpotOrderByClientOrderIdOptions : EndpointOptions<GetOrderRequest, ISpotOrderClientIdRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve a spot order by its client order id";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public GetSpotOrderByClientOrderIdOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderClientIdRestClient.GetSpotOrderByClientOrderIdAsync)) public GetSpotOrderByClientOrderIdOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderClientIdRestClient.GetSpotOrderByClientOrderIdAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(GetOrderRequest request, ISpotOrderClientIdRestClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
return base.ValidateRequest(request, client);
}
} }
} }
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotOrderOptions : EndpointOptions<GetOrderRequest, ISpotOrderRestClient> public class GetSpotOrderOptions : EndpointOptions<GetOrderRequest, ISpotOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve a spot order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public GetSpotOrderOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderRestClient.GetSpotOrderAsync)) public GetSpotOrderOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderRestClient.GetSpotOrderAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(GetOrderRequest request, ISpotOrderRestClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
return base.ValidateRequest(request, client);
}
} }
} }
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotOrderTradesOptions : EndpointOptions<GetOrderTradesRequest, ISpotOrderRestClient> public class GetSpotOrderTradesOptions : EndpointOptions<GetOrderTradesRequest, ISpotOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve trades for a spot order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public GetSpotOrderTradesOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderRestClient.GetSpotOrderTradesAsync)) public GetSpotOrderTradesOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotOrderRestClient.GetSpotOrderTradesAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(GetOrderTradesRequest request, ISpotOrderRestClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
return base.ValidateRequest(request, client);
}
} }
} }
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,53 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotSymbolsOptions : EndpointOptions<GetSymbolsRequest, ISpotSymbolRestClient> public class GetSpotSymbolsOptions : EndpointOptions<GetSymbolsRequest, ISpotSymbolRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve supported spot symbols and their trading rules";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public GetSpotSymbolsOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotSymbolRestClient.GetSpotSymbolsAsync)) public GetSpotSymbolsOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotSymbolRestClient.GetSpotSymbolsAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(GetSymbolsRequest request, ISpotSymbolRestClient client)
{
if (request.BaseAssetType != null && request.BaseAssetSubType != null)
{
var error = ValidateAssetTypeCombination(request.BaseAssetType.Value, request.BaseAssetSubType.Value);
if (error != null)
return error;
}
if (request.QuoteAssetType != null && request.QuoteAssetSubType != null)
{
var error = ValidateAssetTypeCombination(request.QuoteAssetType.Value, request.QuoteAssetSubType.Value);
if (error != null)
return error;
}
return base.ValidateRequest(request, client);
}
private Error? ValidateAssetTypeCombination(SharedAssetType type, SharedAssetSubType subType)
{
if (type == SharedAssetType.Crypto
&& (subType == SharedAssetSubType.Commodity
|| (subType == SharedAssetSubType.Equity)))
{
return ArgumentError.Invalid(nameof(GetSymbolsRequest.BaseAssetSubType), $"Invalid combination of asset type filters: {type} and {subType}");
}
if (type == SharedAssetType.TradFi && subType == SharedAssetSubType.StableCoin)
return ArgumentError.Invalid(nameof(GetSymbolsRequest.BaseAssetSubType), $"Invalid combination of asset type filters: {type} and {subType}");
if (type == SharedAssetType.Fiat)
return ArgumentError.Invalid(nameof(GetSymbolsRequest.BaseAssetSubType), $"Invalid combination of asset type filters: {type} and {subType}");
return null;
}
} }
} }
@@ -1,4 +1,4 @@
using System.Text; using System.Text;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotTickerOptions : EndpointOptions<GetTickerRequest, ISpotTickerRestClient> public class GetSpotTickerOptions : EndpointOptions<GetTickerRequest, ISpotTickerRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve price ticker information for a spot symbol";
/// <summary> /// <summary>
/// Type of ticker calculation /// Type of ticker calculation
/// </summary> /// </summary>
@@ -24,7 +27,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Ticker data calculation type: {TickerType}"); sb.AppendLine($" Ticker data calculation type: {TickerType}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using System.Text; using System.Text;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotTickersOptions : EndpointOptions<GetTickersRequest, ISpotTickerRestClient> public class GetSpotTickersOptions : EndpointOptions<GetTickersRequest, ISpotTickerRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve price ticker information for all spot symbols";
/// <summary> /// <summary>
/// Type of ticker calculation /// Type of ticker calculation
/// </summary> /// </summary>
@@ -24,7 +27,7 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Ticker data calculation type: {TickerType}"); sb.AppendLine($" Ticker data calculation type: {TickerType}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,5 @@
using System; using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotTriggerOrderOptions : EndpointOptions<GetOrderRequest, ISpotTriggerOrderRestClient> public class GetSpotTriggerOrderOptions : EndpointOptions<GetOrderRequest, ISpotTriggerOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve a spot trigger order";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public GetSpotTriggerOrderOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotTriggerOrderRestClient.GetSpotTriggerOrderAsync)) public GetSpotTriggerOrderOptions(string exchange, bool authenticated) : base(exchange, authenticated, nameof(ISpotTriggerOrderRestClient.GetSpotTriggerOrderAsync))
{ {
} }
/// <inheritdoc />
public override Error? ValidateRequest(GetOrderRequest request, ISpotTriggerOrderRestClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
return base.ValidateRequest(request, client);
}
} }
} }
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetSpotUserTradesOptions : PaginatedEndpointOptions<GetUserTradesRequest, ISpotOrderRestClient> public class GetSpotUserTradesOptions : PaginatedEndpointOptions<GetUserTradesRequest, ISpotOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve spot user trade history";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -20,6 +23,9 @@ namespace CryptoExchange.Net.SharedApis
/// <inheritdoc /> /// <inheritdoc />
public override Error? ValidateRequest(GetUserTradesRequest request, ISpotOrderRestClient client) public override Error? ValidateRequest(GetUserTradesRequest request, ISpotOrderRestClient client)
{ {
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
if (!SupportsAscending && request.Direction == DataDirection.Ascending) if (!SupportsAscending && request.Direction == DataDirection.Ascending)
return ArgumentError.Invalid(nameof(GetUserTradesRequest.Direction), $"Ascending direction is not supported"); return ArgumentError.Invalid(nameof(GetUserTradesRequest.Direction), $"Ascending direction is not supported");
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetTradeHistoryOptions : PaginatedEndpointOptions<GetTradeHistoryRequest, ITradeHistoryRestClient> public class GetTradeHistoryOptions : PaginatedEndpointOptions<GetTradeHistoryRequest, ITradeHistoryRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve public trade history for a symbol";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class GetWithdrawalsOptions : PaginatedEndpointOptions<GetWithdrawalsRequest, IWithdrawalRestClient> public class GetWithdrawalsOptions : PaginatedEndpointOptions<GetWithdrawalsRequest, IWithdrawalRestClient>
{ {
/// <inheritdoc />
public override string Description => "Retrieve withdrawal history";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using System; using System;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Text; using System.Text;
@@ -8,7 +8,7 @@ namespace CryptoExchange.Net.SharedApis
/// Options for paginated endpoints /// Options for paginated endpoints
/// </summary> /// </summary>
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
public class PaginatedEndpointOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] TRequest, TClient> : EndpointOptions<TRequest, TClient> public abstract class PaginatedEndpointOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] TRequest, TClient> : EndpointOptions<TRequest, TClient>
where TRequest : SharedRequest where TRequest : SharedRequest
where TClient : ISharedClient where TClient : ISharedClient
#else #else
@@ -63,12 +63,12 @@ namespace CryptoExchange.Net.SharedApis
public override string ToString() public override string ToString()
{ {
var sb = new StringBuilder(base.ToString()); var sb = new StringBuilder(base.ToString());
sb.AppendLine($"Ascending retrieval supported: {SupportsAscending}"); sb.AppendLine($" Ascending retrieval supported: {SupportsAscending}");
sb.AppendLine($"Descending retrieval supported: {SupportsDescending}"); sb.AppendLine($" Descending retrieval supported: {SupportsDescending}");
sb.AppendLine($"Time period filter supported: {TimePeriodFilterSupport}"); sb.AppendLine($" Time period filter supported: {TimePeriodFilterSupport}");
sb.AppendLine($"Max limit: {MaxLimit}"); sb.AppendLine($" Max limit: {MaxLimit}");
if (MaxAge.HasValue) if (MaxAge.HasValue)
sb.AppendLine($"Max age: {MaxAge}"); sb.AppendLine($" Max age: {MaxAge}");
return sb.ToString(); return sb.ToString();
} }
} }
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class PlaceFuturesOrderOptions : EndpointOptions<PlaceFuturesOrderRequest, IFuturesOrderRestClient> public class PlaceFuturesOrderOptions : EndpointOptions<PlaceFuturesOrderRequest, IFuturesOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Place a new futures order";
/// <summary> /// <summary>
/// Whether or not the API supports setting take profit / stop loss with the order /// Whether or not the API supports setting take profit / stop loss with the order
/// </summary> /// </summary>
@@ -0,0 +1,56 @@
using CryptoExchange.Net.Objects;
using System;
using System.Linq;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Options for placing a new futures order
/// </summary>
public class PlaceFuturesOrderSocketOptions : EndpointOptions<PlaceFuturesOrderRequest, IFuturesOrderManagementSocketClient>
{
/// <inheritdoc />
public override string Description => "Place a new futures order over a socket connection";
/// <summary>
/// Whether or not the API supports setting take profit / stop loss with the order
/// </summary>
public bool SupportsTpSl { get; set; }
/// <summary>
/// ctor
/// </summary>
public PlaceFuturesOrderSocketOptions(string exchange, bool supportsTpSl) : base(exchange, true, nameof(IFuturesOrderManagementSocketClient.PlaceFuturesOrderAsync))
{
SupportsTpSl = supportsTpSl;
}
/// <summary>
/// Validate a request
/// </summary>
public override Error? ValidateRequest(
PlaceFuturesOrderRequest request,
IFuturesOrderManagementSocketClient client
)
{
if (!SupportsTpSl && (request.StopLossPrice != null || request.TakeProfitPrice != null))
return ArgumentError.Invalid(nameof(PlaceFuturesOrderRequest.StopLossPrice) + " / " + nameof(PlaceFuturesOrderRequest.TakeProfitPrice), "Tp/Sl parameters not supported");
if (request.OrderType == SharedOrderType.Other)
throw new ArgumentException("OrderType can't be `Other`", nameof(request.OrderType));
if (!client.FuturesSupportedOrderTypes.Contains(request.OrderType))
return ArgumentError.Invalid(nameof(PlaceFuturesOrderRequest.OrderType), "Order type not supported");
if (request.TimeInForce != null && !client.FuturesSupportedTimeInForce.Contains(request.TimeInForce.Value))
return ArgumentError.Invalid(nameof(PlaceFuturesOrderRequest.TimeInForce), "Order time in force not supported");
var quantityError = client.FuturesSupportedOrderQuantity.Validate(request.Side, request.OrderType, request.Quantity);
if (quantityError != null)
return quantityError;
return base.ValidateRequest(request, client);
}
}
}
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class PlaceFuturesTriggerOrderOptions : EndpointOptions<PlaceFuturesTriggerOrderRequest, IFuturesTriggerOrderRestClient> public class PlaceFuturesTriggerOrderOptions : EndpointOptions<PlaceFuturesTriggerOrderRequest, IFuturesTriggerOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Place a new futures trigger order";
/// <summary> /// <summary>
/// When true the API holds the funds until the order is triggered or canceled. When false the funds will only be required when the order is triggered and will fail if the funds are not available at that time. /// When true the API holds the funds until the order is triggered or canceled. When false the funds will only be required when the order is triggered and will fail if the funds are not available at that time.
/// </summary> /// </summary>
@@ -19,19 +22,5 @@ namespace CryptoExchange.Net.SharedApis
{ {
HoldsFunds = holdsFunds; HoldsFunds = holdsFunds;
} }
/// <summary>
/// Validate a request
/// </summary>
public override Error? ValidateRequest(
PlaceFuturesTriggerOrderRequest request,
IFuturesTriggerOrderRestClient client)
{
//var quantityError = client.FuturesSupportedOrderQuantity.Validate(request.OrderDirection, request.OrderPrice == null ? SharedOrderType.Market : SharedOrderType.Limit, request.Quantity);
//if (quantityError != null)
// return quantityError;
return base.ValidateRequest(request, client);
}
} }
} }
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class PlaceSpotOrderOptions : EndpointOptions<PlaceSpotOrderRequest, ISpotOrderRestClient> public class PlaceSpotOrderOptions : EndpointOptions<PlaceSpotOrderRequest, ISpotOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Place a new spot order";
/// <summary> /// <summary>
/// ctor /// ctor
@@ -24,6 +27,9 @@ namespace CryptoExchange.Net.SharedApis
PlaceSpotOrderRequest request, PlaceSpotOrderRequest request,
ISpotOrderRestClient client) ISpotOrderRestClient client)
{ {
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
if (request.OrderType == SharedOrderType.Other) if (request.OrderType == SharedOrderType.Other)
throw new ArgumentException("OrderType can't be `Other`", nameof(request.OrderType)); throw new ArgumentException("OrderType can't be `Other`", nameof(request.OrderType));
@@ -0,0 +1,49 @@
using CryptoExchange.Net.Objects;
using System;
using System.Linq;
namespace CryptoExchange.Net.SharedApis
{
/// <summary>
/// Options for placing a new spot order
/// </summary>
public class PlaceSpotOrderSocketOptions : EndpointOptions<PlaceSpotOrderRequest, ISpotOrderManagementSocketClient>
{
/// <inheritdoc />
public override string Description => "Place a new spot order over a socket connection";
/// <summary>
/// ctor
/// </summary>
public PlaceSpotOrderSocketOptions(string exchange) : base(exchange, true, nameof(ISpotOrderManagementSocketClient.PlaceSpotOrderAsync))
{
}
/// <summary>
/// Validate a request
/// </summary>
public override Error? ValidateRequest(
PlaceSpotOrderRequest request,
ISpotOrderManagementSocketClient client)
{
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
if (request.OrderType == SharedOrderType.Other)
throw new ArgumentException("OrderType can't be `Other`", nameof(request.OrderType));
if (!client.SpotSupportedOrderTypes.Contains(request.OrderType))
return ArgumentError.Invalid(nameof(PlaceSpotOrderRequest.OrderType), "Order type not supported");
if (request.TimeInForce != null && !client.SpotSupportedTimeInForce.Contains(request.TimeInForce.Value))
return ArgumentError.Invalid(nameof(PlaceSpotOrderRequest.TimeInForce), "Order time in force not supported");
var quantityError = client.SpotSupportedOrderQuantity.Validate(request.Side, request.OrderType, request.Quantity);
if (quantityError != null)
return quantityError;
return base.ValidateRequest(request, client);
}
}
}
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class PlaceSpotTriggerOrderOptions : EndpointOptions<PlaceSpotTriggerOrderRequest, ISpotOrderRestClient> public class PlaceSpotTriggerOrderOptions : EndpointOptions<PlaceSpotTriggerOrderRequest, ISpotOrderRestClient>
{ {
/// <inheritdoc />
public override string Description => "Place a new spot trigger order";
/// <summary> /// <summary>
/// When true the API holds the funds until the order is triggered or canceled. When false the funds will only be required when the order is triggered and will fail if the funds are not available at that time. /// When true the API holds the funds until the order is triggered or canceled. When false the funds will only be required when the order is triggered and will fail if the funds are not available at that time.
/// </summary> /// </summary>
@@ -27,6 +30,9 @@ namespace CryptoExchange.Net.SharedApis
PlaceSpotTriggerOrderRequest request, PlaceSpotTriggerOrderRequest request,
ISpotOrderRestClient client) ISpotOrderRestClient client)
{ {
if (request.Symbol!.TradingMode != TradingMode.Spot)
return ArgumentError.Invalid("TradingMode", $"TradingMode.{request.Symbol!.TradingMode} is not supported, should be Spot");
var quantityError = client.SpotSupportedOrderQuantity.Validate(request.OrderSide, request.OrderPrice == null ? SharedOrderType.Market : SharedOrderType.Limit, request.Quantity); var quantityError = client.SpotSupportedOrderQuantity.Validate(request.OrderSide, request.OrderPrice == null ? SharedOrderType.Market : SharedOrderType.Limit, request.Quantity);
if (quantityError != null) if (quantityError != null)
return quantityError; return quantityError;
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class SetFuturesTpSlOptions : EndpointOptions<SetTpSlRequest, IFuturesTpSlRestClient> public class SetFuturesTpSlOptions : EndpointOptions<SetTpSlRequest, IFuturesTpSlRestClient>
{ {
/// <inheritdoc />
public override string Description => "Set take profit or stop loss values for a futures position";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,10 +1,13 @@
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
/// <summary> /// <summary>
/// Options for setting leverage /// Options for setting leverage
/// </summary> /// </summary>
public class SetLeverageOptions : EndpointOptions<SetLeverageRequest, ILeverageRestClient> public class SetLeverageOptions : EndpointOptions<SetLeverageRequest, ILeverageRestClient>
{ {
/// <inheritdoc />
public override string Description => "Set the leverage for a futures symbol";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,10 +1,13 @@
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
/// <summary> /// <summary>
/// Options for setting position mode /// Options for setting position mode
/// </summary> /// </summary>
public class SetPositionModeOptions : EndpointOptions<SetPositionModeRequest, IPositionModeRestClient> public class SetPositionModeOptions : EndpointOptions<SetPositionModeRequest, IPositionModeRestClient>
{ {
/// <inheritdoc />
public override string Description => "Set the futures position mode";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,5 +1,6 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System.Linq; using System.Linq;
using System.Text;
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
@@ -8,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class TransferOptions : EndpointOptions<TransferRequest, ITransferRestClient> public class TransferOptions : EndpointOptions<TransferRequest, ITransferRestClient>
{ {
/// <inheritdoc />
public override string Description => "Transfer funds between account types";
/// <summary> /// <summary>
/// Supported account types /// Supported account types
/// </summary> /// </summary>
@@ -36,5 +40,13 @@ namespace CryptoExchange.Net.SharedApis
return base.ValidateRequest(request, client); return base.ValidateRequest(request, client);
} }
/// <inheritdoc />
public override string ToString()
{
var sb = new StringBuilder(base.ToString());
sb.AppendLine($" Supported accounts: {string.Join(", ", SupportedAccountTypes)}");
return sb.ToString();
}
} }
} }
@@ -1,10 +1,13 @@
namespace CryptoExchange.Net.SharedApis namespace CryptoExchange.Net.SharedApis
{ {
/// <summary> /// <summary>
/// Options for requesting a withdrawal /// Options for requesting a withdrawal
/// </summary> /// </summary>
public class WithdrawOptions : EndpointOptions<WithdrawRequest, IWithdrawRestClient> public class WithdrawOptions : EndpointOptions<WithdrawRequest, IWithdrawRestClient>
{ {
/// <inheritdoc />
public override string Description => "Withdraw an asset";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class SubscribeBalanceOptions : EndpointOptions<SubscribeBalancesRequest, IBalanceSocketClient> public class SubscribeBalanceOptions : EndpointOptions<SubscribeBalancesRequest, IBalanceSocketClient>
{ {
/// <inheritdoc />
public override string Description => "Subscribe to balance updates";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class SubscribeBookTickerOptions : EndpointOptions<SubscribeBookTickerRequest, IBookTickerSocketClient> public class SubscribeBookTickerOptions : EndpointOptions<SubscribeBookTickerRequest, IBookTickerSocketClient>
{ {
/// <inheritdoc />
public override string Description => "Subscribe to best bid and ask price updates";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class SubscribeFuturesOrderOptions : EndpointOptions<SubscribeFuturesOrderRequest, IFuturesOrderSocketClient> public class SubscribeFuturesOrderOptions : EndpointOptions<SubscribeFuturesOrderRequest, IFuturesOrderSocketClient>
{ {
/// <inheritdoc />
public override string Description => "Subscribe to futures order updates";
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class SubscribeKlineOptions : EndpointOptions<SubscribeKlineRequest, IKlineSocketClient> public class SubscribeKlineOptions : EndpointOptions<SubscribeKlineRequest, IKlineSocketClient>
{ {
/// <inheritdoc />
public override string Description => "Subscribe to candlestick updates for a symbol";
/// <summary> /// <summary>
/// Kline intervals supported for updates /// Kline intervals supported for updates
/// </summary> /// </summary>
@@ -1,4 +1,4 @@
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using System; using System;
using System.Linq; using System.Linq;
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
/// </summary> /// </summary>
public class SubscribeOrderBookOptions : EndpointOptions<SubscribeOrderBookRequest, IOrderBookSocketClient> public class SubscribeOrderBookOptions : EndpointOptions<SubscribeOrderBookRequest, IOrderBookSocketClient>
{ {
/// <inheritdoc />
public override string Description => "Subscribe to order book updates for a symbol";
/// <summary> /// <summary>
/// Order book depths supported for updates /// Order book depths supported for updates
/// </summary> /// </summary>

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