mirror of
https://github.com/JKorf/CryptoExchange.Net.git
synced 2026-10-04 18:33:39 +00:00
Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4a4930d658 | |||
| ca245959a2 | |||
| ff43d202d4 | |||
| d1947e643b | |||
| 6fec65cd6a | |||
| 053bcf6ecc | |||
| 6957ba44f5 | |||
| c1af97dd4a | |||
| ecfe3cf392 | |||
| ac1e9cf2ab | |||
| 4987e6be70 | |||
| 9100c0d7f3 | |||
| 5b1ae30e4b | |||
| 36a06e8a9a | |||
| e7eb559074 | |||
| 79e2efec70 | |||
| c8c6d14329 | |||
| b8bd30a09d | |||
| c2b58ab19a | |||
| 90a031c595 | |||
| 860d753ad6 | |||
| e16c91792c | |||
| a3d95da9fa | |||
| 907399b878 | |||
| 9eab0d967e | |||
| 0dee68e8ae | |||
| d838d3377f | |||
| 2141ad9061 | |||
| 9be8798ccf | |||
| 4803ed91cd | |||
| 20bddd5c37 | |||
| 0e75ddb3d0 | |||
| 0e5b46002c | |||
| 8f7c71f9ce | |||
| 73377fbb87 | |||
| 3a00d6371a | |||
| caf6d36bcd | |||
| e078a373da | |||
| 007743f5a1 | |||
| d06f891cee | |||
| 8dcbb687f5 | |||
| fcb36f7ee0 | |||
| 3cffd67518 | |||
| ecd00ea707 | |||
| 38a7b981ce | |||
| c41cc3c4c7 | |||
| 4accc8039b | |||
| 87c86ec0c0 | |||
| d9850da282 | |||
| c4a8b02054 | |||
| 34b7258496 | |||
| 69099922c9 | |||
| 64c1cd5fa8 | |||
| 936ac6640b | |||
| 68ad9ae114 | |||
| 6238c17471 | |||
| 52e6fbfe47 | |||
| 4129622d71 | |||
| 95e0aefb9f | |||
| dd1cefdc90 |
@@ -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.
|
||||
|
||||
## 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
|
||||
|
||||
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
|
||||
|
||||
- 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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
## 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
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -67,6 +67,32 @@ var btcusdtPerp = new SharedSymbol(TradingMode.PerpetualLinear, "BTC", "USDT");
|
||||
|
||||
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
|
||||
|
||||
**REST:**
|
||||
@@ -80,6 +106,7 @@ For exchanges that use exotic asset names, see the AssetAliases configuration.
|
||||
- `ITickerSocketClient`, `IBookTickerSocketClient`
|
||||
- `IOrderBookSocketClient`, `ITradeSocketClient`, `IKlineSocketClient`
|
||||
- `IUserTradeSocketClient`, `ISpotOrderSocketClient`, `IFuturesOrderSocketClient`, `IPositionSocketClient`, `IBalanceSocketClient`
|
||||
- Order commands: `ISpotOrderManagementSocketClient`, `IFuturesOrderManagementSocketClient`
|
||||
|
||||
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 waiters = new List<Task<bool>>();
|
||||
for(var i = 0; i < 10; i++)
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
waiters.Add(evnt.WaitAsync());
|
||||
}
|
||||
|
||||
List<bool>? results = null;
|
||||
var resultsWaiter = Task.Run(async () =>
|
||||
{
|
||||
await Task.WhenAll(waiters);
|
||||
results = waiters.Select(w => w.Result).ToList();
|
||||
});
|
||||
var remaining = waiters.ToList();
|
||||
|
||||
for(var i = 1; i <= 10; i++)
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
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(10 == results?.Count(r => r));
|
||||
Assert.That(remaining, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -138,6 +138,68 @@ namespace CryptoExchange.Net.UnitTests.ClientTests
|
||||
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()]
|
||||
public async Task ErrorResponse_ShouldNot_ConfirmSubscription()
|
||||
{
|
||||
|
||||
@@ -25,6 +25,17 @@ namespace CryptoExchange.Net.UnitTests.ConverterTests
|
||||
Assert.That(output!.Value == expected);
|
||||
}
|
||||
|
||||
[TestCase(1, true)]
|
||||
[TestCase(2, true)]
|
||||
[TestCase(0, false)]
|
||||
[TestCase(-1, false)]
|
||||
public void TestBoolConverterInts(int value, bool? expected)
|
||||
{
|
||||
var val = $"{value}";
|
||||
var output = JsonSerializer.Deserialize<STJBoolObject>($"{{ \"Value\": {val} }}", SerializerOptions.WithConverters(new TestSerializerContext()));
|
||||
Assert.That(output!.Value == expected);
|
||||
}
|
||||
|
||||
[TestCase("1", true)]
|
||||
[TestCase("true", true)]
|
||||
[TestCase("yes", true)]
|
||||
|
||||
@@ -15,6 +15,7 @@ namespace CryptoExchange.Net.UnitTests.ConverterTests
|
||||
[TestCase("1620777600000")]
|
||||
[TestCase("2021-05-12T00:00:00.000Z")]
|
||||
[TestCase("2021-05-12T00:00:00.000000000Z")]
|
||||
[TestCase("2021-05-12 00:00:00.000000+00:00:00")]
|
||||
[TestCase("0.000000", true)]
|
||||
[TestCase("0", true)]
|
||||
[TestCase("", true)]
|
||||
|
||||
@@ -36,9 +36,13 @@ namespace CryptoExchange.Net.UnitTests.Implementations
|
||||
protected override TestAuthenticationProvider CreateAuthenticationProvider(TestCredentials 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;
|
||||
}
|
||||
|
||||
#pragma warning disable CS0067 // The event is never used, but it's required by the interface
|
||||
public event Action? OnMessageRouterUpdated;
|
||||
|
||||
#pragma warning restore CS0067
|
||||
public bool Handle(string typeIdentifier, string? topicFilter, SocketConnection socketConnection, DateTime receiveTime, string? originalData, object result)
|
||||
{
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Sockets;
|
||||
using CryptoExchange.Net.Sockets.Default;
|
||||
using CryptoExchange.Net.Sockets.Default.Routing;
|
||||
using CryptoExchange.Net.UnitTests.Implementations;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
|
||||
namespace CryptoExchange.Net.UnitTests.SocketRoutingTests
|
||||
{
|
||||
[TestFixture]
|
||||
public class SubscriptionTests
|
||||
{
|
||||
[Test]
|
||||
public void Handle_Should_OnlyCompleteSubscriptionQuery_ForMatchingTopic()
|
||||
{
|
||||
// arrange
|
||||
var topicASubscription = new TopicSubscription("topic-a");
|
||||
var topicBSubscription = new TopicSubscription("topic-b");
|
||||
var topicAQuery = topicASubscription.CreateSubscriptionQuery(null!)!;
|
||||
var topicBQuery = topicBSubscription.CreateSubscriptionQuery(null!)!;
|
||||
|
||||
// act
|
||||
var topicAHandled = topicASubscription.Handle("type", "topic-a", null!, DateTime.UtcNow, "original", "data");
|
||||
var topicBHandled = topicBSubscription.Handle("type", "topic-a", null!, DateTime.UtcNow, "original", "data");
|
||||
|
||||
// assert
|
||||
Assert.That(topicAHandled, Is.True);
|
||||
Assert.That(topicBHandled, Is.False);
|
||||
Assert.That(topicAQuery.Completed, Is.True);
|
||||
Assert.That(topicAQuery.Success, Is.True);
|
||||
Assert.That(topicBQuery.Completed, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Handle_Should_CompleteSubscriptionQuery_BeforeInvokingMatchingHandler()
|
||||
{
|
||||
// arrange
|
||||
Query? query = null;
|
||||
var queryCompletedWhenHandlerInvoked = false;
|
||||
var subscription = new TopicSubscription("topic", () => queryCompletedWhenHandlerInvoked = query!.Completed);
|
||||
query = subscription.CreateSubscriptionQuery(null!)!;
|
||||
|
||||
// act
|
||||
subscription.Handle("type", "topic", null!, DateTime.UtcNow, "original", "data");
|
||||
|
||||
// assert
|
||||
Assert.That(queryCompletedWhenHandlerInvoked, Is.True);
|
||||
}
|
||||
|
||||
[TestCase(null)]
|
||||
[TestCase("topic")]
|
||||
public void Handle_Should_CompleteSubscriptionQuery_ForUnfilteredRoute(string? topicFilter)
|
||||
{
|
||||
// arrange
|
||||
var subscription = new TopicSubscription(topic: null);
|
||||
var query = subscription.CreateSubscriptionQuery(null!)!;
|
||||
|
||||
// act
|
||||
var handled = subscription.Handle("type", topicFilter, null!, DateTime.UtcNow, "original", "data");
|
||||
|
||||
// assert
|
||||
Assert.That(handled, Is.True);
|
||||
Assert.That(query.Completed, Is.True);
|
||||
Assert.That(query.Success, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Handle_Should_TreatEmptyTopicFilterAsUnfilteredRoute()
|
||||
{
|
||||
// arrange
|
||||
var subscription = new TopicSubscription(string.Empty);
|
||||
var query = subscription.CreateSubscriptionQuery(null!)!;
|
||||
|
||||
// act
|
||||
var handled = subscription.Handle("type", "topic", null!, DateTime.UtcNow, "original", "data");
|
||||
|
||||
// assert
|
||||
Assert.That(handled, Is.True);
|
||||
Assert.That(query.Completed, Is.True);
|
||||
Assert.That(query.Success, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Handle_Should_CompleteSubscriptionQuery_ForAnyMatchingTopic()
|
||||
{
|
||||
// arrange
|
||||
var subscription = new TopicSubscription(["topic-a", "topic-b"]);
|
||||
var query = subscription.CreateSubscriptionQuery(null!)!;
|
||||
|
||||
// act
|
||||
var handled = subscription.Handle("type", "topic-b", null!, DateTime.UtcNow, "original", "data");
|
||||
|
||||
// assert
|
||||
Assert.That(handled, Is.True);
|
||||
Assert.That(query.Completed, Is.True);
|
||||
Assert.That(query.Success, Is.True);
|
||||
}
|
||||
|
||||
private sealed class TopicSubscription : Subscription
|
||||
{
|
||||
public TopicSubscription(string? topic, Action? handler = null)
|
||||
: base(NullLogger.Instance, false)
|
||||
{
|
||||
MessageRouter = MessageRouter.CreateForEvent<string>("type", topic, (_, _, _, _) =>
|
||||
{
|
||||
handler?.Invoke();
|
||||
return CallResult.Ok();
|
||||
});
|
||||
}
|
||||
|
||||
public TopicSubscription(string[] topics)
|
||||
: base(NullLogger.Instance, false)
|
||||
{
|
||||
MessageRouter = MessageRouter.CreateForEvent<string>("type", topics, (_, _, _, _) => CallResult.Ok());
|
||||
}
|
||||
|
||||
protected override Query? GetSubQuery(SocketConnection connection)
|
||||
{
|
||||
return new TestQuery(new TestSocketMessage { Id = 1, Data = "Sub" }, false)
|
||||
{
|
||||
TimeoutBehavior = TimeoutBehavior.Succeed
|
||||
};
|
||||
}
|
||||
|
||||
protected override Query? GetUnsubQuery(SocketConnection connection) => null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -198,7 +198,7 @@ namespace CryptoExchange.Net.Clients
|
||||
string? cacheKey = null;
|
||||
if (ShouldCache(definition))
|
||||
{
|
||||
cacheKey = definition.FullUrl + definition + uriParameters?.ToFormData();
|
||||
cacheKey = GetCacheKey(definition, uriParameters);
|
||||
_logger.CheckingCache(cacheKey);
|
||||
var cachedValue = _cache.Get(cacheKey, ClientOptions.CachingMaxAge);
|
||||
if (cachedValue != null)
|
||||
@@ -800,6 +800,13 @@ namespace CryptoExchange.Net.Clients
|
||||
&& definition.Method == HttpMethod.Get
|
||||
&& !definition.PreventCaching;
|
||||
|
||||
/// <summary>
|
||||
/// Produce a unique cache key for the request based on the request definition and parameters.
|
||||
/// </summary>
|
||||
protected virtual string GetCacheKey(RequestDefinition definition, Parameters? parameters)
|
||||
{
|
||||
return definition.FullUrl + definition + parameters?.ToFormData();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public virtual void SetOptions(UpdateOptions options)
|
||||
@@ -889,6 +896,12 @@ namespace CryptoExchange.Net.Clients
|
||||
|
||||
ApiCredentials = (TApiCredentials?)options.ApiCredentials?.Copy() ?? ApiCredentials;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string GetCacheKey(RequestDefinition definition, Parameters? parameters)
|
||||
{
|
||||
return definition.FullUrl + definition + parameters?.ToFormData() + GetAuthenticationProvider()?.Key;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
@@ -97,6 +97,11 @@ namespace CryptoExchange.Net.Clients
|
||||
/// </summary>
|
||||
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 />
|
||||
public double IncomingKbps
|
||||
{
|
||||
@@ -625,6 +630,21 @@ namespace CryptoExchange.Net.Clients
|
||||
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>
|
||||
/// Gets a connection for a new subscription or query. Can be an existing if there are open position or a new one.
|
||||
/// </summary>
|
||||
@@ -643,10 +663,7 @@ namespace CryptoExchange.Net.Clients
|
||||
string? topic = null,
|
||||
int individualSubscriptionCount = 1)
|
||||
{
|
||||
var socketQuery = _socketConnections.Where(s => s.Value.ConnectionUriString.Equals(address.TrimEnd('/'), StringComparison.Ordinal)
|
||||
&& 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
|
||||
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
|
||||
|
||||
// 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;
|
||||
@@ -676,49 +693,32 @@ namespace CryptoExchange.Net.Clients
|
||||
_logger.WaitedForReconnectingSocket((long)(DateTime.UtcNow - delayStart).TotalMilliseconds);
|
||||
|
||||
socketQuery = socketQuery.Where(s => (s.Status == SocketStatus.None || s.Status == SocketStatus.Connected)
|
||||
&& (s.Authenticated == authenticated || !authenticated)
|
||||
&& (s.Authenticated == authenticated || !authenticated || UsePublicConnectionForAuth)
|
||||
&& s.Connected).ToList();
|
||||
|
||||
SocketConnection? connection;
|
||||
if (!dedicatedRequestConnection)
|
||||
{
|
||||
connection = socketQuery
|
||||
.Where(s => !s.DedicatedRequestConnection.IsDedicatedRequestConnection)
|
||||
.OrderBy(s => s.UserSubscriptionCount)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
else
|
||||
bool maxConnectionsReached = _socketConnections.Count >= (ApiOptions.MaxSocketConnections ?? ClientOptions.MaxSocketConnections);
|
||||
SocketConnection? connection = null;
|
||||
if (dedicatedRequestConnection)
|
||||
{
|
||||
connection = socketQuery.Where(s => s.DedicatedRequestConnection.IsDedicatedRequestConnection).FirstOrDefault();
|
||||
if (connection != null && !connection.DedicatedRequestConnection.Authenticated)
|
||||
// Mark dedicated request connection as authenticated if the request is authenticated
|
||||
connection.DedicatedRequestConnection.Authenticated = authenticated;
|
||||
|
||||
if (connection == null)
|
||||
// Fall back to an existing connection if there is no dedicated request connection available
|
||||
connection = socketQuery.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);
|
||||
|
||||
var currentCount = connection.Subscriptions.Sum(x => x.IndividualSubscriptionCount);
|
||||
if (currentCount + individualSubscriptionCount <= MaxIndividualSubscriptionsPerConnection)
|
||||
return CallResult.Ok(connection);
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
|
||||
if (connection != null)
|
||||
return CallResult.Ok(connection);
|
||||
|
||||
if (maxConnectionsReached)
|
||||
return CallResult.Fail<SocketConnection>(new InvalidOperationError("Max amount of socket connections reached"));
|
||||
|
||||
@@ -784,6 +784,23 @@ namespace CryptoExchange.Net.Clients
|
||||
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>
|
||||
/// Process an unhandled message
|
||||
/// </summary>
|
||||
|
||||
@@ -14,21 +14,19 @@ using System.Text;
|
||||
namespace CryptoExchange.Net.Clients
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public abstract class UserClientProvider<TRestClient, TSocketClient, TRestOptions, TSocketOptions, TCredentials, TEnvironment>
|
||||
public abstract class 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, TRestClient> _restClients = new ConcurrentDictionary<string, TRestClient>();
|
||||
private ConcurrentDictionary<string, TSocketClient> _socketClients = new ConcurrentDictionary<string, TSocketClient>();
|
||||
|
||||
private readonly IOptions<TRestOptions> _restOptions;
|
||||
private readonly IOptions<TSocketOptions> _socketOptions;
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly ILoggerFactory? _loggerFactory;
|
||||
/// <summary>
|
||||
/// Logger factory
|
||||
/// </summary>
|
||||
protected readonly ILoggerFactory? _loggerFactory;
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract string ExchangeName { get; }
|
||||
@@ -39,17 +37,14 @@ namespace CryptoExchange.Net.Clients
|
||||
public UserClientProvider(
|
||||
HttpClient? httpClient,
|
||||
ILoggerFactory? loggerFactory,
|
||||
IOptions<TRestOptions> restOptions,
|
||||
IOptions<TSocketOptions> socketOptions)
|
||||
IOptions<TRestOptions> restOptions)
|
||||
{
|
||||
_httpClient = httpClient ?? new HttpClient();
|
||||
_httpClient.Timeout = restOptions.Value.RequestTimeout;
|
||||
_loggerFactory = loggerFactory;
|
||||
_restOptions = restOptions;
|
||||
_socketOptions = socketOptions;
|
||||
}
|
||||
|
||||
|
||||
private IOptions<TRestOptions> SetRestEnvironment(IOptions<TRestOptions> options, TEnvironment? environment)
|
||||
{
|
||||
if (environment == null)
|
||||
@@ -61,22 +56,10 @@ namespace CryptoExchange.Net.Clients
|
||||
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 />
|
||||
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);
|
||||
CreateSocketClient(userIdentifier, credentials, environment);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -88,15 +71,6 @@ namespace CryptoExchange.Net.Clients
|
||||
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)
|
||||
{
|
||||
var clientRestOptions = SetRestEnvironment(_restOptions, environment);
|
||||
@@ -109,6 +83,94 @@ namespace CryptoExchange.Net.Clients
|
||||
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)
|
||||
{
|
||||
var clientSocketOptions = SetSocketEnvironment(_socketOptions, environment);
|
||||
@@ -121,15 +183,6 @@ namespace CryptoExchange.Net.Clients
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs a new instance of the rest client
|
||||
/// </summary>
|
||||
protected abstract TRestClient ConstructRestClient(
|
||||
HttpClient client,
|
||||
ILoggerFactory? loggerFactory,
|
||||
IOptions<TRestOptions> options);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Constructs a new instance of the socket client
|
||||
/// </summary>
|
||||
@@ -137,36 +190,23 @@ namespace CryptoExchange.Net.Clients
|
||||
ILoggerFactory? loggerFactory,
|
||||
IOptions<TSocketOptions> options);
|
||||
|
||||
|
||||
/// <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);
|
||||
restClient?.Dispose();
|
||||
socketClient?.Dispose();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Clear()
|
||||
public override void Clear()
|
||||
{
|
||||
foreach (var client in _restClients.Values)
|
||||
client.Dispose();
|
||||
_restClients.Clear();
|
||||
base.Clear();
|
||||
|
||||
foreach (var client in _socketClients.Values)
|
||||
client.Dispose();
|
||||
_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
||||
if (reader.TokenType == JsonTokenType.Number)
|
||||
{
|
||||
var number = reader.GetInt16();
|
||||
if (number > 1)
|
||||
if (number >= 1)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
|
||||
@@ -198,6 +198,9 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson.MessageHandlers
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
var written = new StreamReader(stream).ReadBlock(dataSnippet, 0, _errorResponseSnippetLimit);
|
||||
var data = new string(dataSnippet, 0, written);
|
||||
errorMsg += $": {data}";
|
||||
errorMsg += $": {(string.IsNullOrEmpty(data) ? "(empty)" : data)}";
|
||||
if (data.Length == _errorResponseSnippetLimit)
|
||||
errorMsg += " (truncated)";
|
||||
}
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
<PackageId>CryptoExchange.Net</PackageId>
|
||||
<Authors>JKorf</Authors>
|
||||
<Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description>
|
||||
<PackageVersion>12.0.0</PackageVersion>
|
||||
<AssemblyVersion>12.0.0</AssemblyVersion>
|
||||
<FileVersion>12.0.0</FileVersion>
|
||||
<PackageVersion>12.5.1</PackageVersion>
|
||||
<AssemblyVersion>12.5.1</AssemblyVersion>
|
||||
<FileVersion>12.5.1</FileVersion>
|
||||
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
|
||||
<PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange;CryptoExchange.Net</PackageTags>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
|
||||
@@ -33,7 +33,7 @@ namespace CryptoExchange.Net
|
||||
if (keyedCache != null && DateTime.UtcNow - keyedCache.UpdateTime < TimeSpan.FromMinutes(60))
|
||||
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>
|
||||
@@ -118,6 +118,22 @@ namespace CryptoExchange.Net
|
||||
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
|
||||
{
|
||||
private ExchangeInfo? _noKeyCache;
|
||||
@@ -163,7 +179,7 @@ namespace CryptoExchange.Net
|
||||
|
||||
public SharedSymbol? ParseSymbol(string? key, string symbolName)
|
||||
{
|
||||
SharedSymbol? symbolInfo = null;
|
||||
SharedSpotSymbol? symbolInfo = null;
|
||||
if (key == null)
|
||||
{
|
||||
if (_noKeyCache != null)
|
||||
@@ -173,7 +189,7 @@ namespace CryptoExchange.Net
|
||||
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
DeliverTime = symbolInfo.DeliverTime
|
||||
DeliverTime = (symbolInfo as SharedFuturesSymbol)?.DeliveryTime
|
||||
};
|
||||
}
|
||||
|
||||
@@ -265,7 +281,7 @@ namespace CryptoExchange.Net
|
||||
{
|
||||
return _noKeyCache.Symbols
|
||||
.Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase))
|
||||
.Select(x => x.Value)
|
||||
.Select(x => x.Value.SharedSymbol)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
@@ -274,7 +290,7 @@ namespace CryptoExchange.Net
|
||||
{
|
||||
result.AddRange(cache.Symbols
|
||||
.Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase))
|
||||
.Select(x => x.Value));
|
||||
.Select(x => x.Value.SharedSymbol));
|
||||
}
|
||||
|
||||
return result.ToArray();
|
||||
@@ -286,18 +302,63 @@ namespace CryptoExchange.Net
|
||||
|
||||
return exchangeInfo.Symbols
|
||||
.Where(x => x.Value.BaseAsset.Equals(baseAsset, StringComparison.InvariantCultureIgnoreCase))
|
||||
.Select(x => x.Value)
|
||||
.Select(x => x.Value.SharedSymbol)
|
||||
.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
|
||||
{
|
||||
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;
|
||||
Symbols = symbols;
|
||||
|
||||
@@ -461,11 +461,15 @@ namespace CryptoExchange.Net
|
||||
|
||||
if (typeof(ISpotOrderSocketClient).IsAssignableFrom(typeof(T)))
|
||||
services.AddTransient(x => (ISpotOrderSocketClient)client(x)!);
|
||||
if (typeof(ISpotOrderManagementSocketClient).IsAssignableFrom(typeof(T)))
|
||||
services.AddTransient(x => (ISpotOrderManagementSocketClient)client(x)!);
|
||||
|
||||
if (typeof(IFuturesOrderSocketClient).IsAssignableFrom(typeof(T)))
|
||||
services.AddTransient(x => (IFuturesOrderSocketClient)client(x)!);
|
||||
if (typeof(IPositionSocketClient).IsAssignableFrom(typeof(T)))
|
||||
services.AddTransient(x => (IPositionSocketClient)client(x)!);
|
||||
if (typeof(IFuturesOrderManagementSocketClient).IsAssignableFrom(typeof(T)))
|
||||
services.AddTransient(x => (IFuturesOrderManagementSocketClient)client(x)!);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -24,8 +24,9 @@ namespace CryptoExchange.Net.Interfaces
|
||||
/// <param name="interval">Kline interval</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="exchangeParameters">Exchange parameters</param>
|
||||
/// <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>
|
||||
/// 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="limit">The max amount of trades to retain</param>
|
||||
/// <param name="period">The max period the data should be retained</param>
|
||||
/// <param name="exchangeParameters">Exchange parameters</param>
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ using CryptoExchange.Net.Objects.Options;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Pipelines;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
|
||||
@@ -14,6 +16,61 @@ namespace CryptoExchange.Net
|
||||
/// </summary>
|
||||
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;
|
||||
/// <summary>
|
||||
/// 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");
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Create a new HttpMessageHandler instance
|
||||
/// </summary>
|
||||
|
||||
@@ -180,7 +180,7 @@ namespace CryptoExchange.Net.Logging.Extensions
|
||||
_receivedMessageNotMatchedToAnyListener = LoggerMessage.Define<int, string, string, string>(
|
||||
LogLevel.Warning,
|
||||
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>(
|
||||
LogLevel.Warning,
|
||||
@@ -326,9 +326,9 @@ namespace CryptoExchange.Net.Logging.Extensions
|
||||
_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)
|
||||
|
||||
@@ -233,7 +233,7 @@ namespace CryptoExchange.Net.Objects
|
||||
/// Add key as comma separated values
|
||||
/// </summary>
|
||||
#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
|
||||
public void AddCommaSeparated<T>(string key, IEnumerable<T>? values)
|
||||
#endif
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
|
||||
@@ -8,8 +9,11 @@ namespace CryptoExchange.Net.Objects;
|
||||
/// <summary>
|
||||
/// Call result
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{DebugView,nq}")]
|
||||
public record CallResult : ICallResult
|
||||
{
|
||||
private string DebugView => Success ? "Success" : $"Error: {Error}";
|
||||
|
||||
private static CallResult _successResult = new CallResult();
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using CryptoExchange.Net.SharedApis;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
@@ -12,8 +13,11 @@ namespace CryptoExchange.Net.Objects;
|
||||
/// <summary>
|
||||
/// HTTP call result
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{DebugView,nq}")]
|
||||
public record HttpResult : IHttpResult
|
||||
{
|
||||
private string DebugView => $"[Req {RequestId}] " + (Success ? "Success" : $"Error: {Error}");
|
||||
|
||||
/// <summary>
|
||||
/// Create a new success HTTP result
|
||||
/// </summary>
|
||||
@@ -251,8 +255,32 @@ public record HttpResult : IHttpResult
|
||||
|
||||
|
||||
/// <inheritdoc />
|
||||
[DebuggerDisplay("{DebugView,nq}")]
|
||||
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>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
|
||||
@@ -8,8 +9,11 @@ namespace CryptoExchange.Net.Objects;
|
||||
/// <summary>
|
||||
/// WebSocket call result
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{DebugView,nq}")]
|
||||
public record WebSocketResult : IWebSocketResult
|
||||
{
|
||||
private string DebugView => $"[Sckt {ConnectionId}] " + (RequestId == null ? "" : $"[Req {RequestId}] ") + (Success ? "Success" : $"Error: {Error}");
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
@@ -183,7 +187,7 @@ public record WebSocketResult<T> : WebSocketResult, IWebSocketResult<T>
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public record QueryResult : WebSocketResult
|
||||
public record QueryResult : WebSocketResult, IQueryResult
|
||||
{
|
||||
/// <summary>
|
||||
/// ctor
|
||||
@@ -208,6 +212,8 @@ public record QueryResult : WebSocketResult
|
||||
Url = result.Url,
|
||||
RequestId = result.RequestId,
|
||||
ResponseTime = result.ResponseTime,
|
||||
OriginalData = result.OriginalData,
|
||||
RequestBody = result.RequestBody
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -288,6 +294,9 @@ public record QueryResult : WebSocketResult
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? RequestBody { get; init; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? OriginalData { get; init; }
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -314,7 +323,4 @@ public record QueryResult<T> : QueryResult, IQueryResult<T>
|
||||
public new bool Success => Error == null;
|
||||
/// <inheritdoc />
|
||||
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>
|
||||
public class UpdateSubscription
|
||||
{
|
||||
private readonly SocketConnection _connection;
|
||||
private readonly SocketConnection? _connection;
|
||||
private readonly ManualUpdateSubscription? _manualSubscription;
|
||||
internal readonly Subscription _subscription;
|
||||
|
||||
#if NET9_0_OR_GREATER
|
||||
@@ -102,7 +103,7 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
/// <summary>
|
||||
/// The id of the socket
|
||||
/// </summary>
|
||||
public int SocketId => _connection.SocketId;
|
||||
public int SocketId => _connection?.SocketId ?? _manualSubscription!.SocketId;
|
||||
|
||||
/// <summary>
|
||||
/// The id of the subscription
|
||||
@@ -112,12 +113,12 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
/// <summary>
|
||||
/// The last timestamp anything was received from the server
|
||||
/// </summary>
|
||||
public DateTime? LastReceiveTime => _connection.LastReceiveTime;
|
||||
public DateTime? LastReceiveTime => _connection?.LastReceiveTime ?? _manualSubscription!.LastReceiveTime;
|
||||
|
||||
/// <summary>
|
||||
/// The current websocket status
|
||||
/// </summary>
|
||||
public SocketStatus SocketStatus => _connection.Status;
|
||||
public SocketStatus SocketStatus => _connection?.Status ?? _manualSubscription!.SocketStatus;
|
||||
|
||||
/// <summary>
|
||||
/// The current subscription status
|
||||
@@ -143,6 +144,18 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
_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()
|
||||
{
|
||||
lock (_eventLock)
|
||||
@@ -150,22 +163,26 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
if (!_connectionEventsSubscribed)
|
||||
return;
|
||||
|
||||
_connection.ConnectionClosed -= HandleConnectionClosedEvent;
|
||||
_connection.ConnectionLost -= HandleConnectionLostEvent;
|
||||
_connection.ConnectionRestored -= HandleConnectionRestoredEvent;
|
||||
_connection.ResubscribingFailed -= HandleResubscribeFailedEvent;
|
||||
_connection.ActivityPaused -= HandlePausedEvent;
|
||||
_connection.ActivityUnpaused -= HandleUnpausedEvent;
|
||||
if (_connection != null)
|
||||
{
|
||||
_connection.ConnectionClosed -= HandleConnectionClosedEvent;
|
||||
_connection.ConnectionLost -= HandleConnectionLostEvent;
|
||||
_connection.ConnectionRestored -= HandleConnectionRestoredEvent;
|
||||
_connection.ResubscribingFailed -= HandleResubscribeFailedEvent;
|
||||
_connection.ActivityPaused -= HandlePausedEvent;
|
||||
_connection.ActivityUnpaused -= HandleUnpausedEvent;
|
||||
}
|
||||
|
||||
_connectionEventsSubscribed = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleConnectionClosedEvent()
|
||||
internal void HandleConnectionClosedEvent()
|
||||
{
|
||||
UnsubscribeConnectionEvents();
|
||||
|
||||
// If we're not the subscription closing this connection don't bother emitting
|
||||
if (!_subscription.IsClosingConnection)
|
||||
if (_connection != null && !_subscription.IsClosingConnection)
|
||||
return;
|
||||
|
||||
List<Action> handlers;
|
||||
@@ -176,7 +193,7 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
callback();
|
||||
}
|
||||
|
||||
private void HandleConnectionLostEvent()
|
||||
internal void HandleConnectionLostEvent()
|
||||
{
|
||||
if (!_subscription.Active)
|
||||
{
|
||||
@@ -192,7 +209,7 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
callback();
|
||||
}
|
||||
|
||||
private void HandleConnectionRestoredEvent(TimeSpan period)
|
||||
internal void HandleConnectionRestoredEvent(TimeSpan period)
|
||||
{
|
||||
if (!_subscription.Active)
|
||||
{
|
||||
@@ -208,7 +225,7 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
callback(period);
|
||||
}
|
||||
|
||||
private void HandleResubscribeFailedEvent(Error error)
|
||||
internal void HandleResubscribeFailedEvent(Error error)
|
||||
{
|
||||
if (!_subscription.Active)
|
||||
{
|
||||
@@ -224,7 +241,7 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
callback(error);
|
||||
}
|
||||
|
||||
private void HandlePausedEvent()
|
||||
internal void HandlePausedEvent()
|
||||
{
|
||||
if (!_subscription.Active)
|
||||
{
|
||||
@@ -240,7 +257,7 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
callback();
|
||||
}
|
||||
|
||||
private void HandleUnpausedEvent()
|
||||
internal void HandleUnpausedEvent()
|
||||
{
|
||||
if (!_subscription.Active)
|
||||
{
|
||||
@@ -262,7 +279,10 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
/// <returns></returns>
|
||||
public Task CloseAsync()
|
||||
{
|
||||
return _connection.CloseAsync(_subscription);
|
||||
if (_connection != null)
|
||||
return _connection.CloseAsync(_subscription);
|
||||
|
||||
return _manualSubscription!.CloseAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -271,7 +291,10 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
/// <returns></returns>
|
||||
public Task ReconnectAsync()
|
||||
{
|
||||
return _connection.TriggerReconnectAsync();
|
||||
if (_connection != null)
|
||||
return _connection.TriggerReconnectAsync();
|
||||
|
||||
return _manualSubscription!.ReconnectAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -280,7 +303,13 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
/// <returns></returns>
|
||||
internal async Task UnsubscribeAsync()
|
||||
{
|
||||
await _connection.UnsubscribeAsync(_subscription).ConfigureAwait(false);
|
||||
if (_connection != null)
|
||||
{
|
||||
await _connection.UnsubscribeAsync(_subscription).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await _manualSubscription!.CloseAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -289,7 +318,10 @@ namespace CryptoExchange.Net.Objects.Sockets
|
||||
/// <returns></returns>
|
||||
internal async Task<CallResult> ResubscribeAsync()
|
||||
{
|
||||
return await _connection.ResubscribeAsync(_subscription).ConfigureAwait(false);
|
||||
if (_connection != null)
|
||||
return await _connection.ResubscribeAsync(_subscription).ConfigureAwait(false);
|
||||
|
||||
return await _manualSubscription!.ResubscribeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,6 +289,7 @@ namespace CryptoExchange.Net.OrderBook
|
||||
if (!startResult.Success)
|
||||
{
|
||||
Status = OrderBookStatus.Disconnected;
|
||||
_queueEvent.Set();
|
||||
return CallResult.Fail(startResult.Error!);
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
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>
|
||||
/// 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 />
|
||||
|
||||
@@ -44,7 +44,6 @@ namespace CryptoExchange.Net.SharedApis
|
||||
PlaceSpotOrderOptions PlaceSpotOrderOptions { get; }
|
||||
/// <summary>
|
||||
/// 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>
|
||||
/// <param name="request">Request info</param>
|
||||
/// <param name="ct">Cancellation token</param>
|
||||
|
||||
@@ -9,6 +9,11 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
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>
|
||||
/// 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 />
|
||||
|
||||
+66
@@ -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);
|
||||
}
|
||||
}
|
||||
+66
@@ -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);
|
||||
|
||||
}
|
||||
}
|
||||
+3
@@ -5,6 +5,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class CancelFuturesOrderByClientOrderIdOptions : EndpointOptions<CancelOrderRequest, IFuturesOrderClientIdRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Cancel a futures order by its client order id";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class CancelFuturesOrderOptions : EndpointOptions<CancelOrderRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Cancel a futures order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+22
@@ -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.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class CancelFuturesTpSlOptions : EndpointOptions<CancelTpSlRequest, IFuturesTpSlRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Cancel a take profit or stop loss order for a futures position";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class CancelFuturesTriggerOrderOptions : EndpointOptions<CancelOrderRequest, IFuturesTriggerOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Cancel a futures trigger order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+14
-1
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class CancelSpotOrderByClientOrderIdOptions : EndpointOptions<CancelOrderRequest, ISpotOrderClientIdRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Cancel a spot order by its client order id";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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.Text;
|
||||
|
||||
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class CancelSpotOrderOptions : EndpointOptions<CancelOrderRequest, ISpotOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Cancel a spot order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+32
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class CancelSpotTriggerOrderOptions : EndpointOptions<CancelOrderRequest, ISpotTriggerOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Cancel a spot trigger order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class ClosePositionOptions : EndpointOptions<ClosePositionRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Close an open futures position";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -41,6 +41,10 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// Whether the call is supported. If false the exchange API does not support this operation.
|
||||
/// </summary>
|
||||
public bool Supported { get; set; } = true;
|
||||
/// <summary>
|
||||
/// Description of the endpoint
|
||||
/// </summary>
|
||||
public abstract string Description { get; }
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
@@ -68,9 +72,14 @@ namespace CryptoExchange.Net.SharedApis
|
||||
return ArgumentError.Invalid("TradingMode", $"TradingMode.{tradingMode} is not supported, supported types: {string.Join(", ", supportedTradingModes)}");
|
||||
|
||||
foreach (var param in RequiredExchangeParameters)
|
||||
{
|
||||
{
|
||||
if (param.Names!.All(x => ExchangeParameters.HasValue(exchangeParameters, Exchange, x, param.ValueType) != true))
|
||||
return ArgumentError.Invalid(string.Join("/", param.Names!), $"One of exchange parameters `{string.Join(", ", param.Names!)}` for exchange `{Exchange}` should be provided. Example: {param.ExampleValue}");
|
||||
{
|
||||
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 null;
|
||||
@@ -82,7 +91,7 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">Type of data</typeparam>
|
||||
#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
|
||||
#else
|
||||
public abstract class EndpointOptions<TRequest> : EndpointOptions
|
||||
@@ -149,7 +158,12 @@ namespace CryptoExchange.Net.SharedApis
|
||||
foreach (var param in RequiredOptionalParameters)
|
||||
{
|
||||
if (param.Names!.All(x => _requestProperties.Single(p => p.Name == x).GetValue(request, null) == null))
|
||||
return ArgumentError.Invalid(string.Join("/", param.Names!), $"One of optional parameters `{string.Join(", ", param.Names!)}` for exchange `{Exchange}` should be provided. Example: {param.ExampleValue}");
|
||||
{
|
||||
if (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}");
|
||||
}
|
||||
}
|
||||
|
||||
if (request is SharedSymbolRequest symbolsRequest)
|
||||
@@ -171,32 +185,40 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// <inheritdoc />
|
||||
public override string ToString()
|
||||
{
|
||||
if (!Supported)
|
||||
return $"{Exchange} {EndpointName} NOT SUPPORTED";
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine($"{Exchange} {EndpointName}");
|
||||
sb.AppendLine($"Needs authentication: {NeedsAuthentication}");
|
||||
if (!string.IsNullOrEmpty(RequestNotes))
|
||||
sb.AppendLine($"{EndpointName}");
|
||||
if (!Supported)
|
||||
{
|
||||
sb.AppendLine(" NOT SUPPORTED");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
sb.AppendLine($"{Description}");
|
||||
if (!string.IsNullOrEmpty(RequestNotes))
|
||||
{
|
||||
sb.Append(" Notes: ");
|
||||
sb.AppendLine(RequestNotes);
|
||||
}
|
||||
if (RequiredOptionalParameters.Any())
|
||||
{
|
||||
sb.AppendLine($"Required optional parameters:");
|
||||
sb.AppendLine($" Required optional parameters:");
|
||||
foreach(var param in RequiredOptionalParameters)
|
||||
sb.AppendLine($" {param}");
|
||||
}
|
||||
if (RequiredExchangeParameters.Any())
|
||||
{
|
||||
sb.AppendLine($"Required exchange specific parameters:");
|
||||
sb.AppendLine($" Required exchange specific parameters:");
|
||||
foreach (var param in RequiredExchangeParameters)
|
||||
sb.AppendLine($" {param}");
|
||||
}
|
||||
if (OptionalExchangeParameters.Any())
|
||||
{
|
||||
sb.AppendLine($"Optional exchange specific parameters:");
|
||||
sb.AppendLine($" Optional exchange specific parameters:");
|
||||
foreach (var param in OptionalExchangeParameters)
|
||||
sb.AppendLine($" {param}");
|
||||
}
|
||||
sb.Append(" Needs authentication: ");
|
||||
sb.AppendLine($"{NeedsAuthentication}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
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>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
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>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System.Linq;
|
||||
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
@@ -8,6 +8,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetBalancesOptions : EndpointOptions<GetBalancesRequest, IBalanceRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve account balances";
|
||||
|
||||
/// <summary>
|
||||
/// Supported account types
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetBookTickerOptions : EndpointOptions<GetBookTickerRequest, IBookTickerRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve the best bid and ask price for a symbol";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetDepositAddressesOptions : EndpointOptions<GetDepositAddressesRequest, IDepositRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve deposit addresses for an asset";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetDepositsOptions : PaginatedEndpointOptions<GetDepositsRequest, IDepositRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve deposit history";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFeeOptions : EndpointOptions<GetFeeRequest, IFeeRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve trading fee information";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFundingRateHistoryOptions : PaginatedEndpointOptions<GetFundingRateHistoryRequest, IFundingRateRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve historical funding rates for a futures symbol";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesClosedOrdersOptions : PaginatedEndpointOptions<GetClosedOrdersRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve closed futures orders";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesOrderByClientOrderIdOptions : EndpointOptions<GetOrderRequest, IFuturesOrderClientIdRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve a futures order by its client order id";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesOrderOptions : EndpointOptions<GetOrderRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve a futures order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesOrderTradesOptions : EndpointOptions<GetOrderTradesRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve trades for a futures order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,11 +10,52 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesSymbolsOptions : EndpointOptions<GetSymbolsRequest, IFuturesSymbolRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve supported futures symbols and their trading rules";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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
|
||||
{
|
||||
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesTickerOptions : EndpointOptions<GetTickerRequest, IFuturesTickerRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve price ticker information for a futures symbol";
|
||||
|
||||
/// <summary>
|
||||
/// Type of ticker calculation
|
||||
/// </summary>
|
||||
@@ -24,7 +27,7 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder(base.ToString());
|
||||
sb.AppendLine($"Ticker data calculation type: {TickerType}");
|
||||
sb.AppendLine($" Ticker data calculation type: {TickerType}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Text;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesTickersOptions : EndpointOptions<GetTickersRequest, IFuturesTickerRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve price ticker information for all futures symbols";
|
||||
|
||||
/// <summary>
|
||||
/// Type of ticker calculation
|
||||
/// </summary>
|
||||
@@ -24,7 +27,7 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder(base.ToString());
|
||||
sb.AppendLine($"Ticker data calculation type: {TickerType}");
|
||||
sb.AppendLine($" Ticker data calculation type: {TickerType}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesTriggerOrderOptions : EndpointOptions<GetOrderRequest, IFuturesTriggerOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve a futures trigger order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetFuturesUserTradesOptions : PaginatedEndpointOptions<GetUserTradesRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve futures user trade history";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+6
-3
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -10,6 +10,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetIndexPriceKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IIndexPriceKlineRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve index price candlestick data";
|
||||
|
||||
/// <summary>
|
||||
/// The supported kline intervals
|
||||
/// </summary>
|
||||
@@ -108,9 +111,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string 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)
|
||||
sb.AppendLine($"Max total data points available: {MaxTotalDataPoints}");
|
||||
sb.AppendLine($" Max total data points available: {MaxTotalDataPoints}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -10,6 +10,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IKlineRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve candlestick data for a symbol";
|
||||
|
||||
/// <summary>
|
||||
/// The supported kline intervals
|
||||
/// </summary>
|
||||
@@ -108,9 +111,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string 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)
|
||||
sb.AppendLine($"Max total data points available: {MaxTotalDataPoints}");
|
||||
sb.AppendLine($" Max total data points available: {MaxTotalDataPoints}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetLeverageOptions : EndpointOptions<GetLeverageRequest, ILeverageRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve the current leverage for a futures symbol";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -10,6 +10,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetMarkPriceKlinesOptions : PaginatedEndpointOptions<GetKlinesRequest, IMarkPriceKlineRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve mark price candlestick data";
|
||||
|
||||
/// <summary>
|
||||
/// The supported kline intervals
|
||||
/// </summary>
|
||||
@@ -108,9 +111,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string 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)
|
||||
sb.AppendLine($"Max total data points available: {MaxTotalDataPoints}");
|
||||
sb.AppendLine($" Max total data points available: {MaxTotalDataPoints}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetOpenFuturesOrdersOptions : EndpointOptions<GetOpenOrdersRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve open futures orders";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetOpenInterestOptions : EndpointOptions<GetOpenInterestRequest, IOpenInterestRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve open interest for a futures symbol";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetOpenSpotOrdersOptions : EndpointOptions<GetOpenOrdersRequest, ISpotOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve open spot orders";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -10,6 +10,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetOrderBookOptions : EndpointOptions<GetOrderBookRequest, IOrderBookRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve the current order book for a symbol";
|
||||
|
||||
/// <summary>
|
||||
/// Supported order book depths
|
||||
/// </summary>
|
||||
@@ -65,7 +68,7 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetPositionHistoryOptions : PaginatedEndpointOptions<GetPositionHistoryRequest, IPositionHistoryRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve historical futures positions";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
/// <summary>
|
||||
/// Options for requesting current position mode
|
||||
/// </summary>
|
||||
public class GetPositionModeOptions : EndpointOptions<GetPositionModeRequest, IPositionModeRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve the current futures position mode";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetPositionsOptions : EndpointOptions<GetPositionsRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve open futures positions";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
@@ -8,6 +8,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetRecentTradesOptions : EndpointOptions<GetRecentTradesRequest, IRecentTradeRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve recent public trades for a symbol";
|
||||
|
||||
/// <summary>
|
||||
/// The max number of trades that can be requested
|
||||
/// </summary>
|
||||
@@ -39,7 +42,7 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder(base.ToString());
|
||||
sb.AppendLine($"Max data points: {MaxLimit}");
|
||||
sb.AppendLine($" Max data points: {MaxLimit}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
+7
-1
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotClosedOrdersOptions : PaginatedEndpointOptions<GetClosedOrdersRequest, ISpotOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve closed spot orders";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
@@ -20,6 +23,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
return ArgumentError.Invalid(nameof(GetClosedOrdersRequest.Direction), $"Ascending direction is not supported");
|
||||
|
||||
|
||||
+14
-1
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotOrderByClientOrderIdOptions : EndpointOptions<GetOrderRequest, ISpotOrderClientIdRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve a spot order by its client order id";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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.Text;
|
||||
|
||||
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotOrderOptions : EndpointOptions<GetOrderRequest, ISpotOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve a spot order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+14
-1
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotOrderTradesOptions : EndpointOptions<GetOrderTradesRequest, ISpotOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve trades for a spot order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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.Text;
|
||||
|
||||
@@ -9,11 +10,53 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotSymbolsOptions : EndpointOptions<GetSymbolsRequest, ISpotSymbolRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve supported spot symbols and their trading rules";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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
|
||||
{
|
||||
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotTickerOptions : EndpointOptions<GetTickerRequest, ISpotTickerRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve price ticker information for a spot symbol";
|
||||
|
||||
/// <summary>
|
||||
/// Type of ticker calculation
|
||||
/// </summary>
|
||||
@@ -24,7 +27,7 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder(base.ToString());
|
||||
sb.AppendLine($"Ticker data calculation type: {TickerType}");
|
||||
sb.AppendLine($" Ticker data calculation type: {TickerType}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Text;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotTickersOptions : EndpointOptions<GetTickersRequest, ISpotTickerRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve price ticker information for all spot symbols";
|
||||
|
||||
/// <summary>
|
||||
/// Type of ticker calculation
|
||||
/// </summary>
|
||||
@@ -24,7 +27,7 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder(base.ToString());
|
||||
sb.AppendLine($"Ticker data calculation type: {TickerType}");
|
||||
sb.AppendLine($" Ticker data calculation type: {TickerType}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
+14
-1
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,11 +10,23 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotTriggerOrderOptions : EndpointOptions<GetOrderRequest, ISpotTriggerOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve a spot trigger order";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
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.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetSpotUserTradesOptions : PaginatedEndpointOptions<GetUserTradesRequest, ISpotOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve spot user trade history";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
@@ -20,6 +23,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
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.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetTradeHistoryOptions : PaginatedEndpointOptions<GetTradeHistoryRequest, ITradeHistoryRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve public trade history for a symbol";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class GetWithdrawalsOptions : PaginatedEndpointOptions<GetWithdrawalsRequest, IWithdrawalRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Retrieve withdrawal history";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// Options for paginated endpoints
|
||||
/// </summary>
|
||||
#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 TClient : ISharedClient
|
||||
#else
|
||||
@@ -63,12 +63,12 @@ namespace CryptoExchange.Net.SharedApis
|
||||
public override string ToString()
|
||||
{
|
||||
var sb = new StringBuilder(base.ToString());
|
||||
sb.AppendLine($"Ascending retrieval supported: {SupportsAscending}");
|
||||
sb.AppendLine($"Descending retrieval supported: {SupportsDescending}");
|
||||
sb.AppendLine($"Time period filter supported: {TimePeriodFilterSupport}");
|
||||
sb.AppendLine($"Max limit: {MaxLimit}");
|
||||
sb.AppendLine($" Ascending retrieval supported: {SupportsAscending}");
|
||||
sb.AppendLine($" Descending retrieval supported: {SupportsDescending}");
|
||||
sb.AppendLine($" Time period filter supported: {TimePeriodFilterSupport}");
|
||||
sb.AppendLine($" Max limit: {MaxLimit}");
|
||||
if (MaxAge.HasValue)
|
||||
sb.AppendLine($"Max age: {MaxAge}");
|
||||
sb.AppendLine($" Max age: {MaxAge}");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Linq;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class PlaceFuturesOrderOptions : EndpointOptions<PlaceFuturesOrderRequest, IFuturesOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Place a new futures order";
|
||||
|
||||
/// <summary>
|
||||
/// Whether or not the API supports setting take profit / stop loss with the order
|
||||
/// </summary>
|
||||
|
||||
+56
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+4
-15
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class PlaceFuturesTriggerOrderOptions : EndpointOptions<PlaceFuturesTriggerOrderRequest, IFuturesTriggerOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Place a new futures trigger order";
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
@@ -19,19 +22,5 @@ namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
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.Linq;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class PlaceSpotOrderOptions : EndpointOptions<PlaceSpotOrderRequest, ISpotOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Place a new spot order";
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
@@ -24,6 +27,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
PlaceSpotOrderRequest request,
|
||||
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)
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
@@ -7,6 +7,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class PlaceSpotTriggerOrderOptions : EndpointOptions<PlaceSpotTriggerOrderRequest, ISpotOrderRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Place a new spot trigger order";
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
@@ -27,6 +30,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
PlaceSpotTriggerOrderRequest request,
|
||||
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);
|
||||
if (quantityError != null)
|
||||
return quantityError;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class SetFuturesTpSlOptions : EndpointOptions<SetTpSlRequest, IFuturesTpSlRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Set take profit or stop loss values for a futures position";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
/// <summary>
|
||||
/// Options for setting leverage
|
||||
/// </summary>
|
||||
public class SetLeverageOptions : EndpointOptions<SetLeverageRequest, ILeverageRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Set the leverage for a futures symbol";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
/// <summary>
|
||||
/// Options for setting position mode
|
||||
/// </summary>
|
||||
public class SetPositionModeOptions : EndpointOptions<SetPositionModeRequest, IPositionModeRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Set the futures position mode";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace CryptoExchange.Net.SharedApis
|
||||
{
|
||||
@@ -8,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class TransferOptions : EndpointOptions<TransferRequest, ITransferRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Transfer funds between account types";
|
||||
|
||||
/// <summary>
|
||||
/// Supported account types
|
||||
/// </summary>
|
||||
@@ -36,5 +40,13 @@ namespace CryptoExchange.Net.SharedApis
|
||||
|
||||
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>
|
||||
/// Options for requesting a withdrawal
|
||||
/// </summary>
|
||||
public class WithdrawOptions : EndpointOptions<WithdrawRequest, IWithdrawRestClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Withdraw an asset";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
using CryptoExchange.Net.Objects;
|
||||
using CryptoExchange.Net.Objects;
|
||||
using System;
|
||||
using System.Linq;
|
||||
|
||||
@@ -9,6 +9,9 @@ namespace CryptoExchange.Net.SharedApis
|
||||
/// </summary>
|
||||
public class SubscribeBalanceOptions : EndpointOptions<SubscribeBalancesRequest, IBalanceSocketClient>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Subscribe to balance updates";
|
||||
|
||||
/// <summary>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user