mirror of
https://github.com/JKorf/CryptoExchange.Net.git
synced 2026-08-12 17:03:10 +00:00
Compare commits
63 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b66f12ff75 | |||
| 0403384beb | |||
| 7d7bc35869 | |||
| 48797038be | |||
| d21792d04c | |||
| 8414e9d94f | |||
| ab0243445d | |||
| f2cf70b02f | |||
| 9ff417bba8 | |||
| 6b43d08a4d | |||
| 39bf7fe9b9 | |||
| b5893c3b60 | |||
| 15657ba683 | |||
| 1aed9f0c67 | |||
| 17f1560310 | |||
| 41de0a3150 | |||
| 3e410be611 | |||
| be75449e4a | |||
| b1b05c8f6b | |||
| a0e588c3de | |||
| 9e86a08327 | |||
| ed007b5272 | |||
| bdd5526244 | |||
| ce35e30688 | |||
| b40f72b1b0 | |||
| 31a6cf285b | |||
| 1842f4fda0 | |||
| 7a58902ab6 | |||
| 3cb91296ca | |||
| 130ed40580 | |||
| 94cb2caf0b | |||
| 917d060827 | |||
| c58bc2be07 | |||
| ff3356e2b4 | |||
| 79434c7be5 | |||
| 168dabc11f | |||
| 71ee263683 | |||
| 7239b9c289 | |||
| 84d36544e4 | |||
| a71f57ae7f | |||
| 6e5bcd5e9a | |||
| 4131e563c3 | |||
| 613766dbca | |||
| 23b07d709e | |||
| bbbdac2fd3 | |||
| c614b7869c | |||
| 1f31e4a9d7 | |||
| 6cb6cd6b11 | |||
| 17ffec329f | |||
| 7a3927ef49 | |||
| c1b0437c93 | |||
| 23e947f258 | |||
| b8686d60b9 | |||
| 5d3de52da6 | |||
| fee18fd183 | |||
| 3a43d461a3 | |||
| 5f409efad3 | |||
| cc1f0796fe | |||
| b1cd9b5412 | |||
| 42003a0247 | |||
| d89c2bde94 | |||
| 3e6bdaafc6 | |||
| 93e4722a81 |
@@ -16,7 +16,7 @@ jobs:
|
|||||||
- name: Setup .NET
|
- name: Setup .NET
|
||||||
uses: actions/setup-dotnet@v1
|
uses: actions/setup-dotnet@v1
|
||||||
with:
|
with:
|
||||||
dotnet-version: 6.0.x
|
dotnet-version: 8.0.x
|
||||||
- name: Restore dependencies
|
- name: Restore dependencies
|
||||||
run: dotnet restore
|
run: dotnet restore
|
||||||
- name: Build
|
- name: Build
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0"></PackageReference>
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1"></PackageReference>
|
||||||
<PackageReference Include="Moq" Version="4.20.70" />
|
<PackageReference Include="Moq" Version="4.20.72" />
|
||||||
<PackageReference Include="NUnit" Version="4.1.0"></PackageReference>
|
<PackageReference Include="NUnit" Version="4.2.2"></PackageReference>
|
||||||
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0"></PackageReference>
|
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0"></PackageReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -100,6 +100,10 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
Assert.That(authProvider1.GetSecret() == "222");
|
Assert.That(authProvider1.GetSecret() == "222");
|
||||||
Assert.That(authProvider2.GetKey() == "123");
|
Assert.That(authProvider2.GetKey() == "123");
|
||||||
Assert.That(authProvider2.GetSecret() == "456");
|
Assert.That(authProvider2.GetSecret() == "456");
|
||||||
|
|
||||||
|
// Cleanup static values
|
||||||
|
TestClientOptions.Default.ApiCredentials = null;
|
||||||
|
TestClientOptions.Default.Api1Options.ApiCredentials = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
@@ -121,6 +125,10 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
Assert.That(authProvider2.GetKey() == "123");
|
Assert.That(authProvider2.GetKey() == "123");
|
||||||
Assert.That(authProvider2.GetSecret() == "456");
|
Assert.That(authProvider2.GetSecret() == "456");
|
||||||
Assert.That(client.Api2.BaseAddress == "https://localhost:123");
|
Assert.That(client.Api2.BaseAddress == "https://localhost:123");
|
||||||
|
|
||||||
|
// Cleanup static values
|
||||||
|
TestClientOptions.Default.ApiCredentials = null;
|
||||||
|
TestClientOptions.Default.Api1Options.ApiCredentials = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +142,14 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
Environment = new TestEnvironment("test", "https://test.com")
|
Environment = new TestEnvironment("test", "https://test.com")
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public TestClientOptions()
|
||||||
|
{
|
||||||
|
Default?.Set(this);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The default receive window for requests
|
/// The default receive window for requests
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -143,12 +159,12 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
|
|
||||||
public RestApiOptions Api2Options { get; set; } = new RestApiOptions();
|
public RestApiOptions Api2Options { get; set; } = new RestApiOptions();
|
||||||
|
|
||||||
internal TestClientOptions Copy()
|
internal TestClientOptions Set(TestClientOptions targetOptions)
|
||||||
{
|
{
|
||||||
var options = Copy<TestClientOptions>();
|
targetOptions = base.Set<TestClientOptions>(targetOptions);
|
||||||
options.Api1Options = Api1Options.Copy<RestApiOptions>();
|
targetOptions.Api1Options = Api1Options.Set(targetOptions.Api1Options);
|
||||||
options.Api2Options = Api2Options.Copy<RestApiOptions>();
|
targetOptions.Api2Options = Api2Options.Set(targetOptions.Api2Options);
|
||||||
return options;
|
return targetOptions;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -302,7 +302,7 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
public async Task ApiKeyRateLimiterBasics(string key1, string key2, string endpoint1, string endpoint2, bool expectLimited)
|
public async Task ApiKeyRateLimiterBasics(string key1, string key2, string endpoint1, string endpoint2, bool expectLimited)
|
||||||
{
|
{
|
||||||
var rateLimiter = new RateLimitGate("Test");
|
var rateLimiter = new RateLimitGate("Test");
|
||||||
rateLimiter.AddGuard(new RateLimitGuard(RateLimitGuard.PerApiKey, new AuthenticatedEndpointFilter(true), 1, TimeSpan.FromSeconds(0.1), RateLimitWindowType.Fixed));
|
rateLimiter.AddGuard(new RateLimitGuard(RateLimitGuard.PerApiKey, new AuthenticatedEndpointFilter(true), 1, TimeSpan.FromSeconds(0.1), RateLimitWindowType.Sliding));
|
||||||
var requestDefinition1 = new RequestDefinition(endpoint1, HttpMethod.Get) { Authenticated = key1 != null };
|
var requestDefinition1 = new RequestDefinition(endpoint1, HttpMethod.Get) { Authenticated = key1 != null };
|
||||||
var requestDefinition2 = new RequestDefinition(endpoint2, HttpMethod.Get) { Authenticated = key2 != null };
|
var requestDefinition2 = new RequestDefinition(endpoint2, HttpMethod.Get) { Authenticated = key2 != null };
|
||||||
|
|
||||||
@@ -370,5 +370,20 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
var result2 = await rateLimiter.ProcessAsync(new TraceLogger(), 1, RateLimitItemType.Connection, new RequestDefinition("1", HttpMethod.Get), host2, "123", 1, RateLimitingBehaviour.Wait, default);
|
var result2 = await rateLimiter.ProcessAsync(new TraceLogger(), 1, RateLimitItemType.Connection, new RequestDefinition("1", HttpMethod.Get), host2, "123", 1, RateLimitingBehaviour.Wait, default);
|
||||||
Assert.That(expectLimited ? evnt != null : evnt == null);
|
Assert.That(expectLimited ? evnt != null : evnt == null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ConnectionRateLimiterCancel()
|
||||||
|
{
|
||||||
|
var rateLimiter = new RateLimitGate("Test");
|
||||||
|
rateLimiter.AddGuard(new RateLimitGuard(RateLimitGuard.PerHost, new LimitItemTypeFilter(RateLimitItemType.Connection), 1, TimeSpan.FromSeconds(10), RateLimitWindowType.Fixed));
|
||||||
|
|
||||||
|
RateLimitEvent evnt = null;
|
||||||
|
rateLimiter.RateLimitTriggered += (x) => { evnt = x; };
|
||||||
|
var ct = new CancellationTokenSource(TimeSpan.FromSeconds(0.2));
|
||||||
|
|
||||||
|
var result1 = await rateLimiter.ProcessAsync(new TraceLogger(), 1, RateLimitItemType.Connection, new RequestDefinition("1", HttpMethod.Get), "https://test.com", "123", 1, RateLimitingBehaviour.Wait, ct.Token);
|
||||||
|
var result2 = await rateLimiter.ProcessAsync(new TraceLogger(), 1, RateLimitItemType.Connection, new RequestDefinition("1", HttpMethod.Get), "https://test.com", "123", 1, RateLimitingBehaviour.Wait, ct.Token);
|
||||||
|
Assert.That(result2.Error, Is.TypeOf<CancellationRequestedError>());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ using NUnit.Framework;
|
|||||||
using System;
|
using System;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using NUnit.Framework.Legacy;
|
using NUnit.Framework.Legacy;
|
||||||
|
using CryptoExchange.Net.Converters;
|
||||||
|
using CryptoExchange.Net.Testing.Comparers;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.UnitTests
|
namespace CryptoExchange.Net.UnitTests
|
||||||
{
|
{
|
||||||
@@ -242,6 +244,44 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
var result = JsonSerializer.Deserialize<STJDecimalObject>("{ \"test\": " + value + "}");
|
var result = JsonSerializer.Deserialize<STJDecimalObject>("{ \"test\": " + value + "}");
|
||||||
Assert.That(result.Test, Is.EqualTo(expected == -999 ? decimal.MaxValue : expected));
|
Assert.That(result.Test, Is.EqualTo(expected == -999 ? decimal.MaxValue : expected));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Test()]
|
||||||
|
public void TestArrayConverter()
|
||||||
|
{
|
||||||
|
var data = new Test()
|
||||||
|
{
|
||||||
|
Prop1 = 2,
|
||||||
|
Prop2 = null,
|
||||||
|
Prop3 = "123",
|
||||||
|
Prop3Again = "123",
|
||||||
|
Prop4 = null,
|
||||||
|
Prop5 = new Test2
|
||||||
|
{
|
||||||
|
Prop21 = 3,
|
||||||
|
Prop22 = "456"
|
||||||
|
},
|
||||||
|
Prop6 = new Test3
|
||||||
|
{
|
||||||
|
Prop31 = 4,
|
||||||
|
Prop32 = "789"
|
||||||
|
},
|
||||||
|
Prop7 = TestEnum.Two
|
||||||
|
};
|
||||||
|
|
||||||
|
var serialized = JsonSerializer.Serialize(data);
|
||||||
|
var deserialized = JsonSerializer.Deserialize<Test>(serialized);
|
||||||
|
|
||||||
|
Assert.That(deserialized.Prop1, Is.EqualTo(2));
|
||||||
|
Assert.That(deserialized.Prop2, Is.Null);
|
||||||
|
Assert.That(deserialized.Prop3, Is.EqualTo("123"));
|
||||||
|
Assert.That(deserialized.Prop3Again, Is.EqualTo("123"));
|
||||||
|
Assert.That(deserialized.Prop4, Is.Null);
|
||||||
|
Assert.That(deserialized.Prop5.Prop21, Is.EqualTo(3));
|
||||||
|
Assert.That(deserialized.Prop5.Prop22, Is.EqualTo("456"));
|
||||||
|
Assert.That(deserialized.Prop6.Prop31, Is.EqualTo(4));
|
||||||
|
Assert.That(deserialized.Prop6.Prop32, Is.EqualTo("789"));
|
||||||
|
Assert.That(deserialized.Prop7, Is.EqualTo(TestEnum.Two));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class STJDecimalObject
|
public class STJDecimalObject
|
||||||
@@ -281,4 +321,42 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
[JsonConverter(typeof(BoolConverter))]
|
[JsonConverter(typeof(BoolConverter))]
|
||||||
public bool Value { get; set; }
|
public bool Value { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[JsonConverter(typeof(ArrayConverter))]
|
||||||
|
record Test
|
||||||
|
{
|
||||||
|
[ArrayProperty(0)]
|
||||||
|
public int Prop1 { get; set; }
|
||||||
|
[ArrayProperty(1)]
|
||||||
|
public int? Prop2 { get; set; }
|
||||||
|
[ArrayProperty(2)]
|
||||||
|
public string Prop3 { get; set; }
|
||||||
|
[ArrayProperty(2)]
|
||||||
|
public string Prop3Again { get; set; }
|
||||||
|
[ArrayProperty(3)]
|
||||||
|
public string Prop4 { get; set; }
|
||||||
|
[ArrayProperty(4)]
|
||||||
|
public Test2 Prop5 { get; set; }
|
||||||
|
[ArrayProperty(5)]
|
||||||
|
public Test3 Prop6 { get; set; }
|
||||||
|
[ArrayProperty(6), JsonConverter(typeof(EnumConverter))]
|
||||||
|
public TestEnum? Prop7 { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonConverter(typeof(ArrayConverter))]
|
||||||
|
record Test2
|
||||||
|
{
|
||||||
|
[ArrayProperty(0)]
|
||||||
|
public int Prop21 { get; set; }
|
||||||
|
[ArrayProperty(1)]
|
||||||
|
public string Prop22 { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
record Test3
|
||||||
|
{
|
||||||
|
[JsonPropertyName("prop31")]
|
||||||
|
public int Prop31 { get; set; }
|
||||||
|
[JsonPropertyName("prop32")]
|
||||||
|
public string Prop32 { get; set; }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ using CryptoExchange.Net.Authentication;
|
|||||||
using CryptoExchange.Net.Clients;
|
using CryptoExchange.Net.Clients;
|
||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.Objects.Options;
|
using CryptoExchange.Net.Objects.Options;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
using CryptoExchange.Net.UnitTests.TestImplementations;
|
using CryptoExchange.Net.UnitTests.TestImplementations;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
@@ -19,7 +20,7 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
|
|
||||||
public TestBaseClient(): base(null, "Test")
|
public TestBaseClient(): base(null, "Test")
|
||||||
{
|
{
|
||||||
var options = TestClientOptions.Default.Copy();
|
var options = new TestClientOptions();
|
||||||
Initialize(options);
|
Initialize(options);
|
||||||
SubClient = AddApiClient(new TestSubClient(options, new RestApiOptions()));
|
SubClient = AddApiClient(new TestSubClient(options, new RestApiOptions()));
|
||||||
}
|
}
|
||||||
@@ -55,7 +56,7 @@ namespace CryptoExchange.Net.UnitTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override string FormatSymbol(string baseAsset, string quoteAsset) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||||
public override TimeSpan? GetTimeOffset() => null;
|
public override TimeSpan? GetTimeOffset() => null;
|
||||||
public override TimeSyncInfo GetTimeSyncInfo() => null;
|
public override TimeSyncInfo GetTimeSyncInfo() => null;
|
||||||
protected override AuthenticationProvider CreateAuthenticationProvider(ApiCredentials credentials) => throw new NotImplementedException();
|
protected override AuthenticationProvider CreateAuthenticationProvider(ApiCredentials credentials) => throw new NotImplementedException();
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ using System.Collections.Generic;
|
|||||||
using CryptoExchange.Net.Objects.Options;
|
using CryptoExchange.Net.Objects.Options;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using CryptoExchange.Net.Clients;
|
using CryptoExchange.Net.Clients;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.UnitTests.TestImplementations
|
namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||||
{
|
{
|
||||||
@@ -23,22 +25,17 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
|
|||||||
public TestRestApi1Client Api1 { get; }
|
public TestRestApi1Client Api1 { get; }
|
||||||
public TestRestApi2Client Api2 { get; }
|
public TestRestApi2Client Api2 { get; }
|
||||||
|
|
||||||
public TestRestClient(Action<TestClientOptions> optionsFunc) : this(optionsFunc, null)
|
public TestRestClient(Action<TestClientOptions> optionsDelegate = null)
|
||||||
|
: this(null, null, Options.Create(ApplyOptionsDelegate(optionsDelegate)))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public TestRestClient(ILoggerFactory loggerFactory = null, HttpClient httpClient = null) : this((x) => { }, httpClient, loggerFactory)
|
public TestRestClient(HttpClient httpClient, ILoggerFactory loggerFactory, IOptions<TestClientOptions> options) : base(loggerFactory, "Test")
|
||||||
{
|
{
|
||||||
}
|
Initialize(options.Value);
|
||||||
|
|
||||||
public TestRestClient(Action<TestClientOptions> optionsFunc, HttpClient httpClient = null, ILoggerFactory loggerFactory = null) : base(loggerFactory, "Test")
|
Api1 = new TestRestApi1Client(options.Value);
|
||||||
{
|
Api2 = new TestRestApi2Client(options.Value);
|
||||||
var options = TestClientOptions.Default.Copy();
|
|
||||||
optionsFunc(options);
|
|
||||||
Initialize(options);
|
|
||||||
|
|
||||||
Api1 = new TestRestApi1Client(options);
|
|
||||||
Api2 = new TestRestApi2Client(options);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SetResponse(string responseData, out IRequest requestObj)
|
public void SetResponse(string responseData, out IRequest requestObj)
|
||||||
@@ -138,7 +135,7 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override string FormatSymbol(string baseAsset, string quoteAsset) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||||
|
|
||||||
public async Task<CallResult<T>> Request<T>(CancellationToken ct = default) where T : class
|
public async Task<CallResult<T>> Request<T>(CancellationToken ct = default) where T : class
|
||||||
{
|
{
|
||||||
@@ -182,7 +179,7 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override string FormatSymbol(string baseAsset, string quoteAsset) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||||
|
|
||||||
public async Task<CallResult<T>> Request<T>(CancellationToken ct = default) where T : class
|
public async Task<CallResult<T>> Request<T>(CancellationToken ct = default) where T : class
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ using CryptoExchange.Net.UnitTests.TestImplementations.Sockets;
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using CryptoExchange.Net.Testing.Implementations;
|
using CryptoExchange.Net.Testing.Implementations;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.UnitTests.TestImplementations
|
namespace CryptoExchange.Net.UnitTests.TestImplementations
|
||||||
{
|
{
|
||||||
@@ -21,25 +23,20 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
|
|||||||
{
|
{
|
||||||
public TestSubSocketClient SubClient { get; }
|
public TestSubSocketClient SubClient { get; }
|
||||||
|
|
||||||
public TestSocketClient(ILoggerFactory loggerFactory = null) : this((x) => { }, loggerFactory)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create a new instance of KucoinSocketClient
|
/// Create a new instance of KucoinSocketClient
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="optionsFunc">Configure the options to use for this client</param>
|
/// <param name="optionsFunc">Configure the options to use for this client</param>
|
||||||
public TestSocketClient(Action<TestSocketOptions> optionsFunc) : this(optionsFunc, null)
|
public TestSocketClient(Action<TestSocketOptions> optionsDelegate = null)
|
||||||
|
: this(Options.Create(ApplyOptionsDelegate(optionsDelegate)), null)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public TestSocketClient(Action<TestSocketOptions> optionsFunc, ILoggerFactory loggerFactory = null) : base(loggerFactory, "Test")
|
public TestSocketClient(IOptions<TestSocketOptions> options, ILoggerFactory loggerFactory = null) : base(loggerFactory, "Test")
|
||||||
{
|
{
|
||||||
var options = TestSocketOptions.Default.Copy<TestSocketOptions>();
|
Initialize(options.Value);
|
||||||
optionsFunc(options);
|
|
||||||
Initialize(options);
|
|
||||||
|
|
||||||
SubClient = AddApiClient(new TestSubSocketClient(options, options.SubOptions));
|
SubClient = AddApiClient(new TestSubSocketClient(options.Value, options.Value.SubOptions));
|
||||||
SubClient.SocketFactory = new Mock<IWebsocketFactory>().Object;
|
SubClient.SocketFactory = new Mock<IWebsocketFactory>().Object;
|
||||||
Mock.Get(SubClient.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny<ILogger>(), It.IsAny<WebSocketParameters>())).Returns(new TestSocket("https://test.com"));
|
Mock.Get(SubClient.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny<ILogger>(), It.IsAny<WebSocketParameters>())).Returns(new TestSocket("https://test.com"));
|
||||||
}
|
}
|
||||||
@@ -69,7 +66,22 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
|
|||||||
Environment = new TestEnvironment("Live", "https://test.test")
|
Environment = new TestEnvironment("Live", "https://test.test")
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public TestSocketOptions()
|
||||||
|
{
|
||||||
|
Default?.Set(this);
|
||||||
|
}
|
||||||
|
|
||||||
public SocketApiOptions SubOptions { get; set; } = new SocketApiOptions();
|
public SocketApiOptions SubOptions { get; set; } = new SocketApiOptions();
|
||||||
|
|
||||||
|
internal TestSocketOptions Set(TestSocketOptions targetOptions)
|
||||||
|
{
|
||||||
|
targetOptions = base.Set<TestSocketOptions>(targetOptions);
|
||||||
|
targetOptions.SubOptions = SubOptions.Set(targetOptions.SubOptions);
|
||||||
|
return targetOptions;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class TestSubSocketClient : SocketApiClient
|
public class TestSubSocketClient : SocketApiClient
|
||||||
@@ -86,7 +98,7 @@ namespace CryptoExchange.Net.UnitTests.TestImplementations
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override string FormatSymbol(string baseAsset, string quoteAsset) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
public override string FormatSymbol(string baseAsset, string quoteAsset, TradingMode futuresType, DateTime? deliverDate = null) => $"{baseAsset.ToUpperInvariant()}{quoteAsset.ToUpperInvariant()}";
|
||||||
|
|
||||||
internal IWebsocket CreateSocketInternal(string address)
|
internal IWebsocket CreateSocketInternal(string address)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorClient", "Examples\Bl
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{5734C2A9-F12C-4754-A8B9-640C24DC4E02}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{5734C2A9-F12C-4754-A8B9-640C24DC4E02}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleClient", "Examples\ConsoleClient\ConsoleClient.csproj", "{23480C58-23BF-4EBF-A173-B7F51A043A99}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleClient", "Examples\ConsoleClient\ConsoleClient.csproj", "{23480C58-23BF-4EBF-A173-B7F51A043A99}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedClients", "Examples\SharedClients\SharedClients.csproj", "{988A87EF-EAEA-4313-A6CF-FA869813D5AB}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
@@ -35,6 +37,10 @@ Global
|
|||||||
{23480C58-23BF-4EBF-A173-B7F51A043A99}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{23480C58-23BF-4EBF-A173-B7F51A043A99}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{23480C58-23BF-4EBF-A173-B7F51A043A99}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{23480C58-23BF-4EBF-A173-B7F51A043A99}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{23480C58-23BF-4EBF-A173-B7F51A043A99}.Release|Any CPU.Build.0 = Release|Any CPU
|
{23480C58-23BF-4EBF-A173-B7F51A043A99}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{988A87EF-EAEA-4313-A6CF-FA869813D5AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{988A87EF-EAEA-4313-A6CF-FA869813D5AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{988A87EF-EAEA-4313-A6CF-FA869813D5AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{988A87EF-EAEA-4313-A6CF-FA869813D5AB}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
@@ -42,6 +48,7 @@ Global
|
|||||||
GlobalSection(NestedProjects) = preSolution
|
GlobalSection(NestedProjects) = preSolution
|
||||||
{AF4F5C19-162E-48F4-8B0B-BA5A2D7CE06A} = {5734C2A9-F12C-4754-A8B9-640C24DC4E02}
|
{AF4F5C19-162E-48F4-8B0B-BA5A2D7CE06A} = {5734C2A9-F12C-4754-A8B9-640C24DC4E02}
|
||||||
{23480C58-23BF-4EBF-A173-B7F51A043A99} = {5734C2A9-F12C-4754-A8B9-640C24DC4E02}
|
{23480C58-23BF-4EBF-A173-B7F51A043A99} = {5734C2A9-F12C-4754-A8B9-640C24DC4E02}
|
||||||
|
{988A87EF-EAEA-4313-A6CF-FA869813D5AB} = {5734C2A9-F12C-4754-A8B9-640C24DC4E02}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
SolutionGuid = {0D1B9CE9-E0B7-4B8B-88BF-6EA2CC8CA3D7}
|
SolutionGuid = {0D1B9CE9-E0B7-4B8B-88BF-6EA2CC8CA3D7}
|
||||||
|
|||||||
@@ -11,41 +11,32 @@ namespace CryptoExchange.Net.Authentication
|
|||||||
public class ApiCredentials
|
public class ApiCredentials
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The api key to authenticate requests
|
/// The api key / label to authenticate requests
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Key { get; }
|
public string Key { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The api secret to authenticate requests
|
/// The api secret or private key to authenticate requests
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Secret { get; }
|
public string Secret { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Type of the credentials
|
/// Type of the credentials
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public ApiCredentialsType CredentialType { get; }
|
public ApiCredentialsType CredentialType { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create Api credentials providing an api key and secret for authentication
|
/// Create Api credentials providing an api key and secret for authentication
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="key">The api key used for identification</param>
|
/// <param name="key">The api key / label used for identification</param>
|
||||||
/// <param name="secret">The api secret used for signing</param>
|
/// <param name="secret">The api secret or private key used for signing</param>
|
||||||
public ApiCredentials(string key, string secret) : this(key, secret, ApiCredentialsType.Hmac)
|
/// <param name="credentialType">The type of credentials</param>
|
||||||
{
|
public ApiCredentials(string key, string secret, ApiCredentialsType credentialType = ApiCredentialsType.Hmac)
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Create Api credentials providing an api key and secret for authentication
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="key">The api key used for identification</param>
|
|
||||||
/// <param name="secret">The api secret used for signing</param>
|
|
||||||
/// <param name="credentialsType">The type of credentials</param>
|
|
||||||
public ApiCredentials(string key, string secret, ApiCredentialsType credentialsType)
|
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret))
|
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret))
|
||||||
throw new ArgumentException("Key and secret can't be null/empty");
|
throw new ArgumentException("Key and secret can't be null/empty");
|
||||||
|
|
||||||
CredentialType = credentialsType;
|
CredentialType = credentialType;
|
||||||
Key = key;
|
Key = key;
|
||||||
Secret = secret;
|
Secret = secret;
|
||||||
}
|
}
|
||||||
@@ -65,7 +56,7 @@ namespace CryptoExchange.Net.Authentication
|
|||||||
/// <param name="inputStream">The stream containing the json data</param>
|
/// <param name="inputStream">The stream containing the json data</param>
|
||||||
/// <param name="identifierKey">A key to identify the credentials for the API. For example, when set to `binanceKey` the json data should contain a value for the property `binanceKey`. Defaults to 'apiKey'.</param>
|
/// <param name="identifierKey">A key to identify the credentials for the API. For example, when set to `binanceKey` the json data should contain a value for the property `binanceKey`. Defaults to 'apiKey'.</param>
|
||||||
/// <param name="identifierSecret">A key to identify the credentials for the API. For example, when set to `binanceSecret` the json data should contain a value for the property `binanceSecret`. Defaults to 'apiSecret'.</param>
|
/// <param name="identifierSecret">A key to identify the credentials for the API. For example, when set to `binanceSecret` the json data should contain a value for the property `binanceSecret`. Defaults to 'apiSecret'.</param>
|
||||||
public ApiCredentials(Stream inputStream, string? identifierKey = null, string? identifierSecret = null)
|
public static ApiCredentials FromStream(Stream inputStream, string? identifierKey = null, string? identifierSecret = null)
|
||||||
{
|
{
|
||||||
var accessor = new SystemTextJsonStreamMessageAccessor();
|
var accessor = new SystemTextJsonStreamMessageAccessor();
|
||||||
if (!accessor.Read(inputStream, false).Result)
|
if (!accessor.Read(inputStream, false).Result)
|
||||||
@@ -75,11 +66,9 @@ namespace CryptoExchange.Net.Authentication
|
|||||||
var secret = accessor.GetValue<string>(MessagePath.Get().Property(identifierSecret ?? "apiSecret"));
|
var secret = accessor.GetValue<string>(MessagePath.Get().Property(identifierSecret ?? "apiSecret"));
|
||||||
if (key == null || secret == null)
|
if (key == null || secret == null)
|
||||||
throw new ArgumentException("apiKey or apiSecret value not found in Json credential file");
|
throw new ArgumentException("apiKey or apiSecret value not found in Json credential file");
|
||||||
|
|
||||||
Key = key;
|
|
||||||
Secret = secret;
|
|
||||||
|
|
||||||
inputStream.Seek(0, SeekOrigin.Begin);
|
inputStream.Seek(0, SeekOrigin.Begin);
|
||||||
|
return new ApiCredentials(key, secret);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ namespace CryptoExchange.Net.Authentication
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get the API key of the current credentials
|
/// Get the API key of the current credentials
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string ApiKey => _credentials.Key;
|
public string ApiKey => _credentials.Key!;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// ctor
|
/// ctor
|
||||||
@@ -39,7 +39,7 @@ namespace CryptoExchange.Net.Authentication
|
|||||||
/// <param name="credentials"></param>
|
/// <param name="credentials"></param>
|
||||||
protected AuthenticationProvider(ApiCredentials credentials)
|
protected AuthenticationProvider(ApiCredentials credentials)
|
||||||
{
|
{
|
||||||
if (credentials.Secret == null)
|
if (credentials.Key == null || credentials.Secret == null)
|
||||||
throw new ArgumentException("ApiKey/Secret needed");
|
throw new ArgumentException("ApiKey/Secret needed");
|
||||||
|
|
||||||
_credentials = credentials;
|
_credentials = credentials;
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
using CryptoExchange.Net.Authentication;
|
using CryptoExchange.Net.Authentication;
|
||||||
using CryptoExchange.Net.Interfaces;
|
using CryptoExchange.Net.Interfaces;
|
||||||
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.Objects.Options;
|
using CryptoExchange.Net.Objects.Options;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Clients
|
namespace CryptoExchange.Net.Clients
|
||||||
@@ -36,6 +38,11 @@ namespace CryptoExchange.Net.Clients
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool OutputOriginalData { get; }
|
public bool OutputOriginalData { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether or not API credentials have been configured for this client. Does not check the credentials are actually valid.
|
||||||
|
/// </summary>
|
||||||
|
public bool Authenticated => ApiOptions.ApiCredentials != null || ClientOptions.ApiCredentials != null;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Api options
|
/// Api options
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -76,11 +83,12 @@ namespace CryptoExchange.Net.Clients
|
|||||||
protected abstract AuthenticationProvider CreateAuthenticationProvider(ApiCredentials credentials);
|
protected abstract AuthenticationProvider CreateAuthenticationProvider(ApiCredentials credentials);
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public abstract string FormatSymbol(string baseAsset, string quoteAsset);
|
public abstract string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverDate = null);
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void SetApiCredentials<T>(T credentials) where T : ApiCredentials
|
public void SetApiCredentials<T>(T credentials) where T : ApiCredentials
|
||||||
{
|
{
|
||||||
|
ApiOptions.ApiCredentials = credentials;
|
||||||
if (credentials != null)
|
if (credentials != null)
|
||||||
AuthenticationProvider = CreateAuthenticationProvider(credentials.Copy());
|
AuthenticationProvider = CreateAuthenticationProvider(credentials.Copy());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,28 @@ namespace CryptoExchange.Net.Clients
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public abstract class BaseClient : IDisposable
|
public abstract class BaseClient : IDisposable
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Version of the CryptoExchange.Net base library
|
||||||
|
/// </summary>
|
||||||
|
public Version CryptoExchangeLibVersion { get; } = typeof(BaseClient).Assembly.GetName().Version;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Version of the client implementation
|
||||||
|
/// </summary>
|
||||||
|
public Version ExchangeLibVersion
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock(_versionLock)
|
||||||
|
{
|
||||||
|
if (_exchangeVersion == null)
|
||||||
|
_exchangeVersion = GetType().Assembly.GetName().Version;
|
||||||
|
|
||||||
|
return _exchangeVersion;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The name of the API the client is for
|
/// The name of the API the client is for
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -27,6 +49,9 @@ namespace CryptoExchange.Net.Clients
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
protected internal ILogger _logger;
|
protected internal ILogger _logger;
|
||||||
|
|
||||||
|
private object _versionLock = new object();
|
||||||
|
private Version _exchangeVersion;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Provided client options
|
/// Provided client options
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -57,7 +82,7 @@ namespace CryptoExchange.Net.Clients
|
|||||||
throw new ArgumentNullException(nameof(options));
|
throw new ArgumentNullException(nameof(options));
|
||||||
|
|
||||||
ClientOptions = options;
|
ClientOptions = options;
|
||||||
_logger.Log(LogLevel.Trace, $"Client configuration: {options}, CryptoExchange.Net: v{typeof(BaseClient).Assembly.GetName().Version}, {Exchange}.Net: v{GetType().Assembly.GetName().Version}");
|
_logger.Log(LogLevel.Trace, $"Client configuration: {options}, CryptoExchange.Net: v{CryptoExchangeLibVersion}, {Exchange}.Net: v{ExchangeLibVersion}");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -84,6 +109,16 @@ namespace CryptoExchange.Net.Clients
|
|||||||
return apiClient;
|
return apiClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Apply the options delegate to a new options instance
|
||||||
|
/// </summary>
|
||||||
|
protected static T ApplyOptionsDelegate<T>(Action<T>? del) where T: new()
|
||||||
|
{
|
||||||
|
var opts = new T();
|
||||||
|
del?.Invoke(opts);
|
||||||
|
return opts;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Dispose
|
/// Dispose
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ using CryptoExchange.Net.RateLimiting;
|
|||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using CryptoExchange.Net.Requests;
|
using CryptoExchange.Net.Requests;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Clients
|
namespace CryptoExchange.Net.Clients
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ using CryptoExchange.Net.RateLimiting.Interfaces;
|
|||||||
using CryptoExchange.Net.Sockets;
|
using CryptoExchange.Net.Sockets;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections;
|
|
||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
@@ -73,6 +72,11 @@ namespace CryptoExchange.Net.Clients
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
protected List<DedicatedConnectionConfig> DedicatedConnectionConfigs { get; set; } = new List<DedicatedConnectionConfig>();
|
protected List<DedicatedConnectionConfig> DedicatedConnectionConfigs { get; set; } = new List<DedicatedConnectionConfig>();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether to allow multiple subscriptions with the same topic on the same connection
|
||||||
|
/// </summary>
|
||||||
|
protected bool AllowTopicsOnTheSameConnection { get; set; } = true;
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public double IncomingKbps
|
public double IncomingKbps
|
||||||
{
|
{
|
||||||
@@ -212,7 +216,7 @@ namespace CryptoExchange.Net.Clients
|
|||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
// Get a new or existing socket connection
|
// Get a new or existing socket connection
|
||||||
var socketResult = await GetSocketConnection(url, subscription.Authenticated, false).ConfigureAwait(false);
|
var socketResult = await GetSocketConnection(url, subscription.Authenticated, false, subscription.Topic).ConfigureAwait(false);
|
||||||
if (!socketResult)
|
if (!socketResult)
|
||||||
return socketResult.As<UpdateSubscription>(null);
|
return socketResult.As<UpdateSubscription>(null);
|
||||||
|
|
||||||
@@ -404,7 +408,7 @@ namespace CryptoExchange.Net.Clients
|
|||||||
return new CallResult(new NoApiCredentialsError());
|
return new CallResult(new NoApiCredentialsError());
|
||||||
|
|
||||||
_logger.AttemptingToAuthenticate(socket.SocketId);
|
_logger.AttemptingToAuthenticate(socket.SocketId);
|
||||||
var authRequest = GetAuthenticationRequest(socket);
|
var authRequest = await GetAuthenticationRequestAsync(socket).ConfigureAwait(false);
|
||||||
if (authRequest != null)
|
if (authRequest != null)
|
||||||
{
|
{
|
||||||
var result = await socket.SendAndWaitQueryAsync(authRequest).ConfigureAwait(false);
|
var result = await socket.SendAndWaitQueryAsync(authRequest).ConfigureAwait(false);
|
||||||
@@ -429,7 +433,7 @@ namespace CryptoExchange.Net.Clients
|
|||||||
/// Should return the request which can be used to authenticate a socket connection
|
/// Should return the request which can be used to authenticate a socket connection
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
protected internal virtual Query? GetAuthenticationRequest(SocketConnection connection) => throw new NotImplementedException();
|
protected internal virtual Task<Query?> GetAuthenticationRequestAsync(SocketConnection connection) => throw new NotImplementedException();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Adds a system subscription. Used for example to reply to ping requests
|
/// Adds a system subscription. Used for example to reply to ping requests
|
||||||
@@ -479,23 +483,28 @@ namespace CryptoExchange.Net.Clients
|
|||||||
/// <param name="address">The address the socket is for</param>
|
/// <param name="address">The address the socket is for</param>
|
||||||
/// <param name="authenticated">Whether the socket should be authenticated</param>
|
/// <param name="authenticated">Whether the socket should be authenticated</param>
|
||||||
/// <param name="dedicatedRequestConnection">Whether a dedicated request connection should be returned</param>
|
/// <param name="dedicatedRequestConnection">Whether a dedicated request connection should be returned</param>
|
||||||
|
/// <param name="topic">The subscription topic, can be provided when multiple of the same topics are not allowed on a connection</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
protected virtual async Task<CallResult<SocketConnection>> GetSocketConnection(string address, bool authenticated, bool dedicatedRequestConnection)
|
protected virtual async Task<CallResult<SocketConnection>> GetSocketConnection(string address, bool authenticated, bool dedicatedRequestConnection, string? topic = null)
|
||||||
{
|
{
|
||||||
var socketQuery = socketConnections.Where(s => (s.Value.Status == SocketConnection.SocketStatus.None || s.Value.Status == SocketConnection.SocketStatus.Connected)
|
var socketQuery = socketConnections.Where(s => (s.Value.Status == SocketConnection.SocketStatus.None || s.Value.Status == SocketConnection.SocketStatus.Connected)
|
||||||
&& s.Value.Tag.TrimEnd('/') == address.TrimEnd('/')
|
&& s.Value.Tag.TrimEnd('/') == address.TrimEnd('/')
|
||||||
&& s.Value.ApiClient.GetType() == GetType()
|
&& s.Value.ApiClient.GetType() == GetType()
|
||||||
&& (s.Value.Authenticated == authenticated || !authenticated)
|
&& (s.Value.Authenticated == authenticated || !authenticated)
|
||||||
|
&& (AllowTopicsOnTheSameConnection || !s.Value.Topics.Contains(topic))
|
||||||
&& s.Value.Connected);
|
&& s.Value.Connected);
|
||||||
|
|
||||||
SocketConnection connection;
|
SocketConnection connection;
|
||||||
if (!dedicatedRequestConnection)
|
if (!dedicatedRequestConnection)
|
||||||
{
|
{
|
||||||
connection = socketQuery.Where(s => !s.Value.DedicatedRequestConnection).OrderBy(s => s.Value.UserSubscriptionCount).FirstOrDefault().Value;
|
connection = socketQuery.Where(s => !s.Value.DedicatedRequestConnection.IsDedicatedRequestConnection).OrderBy(s => s.Value.UserSubscriptionCount).FirstOrDefault().Value;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
connection = socketQuery.Where(s => s.Value.DedicatedRequestConnection).FirstOrDefault().Value;
|
connection = socketQuery.Where(s => s.Value.DedicatedRequestConnection.IsDedicatedRequestConnection).FirstOrDefault().Value;
|
||||||
|
if (connection != null && !connection.DedicatedRequestConnection.Authenticated)
|
||||||
|
// Mark dedicated request connection as authenticated if the request is authenticated
|
||||||
|
connection.DedicatedRequestConnection.Authenticated = authenticated;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (connection != null)
|
if (connection != null)
|
||||||
@@ -519,7 +528,15 @@ namespace CryptoExchange.Net.Clients
|
|||||||
var socket = CreateSocket(connectionAddress.Data!);
|
var socket = CreateSocket(connectionAddress.Data!);
|
||||||
var socketConnection = new SocketConnection(_logger, this, socket, address);
|
var socketConnection = new SocketConnection(_logger, this, socket, address);
|
||||||
socketConnection.UnhandledMessage += HandleUnhandledMessage;
|
socketConnection.UnhandledMessage += HandleUnhandledMessage;
|
||||||
socketConnection.DedicatedRequestConnection = dedicatedRequestConnection;
|
socketConnection.ConnectRateLimitedAsync += HandleConnectRateLimitedAsync;
|
||||||
|
if (dedicatedRequestConnection)
|
||||||
|
{
|
||||||
|
socketConnection.DedicatedRequestConnection = new DedicatedConnectionState
|
||||||
|
{
|
||||||
|
IsDedicatedRequestConnection = dedicatedRequestConnection,
|
||||||
|
Authenticated = authenticated
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var ptg in PeriodicTaskRegistrations)
|
foreach (var ptg in PeriodicTaskRegistrations)
|
||||||
socketConnection.QueryPeriodic(ptg.Identifier, ptg.Interval, ptg.QueryDelegate, ptg.Callback);
|
socketConnection.QueryPeriodic(ptg.Identifier, ptg.Interval, ptg.QueryDelegate, ptg.Callback);
|
||||||
@@ -538,6 +555,19 @@ namespace CryptoExchange.Net.Clients
|
|||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Process connect rate limited
|
||||||
|
/// </summary>
|
||||||
|
protected async virtual Task HandleConnectRateLimitedAsync()
|
||||||
|
{
|
||||||
|
if (ClientOptions.RateLimiterEnabled && RateLimiter is not null && ClientOptions.ConnectDelayAfterRateLimited is not null)
|
||||||
|
{
|
||||||
|
var retryAfter = DateTime.UtcNow.Add(ClientOptions.ConnectDelayAfterRateLimited.Value);
|
||||||
|
_logger.AddingRetryAfterGuard(retryAfter);
|
||||||
|
await RateLimiter.SetRetryAfterGuardAsync(retryAfter, RateLimiting.RateLimitItemType.Connection).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Connect a socket
|
/// Connect a socket
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -639,7 +669,7 @@ namespace CryptoExchange.Net.Clients
|
|||||||
var tasks = new List<Task>();
|
var tasks = new List<Task>();
|
||||||
{
|
{
|
||||||
var socketList = socketConnections.Values;
|
var socketList = socketConnections.Values;
|
||||||
foreach (var connection in socketList.Where(s => !s.DedicatedRequestConnection))
|
foreach (var connection in socketList.Where(s => !s.DedicatedRequestConnection.IsDedicatedRequestConnection))
|
||||||
tasks.Add(connection.CloseAsync());
|
tasks.Add(connection.CloseAsync());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using Microsoft.Extensions.Primitives;
|
using Newtonsoft.Json;
|
||||||
using Newtonsoft.Json;
|
|
||||||
using System;
|
using System;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
|||||||
@@ -38,12 +38,67 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
private class ArrayConverterInner<T> : JsonConverter<T>
|
private class ArrayConverterInner<T> : JsonConverter<T>
|
||||||
{
|
{
|
||||||
private static readonly ConcurrentDictionary<Type, List<ArrayPropertyInfo>> _typeAttributesCache = new ConcurrentDictionary<Type, List<ArrayPropertyInfo>>();
|
private static readonly ConcurrentDictionary<Type, List<ArrayPropertyInfo>> _typeAttributesCache = new ConcurrentDictionary<Type, List<ArrayPropertyInfo>>();
|
||||||
|
private static readonly ConcurrentDictionary<Type, JsonSerializerOptions> _converterOptionsCache = new ConcurrentDictionary<Type, JsonSerializerOptions>();
|
||||||
|
|
||||||
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
|
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
|
||||||
{
|
{
|
||||||
// TODO
|
if (value == null)
|
||||||
throw new NotImplementedException();
|
{
|
||||||
|
writer.WriteNullValue();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.WriteStartArray();
|
||||||
|
|
||||||
|
var valueType = value.GetType();
|
||||||
|
if (!_typeAttributesCache.TryGetValue(valueType, out var typeAttributes))
|
||||||
|
typeAttributes = CacheTypeAttributes(valueType);
|
||||||
|
|
||||||
|
var ordered = typeAttributes.Where(x => x.ArrayProperty != null).OrderBy(p => p.ArrayProperty.Index);
|
||||||
|
var last = -1;
|
||||||
|
foreach (var prop in ordered)
|
||||||
|
{
|
||||||
|
if (prop.ArrayProperty.Index == last)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
while (prop.ArrayProperty.Index != last + 1)
|
||||||
|
{
|
||||||
|
writer.WriteNullValue();
|
||||||
|
last += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
last = prop.ArrayProperty.Index;
|
||||||
|
|
||||||
|
var objValue = prop.PropertyInfo.GetValue(value);
|
||||||
|
if (objValue == null)
|
||||||
|
{
|
||||||
|
writer.WriteNullValue();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonSerializerOptions? typeOptions = null;
|
||||||
|
if (prop.JsonConverterType != null)
|
||||||
|
{
|
||||||
|
var converter = (JsonConverter)Activator.CreateInstance(prop.JsonConverterType);
|
||||||
|
typeOptions = new JsonSerializerOptions();
|
||||||
|
typeOptions.Converters.Clear();
|
||||||
|
typeOptions.Converters.Add(converter);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (prop.JsonConverterType == null && IsSimple(prop.PropertyInfo.PropertyType))
|
||||||
|
{
|
||||||
|
if (prop.PropertyInfo.PropertyType == typeof(string))
|
||||||
|
writer.WriteStringValue(Convert.ToString(objValue, CultureInfo.InvariantCulture));
|
||||||
|
else
|
||||||
|
writer.WriteRawValue(Convert.ToString(objValue, CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
JsonSerializer.Serialize(writer, objValue, typeOptions ?? options);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.WriteEndArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@@ -53,7 +108,20 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
return default;
|
return default;
|
||||||
|
|
||||||
var result = Activator.CreateInstance(typeToConvert);
|
var result = Activator.CreateInstance(typeToConvert);
|
||||||
return (T)ParseObject(ref reader, result, typeToConvert);
|
return (T)ParseObject(ref reader, result, typeToConvert, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSimple(Type type)
|
||||||
|
{
|
||||||
|
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
|
||||||
|
{
|
||||||
|
// nullable type, check if the nested type is simple.
|
||||||
|
return IsSimple(type.GetGenericArguments()[0]);
|
||||||
|
}
|
||||||
|
return type.IsPrimitive
|
||||||
|
|| type.IsEnum
|
||||||
|
|| type == typeof(string)
|
||||||
|
|| type == typeof(decimal);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<ArrayPropertyInfo> CacheTypeAttributes(Type type)
|
private static List<ArrayPropertyInfo> CacheTypeAttributes(Type type)
|
||||||
@@ -71,7 +139,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
ArrayProperty = att,
|
ArrayProperty = att,
|
||||||
PropertyInfo = property,
|
PropertyInfo = property,
|
||||||
DefaultDeserialization = property.GetCustomAttribute<JsonConversionAttribute>() != null,
|
DefaultDeserialization = property.GetCustomAttribute<JsonConversionAttribute>() != null,
|
||||||
JsonConverterType = property.GetCustomAttribute<JsonConverterAttribute>()?.ConverterType,
|
JsonConverterType = property.GetCustomAttribute<JsonConverterAttribute>()?.ConverterType ?? property.PropertyType.GetCustomAttribute<JsonConverterAttribute>()?.ConverterType,
|
||||||
TargetType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType
|
TargetType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -80,7 +148,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
return attributes;
|
return attributes;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static object ParseObject(ref Utf8JsonReader reader, object result, Type objectType)
|
private static object ParseObject(ref Utf8JsonReader reader, object result, Type objectType, JsonSerializerOptions options)
|
||||||
{
|
{
|
||||||
if (reader.TokenType != JsonTokenType.StartArray)
|
if (reader.TokenType != JsonTokenType.StartArray)
|
||||||
throw new Exception("Not an array");
|
throw new Exception("Not an array");
|
||||||
@@ -94,42 +162,58 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
if (reader.TokenType == JsonTokenType.EndArray)
|
if (reader.TokenType == JsonTokenType.EndArray)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
var attribute = attributes.SingleOrDefault(a => a.ArrayProperty.Index == index);
|
var indexAttributes = attributes.Where(a => a.ArrayProperty.Index == index);
|
||||||
if (attribute == null)
|
if (!indexAttributes.Any())
|
||||||
{
|
{
|
||||||
index++;
|
index++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
var targetType = attribute.TargetType;
|
foreach (var attribute in indexAttributes)
|
||||||
object? value = null;
|
|
||||||
if (attribute.JsonConverterType != null)
|
|
||||||
{
|
{
|
||||||
// Has JsonConverter attribute
|
var targetType = attribute.TargetType;
|
||||||
var options = new JsonSerializerOptions();
|
object? value = null;
|
||||||
options.Converters.Add((JsonConverter)Activator.CreateInstance(attribute.JsonConverterType));
|
if (attribute.JsonConverterType != null)
|
||||||
value = JsonDocument.ParseValue(ref reader).Deserialize(targetType, options);
|
|
||||||
}
|
|
||||||
else if (attribute.DefaultDeserialization)
|
|
||||||
{
|
|
||||||
// Use default deserialization
|
|
||||||
value = JsonDocument.ParseValue(ref reader).Deserialize(targetType);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
value = reader.TokenType switch
|
|
||||||
{
|
{
|
||||||
JsonTokenType.Null => null,
|
if (!_converterOptionsCache.TryGetValue(attribute.JsonConverterType, out var newOptions))
|
||||||
JsonTokenType.False => false,
|
{
|
||||||
JsonTokenType.True => true,
|
var converter = (JsonConverter)Activator.CreateInstance(attribute.JsonConverterType);
|
||||||
JsonTokenType.String => reader.GetString(),
|
newOptions = new JsonSerializerOptions
|
||||||
JsonTokenType.Number => reader.GetDecimal(),
|
{
|
||||||
_ => throw new NotImplementedException($"Array deserialization of type {reader.TokenType} not supported"),
|
NumberHandling = SerializerOptions.WithConverters.NumberHandling,
|
||||||
};
|
PropertyNameCaseInsensitive = SerializerOptions.WithConverters.PropertyNameCaseInsensitive,
|
||||||
|
Converters = { converter },
|
||||||
|
};
|
||||||
|
_converterOptionsCache.TryAdd(attribute.JsonConverterType, newOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
value = JsonDocument.ParseValue(ref reader).Deserialize(targetType, newOptions);
|
||||||
|
}
|
||||||
|
else if (attribute.DefaultDeserialization)
|
||||||
|
{
|
||||||
|
// Use default deserialization
|
||||||
|
value = JsonDocument.ParseValue(ref reader).Deserialize(targetType, options);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
value = reader.TokenType switch
|
||||||
|
{
|
||||||
|
JsonTokenType.Null => null,
|
||||||
|
JsonTokenType.False => false,
|
||||||
|
JsonTokenType.True => true,
|
||||||
|
JsonTokenType.String => reader.GetString(),
|
||||||
|
JsonTokenType.Number => reader.GetDecimal(),
|
||||||
|
JsonTokenType.StartObject => JsonSerializer.Deserialize(ref reader, attribute.TargetType, options),
|
||||||
|
_ => throw new NotImplementedException($"Array deserialization of type {reader.TokenType} not supported"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetType.IsAssignableFrom(value?.GetType()))
|
||||||
|
attribute.PropertyInfo.SetValue(result, value == null ? null : value);
|
||||||
|
else
|
||||||
|
attribute.PropertyInfo.SetValue(result, value == null ? null : Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture));
|
||||||
}
|
}
|
||||||
|
|
||||||
attribute.PropertyInfo.SetValue(result, value == null ? null : Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture));
|
|
||||||
|
|
||||||
index++;
|
index++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using Microsoft.Extensions.Primitives;
|
using System;
|
||||||
using System;
|
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
@@ -58,6 +57,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
var stringValue = reader.GetString();
|
var stringValue = reader.GetString();
|
||||||
if (string.IsNullOrWhiteSpace(stringValue)
|
if (string.IsNullOrWhiteSpace(stringValue)
|
||||||
|| stringValue == "-1"
|
|| stringValue == "-1"
|
||||||
|
|| stringValue == "0001-01-01T00:00:00Z"
|
||||||
|| double.TryParse(stringValue, out var doubleVal) && doubleVal == 0)
|
|| double.TryParse(stringValue, out var doubleVal) && doubleVal == 0)
|
||||||
{
|
{
|
||||||
return default;
|
return default;
|
||||||
|
|||||||
@@ -19,9 +19,13 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
if (reader.TokenType == JsonTokenType.String)
|
if (reader.TokenType == JsonTokenType.String)
|
||||||
{
|
{
|
||||||
var value = reader.GetString();
|
var value = reader.GetString();
|
||||||
if (string.IsNullOrEmpty(value) || string.Equals("null", value))
|
if (string.IsNullOrEmpty(value) || string.Equals("null", value, StringComparison.OrdinalIgnoreCase))
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
|
if (string.Equals("Infinity", value, StringComparison.Ordinal))
|
||||||
|
// Infinity returned by the server, default to max value
|
||||||
|
return decimal.MaxValue;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return decimal.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);
|
return decimal.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Globalization;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
@@ -24,7 +23,14 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
return reader.GetDecimal().ToString();
|
return reader.GetDecimal().ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
return reader.GetString();
|
try
|
||||||
|
{
|
||||||
|
return reader.GetString();
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Diagnostics;
|
|
||||||
using System.Runtime.Serialization;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Globalization;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Converters.SystemTextJson
|
namespace CryptoExchange.Net.Converters.SystemTextJson
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -50,6 +50,11 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
var info = $"Deserialize JsonException: {ex.Message}, Path: {ex.Path}, LineNumber: {ex.LineNumber}, LinePosition: {ex.BytePositionInLine}";
|
var info = $"Deserialize JsonException: {ex.Message}, Path: {ex.Path}, LineNumber: {ex.LineNumber}, LinePosition: {ex.BytePositionInLine}";
|
||||||
return new CallResult<object>(new DeserializeError(info, OriginalDataAvailable ? GetOriginalString() : "[Data only available when OutputOriginal = true in client options]"));
|
return new CallResult<object>(new DeserializeError(info, OriginalDataAvailable ? GetOriginalString() : "[Data only available when OutputOriginal = true in client options]"));
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
var info = $"Deserialize unknown Exception: {ex.Message}";
|
||||||
|
return new CallResult<object>(new DeserializeError(info, OriginalDataAvailable ? GetOriginalString() : "[Data only available when OutputOriginal = true in client options]"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@@ -121,7 +126,14 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
return default;
|
return default;
|
||||||
|
|
||||||
if (value.Value.ValueKind == JsonValueKind.Object || value.Value.ValueKind == JsonValueKind.Array)
|
if (value.Value.ValueKind == JsonValueKind.Object || value.Value.ValueKind == JsonValueKind.Array)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return value.Value.Deserialize<T>(_serializerOptions);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
return default;
|
return default;
|
||||||
|
}
|
||||||
|
|
||||||
if (typeof(T) == typeof(string))
|
if (typeof(T) == typeof(string))
|
||||||
{
|
{
|
||||||
@@ -133,7 +145,20 @@ namespace CryptoExchange.Net.Converters.SystemTextJson
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public List<T?>? GetValues<T>(MessagePath path) => throw new NotImplementedException();
|
public List<T?>? GetValues<T>(MessagePath path)
|
||||||
|
{
|
||||||
|
if (!IsJson)
|
||||||
|
throw new InvalidOperationException("Can't access json data on non-json message");
|
||||||
|
|
||||||
|
var value = GetPathNode(path);
|
||||||
|
if (value == null)
|
||||||
|
return default;
|
||||||
|
|
||||||
|
if (value.Value.ValueKind != JsonValueKind.Array)
|
||||||
|
return default;
|
||||||
|
|
||||||
|
return value.Value.Deserialize<List<T>>()!;
|
||||||
|
}
|
||||||
|
|
||||||
private JsonElement? GetPathNode(MessagePath path)
|
private JsonElement? GetPathNode(MessagePath path)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,9 +6,9 @@
|
|||||||
<PackageId>CryptoExchange.Net</PackageId>
|
<PackageId>CryptoExchange.Net</PackageId>
|
||||||
<Authors>JKorf</Authors>
|
<Authors>JKorf</Authors>
|
||||||
<Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description>
|
<Description>CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.</Description>
|
||||||
<PackageVersion>7.11.0</PackageVersion>
|
<PackageVersion>8.3.0</PackageVersion>
|
||||||
<AssemblyVersion>7.11.0</AssemblyVersion>
|
<AssemblyVersion>8.3.0</AssemblyVersion>
|
||||||
<FileVersion>7.11.0</FileVersion>
|
<FileVersion>8.3.0</FileVersion>
|
||||||
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
|
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
|
||||||
<PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange</PackageTags>
|
<PackageTags>OKX;OKX.Net;Mexc;Mexc.Net;Kucoin;Kucoin.Net;Kraken;Kraken.Net;Huobi;Huobi.Net;CoinEx;CoinEx.Net;Bybit;Bybit.Net;Bitget;Bitget.Net;Bitfinex;Bitfinex.Net;Binance;Binance.Net;CryptoCurrency;CryptoCurrency Exchange</PackageTags>
|
||||||
<RepositoryType>git</RepositoryType>
|
<RepositoryType>git</RepositoryType>
|
||||||
@@ -35,7 +35,7 @@
|
|||||||
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
|
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup Label="Deterministic Build" Condition="'$(Configuration)' == 'Release'">
|
<ItemGroup Label="Deterministic Build" Condition="'$(Configuration)' == 'Release'">
|
||||||
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0">
|
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
@@ -52,12 +52,13 @@
|
|||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
|
||||||
<PackageReference Include="System.Text.Json" Version="8.0.4" />
|
<PackageReference Include="System.Text.Json" Version="8.0.5" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace CryptoExchange.Net
|
namespace CryptoExchange.Net
|
||||||
{
|
{
|
||||||
@@ -12,6 +16,22 @@ namespace CryptoExchange.Net
|
|||||||
{
|
{
|
||||||
private const string _allowedRandomChars = "ABCDEFGHIJKLMONOPQRSTUVWXYZabcdefghijklmonopqrstuvwxyz0123456789";
|
private const string _allowedRandomChars = "ABCDEFGHIJKLMONOPQRSTUVWXYZabcdefghijklmonopqrstuvwxyz0123456789";
|
||||||
|
|
||||||
|
private static readonly Dictionary<int, string> _monthSymbols = new Dictionary<int, string>()
|
||||||
|
{
|
||||||
|
{ 1, "F" },
|
||||||
|
{ 2, "G" },
|
||||||
|
{ 3, "H" },
|
||||||
|
{ 4, "J" },
|
||||||
|
{ 5, "K" },
|
||||||
|
{ 6, "M" },
|
||||||
|
{ 7, "N" },
|
||||||
|
{ 8, "Q" },
|
||||||
|
{ 9, "U" },
|
||||||
|
{ 10, "V" },
|
||||||
|
{ 11, "X" },
|
||||||
|
{ 12, "Z" },
|
||||||
|
};
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The last used id, use NextId() to get the next id and up this
|
/// The last used id, use NextId() to get the next id and up this
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -55,6 +75,11 @@ namespace CryptoExchange.Net
|
|||||||
{
|
{
|
||||||
value -= offset;
|
value -= offset;
|
||||||
}
|
}
|
||||||
|
else if(roundingType == RoundingType.Up)
|
||||||
|
{
|
||||||
|
if (offset != 0)
|
||||||
|
value += (step.Value - offset);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (offset < step / 2)
|
if (offset < step / 2)
|
||||||
@@ -107,17 +132,23 @@ namespace CryptoExchange.Net
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Rounds a value down to
|
/// Rounds a value down
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="i"></param>
|
|
||||||
/// <param name="decimalPlaces"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public static decimal RoundDown(decimal i, double decimalPlaces)
|
public static decimal RoundDown(decimal i, double decimalPlaces)
|
||||||
{
|
{
|
||||||
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
|
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
|
||||||
return Math.Floor(i * power) / power;
|
return Math.Floor(i * power) / power;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Rounds a value up
|
||||||
|
/// </summary>
|
||||||
|
public static decimal RoundUp(decimal i, double decimalPlaces)
|
||||||
|
{
|
||||||
|
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
|
||||||
|
return Math.Ceiling(i * power) / power;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Strips any trailing zero's of a decimal value, useful when converting the value to string.
|
/// Strips any trailing zero's of a decimal value, useful when converting the value to string.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -177,5 +208,70 @@ namespace CryptoExchange.Net
|
|||||||
|
|
||||||
return source + RandomString(totalLength - source.Length);
|
return source + RandomString(totalLength - source.Length);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get the month representation for futures symbol based on the delivery month
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="time">Delivery time</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static string GetDeliveryMonthSymbol(DateTime time) => _monthSymbols[time.Month];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Execute multiple requests to retrieve multiple pages of the result set
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">Type of the client</typeparam>
|
||||||
|
/// <typeparam name="U">Type of the request</typeparam>
|
||||||
|
/// <param name="paginatedFunc">The func to execute with each request</param>
|
||||||
|
/// <param name="request">The request parameters</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static async IAsyncEnumerable<ExchangeWebResult<IEnumerable<T>>> ExecutePages<T, U>(Func<U, INextPageToken?, CancellationToken, Task<ExchangeWebResult<IEnumerable<T>>>> paginatedFunc, U request, [EnumeratorCancellation]CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var result = new List<T>();
|
||||||
|
ExchangeWebResult<IEnumerable<T>> batch;
|
||||||
|
INextPageToken? nextPageToken = null;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
batch = await paginatedFunc(request, nextPageToken, ct).ConfigureAwait(false);
|
||||||
|
yield return batch;
|
||||||
|
if (!batch || ct.IsCancellationRequested)
|
||||||
|
break;
|
||||||
|
|
||||||
|
result.AddRange(batch.Data);
|
||||||
|
nextPageToken = batch.NextPageToken;
|
||||||
|
if (nextPageToken == null)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Apply the rules (price and quantity step size and decimals precision, min/max quantity) from the symbol to the quantity and price
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="symbol">The symbol as retrieved from the exchange</param>
|
||||||
|
/// <param name="quantity">Quantity to trade</param>
|
||||||
|
/// <param name="price">Price to trade at</param>
|
||||||
|
/// <param name="adjustedQuantity">Quantity adjusted to match all trading rules</param>
|
||||||
|
/// <param name="adjustedPrice">Price adjusted to match all trading rules</param>
|
||||||
|
public static void ApplySymbolRules(SharedSpotSymbol symbol, decimal quantity, decimal? price, out decimal adjustedQuantity, out decimal? adjustedPrice)
|
||||||
|
{
|
||||||
|
adjustedPrice = price;
|
||||||
|
adjustedQuantity = quantity;
|
||||||
|
var minNotionalAdjust = false;
|
||||||
|
|
||||||
|
if (price != null)
|
||||||
|
{
|
||||||
|
adjustedPrice = AdjustValueStep(0, decimal.MaxValue, symbol.PriceStep, RoundingType.Down, price.Value);
|
||||||
|
adjustedPrice = symbol.PriceDecimals.HasValue ? RoundDown(price.Value, symbol.PriceDecimals.Value) : adjustedPrice;
|
||||||
|
if (adjustedPrice != 0 && adjustedPrice * quantity < symbol.MinNotionalValue)
|
||||||
|
{
|
||||||
|
adjustedQuantity = symbol.MinNotionalValue.Value / adjustedPrice.Value;
|
||||||
|
minNotionalAdjust = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
adjustedQuantity = AdjustValueStep(symbol.MinTradeQuantity ?? 0, symbol.MaxTradeQuantity ?? decimal.MaxValue, symbol.QuantityStep, minNotionalAdjust ? RoundingType.Up : RoundingType.Down, adjustedQuantity);
|
||||||
|
adjustedQuantity = symbol.QuantityDecimals.HasValue ? (minNotionalAdjust ? RoundUp(adjustedQuantity, symbol.QuantityDecimals.Value) : RoundDown(adjustedQuantity, symbol.QuantityDecimals.Value)) : adjustedQuantity;
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,12 @@ using System.IO.Compression;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using System.Security;
|
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Web;
|
using System.Web;
|
||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
|
|
||||||
namespace CryptoExchange.Net
|
namespace CryptoExchange.Net
|
||||||
{
|
{
|
||||||
@@ -188,6 +189,16 @@ namespace CryptoExchange.Net
|
|||||||
throw new ArgumentException($"No values provided for parameter {argumentName}", argumentName);
|
throw new ArgumentException($"No values provided for parameter {argumentName}", argumentName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Format a string to RFC3339/ISO8601 string
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="dateTime"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static string ToRfc3339String(this DateTime dateTime)
|
||||||
|
{
|
||||||
|
return dateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Format an exception and inner exception to a readable string
|
/// Format an exception and inner exception to a readable string
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -378,6 +389,116 @@ namespace CryptoExchange.Net
|
|||||||
output.Position = 0;
|
output.Position = 0;
|
||||||
return new ReadOnlyMemory<byte>(output.GetBuffer(), 0, (int)output.Length);
|
return new ReadOnlyMemory<byte>(output.GetBuffer(), 0, (int)output.Length);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the trading mode is linear
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsLinear(this TradingMode type) => type == TradingMode.PerpetualLinear || type == TradingMode.DeliveryLinear;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the trading mode is inverse
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsInverse(this TradingMode type) => type == TradingMode.PerpetualInverse || type == TradingMode.DeliveryInverse;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the trading mode is perpetual
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsPerpetual(this TradingMode type) => type == TradingMode.PerpetualInverse || type == TradingMode.PerpetualLinear;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the trading mode is delivery
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsDelivery(this TradingMode type) => type == TradingMode.DeliveryInverse || type == TradingMode.DeliveryLinear;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register rest client interfaces
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection RegisterSharedRestInterfaces<T>(this IServiceCollection services, Func<IServiceProvider, T> client)
|
||||||
|
{
|
||||||
|
if (typeof(IAssetsRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IAssetsRestClient)client(x)!);
|
||||||
|
if (typeof(IBalanceRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IBalanceRestClient)client(x)!);
|
||||||
|
if (typeof(IDepositRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IDepositRestClient)client(x)!);
|
||||||
|
if (typeof(IKlineRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IKlineRestClient)client(x)!);
|
||||||
|
if (typeof(IListenKeyRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IListenKeyRestClient)client(x)!);
|
||||||
|
if (typeof(IOrderBookRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IOrderBookRestClient)client(x)!);
|
||||||
|
if (typeof(IRecentTradeRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IRecentTradeRestClient)client(x)!);
|
||||||
|
if (typeof(ITradeHistoryRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ITradeHistoryRestClient)client(x)!);
|
||||||
|
if (typeof(IWithdrawalRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IWithdrawalRestClient)client(x)!);
|
||||||
|
if (typeof(IWithdrawRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IWithdrawRestClient)client(x)!);
|
||||||
|
|
||||||
|
if (typeof(ISpotOrderRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ISpotOrderRestClient)client(x)!);
|
||||||
|
if (typeof(ISpotSymbolRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ISpotSymbolRestClient)client(x)!);
|
||||||
|
if (typeof(ISpotTickerRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ISpotTickerRestClient)client(x)!);
|
||||||
|
|
||||||
|
if (typeof(IFundingRateRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IFundingRateRestClient)client(x)!);
|
||||||
|
if (typeof(IFuturesOrderRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IFuturesOrderRestClient)client(x)!);
|
||||||
|
if (typeof(IFuturesSymbolRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IFuturesSymbolRestClient)client(x)!);
|
||||||
|
if (typeof(IFuturesTickerRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IFuturesTickerRestClient)client(x)!);
|
||||||
|
if (typeof(IIndexPriceKlineRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IIndexPriceKlineRestClient)client(x)!);
|
||||||
|
if (typeof(ILeverageRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ILeverageRestClient)client(x)!);
|
||||||
|
if (typeof(IMarkPriceKlineRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IMarkPriceKlineRestClient)client(x)!);
|
||||||
|
if (typeof(IOpenInterestRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IOpenInterestRestClient)client(x)!);
|
||||||
|
if (typeof(IPositionHistoryRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IPositionHistoryRestClient)client(x)!);
|
||||||
|
if (typeof(IPositionModeRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IPositionModeRestClient)client(x)!);
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register socket client interfaces
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection RegisterSharedSocketInterfaces<T>(this IServiceCollection services, Func<IServiceProvider, T> client)
|
||||||
|
{
|
||||||
|
if (typeof(IBalanceSocketClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IBalanceSocketClient)client(x)!);
|
||||||
|
if (typeof(IBookTickerSocketClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IBookTickerSocketClient)client(x)!);
|
||||||
|
if (typeof(IKlineSocketClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IKlineSocketClient)client(x)!);
|
||||||
|
if (typeof(IOrderBookRestClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IOrderBookRestClient)client(x)!);
|
||||||
|
if (typeof(ITickerSocketClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ITickerSocketClient)client(x)!);
|
||||||
|
if (typeof(ITickersSocketClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ITickersSocketClient)client(x)!);
|
||||||
|
if (typeof(ITradeSocketClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ITradeSocketClient)client(x)!);
|
||||||
|
if (typeof(IUserTradeSocketClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (IUserTradeSocketClient)client(x)!);
|
||||||
|
|
||||||
|
if (typeof(ISpotOrderSocketClient).IsAssignableFrom(typeof(T)))
|
||||||
|
services.AddTransient(x => (ISpotOrderSocketClient)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)!);
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,131 +8,87 @@ using System.Threading.Tasks;
|
|||||||
namespace CryptoExchange.Net.Interfaces.CommonClients
|
namespace CryptoExchange.Net.Interfaces.CommonClients
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Common rest client endpoints
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IBaseRestClient
|
public interface IBaseRestClient
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The name of the exchange
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
string ExchangeName { get; }
|
string ExchangeName { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Should be triggered on order placing
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
event Action<OrderId> OnOrderPlaced;
|
event Action<OrderId> OnOrderPlaced;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Should be triggered on order cancelling
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
event Action<OrderId> OnOrderCanceled;
|
event Action<OrderId> OnOrderCanceled;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get the symbol name based on a base and quote asset
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="baseAsset">The base asset</param>
|
|
||||||
/// <param name="quoteAsset">The quote asset</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
string GetSymbolName(string baseAsset, string quoteAsset);
|
string GetSymbolName(string baseAsset, string quoteAsset);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get a list of symbols for the exchange
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<Symbol>>> GetSymbolsAsync(CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<Symbol>>> GetSymbolsAsync(CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get a ticker for the exchange
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbol">The symbol to get klines for</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<Ticker>> GetTickerAsync(string symbol, CancellationToken ct = default);
|
Task<WebCallResult<Ticker>> GetTickerAsync(string symbol, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get a list of tickers for the exchange
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<Ticker>>> GetTickersAsync(CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<Ticker>>> GetTickersAsync(CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get a list of candles for a given symbol on the exchange
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbol">The symbol to retrieve the candles for</param>
|
|
||||||
/// <param name="timespan">The timespan to retrieve the candles for. The supported value are dependent on the exchange</param>
|
|
||||||
/// <param name="startTime">[Optional] Start time to retrieve klines for</param>
|
|
||||||
/// <param name="endTime">[Optional] End time to retrieve klines for</param>
|
|
||||||
/// <param name="limit">[Optional] Max number of results</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<Kline>>> GetKlinesAsync(string symbol, TimeSpan timespan, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<Kline>>> GetKlinesAsync(string symbol, TimeSpan timespan, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get the order book for a symbol
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbol">The symbol to get the book for</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<CommonObjects.OrderBook>> GetOrderBookAsync(string symbol, CancellationToken ct = default);
|
Task<WebCallResult<CommonObjects.OrderBook>> GetOrderBookAsync(string symbol, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The recent trades for a symbol
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbol">The symbol to get the trades for</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<Trade>>> GetRecentTradesAsync(string symbol, CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<Trade>>> GetRecentTradesAsync(string symbol, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get balances
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="accountId">[Optional] The account id to retrieve balances for, required for some exchanges, ignored otherwise</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<Balance>>> GetBalancesAsync(string? accountId = null, CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<Balance>>> GetBalancesAsync(string? accountId = null, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get an order by id
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="orderId">The id</param>
|
|
||||||
/// <param name="symbol">[Optional] The symbol the order is on, required for some exchanges, ignored otherwise</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<Order>> GetOrderAsync(string orderId, string? symbol = null, CancellationToken ct = default);
|
Task<WebCallResult<Order>> GetOrderAsync(string orderId, string? symbol = null, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get trades for an order by id
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="orderId">The id</param>
|
|
||||||
/// <param name="symbol">[Optional] The symbol the order is on, required for some exchanges, ignored otherwise</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<UserTrade>>> GetOrderTradesAsync(string orderId, string? symbol = null, CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<UserTrade>>> GetOrderTradesAsync(string orderId, string? symbol = null, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get a list of open orders
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbol">[Optional] The symbol to get open orders for, required for some exchanges, ignored otherwise</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<Order>>> GetOpenOrdersAsync(string? symbol = null, CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<Order>>> GetOpenOrdersAsync(string? symbol = null, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get a list of closed orders
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbol">[Optional] The symbol to get closed orders for, required for some exchanges, ignored otherwise</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<Order>>> GetClosedOrdersAsync(string? symbol = null, CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<Order>>> GetClosedOrdersAsync(string? symbol = null, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Cancel an order by id
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="orderId">The id</param>
|
|
||||||
/// <param name="symbol">[Optional] The symbol the order is on, required for some exchanges, ignored otherwise</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<OrderId>> CancelOrderAsync(string orderId, string? symbol = null, CancellationToken ct = default);
|
Task<WebCallResult<OrderId>> CancelOrderAsync(string orderId, string? symbol = null, CancellationToken ct = default);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,30 +7,18 @@ using CryptoExchange.Net.Objects;
|
|||||||
namespace CryptoExchange.Net.Interfaces.CommonClients
|
namespace CryptoExchange.Net.Interfaces.CommonClients
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Common futures endpoints
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IFuturesClient : IBaseRestClient
|
public interface IFuturesClient : IBaseRestClient
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Place an order
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbol">The symbol the order is for</param>
|
|
||||||
/// <param name="side">The side of the order</param>
|
|
||||||
/// <param name="type">The type of the order</param>
|
|
||||||
/// <param name="quantity">The quantity of the order</param>
|
|
||||||
/// <param name="price">The price of the order, only for limit orders</param>
|
|
||||||
/// <param name="accountId">[Optional] The account id to place the order on, required for some exchanges, ignored otherwise</param>
|
|
||||||
/// <param name="leverage">[Optional] Leverage for this order. This is needed for some exchanges. For exchanges where this is not needed this parameter is ignored (and should be set before hand)</param>
|
|
||||||
/// <param name="clientOrderId">[Optional] Client specified id for this order</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns>The id of the resulting order</returns>
|
|
||||||
Task<WebCallResult<OrderId>> PlaceOrderAsync(string symbol, CommonOrderSide side, CommonOrderType type, decimal quantity, decimal? price = null, int? leverage = null, string? accountId = null, string? clientOrderId = null, CancellationToken ct = default);
|
Task<WebCallResult<OrderId>> PlaceOrderAsync(string symbol, CommonOrderSide side, CommonOrderType type, decimal quantity, decimal? price = null, int? leverage = null, string? accountId = null, string? clientOrderId = null, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get position
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task<WebCallResult<IEnumerable<Position>>> GetPositionsAsync(CancellationToken ct = default);
|
Task<WebCallResult<IEnumerable<Position>>> GetPositionsAsync(CancellationToken ct = default);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,22 +6,13 @@ using System.Threading.Tasks;
|
|||||||
namespace CryptoExchange.Net.Interfaces.CommonClients
|
namespace CryptoExchange.Net.Interfaces.CommonClients
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Common spot endpoints
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface ISpotClient: IBaseRestClient
|
public interface ISpotClient: IBaseRestClient
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Place an order
|
/// DEPRECATED; use <see cref="SharedApis.ISharedClient" /> instead for common/shared functionality. See <see href="https://jkorf.github.io/CryptoExchange.Net/docs/index.html#shared" /> for more info.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbol">The symbol the order is for</param>
|
|
||||||
/// <param name="side">The side of the order</param>
|
|
||||||
/// <param name="type">The type of the order</param>
|
|
||||||
/// <param name="quantity">The quantity of the order</param>
|
|
||||||
/// <param name="price">The price of the order, only for limit orders</param>
|
|
||||||
/// <param name="accountId">[Optional] The account id to place the order on, required for some exchanges, ignored otherwise</param>
|
|
||||||
/// <param name="clientOrderId">[Optional] Client specified id for this order</param>
|
|
||||||
/// <param name="ct">[Optional] Cancellation token for cancelling the request</param>
|
|
||||||
/// <returns>The id of the resulting order</returns>
|
|
||||||
Task<WebCallResult<OrderId>> PlaceOrderAsync(string symbol, CommonOrderSide side, CommonOrderType type, decimal quantity, decimal? price = null, string? accountId = null, string? clientOrderId = null, CancellationToken ct = default);
|
Task<WebCallResult<OrderId>> PlaceOrderAsync(string symbol, CommonOrderSide side, CommonOrderType type, decimal quantity, decimal? price = null, string? accountId = null, string? clientOrderId = null, CancellationToken ct = default);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
using CryptoExchange.Net.Authentication;
|
using CryptoExchange.Net.Authentication;
|
||||||
|
using CryptoExchange.Net.Objects;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
|
using System;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Interfaces
|
namespace CryptoExchange.Net.Interfaces
|
||||||
{
|
{
|
||||||
@@ -17,8 +20,10 @@ namespace CryptoExchange.Net.Interfaces
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="baseAsset">The base asset</param>
|
/// <param name="baseAsset">The base asset</param>
|
||||||
/// <param name="quoteAsset">The quote asset</param>
|
/// <param name="quoteAsset">The quote asset</param>
|
||||||
|
/// <param name="tradingMode">The trading mode</param>
|
||||||
|
/// <param name="deliverDate">The deliver date for a delivery futures symbol</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
string FormatSymbol(string baseAsset, string quoteAsset);
|
string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverDate = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Set the API credentials for this API client
|
/// Set the API credentials for this API client
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using CryptoExchange.Net.Objects.Options;
|
using CryptoExchange.Net.Objects.Options;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Interfaces
|
namespace CryptoExchange.Net.Interfaces
|
||||||
@@ -23,5 +24,12 @@ namespace CryptoExchange.Net.Interfaces
|
|||||||
/// <param name="options">Options for the order book</param>
|
/// <param name="options">Options for the order book</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public ISymbolOrderBook Create(string baseAsset, string quoteAsset, Action<TOptions>? options = null);
|
public ISymbolOrderBook Create(string baseAsset, string quoteAsset, Action<TOptions>? options = null);
|
||||||
|
/// <summary>
|
||||||
|
/// Create a new order book by base and quote asset names
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="symbol">Symbol</param>
|
||||||
|
/// <param name="options">Options for the order book</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ISymbolOrderBook Create(SharedSymbol symbol, Action<TOptions>? options = null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Security;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ namespace CryptoExchange.Net.Interfaces
|
|||||||
Task UnsubscribeAsync(UpdateSubscription subscription);
|
Task UnsubscribeAsync(UpdateSubscription subscription);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Prepare connections which can subsequently be used for sending websocket requests.
|
/// Prepare connections which can subsequently be used for sending websocket requests. Note that this is not required. If not prepared it will be initialized at the first websocket request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<CallResult> PrepareConnectionsAsync();
|
Task<CallResult> PrepareConnectionsAsync();
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ namespace CryptoExchange.Net.Interfaces
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
event Func<int, Task>? OnRequestRateLimited;
|
event Func<int, Task>? OnRequestRateLimited;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
/// Connection was ratelimited and couldn't be established
|
||||||
|
/// </summary>
|
||||||
|
event Func<Task>? OnConnectRateLimited;
|
||||||
|
/// <summary>
|
||||||
/// Websocket error event
|
/// Websocket error event
|
||||||
/// </summary>
|
/// </summary>
|
||||||
event Func<Exception, Task> OnError;
|
event Func<Exception, Task> OnError;
|
||||||
|
|||||||
+25
@@ -25,6 +25,7 @@ namespace CryptoExchange.Net.Logging.Extensions
|
|||||||
private static readonly Action<ILogger, int, string, Exception?> _sendLoopStoppedWithException;
|
private static readonly Action<ILogger, int, string, Exception?> _sendLoopStoppedWithException;
|
||||||
private static readonly Action<ILogger, int, Exception?> _sendLoopFinished;
|
private static readonly Action<ILogger, int, Exception?> _sendLoopFinished;
|
||||||
private static readonly Action<ILogger, int, string, string ,Exception?> _receivedCloseMessage;
|
private static readonly Action<ILogger, int, string, string ,Exception?> _receivedCloseMessage;
|
||||||
|
private static readonly Action<ILogger, int, string, string ,Exception?> _receivedCloseConfirmation;
|
||||||
private static readonly Action<ILogger, int, int, Exception?> _receivedPartialMessage;
|
private static readonly Action<ILogger, int, int, Exception?> _receivedPartialMessage;
|
||||||
private static readonly Action<ILogger, int, int, Exception?> _receivedSingleMessage;
|
private static readonly Action<ILogger, int, int, Exception?> _receivedSingleMessage;
|
||||||
private static readonly Action<ILogger, int, long, Exception?> _reassembledMessage;
|
private static readonly Action<ILogger, int, long, Exception?> _reassembledMessage;
|
||||||
@@ -33,6 +34,7 @@ namespace CryptoExchange.Net.Logging.Extensions
|
|||||||
private static readonly Action<ILogger, int, Exception?> _receiveLoopFinished;
|
private static readonly Action<ILogger, int, Exception?> _receiveLoopFinished;
|
||||||
private static readonly Action<ILogger, int, TimeSpan?, Exception?> _startingTaskForNoDataReceivedCheck;
|
private static readonly Action<ILogger, int, TimeSpan?, Exception?> _startingTaskForNoDataReceivedCheck;
|
||||||
private static readonly Action<ILogger, int, TimeSpan?, Exception?> _noDataReceiveTimoutReconnect;
|
private static readonly Action<ILogger, int, TimeSpan?, Exception?> _noDataReceiveTimoutReconnect;
|
||||||
|
private static readonly Action<ILogger, int, string, string, Exception?> _socketProcessingStateChanged;
|
||||||
|
|
||||||
static CryptoExchangeWebSocketClientLoggingExtension()
|
static CryptoExchangeWebSocketClientLoggingExtension()
|
||||||
{
|
{
|
||||||
@@ -170,6 +172,17 @@ namespace CryptoExchange.Net.Logging.Extensions
|
|||||||
LogLevel.Debug,
|
LogLevel.Debug,
|
||||||
new EventId(1027, "NoDataReceiveTimeoutReconnect"),
|
new EventId(1027, "NoDataReceiveTimeoutReconnect"),
|
||||||
"[Sckt {SocketId}] no data received for {Timeout}, reconnecting socket");
|
"[Sckt {SocketId}] no data received for {Timeout}, reconnecting socket");
|
||||||
|
|
||||||
|
_receivedCloseConfirmation = LoggerMessage.Define<int, string, string>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(1028, "ReceivedCloseMessage"),
|
||||||
|
"[Sckt {SocketId}] received `Close` message confirming our close request, CloseStatus: {CloseStatus}, CloseStatusDescription: {CloseStatusDescription}");
|
||||||
|
|
||||||
|
_socketProcessingStateChanged = LoggerMessage.Define<int, string, string>(
|
||||||
|
LogLevel.Trace,
|
||||||
|
new EventId(1028, "SocketProcessingStateChanged"),
|
||||||
|
"[Sckt {Id}] processing state change: {PreviousState} -> {NewState}");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SocketConnecting(
|
public static void SocketConnecting(
|
||||||
@@ -286,6 +299,12 @@ namespace CryptoExchange.Net.Logging.Extensions
|
|||||||
_receivedCloseMessage(logger, socketId, webSocketCloseStatus, closeStatusDescription, null);
|
_receivedCloseMessage(logger, socketId, webSocketCloseStatus, closeStatusDescription, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void SocketReceivedCloseConfirmation(
|
||||||
|
this ILogger logger, int socketId, string webSocketCloseStatus, string closeStatusDescription)
|
||||||
|
{
|
||||||
|
_receivedCloseConfirmation(logger, socketId, webSocketCloseStatus, closeStatusDescription, null);
|
||||||
|
}
|
||||||
|
|
||||||
public static void SocketReceivedPartialMessage(
|
public static void SocketReceivedPartialMessage(
|
||||||
this ILogger logger, int socketId, int countBytes)
|
this ILogger logger, int socketId, int countBytes)
|
||||||
{
|
{
|
||||||
@@ -333,5 +352,11 @@ namespace CryptoExchange.Net.Logging.Extensions
|
|||||||
{
|
{
|
||||||
_noDataReceiveTimoutReconnect(logger, socketId, timeSpan, null);
|
_noDataReceiveTimoutReconnect(logger, socketId, timeSpan, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void SocketProcessingStateChanged(
|
||||||
|
this ILogger logger, int socketId, string prevState, string newState)
|
||||||
|
{
|
||||||
|
_socketProcessingStateChanged(logger, socketId, prevState, newState, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ namespace CryptoExchange.Net.Logging.Extensions
|
|||||||
private static readonly Action<ILogger, Exception?> _disposingSocketClient;
|
private static readonly Action<ILogger, Exception?> _disposingSocketClient;
|
||||||
private static readonly Action<ILogger, int, int, Exception?> _unsubscribingSubscription;
|
private static readonly Action<ILogger, int, int, Exception?> _unsubscribingSubscription;
|
||||||
private static readonly Action<ILogger, int, Exception?> _reconnectingAllConnections;
|
private static readonly Action<ILogger, int, Exception?> _reconnectingAllConnections;
|
||||||
|
private static readonly Action<ILogger, DateTime, Exception?> _addingRetryAfterGuard;
|
||||||
|
|
||||||
static SocketApiClientLoggingExtension()
|
static SocketApiClientLoggingExtension()
|
||||||
{
|
{
|
||||||
@@ -104,6 +105,11 @@ namespace CryptoExchange.Net.Logging.Extensions
|
|||||||
LogLevel.Information,
|
LogLevel.Information,
|
||||||
new EventId(3017, "ReconnectingAll"),
|
new EventId(3017, "ReconnectingAll"),
|
||||||
"Reconnecting all {ConnectionCount} connections");
|
"Reconnecting all {ConnectionCount} connections");
|
||||||
|
|
||||||
|
_addingRetryAfterGuard = LoggerMessage.Define<DateTime>(
|
||||||
|
LogLevel.Warning,
|
||||||
|
new EventId(3018, "AddRetryAfterGuard"),
|
||||||
|
"Adding RetryAfterGuard ({RetryAfter}) because the connection attempt was rate limited");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void FailedToAddSubscriptionRetryOnDifferentConnection(this ILogger logger, int socketId)
|
public static void FailedToAddSubscriptionRetryOnDifferentConnection(this ILogger logger, int socketId)
|
||||||
@@ -185,5 +191,10 @@ namespace CryptoExchange.Net.Logging.Extensions
|
|||||||
{
|
{
|
||||||
_reconnectingAllConnections(logger, connectionCount, null);
|
_reconnectingAllConnections(logger, connectionCount, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void AddingRetryAfterGuard(this ILogger logger, DateTime retryAfter)
|
||||||
|
{
|
||||||
|
_addingRetryAfterGuard(logger, retryAfter, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,292 @@
|
|||||||
|
using System;
|
||||||
|
using CryptoExchange.Net.Objects;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.Logging.Extensions
|
||||||
|
{
|
||||||
|
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
|
||||||
|
|
||||||
|
public static class TrackerLoggingExtensions
|
||||||
|
{
|
||||||
|
private static readonly Action<ILogger, string, SyncStatus, SyncStatus, Exception?> _klineTrackerStatusChanged;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _klineTrackerStarting;
|
||||||
|
private static readonly Action<ILogger, string, string, Exception?> _klineTrackerStartFailed;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _klineTrackerStarted;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _klineTrackerStopping;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _klineTrackerStopped;
|
||||||
|
private static readonly Action<ILogger, string, DateTime, Exception?> _klineTrackerInitialDataSet;
|
||||||
|
private static readonly Action<ILogger, string, DateTime, Exception?> _klineTrackerKlineUpdated;
|
||||||
|
private static readonly Action<ILogger, string, DateTime, Exception?> _klineTrackerKlineAdded;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _klineTrackerConnectionLost;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _klineTrackerConnectionClosed;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _klineTrackerConnectionRestored;
|
||||||
|
|
||||||
|
private static readonly Action<ILogger, string, SyncStatus, SyncStatus, Exception?> _tradeTrackerStatusChanged;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _tradeTrackerStarting;
|
||||||
|
private static readonly Action<ILogger, string, string, Exception?> _tradeTrackerStartFailed;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _tradeTrackerStarted;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _tradeTrackerStopping;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _tradeTrackerStopped;
|
||||||
|
private static readonly Action<ILogger, string, int, long, Exception?> _tradeTrackerInitialDataSet;
|
||||||
|
private static readonly Action<ILogger, string, long, Exception?> _tradeTrackerPreSnapshotSkip;
|
||||||
|
private static readonly Action<ILogger, string, long, Exception?> _tradeTrackerPreSnapshotApplied;
|
||||||
|
private static readonly Action<ILogger, string, long, Exception?> _tradeTrackerTradeAdded;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _tradeTrackerConnectionLost;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _tradeTrackerConnectionClosed;
|
||||||
|
private static readonly Action<ILogger, string, Exception?> _tradeTrackerConnectionRestored;
|
||||||
|
|
||||||
|
static TrackerLoggingExtensions()
|
||||||
|
{
|
||||||
|
_klineTrackerStatusChanged = LoggerMessage.Define<string, SyncStatus, SyncStatus>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(6001, "KlineTrackerStatusChanged"),
|
||||||
|
"Kline tracker for {Symbol} status changed: {OldStatus} => {NewStatus}");
|
||||||
|
|
||||||
|
_klineTrackerStarting = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(6002, "KlineTrackerStarting"),
|
||||||
|
"Kline tracker for {Symbol} starting");
|
||||||
|
|
||||||
|
_klineTrackerStartFailed = LoggerMessage.Define<string, string>(
|
||||||
|
LogLevel.Warning,
|
||||||
|
new EventId(6003, "KlineTrackerStartFailed"),
|
||||||
|
"Kline tracker for {Symbol} failed to start: {Error}");
|
||||||
|
|
||||||
|
_klineTrackerStarted = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Information,
|
||||||
|
new EventId(6004, "KlineTrackerStarted"),
|
||||||
|
"Kline tracker for {Symbol} started");
|
||||||
|
|
||||||
|
_klineTrackerStopping = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(6005, "KlineTrackerStopping"),
|
||||||
|
"Kline tracker for {Symbol} stopping");
|
||||||
|
|
||||||
|
_klineTrackerStopped = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Information,
|
||||||
|
new EventId(6006, "KlineTrackerStopped"),
|
||||||
|
"Kline tracker for {Symbol} stopped");
|
||||||
|
|
||||||
|
_klineTrackerInitialDataSet = LoggerMessage.Define<string, DateTime>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(6007, "KlineTrackerInitialDataSet"),
|
||||||
|
"Kline tracker for {Symbol} initial data set, last timestamp: {LastTime}");
|
||||||
|
|
||||||
|
_klineTrackerKlineUpdated = LoggerMessage.Define<string, DateTime>(
|
||||||
|
LogLevel.Trace,
|
||||||
|
new EventId(6008, "KlineTrackerKlineUpdated"),
|
||||||
|
"Kline tracker for {Symbol} kline updated for open time: {LastTime}");
|
||||||
|
|
||||||
|
_klineTrackerKlineAdded = LoggerMessage.Define<string, DateTime>(
|
||||||
|
LogLevel.Trace,
|
||||||
|
new EventId(6009, "KlineTrackerKlineAdded"),
|
||||||
|
"Kline tracker for {Symbol} new kline for open time: {LastTime}");
|
||||||
|
|
||||||
|
_klineTrackerConnectionLost = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Warning,
|
||||||
|
new EventId(6010, "KlineTrackerConnectionLost"),
|
||||||
|
"Kline tracker for {Symbol} connection lost");
|
||||||
|
|
||||||
|
_klineTrackerConnectionClosed = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Warning,
|
||||||
|
new EventId(6011, "KlineTrackerConnectionClosed"),
|
||||||
|
"Kline tracker for {Symbol} disconnected");
|
||||||
|
|
||||||
|
_klineTrackerConnectionRestored = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Information,
|
||||||
|
new EventId(6012, "KlineTrackerConnectionRestored"),
|
||||||
|
"Kline tracker for {Symbol} successfully resynchronized");
|
||||||
|
|
||||||
|
|
||||||
|
_tradeTrackerStatusChanged = LoggerMessage.Define<string, SyncStatus, SyncStatus>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(6013, "KlineTrackerStatusChanged"),
|
||||||
|
"Trade tracker for {Symbol} status changed: {OldStatus} => {NewStatus}");
|
||||||
|
|
||||||
|
_tradeTrackerStarting = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(6014, "KlineTrackerStarting"),
|
||||||
|
"Trade tracker for {Symbol} starting");
|
||||||
|
|
||||||
|
_tradeTrackerStartFailed = LoggerMessage.Define<string, string>(
|
||||||
|
LogLevel.Warning,
|
||||||
|
new EventId(6015, "KlineTrackerStartFailed"),
|
||||||
|
"Trade tracker for {Symbol} failed to start: {Error}");
|
||||||
|
|
||||||
|
_tradeTrackerStarted = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Information,
|
||||||
|
new EventId(6016, "KlineTrackerStarted"),
|
||||||
|
"Trade tracker for {Symbol} started");
|
||||||
|
|
||||||
|
_tradeTrackerStopping = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(6017, "KlineTrackerStopping"),
|
||||||
|
"Trade tracker for {Symbol} stopping");
|
||||||
|
|
||||||
|
_tradeTrackerStopped = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Information,
|
||||||
|
new EventId(6018, "KlineTrackerStopped"),
|
||||||
|
"Trade tracker for {Symbol} stopped");
|
||||||
|
|
||||||
|
_tradeTrackerInitialDataSet = LoggerMessage.Define<string, int, long>(
|
||||||
|
LogLevel.Debug,
|
||||||
|
new EventId(6019, "TradeTrackerInitialDataSet"),
|
||||||
|
"Trade tracker for {Symbol} snapshot set, Count: {Count}, Last id: {LastId}");
|
||||||
|
|
||||||
|
_tradeTrackerPreSnapshotSkip = LoggerMessage.Define<string, long>(
|
||||||
|
LogLevel.Trace,
|
||||||
|
new EventId(6020, "TradeTrackerPreSnapshotSkip"),
|
||||||
|
"Trade tracker for {Symbol} skipping {Id}, already in snapshot");
|
||||||
|
|
||||||
|
_tradeTrackerPreSnapshotApplied = LoggerMessage.Define<string, long>(
|
||||||
|
LogLevel.Trace,
|
||||||
|
new EventId(6021, "TradeTrackerPreSnapshotApplied"),
|
||||||
|
"Trade tracker for {Symbol} adding {Id} from pre-snapshot");
|
||||||
|
|
||||||
|
_tradeTrackerTradeAdded = LoggerMessage.Define<string, long>(
|
||||||
|
LogLevel.Trace,
|
||||||
|
new EventId(6022, "TradeTrackerTradeAdded"),
|
||||||
|
"Trade tracker for {Symbol} adding trade {Id}");
|
||||||
|
|
||||||
|
_tradeTrackerConnectionLost = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Warning,
|
||||||
|
new EventId(6023, "TradeTrackerConnectionLost"),
|
||||||
|
"Trade tracker for {Symbol} connection lost");
|
||||||
|
|
||||||
|
_tradeTrackerConnectionClosed = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Warning,
|
||||||
|
new EventId(6024, "TradeTrackerConnectionClosed"),
|
||||||
|
"Trade tracker for {Symbol} disconnected");
|
||||||
|
|
||||||
|
_tradeTrackerConnectionRestored = LoggerMessage.Define<string>(
|
||||||
|
LogLevel.Information,
|
||||||
|
new EventId(6025, "TradeTrackerConnectionRestored"),
|
||||||
|
"Trade tracker for {Symbol} successfully resynchronized");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerStatusChanged(this ILogger logger, string symbol, SyncStatus oldStatus, SyncStatus newStatus)
|
||||||
|
{
|
||||||
|
_klineTrackerStatusChanged(logger, symbol, oldStatus, newStatus, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerStarting(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_klineTrackerStarting(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerStartFailed(this ILogger logger, string symbol, string error)
|
||||||
|
{
|
||||||
|
_klineTrackerStartFailed(logger, symbol, error, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerStarted(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_klineTrackerStarted(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerStopping(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_klineTrackerStopping(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerStopped(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_klineTrackerStopped(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerInitialDataSet(this ILogger logger, string symbol, DateTime lastTime)
|
||||||
|
{
|
||||||
|
_klineTrackerInitialDataSet(logger, symbol, lastTime, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerKlineUpdated(this ILogger logger, string symbol, DateTime lastTime)
|
||||||
|
{
|
||||||
|
_klineTrackerKlineUpdated(logger, symbol, lastTime, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerKlineAdded(this ILogger logger, string symbol, DateTime lastTime)
|
||||||
|
{
|
||||||
|
_klineTrackerKlineAdded(logger, symbol, lastTime, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerConnectionLost(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_klineTrackerConnectionLost(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerConnectionClosed(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_klineTrackerConnectionClosed(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void KlineTrackerConnectionRestored(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_klineTrackerConnectionRestored(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerStatusChanged(this ILogger logger, string symbol, SyncStatus oldStatus, SyncStatus newStatus)
|
||||||
|
{
|
||||||
|
_tradeTrackerStatusChanged(logger, symbol, oldStatus, newStatus, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerStarting(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_tradeTrackerStarting(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerStartFailed(this ILogger logger, string symbol, string error)
|
||||||
|
{
|
||||||
|
_tradeTrackerStartFailed(logger, symbol, error, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerStarted(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_tradeTrackerStarted(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerStopping(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_tradeTrackerStopping(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerStopped(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_tradeTrackerStopped(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerInitialDataSet(this ILogger logger, string symbol, int count, long lastId)
|
||||||
|
{
|
||||||
|
_tradeTrackerInitialDataSet(logger, symbol, count, lastId, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerPreSnapshotSkip(this ILogger logger, string symbol, long lastId)
|
||||||
|
{
|
||||||
|
_tradeTrackerPreSnapshotSkip(logger, symbol, lastId, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerPreSnapshotApplied(this ILogger logger, string symbol, long lastId)
|
||||||
|
{
|
||||||
|
_tradeTrackerPreSnapshotApplied(logger, symbol, lastId, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerTradeAdded(this ILogger logger, string symbol, long lastId)
|
||||||
|
{
|
||||||
|
_tradeTrackerTradeAdded(logger, symbol, lastId, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerConnectionLost(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_tradeTrackerConnectionLost(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerConnectionClosed(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_tradeTrackerConnectionClosed(logger, symbol, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void TradeTrackerConnectionRestored(this ILogger logger, string symbol)
|
||||||
|
{
|
||||||
|
_tradeTrackerConnectionRestored(logger, symbol, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
using System.Security;
|
namespace CryptoExchange.Net.Objects
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Objects
|
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Proxy info
|
/// Proxy info
|
||||||
@@ -10,30 +8,21 @@ namespace CryptoExchange.Net.Objects
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// The host address of the proxy
|
/// The host address of the proxy
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Host { get; }
|
public string Host { get; set; }
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The port of the proxy
|
/// The port of the proxy
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int Port { get; }
|
public int Port { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The login of the proxy
|
/// The login of the proxy
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? Login { get; }
|
public string? Login { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The password of the proxy
|
/// The password of the proxy
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? Password { get; }
|
public string? Password { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Create new settings for a proxy
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="host">The proxy hostname/ip</param>
|
|
||||||
/// <param name="port">The proxy port</param>
|
|
||||||
public ApiProxy(string host, int port): this(host, port, null, null)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create new settings for a proxy
|
/// Create new settings for a proxy
|
||||||
@@ -42,7 +31,7 @@ namespace CryptoExchange.Net.Objects
|
|||||||
/// <param name="port">The proxy port</param>
|
/// <param name="port">The proxy port</param>
|
||||||
/// <param name="login">The proxy login</param>
|
/// <param name="login">The proxy login</param>
|
||||||
/// <param name="password">The proxy password</param>
|
/// <param name="password">The proxy password</param>
|
||||||
public ApiProxy(string host, int port, string? login, string? password)
|
public ApiProxy(string host, int port, string? login = null, string? password = null)
|
||||||
{
|
{
|
||||||
Host = host;
|
Host = host;
|
||||||
Port = port;
|
Port = port;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using CryptoExchange.Net.SharedApis;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
@@ -284,6 +285,32 @@ namespace CryptoExchange.Net.Objects
|
|||||||
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, 0, null, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, ResultDataSource.Server, data, Error);
|
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, 0, null, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, ResultDataSource.Server, data, Error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="K">The new type</typeparam>
|
||||||
|
/// <param name="exchange">The exchange</param>
|
||||||
|
/// <param name="tradeMode">Trade mode the result applies to</param>
|
||||||
|
/// <param name="data">The data</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode tradeMode, [AllowNull] K data)
|
||||||
|
{
|
||||||
|
return new ExchangeWebResult<K>(exchange, tradeMode, this.As<K>(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="K">The new type</typeparam>
|
||||||
|
/// <param name="exchange">The exchange</param>
|
||||||
|
/// <param name="tradeModes">Trade modes the result applies to</param>
|
||||||
|
/// <param name="data">The data</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode[]? tradeModes, [AllowNull] K data)
|
||||||
|
{
|
||||||
|
return new ExchangeWebResult<K>(exchange, tradeModes, this.As<K>(data));
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Copy the WebCallResult to a new data type
|
/// Copy the WebCallResult to a new data type
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -447,6 +474,68 @@ namespace CryptoExchange.Net.Objects
|
|||||||
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, default, error);
|
return new WebCallResult<K>(ResponseStatusCode, ResponseHeaders, ResponseTime, ResponseLength, OriginalData, RequestId, RequestUrl, RequestBody, RequestMethod, RequestHeaders, DataSource, default, error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="exchange">The exchange</param>
|
||||||
|
/// <param name="tradeMode">Trade mode the result applies to</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ExchangeWebResult<T> AsExchangeResult(string exchange, TradingMode tradeMode)
|
||||||
|
{
|
||||||
|
return new ExchangeWebResult<T>(exchange, tradeMode, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="exchange">The exchange</param>
|
||||||
|
/// <param name="tradeModes">Trade modes the result applies to</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ExchangeWebResult<T> AsExchangeResult(string exchange, TradingMode[] tradeModes)
|
||||||
|
{
|
||||||
|
return new ExchangeWebResult<T>(exchange, tradeModes, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="K">The new type</typeparam>
|
||||||
|
/// <param name="exchange">The exchange</param>
|
||||||
|
/// <param name="tradeMode">Trade mode the result applies to</param>
|
||||||
|
/// <param name="data">Data</param>
|
||||||
|
/// <param name="nextPageToken">Next page token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode tradeMode, [AllowNull] K data, INextPageToken? nextPageToken = null)
|
||||||
|
{
|
||||||
|
return new ExchangeWebResult<K>(exchange, tradeMode, As<K>(data), nextPageToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copy the WebCallResult to an ExchangeWebResult of a new data type
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="K">The new type</typeparam>
|
||||||
|
/// <param name="exchange">The exchange</param>
|
||||||
|
/// <param name="tradeModes">Trade modes the result applies to</param>
|
||||||
|
/// <param name="data">Data</param>
|
||||||
|
/// <param name="nextPageToken">Next page token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ExchangeWebResult<K> AsExchangeResult<K>(string exchange, TradingMode[]? tradeModes, [AllowNull] K data, INextPageToken? nextPageToken = null)
|
||||||
|
{
|
||||||
|
return new ExchangeWebResult<K>(exchange, tradeModes, As<K>(data), nextPageToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copy the WebCallResult to an ExchangeWebResult with a specific error
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="K">The new type</typeparam>
|
||||||
|
/// <param name="exchange">The exchange</param>
|
||||||
|
/// <param name="error">The error returned</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ExchangeWebResult<K> AsExchangeError<K>(string exchange, Error error)
|
||||||
|
{
|
||||||
|
return new ExchangeWebResult<K>(exchange, null, AsError<K>(error));
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Return a copy of this result with data source set to cache
|
/// Return a copy of this result with data source set to cache
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -68,6 +68,33 @@
|
|||||||
Json
|
Json
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tracker sync status
|
||||||
|
/// </summary>
|
||||||
|
public enum SyncStatus
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Not connected
|
||||||
|
/// </summary>
|
||||||
|
Disconnected,
|
||||||
|
/// <summary>
|
||||||
|
/// Syncing, data connection is being made
|
||||||
|
/// </summary>
|
||||||
|
Syncing,
|
||||||
|
/// <summary>
|
||||||
|
/// The connection is active, but the full data backlog is not yet reached. For example, a tracker set to retain 10 minutes of data only has 8 minutes of data at this moment.
|
||||||
|
/// </summary>
|
||||||
|
PartiallySynced,
|
||||||
|
/// <summary>
|
||||||
|
/// Synced
|
||||||
|
/// </summary>
|
||||||
|
Synced,
|
||||||
|
/// <summary>
|
||||||
|
/// Disposed
|
||||||
|
/// </summary>
|
||||||
|
Diposed
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Status of the order book
|
/// Status of the order book
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -152,7 +179,11 @@
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Round to closest value
|
/// Round to closest value
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Closest
|
Closest,
|
||||||
|
/// <summary>
|
||||||
|
/// Round up (ceil)
|
||||||
|
/// </summary>
|
||||||
|
Up
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -203,4 +234,5 @@
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
Cache
|
Cache
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,19 +19,15 @@ namespace CryptoExchange.Net.Objects.Options
|
|||||||
public TimeSpan? TimestampRecalculationInterval { get; set; }
|
public TimeSpan? TimestampRecalculationInterval { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create a copy of this options
|
/// Set the values of this options on the target options
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
public T Set<T>(T item) where T : RestApiOptions, new()
|
||||||
/// <returns></returns>
|
|
||||||
public virtual T Copy<T>() where T : RestApiOptions, new()
|
|
||||||
{
|
{
|
||||||
return new T
|
item.ApiCredentials = ApiCredentials?.Copy();
|
||||||
{
|
item.OutputOriginalData = OutputOriginalData;
|
||||||
ApiCredentials = ApiCredentials?.Copy(),
|
item.AutoTimestamp = AutoTimestamp;
|
||||||
OutputOriginalData = OutputOriginalData,
|
item.TimestampRecalculationInterval = TimestampRecalculationInterval;
|
||||||
AutoTimestamp = AutoTimestamp,
|
return item;
|
||||||
TimestampRecalculationInterval = TimestampRecalculationInterval
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,25 +29,21 @@ namespace CryptoExchange.Net.Objects.Options
|
|||||||
public TimeSpan CachingMaxAge { get; set; } = TimeSpan.FromSeconds(5);
|
public TimeSpan CachingMaxAge { get; set; } = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create a copy of this options
|
/// Set the values of this options on the target options
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
public T Set<T>(T item) where T : RestExchangeOptions, new()
|
||||||
/// <returns></returns>
|
|
||||||
public T Copy<T>() where T : RestExchangeOptions, new()
|
|
||||||
{
|
{
|
||||||
return new T
|
item.OutputOriginalData = OutputOriginalData;
|
||||||
{
|
item.AutoTimestamp = AutoTimestamp;
|
||||||
OutputOriginalData = OutputOriginalData,
|
item.TimestampRecalculationInterval = TimestampRecalculationInterval;
|
||||||
AutoTimestamp = AutoTimestamp,
|
item.ApiCredentials = ApiCredentials?.Copy();
|
||||||
TimestampRecalculationInterval = TimestampRecalculationInterval,
|
item.Proxy = Proxy;
|
||||||
ApiCredentials = ApiCredentials?.Copy(),
|
item.RequestTimeout = RequestTimeout;
|
||||||
Proxy = Proxy,
|
item.RateLimiterEnabled = RateLimiterEnabled;
|
||||||
RequestTimeout = RequestTimeout,
|
item.RateLimitingBehaviour = RateLimitingBehaviour;
|
||||||
RateLimiterEnabled = RateLimiterEnabled,
|
item.CachingEnabled = CachingEnabled;
|
||||||
RateLimitingBehaviour = RateLimitingBehaviour,
|
item.CachingMaxAge = CachingMaxAge;
|
||||||
CachingEnabled = CachingEnabled,
|
return item;
|
||||||
CachingMaxAge = CachingMaxAge,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,15 +62,13 @@ namespace CryptoExchange.Net.Objects.Options
|
|||||||
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create a copy of this options
|
/// Set the values of this options on the target options
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
public new T Set<T>(T target) where T : RestExchangeOptions<TEnvironment>, new()
|
||||||
/// <returns></returns>
|
|
||||||
public new T Copy<T>() where T : RestExchangeOptions<TEnvironment>, new()
|
|
||||||
{
|
{
|
||||||
var result = base.Copy<T>();
|
base.Set(target);
|
||||||
result.Environment = Environment;
|
target.Environment = Environment;
|
||||||
return result;
|
return target;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,19 +20,15 @@ namespace CryptoExchange.Net.Objects.Options
|
|||||||
public int? MaxSocketConnections { get; set; }
|
public int? MaxSocketConnections { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create a copy of this options
|
/// Set the values of this options on the target options
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
public T Set<T>(T item) where T : SocketApiOptions, new()
|
||||||
/// <returns></returns>
|
|
||||||
public T Copy<T>() where T : SocketApiOptions, new()
|
|
||||||
{
|
{
|
||||||
return new T
|
item.ApiCredentials = ApiCredentials?.Copy();
|
||||||
{
|
item.OutputOriginalData = OutputOriginalData;
|
||||||
ApiCredentials = ApiCredentials?.Copy(),
|
item.SocketNoDataTimeout = SocketNoDataTimeout;
|
||||||
OutputOriginalData = OutputOriginalData,
|
item.MaxSocketConnections = MaxSocketConnections;
|
||||||
SocketNoDataTimeout = SocketNoDataTimeout,
|
return item;
|
||||||
MaxSocketConnections = MaxSocketConnections,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using CryptoExchange.Net.Authentication;
|
using CryptoExchange.Net.Authentication;
|
||||||
using CryptoExchange.Net.Objects.Sockets;
|
|
||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Objects.Options
|
namespace CryptoExchange.Net.Objects.Options
|
||||||
@@ -47,29 +46,33 @@ namespace CryptoExchange.Net.Objects.Options
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public TimeSpan DelayAfterConnect { get; set; } = TimeSpan.Zero;
|
public TimeSpan DelayAfterConnect { get; set; } = TimeSpan.Zero;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// This delay is used to set a RetryAfter guard on the connection after a rate limit is hit on the server.
|
||||||
|
/// This is used to prevent the client from reconnecting too quickly after a rate limit is hit.
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan? ConnectDelayAfterRateLimited { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create a copy of this options
|
/// Create a copy of this options
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public T Copy<T>() where T : SocketExchangeOptions, new()
|
public T Set<T>(T item) where T : SocketExchangeOptions, new()
|
||||||
{
|
{
|
||||||
return new T
|
item.ApiCredentials = ApiCredentials?.Copy();
|
||||||
{
|
item.OutputOriginalData = OutputOriginalData;
|
||||||
ApiCredentials = ApiCredentials?.Copy(),
|
item.ReconnectPolicy = ReconnectPolicy;
|
||||||
OutputOriginalData = OutputOriginalData,
|
item.DelayAfterConnect = DelayAfterConnect;
|
||||||
ReconnectPolicy = ReconnectPolicy,
|
item.MaxConcurrentResubscriptionsPerSocket = MaxConcurrentResubscriptionsPerSocket;
|
||||||
DelayAfterConnect = DelayAfterConnect,
|
item.ReconnectInterval = ReconnectInterval;
|
||||||
MaxConcurrentResubscriptionsPerSocket = MaxConcurrentResubscriptionsPerSocket,
|
item.SocketNoDataTimeout = SocketNoDataTimeout;
|
||||||
ReconnectInterval = ReconnectInterval,
|
item.SocketSubscriptionsCombineTarget = SocketSubscriptionsCombineTarget;
|
||||||
SocketNoDataTimeout = SocketNoDataTimeout,
|
item.MaxSocketConnections = MaxSocketConnections;
|
||||||
SocketSubscriptionsCombineTarget = SocketSubscriptionsCombineTarget,
|
item.Proxy = Proxy;
|
||||||
MaxSocketConnections = MaxSocketConnections,
|
item.RequestTimeout = RequestTimeout;
|
||||||
Proxy = Proxy,
|
item.RateLimitingBehaviour = RateLimitingBehaviour;
|
||||||
RequestTimeout = RequestTimeout,
|
item.RateLimiterEnabled = RateLimiterEnabled;
|
||||||
RateLimitingBehaviour = RateLimitingBehaviour,
|
return item;
|
||||||
RateLimiterEnabled = RateLimiterEnabled,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,15 +91,13 @@ namespace CryptoExchange.Net.Objects.Options
|
|||||||
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Create a copy of this options
|
/// Set the values of this options on the target options
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
public new T Set<T>(T target) where T : SocketExchangeOptions<TEnvironment>, new()
|
||||||
/// <returns></returns>
|
|
||||||
public new T Copy<T>() where T : SocketExchangeOptions<TEnvironment>, new()
|
|
||||||
{
|
{
|
||||||
var result = base.Copy<T>();
|
base.Set(target);
|
||||||
result.Environment = Environment;
|
target.Environment = Environment;
|
||||||
return result;
|
return target;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System;
|
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Objects
|
namespace CryptoExchange.Net.Objects
|
||||||
@@ -59,12 +58,16 @@ namespace CryptoExchange.Net.Objects
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public IRateLimitGuard? LimitGuard { get; set; }
|
public IRateLimitGuard? LimitGuard { get; set; }
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Whether this request should never be cached
|
/// Whether this request should never be cached
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool PreventCaching { get; set; }
|
public bool PreventCaching { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Connection id
|
||||||
|
/// </summary>
|
||||||
|
public int? ConnectionId { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// ctor
|
/// ctor
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System;
|
|
||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Objects
|
namespace CryptoExchange.Net.Objects
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using CryptoExchange.Net.SharedApis;
|
||||||
|
using System;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.Objects.Sockets
|
namespace CryptoExchange.Net.Objects.Sockets
|
||||||
{
|
{
|
||||||
@@ -38,7 +39,10 @@ namespace CryptoExchange.Net.Objects.Sockets
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public T Data { get; set; }
|
public T Data { get; set; }
|
||||||
|
|
||||||
internal DataEvent(T data, string? streamId, string? symbol, string? originalData, DateTime timestamp, SocketUpdateType? updateType)
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public DataEvent(T data, string? streamId, string? symbol, string? originalData, DateTime timestamp, SocketUpdateType? updateType)
|
||||||
{
|
{
|
||||||
Data = data;
|
Data = data;
|
||||||
StreamId = streamId;
|
StreamId = streamId;
|
||||||
@@ -85,6 +89,19 @@ namespace CryptoExchange.Net.Objects.Sockets
|
|||||||
return new DataEvent<K>(data, streamId, symbol, OriginalData, Timestamp, updateType);
|
return new DataEvent<K>(data, streamId, symbol, OriginalData, Timestamp, updateType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copy the WebCallResult to a new data type
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="K">The new type</typeparam>
|
||||||
|
/// <param name="exchange">The exchange the result is for</param>
|
||||||
|
/// <param name="data">The data</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public ExchangeEvent<K> AsExchangeEvent<K>(string exchange, K data)
|
||||||
|
{
|
||||||
|
return new ExchangeEvent<K>(exchange, this.As<K>(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Specify the symbol
|
/// Specify the symbol
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -30,6 +30,15 @@ namespace CryptoExchange.Net.Objects.Sockets
|
|||||||
remove => _connection.ConnectionClosed -= value;
|
remove => _connection.ConnectionClosed -= value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Event when a lost connection is restored, but the resubscribing of update subscriptions failed
|
||||||
|
/// </summary>
|
||||||
|
public event Action<Error> ResubscribingFailed
|
||||||
|
{
|
||||||
|
add => _connection.ResubscribingFailed += value;
|
||||||
|
remove => _connection.ResubscribingFailed -= value;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Event when the connection is restored. Timespan parameter indicates the time the socket has been offline for before reconnecting.
|
/// Event when the connection is restored. Timespan parameter indicates the time the socket has been offline for before reconnecting.
|
||||||
/// Note that when the executing code is suspended and resumed at a later period (for example, a laptop going to sleep) the disconnect time will be incorrect as the diconnect
|
/// Note that when the executing code is suspended and resumed at a later period (for example, a laptop going to sleep) the disconnect time will be incorrect as the diconnect
|
||||||
|
|||||||
@@ -24,14 +24,14 @@
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Name of the environment
|
/// Name of the environment
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string EnvironmentName { get; init; }
|
public string Name { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="name"></param>
|
/// <param name="name"></param>
|
||||||
protected TradeEnvironment(string name)
|
protected TradeEnvironment(string name)
|
||||||
{
|
{
|
||||||
EnvironmentName = name;
|
Name = name;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using CryptoExchange.Net.Interfaces;
|
using CryptoExchange.Net.Interfaces;
|
||||||
using CryptoExchange.Net.Objects.Options;
|
using CryptoExchange.Net.Objects.Options;
|
||||||
|
using CryptoExchange.Net.SharedApis;
|
||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace CryptoExchange.Net.OrderBook
|
namespace CryptoExchange.Net.OrderBook
|
||||||
@@ -8,14 +9,14 @@ namespace CryptoExchange.Net.OrderBook
|
|||||||
public class OrderBookFactory<TOptions> : IOrderBookFactory<TOptions> where TOptions: OrderBookOptions
|
public class OrderBookFactory<TOptions> : IOrderBookFactory<TOptions> where TOptions: OrderBookOptions
|
||||||
{
|
{
|
||||||
private readonly Func<string, Action<TOptions>?, ISymbolOrderBook> _symbolCtor;
|
private readonly Func<string, Action<TOptions>?, ISymbolOrderBook> _symbolCtor;
|
||||||
private readonly Func<string, string, Action<TOptions>?, ISymbolOrderBook> _assetsCtor;
|
private readonly Func<SharedSymbol, Action<TOptions>?, ISymbolOrderBook> _assetsCtor;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// ctor
|
/// ctor
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="symbolCtor"></param>
|
/// <param name="symbolCtor"></param>
|
||||||
/// <param name="assetsCtor"></param>
|
/// <param name="assetsCtor"></param>
|
||||||
public OrderBookFactory(Func<string, Action<TOptions>?, ISymbolOrderBook> symbolCtor, Func<string, string, Action<TOptions>?, ISymbolOrderBook> assetsCtor)
|
public OrderBookFactory(Func<string, Action<TOptions>?, ISymbolOrderBook> symbolCtor, Func<SharedSymbol, Action<TOptions>?, ISymbolOrderBook> assetsCtor)
|
||||||
{
|
{
|
||||||
_symbolCtor = symbolCtor;
|
_symbolCtor = symbolCtor;
|
||||||
_assetsCtor = assetsCtor;
|
_assetsCtor = assetsCtor;
|
||||||
@@ -25,6 +26,9 @@ namespace CryptoExchange.Net.OrderBook
|
|||||||
public ISymbolOrderBook Create(string symbol, Action<TOptions>? options = null) => _symbolCtor(symbol, options);
|
public ISymbolOrderBook Create(string symbol, Action<TOptions>? options = null) => _symbolCtor(symbol, options);
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public ISymbolOrderBook Create(string baseAsset, string quoteAsset, Action<TOptions>? options = null) => _assetsCtor(baseAsset, quoteAsset, options);
|
public ISymbolOrderBook Create(string baseAsset, string quoteAsset, Action<TOptions>? options = null) => _assetsCtor(new SharedSymbol(TradingMode.Spot, baseAsset, quoteAsset), options);
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public ISymbolOrderBook Create(SharedSymbol symbol, Action<TOptions>? options = null) => _assetsCtor(symbol, options);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System.Security;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Filters
|
namespace CryptoExchange.Net.RateLimiting.Filters
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Security;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Filters
|
namespace CryptoExchange.Net.RateLimiting.Filters
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Security;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Filters
|
namespace CryptoExchange.Net.RateLimiting.Filters
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System.Security;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Filters
|
namespace CryptoExchange.Net.RateLimiting.Filters
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System.Security;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Filters
|
namespace CryptoExchange.Net.RateLimiting.Filters
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System;
|
using System;
|
||||||
using System.Security;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Filters
|
namespace CryptoExchange.Net.RateLimiting.Filters
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ using CryptoExchange.Net.RateLimiting.Interfaces;
|
|||||||
using CryptoExchange.Net.RateLimiting.Trackers;
|
using CryptoExchange.Net.RateLimiting.Trackers;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Security;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Guards
|
namespace CryptoExchange.Net.RateLimiting.Guards
|
||||||
{
|
{
|
||||||
@@ -20,6 +18,10 @@ namespace CryptoExchange.Net.RateLimiting.Guards
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static Func<RequestDefinition, string, string?, string> PerEndpoint { get; } = new Func<RequestDefinition, string, string?, string>((def, host, key) => def.Path + def.Method);
|
public static Func<RequestDefinition, string, string?, string> PerEndpoint { get; } = new Func<RequestDefinition, string, string?, string>((def, host, key) => def.Path + def.Method);
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
/// Apply guard per connection
|
||||||
|
/// </summary>
|
||||||
|
public static Func<RequestDefinition, string, string?, string> PerConnection { get; } = new Func<RequestDefinition, string, string?, string>((def, host, key) => def.ConnectionId.ToString());
|
||||||
|
/// <summary>
|
||||||
/// Apply guard per API key
|
/// Apply guard per API key
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static Func<RequestDefinition, string, string?, string> PerApiKey { get; } = new Func<RequestDefinition, string, string?, string>((def, host, key) => key!);
|
public static Func<RequestDefinition, string, string?, string> PerApiKey { get; } = new Func<RequestDefinition, string, string?, string>((def, host, key) => key!);
|
||||||
@@ -108,7 +110,7 @@ namespace CryptoExchange.Net.RateLimiting.Guards
|
|||||||
|
|
||||||
var delay = tracker.GetWaitTime(requestWeight);
|
var delay = tracker.GetWaitTime(requestWeight);
|
||||||
if (delay == default)
|
if (delay == default)
|
||||||
return LimitCheck.NotNeeded;
|
return LimitCheck.NotNeeded(Limit, TimeSpan, tracker.Current);
|
||||||
|
|
||||||
return LimitCheck.Needed(delay, Limit, TimeSpan, tracker.Current);
|
return LimitCheck.Needed(delay, Limit, TimeSpan, tracker.Current);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.RateLimiting.Interfaces;
|
using CryptoExchange.Net.RateLimiting.Interfaces;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Security;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Guards
|
namespace CryptoExchange.Net.RateLimiting.Guards
|
||||||
{
|
{
|
||||||
@@ -21,25 +18,35 @@ namespace CryptoExchange.Net.RateLimiting.Guards
|
|||||||
public string Name => "RetryAfterGuard";
|
public string Name => "RetryAfterGuard";
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public string Description => $"Pause requests until after {After}";
|
public string Description => $"Pause {Type} until after {After}";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The timestamp after which requests are allowed again
|
/// The timestamp after which requests are allowed again
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public DateTime After { get; private set; }
|
public DateTime After { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The type of rate limit item this guard is for
|
||||||
|
/// </summary>
|
||||||
|
public RateLimitItemType Type { get; private set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// ctor
|
/// ctor
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="after"></param>
|
/// <param name="after"></param>
|
||||||
public RetryAfterGuard(DateTime after)
|
/// <param name="type"></param>
|
||||||
|
public RetryAfterGuard(DateTime after, RateLimitItemType type)
|
||||||
{
|
{
|
||||||
After = after;
|
After = after;
|
||||||
|
Type = type;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public LimitCheck Check(RateLimitItemType type, RequestDefinition definition, string host, string? apiKey, int requestWeight)
|
public LimitCheck Check(RateLimitItemType type, RequestDefinition definition, string host, string? apiKey, int requestWeight)
|
||||||
{
|
{
|
||||||
|
if (type != Type)
|
||||||
|
return LimitCheck.NotApplicable;
|
||||||
|
|
||||||
var dif = (After + _windowBuffer) - DateTime.UtcNow;
|
var dif = (After + _windowBuffer) - DateTime.UtcNow;
|
||||||
if (dif <= TimeSpan.Zero)
|
if (dif <= TimeSpan.Zero)
|
||||||
return LimitCheck.NotApplicable;
|
return LimitCheck.NotApplicable;
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ using CryptoExchange.Net.RateLimiting.Interfaces;
|
|||||||
using CryptoExchange.Net.RateLimiting.Trackers;
|
using CryptoExchange.Net.RateLimiting.Trackers;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Security;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Guards
|
namespace CryptoExchange.Net.RateLimiting.Guards
|
||||||
{
|
{
|
||||||
@@ -65,7 +64,7 @@ namespace CryptoExchange.Net.RateLimiting.Guards
|
|||||||
|
|
||||||
var delay = tracker.GetWaitTime(requestWeight);
|
var delay = tracker.GetWaitTime(requestWeight);
|
||||||
if (delay == default)
|
if (delay == default)
|
||||||
return LimitCheck.NotNeeded;
|
return LimitCheck.NotNeeded(_limit, _period, tracker.Current);
|
||||||
|
|
||||||
return LimitCheck.Needed(delay, _limit, _period, tracker.Current);
|
return LimitCheck.Needed(delay, _limit, _period, tracker.Current);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using System.Security;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Interfaces
|
namespace CryptoExchange.Net.RateLimiting.Interfaces
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using CryptoExchange.Net.RateLimiting.Guards;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using System;
|
using System;
|
||||||
using System.Security;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
@@ -18,6 +16,11 @@ namespace CryptoExchange.Net.RateLimiting.Interfaces
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
event Action<RateLimitEvent> RateLimitTriggered;
|
event Action<RateLimitEvent> RateLimitTriggered;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Event when the rate limit is updated. Note that it's only updated when a request is send, so there are no specific updates when the current usage is decaying.
|
||||||
|
/// </summary>
|
||||||
|
event Action<RateLimitUpdateEvent>? RateLimitUpdated;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Add a rate limit guard
|
/// Add a rate limit guard
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -29,8 +32,9 @@ namespace CryptoExchange.Net.RateLimiting.Interfaces
|
|||||||
/// Set a RetryAfter guard, can be used when a server rate limit is hit and a RetryAfter header is specified
|
/// Set a RetryAfter guard, can be used when a server rate limit is hit and a RetryAfter header is specified
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="retryAfter">The time after which requests can be send again</param>
|
/// <param name="retryAfter">The time after which requests can be send again</param>
|
||||||
|
/// <param name="type">RateLimitType</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task SetRetryAfterGuardAsync(DateTime retryAfter);
|
Task SetRetryAfterGuardAsync(DateTime retryAfter, RateLimitItemType type = RateLimitItemType.Request);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns the 'retry after' timestamp if set
|
/// Returns the 'retry after' timestamp if set
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
using CryptoExchange.Net.Objects;
|
using CryptoExchange.Net.Objects;
|
||||||
using System.Net.Http;
|
|
||||||
using System.Security;
|
|
||||||
|
|
||||||
namespace CryptoExchange.Net.RateLimiting.Interfaces
|
namespace CryptoExchange.Net.RateLimiting.Interfaces
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// No wait needed
|
/// No wait needed
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static LimitCheck NotNeeded { get; } = new LimitCheck(true, default, default, default, default);
|
public static LimitCheck NotNeeded(int limit, TimeSpan period, int current) => new(true, default, limit, period, current);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Wait needed
|
/// Wait needed
|
||||||
|
|||||||
@@ -4,10 +4,14 @@ using System;
|
|||||||
namespace CryptoExchange.Net.RateLimiting
|
namespace CryptoExchange.Net.RateLimiting
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Rate limit event
|
/// Rate limit triggered event
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record RateLimitEvent
|
public record RateLimitEvent
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Id of the item the limit was checked for
|
||||||
|
/// </summary>
|
||||||
|
public int ItemId { get; set; }
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Name of the API limit that is reached
|
/// Name of the API limit that is reached
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -52,18 +56,9 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// ctor
|
/// ctor
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="apiLimit"></param>
|
public RateLimitEvent(int itemId, string apiLimit, string limitDescription, RequestDefinition definition, string host, int current, int requestWeight, int? limit, TimeSpan? timePeriod, TimeSpan? delayTime, RateLimitingBehaviour behaviour)
|
||||||
/// <param name="limitDescription"></param>
|
|
||||||
/// <param name="definition"></param>
|
|
||||||
/// <param name="host"></param>
|
|
||||||
/// <param name="current"></param>
|
|
||||||
/// <param name="requestWeight"></param>
|
|
||||||
/// <param name="limit"></param>
|
|
||||||
/// <param name="timePeriod"></param>
|
|
||||||
/// <param name="delayTime"></param>
|
|
||||||
/// <param name="behaviour"></param>
|
|
||||||
public RateLimitEvent(string apiLimit, string limitDescription, RequestDefinition definition, string host, int current, int requestWeight, int? limit, TimeSpan? timePeriod, TimeSpan? delayTime, RateLimitingBehaviour behaviour)
|
|
||||||
{
|
{
|
||||||
|
ItemId = itemId;
|
||||||
ApiLimit = apiLimit;
|
ApiLimit = apiLimit;
|
||||||
LimitDescription = limitDescription;
|
LimitDescription = limitDescription;
|
||||||
RequestDefinition = definition;
|
RequestDefinition = definition;
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ using System;
|
|||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Security;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
@@ -24,6 +23,8 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public event Action<RateLimitEvent>? RateLimitTriggered;
|
public event Action<RateLimitEvent>? RateLimitTriggered;
|
||||||
|
/// <inheritdoc />
|
||||||
|
public event Action<RateLimitUpdateEvent>? RateLimitUpdated;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// ctor
|
/// ctor
|
||||||
@@ -32,22 +33,30 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
{
|
{
|
||||||
_name = name;
|
_name = name;
|
||||||
_guards = new ConcurrentBag<IRateLimitGuard>();
|
_guards = new ConcurrentBag<IRateLimitGuard>();
|
||||||
_semaphore = new SemaphoreSlim(1);
|
_semaphore = new SemaphoreSlim(1, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task<CallResult> ProcessAsync(ILogger logger, int itemId, RateLimitItemType type, RequestDefinition definition, string host, string? apiKey, int requestWeight, RateLimitingBehaviour rateLimitingBehaviour, CancellationToken ct)
|
public async Task<CallResult> ProcessAsync(ILogger logger, int itemId, RateLimitItemType type, RequestDefinition definition, string host, string? apiKey, int requestWeight, RateLimitingBehaviour rateLimitingBehaviour, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await _semaphore.WaitAsync(ct).ConfigureAwait(false);
|
await _semaphore.WaitAsync(ct).ConfigureAwait(false);
|
||||||
|
bool release = true;
|
||||||
_waitingCount++;
|
_waitingCount++;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return await CheckGuardsAsync(_guards, logger, itemId, type, definition, host, apiKey, requestWeight, rateLimitingBehaviour, ct).ConfigureAwait(false);
|
return await CheckGuardsAsync(_guards, logger, itemId, type, definition, host, apiKey, requestWeight, rateLimitingBehaviour, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
|
// The semaphore has already been released if the task was cancelled
|
||||||
|
release = false;
|
||||||
|
return new CallResult(new CancellationRequestedError());
|
||||||
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
_waitingCount--;
|
_waitingCount--;
|
||||||
_semaphore.Release();
|
if (release)
|
||||||
|
_semaphore.Release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,16 +73,23 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
CancellationToken ct)
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
await _semaphore.WaitAsync(ct).ConfigureAwait(false);
|
await _semaphore.WaitAsync(ct).ConfigureAwait(false);
|
||||||
|
bool release = true;
|
||||||
_waitingCount++;
|
_waitingCount++;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return await CheckGuardsAsync(new IRateLimitGuard[] { guard }, logger, itemId, type, definition, host, apiKey, 1, rateLimitingBehaviour, ct).ConfigureAwait(false);
|
return await CheckGuardsAsync(new IRateLimitGuard[] { guard }, logger, itemId, type, definition, host, apiKey, 1, rateLimitingBehaviour, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
|
// The semaphore has already been released if the task was cancelled
|
||||||
|
release = false;
|
||||||
|
return new CallResult(new CancellationRequestedError());
|
||||||
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
_waitingCount--;
|
_waitingCount--;
|
||||||
_semaphore.Release();
|
if (release)
|
||||||
|
_semaphore.Release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,7 +107,7 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
else
|
else
|
||||||
logger.RateLimitRequestFailed(itemId, definition.Path, guard.Name, guard.Description);
|
logger.RateLimitRequestFailed(itemId, definition.Path, guard.Name, guard.Description);
|
||||||
|
|
||||||
RateLimitTriggered?.Invoke(new RateLimitEvent(_name, guard.Description, definition, host, result.Current, requestWeight, result.Limit, result.Period, result.Delay, rateLimitingBehaviour));
|
RateLimitTriggered?.Invoke(new RateLimitEvent(itemId, _name, guard.Description, definition, host, result.Current, requestWeight, result.Limit, result.Period, result.Delay, rateLimitingBehaviour));
|
||||||
return new CallResult(new ClientRateLimitError($"Rate limit check failed on guard {guard.Name}; {guard.Description}"));
|
return new CallResult(new ClientRateLimitError($"Rate limit check failed on guard {guard.Name}; {guard.Description}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,7 +122,7 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
else
|
else
|
||||||
logger.RateLimitDelayingRequest(itemId, definition.Path, result.Delay, guard.Name, description);
|
logger.RateLimitDelayingRequest(itemId, definition.Path, result.Delay, guard.Name, description);
|
||||||
|
|
||||||
RateLimitTriggered?.Invoke(new RateLimitEvent(_name, guard.Description, definition, host, result.Current, requestWeight, result.Limit, result.Period, result.Delay, rateLimitingBehaviour));
|
RateLimitTriggered?.Invoke(new RateLimitEvent(itemId, _name, guard.Description, definition, host, result.Current, requestWeight, result.Limit, result.Period, result.Delay, rateLimitingBehaviour));
|
||||||
await Task.Delay((int)result.Delay.TotalMilliseconds + 1, ct).ConfigureAwait(false);
|
await Task.Delay((int)result.Delay.TotalMilliseconds + 1, ct).ConfigureAwait(false);
|
||||||
await _semaphore.WaitAsync(ct).ConfigureAwait(false);
|
await _semaphore.WaitAsync(ct).ConfigureAwait(false);
|
||||||
return await CheckGuardsAsync(guards, logger, itemId, type, definition, host, apiKey, requestWeight, rateLimitingBehaviour, ct).ConfigureAwait(false);
|
return await CheckGuardsAsync(guards, logger, itemId, type, definition, host, apiKey, requestWeight, rateLimitingBehaviour, ct).ConfigureAwait(false);
|
||||||
@@ -119,6 +135,8 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
var result = guard.ApplyWeight(type, definition, host, apiKey, requestWeight);
|
var result = guard.ApplyWeight(type, definition, host, apiKey, requestWeight);
|
||||||
if (result.IsApplied)
|
if (result.IsApplied)
|
||||||
{
|
{
|
||||||
|
RateLimitUpdated?.Invoke(new RateLimitUpdateEvent(itemId, _name, guard.Description, result.Current, result.Limit, result.Period));
|
||||||
|
|
||||||
if (type == RateLimitItemType.Connection)
|
if (type == RateLimitItemType.Connection)
|
||||||
logger.RateLimitAppliedConnection(itemId, guard.Name, guard.Description, result.Current);
|
logger.RateLimitAppliedConnection(itemId, guard.Name, guard.Description, result.Current);
|
||||||
else
|
else
|
||||||
@@ -137,7 +155,7 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task SetRetryAfterGuardAsync(DateTime retryAfter)
|
public async Task SetRetryAfterGuardAsync(DateTime retryAfter, RateLimitItemType type)
|
||||||
{
|
{
|
||||||
await _semaphore.WaitAsync().ConfigureAwait(false);
|
await _semaphore.WaitAsync().ConfigureAwait(false);
|
||||||
|
|
||||||
@@ -145,7 +163,7 @@ namespace CryptoExchange.Net.RateLimiting
|
|||||||
{
|
{
|
||||||
var retryAfterGuard = _guards.OfType<RetryAfterGuard>().SingleOrDefault();
|
var retryAfterGuard = _guards.OfType<RetryAfterGuard>().SingleOrDefault();
|
||||||
if (retryAfterGuard == null)
|
if (retryAfterGuard == null)
|
||||||
_guards.Add(new RetryAfterGuard(retryAfter));
|
_guards.Add(new RetryAfterGuard(retryAfter, type));
|
||||||
else
|
else
|
||||||
retryAfterGuard.UpdateAfter(retryAfter);
|
retryAfterGuard.UpdateAfter(retryAfter);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
using CryptoExchange.Net.Objects;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.RateLimiting
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Rate limit update event
|
||||||
|
/// </summary>
|
||||||
|
public record RateLimitUpdateEvent
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Id of the item the limit was checked for
|
||||||
|
/// </summary>
|
||||||
|
public int ItemId { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Name of the API limit that is reached
|
||||||
|
/// </summary>
|
||||||
|
public string ApiLimit { get; set; } = string.Empty;
|
||||||
|
/// <summary>
|
||||||
|
/// Description of the limit that is reached
|
||||||
|
/// </summary>
|
||||||
|
public string LimitDescription { get; set; } = string.Empty;
|
||||||
|
/// <summary>
|
||||||
|
/// The current counter value
|
||||||
|
/// </summary>
|
||||||
|
public int Current { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// The limit per time period
|
||||||
|
/// </summary>
|
||||||
|
public int? Limit { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// The time period the limit is for
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan? TimePeriod { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public RateLimitUpdateEvent(int itemId, string apiLimit, string limitDescription, int current, int? limit, TimeSpan? timePeriod)
|
||||||
|
{
|
||||||
|
ItemId = itemId;
|
||||||
|
ApiLimit = apiLimit;
|
||||||
|
LimitDescription = limitDescription;
|
||||||
|
Current = current;
|
||||||
|
Limit = limit;
|
||||||
|
TimePeriod = timePeriod;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ namespace CryptoExchange.Net.Requests
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class RequestFactory : IRequestFactory
|
public class RequestFactory : IRequestFactory
|
||||||
{
|
{
|
||||||
private HttpClient? _httpClient;
|
private HttpClient? _httpClient;
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void Configure(ApiProxy? proxy, TimeSpan requestTimeout, HttpClient? client = null)
|
public void Configure(ApiProxy? proxy, TimeSpan requestTimeout, HttpClient? client = null)
|
||||||
@@ -19,7 +19,12 @@ namespace CryptoExchange.Net.Requests
|
|||||||
if (client == null)
|
if (client == null)
|
||||||
{
|
{
|
||||||
var handler = new HttpClientHandler();
|
var handler = new HttpClientHandler();
|
||||||
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
|
try
|
||||||
|
{
|
||||||
|
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
|
||||||
|
}
|
||||||
|
catch (PlatformNotSupportedException) { }
|
||||||
|
|
||||||
if (proxy != null)
|
if (proxy != null)
|
||||||
{
|
{
|
||||||
handler.Proxy = new WebProxy
|
handler.Proxy = new WebProxy
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Fee asset selection type
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedFeeAssetType
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Fee is always in the base asset
|
||||||
|
/// </summary>
|
||||||
|
BaseAsset,
|
||||||
|
/// <summary>
|
||||||
|
/// Fee is always in the quote asset
|
||||||
|
/// </summary>
|
||||||
|
QuoteAsset,
|
||||||
|
/// <summary>
|
||||||
|
/// Fee is always in the input asset
|
||||||
|
/// </summary>
|
||||||
|
InputAsset,
|
||||||
|
/// <summary>
|
||||||
|
/// Fee is always in the output asset
|
||||||
|
/// </summary>
|
||||||
|
OutputAsset,
|
||||||
|
/// <summary>
|
||||||
|
/// Fee is variable
|
||||||
|
/// </summary>
|
||||||
|
Variable
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Fee deduction type
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedFeeDeductionType
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The fee is deducted from the output amount. For example buying 1 ETH at 1000 USDT with a 1% fee would cost 1000 USDT and output 0.99 ETH
|
||||||
|
/// </summary>
|
||||||
|
DeductFromOutput,
|
||||||
|
/// <summary>
|
||||||
|
/// The fee is added to the order cost. For example buying 1 ETH at 1000 USDT with a 1% fee would cost 1010 USDT and output 1 ETH
|
||||||
|
/// </summary>
|
||||||
|
AddToCost
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Kline interval
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedKlineInterval
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 5 min
|
||||||
|
/// </summary>
|
||||||
|
FiveMinutes = 60 * 5,
|
||||||
|
/// <summary>
|
||||||
|
/// 15 min
|
||||||
|
/// </summary>
|
||||||
|
FifteenMinutes = 60 * 15,
|
||||||
|
/// <summary>
|
||||||
|
/// 1 hour
|
||||||
|
/// </summary>
|
||||||
|
OneHour = 60 * 60,
|
||||||
|
/// <summary>
|
||||||
|
/// 1 day
|
||||||
|
/// </summary>
|
||||||
|
OneDay = 60 * 60 * 24,
|
||||||
|
/// <summary>
|
||||||
|
/// 1 week
|
||||||
|
/// </summary>
|
||||||
|
OneWeek = 60 * 60 * 24 * 7,
|
||||||
|
/// <summary>
|
||||||
|
/// 1 month
|
||||||
|
/// </summary>
|
||||||
|
OneMonth = 60 * 60 * 24 * 30
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Leverage setting mode
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedLeverageSettingMode
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Leverage is configured per side (in hedge mode)
|
||||||
|
/// </summary>
|
||||||
|
PerSide,
|
||||||
|
/// <summary>
|
||||||
|
/// Leverage is configured for the symbol
|
||||||
|
/// </summary>
|
||||||
|
PerSymbol,
|
||||||
|
/// <summary>
|
||||||
|
/// Leverage is configured for the entire account
|
||||||
|
/// </summary>
|
||||||
|
PerAccount
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Margin mode
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedMarginMode
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Cross margin, margin is shared across symbols
|
||||||
|
/// </summary>
|
||||||
|
Cross,
|
||||||
|
/// <summary>
|
||||||
|
/// Isolated margin, margin is isolated on a symbol
|
||||||
|
/// </summary>
|
||||||
|
Isolated
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Side of an order
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedOrderSide
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Buy order
|
||||||
|
/// </summary>
|
||||||
|
Buy,
|
||||||
|
/// <summary>
|
||||||
|
/// Sell order
|
||||||
|
/// </summary>
|
||||||
|
Sell
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Status of an order
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedOrderStatus
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Order is open waiting to be filled
|
||||||
|
/// </summary>
|
||||||
|
Open,
|
||||||
|
/// <summary>
|
||||||
|
/// Order has been fully filled
|
||||||
|
/// </summary>
|
||||||
|
Filled,
|
||||||
|
/// <summary>
|
||||||
|
/// Order has been canceled
|
||||||
|
/// </summary>
|
||||||
|
Canceled
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Type of an order
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedOrderType
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Limit order, execute at a specific price
|
||||||
|
/// </summary>
|
||||||
|
Limit,
|
||||||
|
/// <summary>
|
||||||
|
/// Limit maker order, a limit order with the condition that is will never be executed as a maker
|
||||||
|
/// </summary>
|
||||||
|
LimitMaker,
|
||||||
|
/// <summary>
|
||||||
|
/// Market order, execute at the best price currently available
|
||||||
|
/// </summary>
|
||||||
|
Market,
|
||||||
|
/// <summary>
|
||||||
|
/// Other order type, used for parsing unsupported order types
|
||||||
|
/// </summary>
|
||||||
|
Other
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Supported pagination type
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedPaginationSupport
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Pagination is not supported for this exchange request
|
||||||
|
/// </summary>
|
||||||
|
NotSupported,
|
||||||
|
/// <summary>
|
||||||
|
/// Pagination is in ascending order
|
||||||
|
/// </summary>
|
||||||
|
Ascending,
|
||||||
|
/// <summary>
|
||||||
|
/// Pagination is in descending order
|
||||||
|
/// </summary>
|
||||||
|
Descending
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Position mode
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedPositionMode
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Hedge mode, a symbol can have both a long and a short position at the same time
|
||||||
|
/// </summary>
|
||||||
|
HedgeMode,
|
||||||
|
/// <summary>
|
||||||
|
/// One way mode, a symbol can only have one open position side at a time
|
||||||
|
/// </summary>
|
||||||
|
OneWay
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Position mode selection type
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedPositionModeSelection
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Position mode is configured per symbol
|
||||||
|
/// </summary>
|
||||||
|
PerSymbol,
|
||||||
|
/// <summary>
|
||||||
|
/// Position mode is configured for the entire account
|
||||||
|
/// </summary>
|
||||||
|
PerAccount
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The side of a position
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedPositionSide
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Long position
|
||||||
|
/// </summary>
|
||||||
|
Long,
|
||||||
|
/// <summary>
|
||||||
|
/// Short position
|
||||||
|
/// </summary>
|
||||||
|
Short
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Quote asset order quantity support
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedQuantityType
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Quantity should be in the base asset
|
||||||
|
/// </summary>
|
||||||
|
BaseAsset,
|
||||||
|
/// <summary>
|
||||||
|
/// Quantity should be in the quote asset
|
||||||
|
/// </summary>
|
||||||
|
QuoteAsset,
|
||||||
|
/// <summary>
|
||||||
|
/// Quantity is in the number of contracts
|
||||||
|
/// </summary>
|
||||||
|
Contracts,
|
||||||
|
/// <summary>
|
||||||
|
/// Quantity can be either base or quote quantity
|
||||||
|
/// </summary>
|
||||||
|
BaseAndQuoteAsset
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The role of a trade
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedRole
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Maker role, put an order on the order book which has been filled
|
||||||
|
/// </summary>
|
||||||
|
Maker,
|
||||||
|
/// <summary>
|
||||||
|
/// Taker role, took an order of the order book to fill
|
||||||
|
/// </summary>
|
||||||
|
Taker
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Type of a symbol
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedSymbolType
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Perpetual linear, contract has no delivery date and is settled in stablecoin
|
||||||
|
/// </summary>
|
||||||
|
PerpetualLinear,
|
||||||
|
/// <summary>
|
||||||
|
/// Perpetual inverse, contract has no delivery date and is settled in crypto
|
||||||
|
/// </summary>
|
||||||
|
PerpetualInverse,
|
||||||
|
/// <summary>
|
||||||
|
/// Delivery linear, contract has a specific delivery date and is settled in stablecoin
|
||||||
|
/// </summary>
|
||||||
|
DeliveryLinear,
|
||||||
|
/// <summary>
|
||||||
|
/// Delivery inverse, contract has a specific delivery date and is settled in crypto
|
||||||
|
/// </summary>
|
||||||
|
DeliveryInverse
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Time in force for an order
|
||||||
|
/// </summary>
|
||||||
|
public enum SharedTimeInForce
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Order is good until canceled
|
||||||
|
/// </summary>
|
||||||
|
GoodTillCanceled,
|
||||||
|
/// <summary>
|
||||||
|
/// Order should execute immediately, not executed part is canceled
|
||||||
|
/// </summary>
|
||||||
|
ImmediateOrCancel,
|
||||||
|
/// <summary>
|
||||||
|
/// Order should execute fully immediately or is fully canceled
|
||||||
|
/// </summary>
|
||||||
|
FillOrKill
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Trading mode
|
||||||
|
/// </summary>
|
||||||
|
public enum TradingMode
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Spot trading
|
||||||
|
/// </summary>
|
||||||
|
Spot,
|
||||||
|
/// <summary>
|
||||||
|
/// Perpetual linear futures
|
||||||
|
/// </summary>
|
||||||
|
PerpetualLinear,
|
||||||
|
/// <summary>
|
||||||
|
/// Delivery linear futures
|
||||||
|
/// </summary>
|
||||||
|
DeliveryLinear,
|
||||||
|
/// <summary>
|
||||||
|
/// Perpetual inverse futures
|
||||||
|
/// </summary>
|
||||||
|
PerpetualInverse,
|
||||||
|
/// <summary>
|
||||||
|
/// Delivery inverse futures
|
||||||
|
/// </summary>
|
||||||
|
DeliveryInverse
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A token which a request can use to retrieve the next page if there are more pages in the result set
|
||||||
|
/// </summary>
|
||||||
|
public interface INextPageToken
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A datetime offset token
|
||||||
|
/// </summary>
|
||||||
|
public record DateTimeToken: INextPageToken
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Last result time
|
||||||
|
/// </summary>
|
||||||
|
public DateTime LastTime { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public DateTimeToken(DateTime timestamp)
|
||||||
|
{
|
||||||
|
LastTime = timestamp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A current page index token
|
||||||
|
/// </summary>
|
||||||
|
public record PageToken: INextPageToken
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The next page index
|
||||||
|
/// </summary>
|
||||||
|
public int Page { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Page size
|
||||||
|
/// </summary>
|
||||||
|
public int PageSize { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public PageToken(int page, int pageSize)
|
||||||
|
{
|
||||||
|
Page = page;
|
||||||
|
PageSize = pageSize;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A id offset token
|
||||||
|
/// </summary>
|
||||||
|
public record FromIdToken : INextPageToken
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The last id from previous result
|
||||||
|
/// </summary>
|
||||||
|
public string FromToken { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public FromIdToken(string fromToken)
|
||||||
|
{
|
||||||
|
FromToken = fromToken;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A cursor token
|
||||||
|
/// </summary>
|
||||||
|
public record CursorToken : INextPageToken
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The next page cursor
|
||||||
|
/// </summary>
|
||||||
|
public string Cursor { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public CursorToken(string cursor)
|
||||||
|
{
|
||||||
|
Cursor = cursor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A result offset token
|
||||||
|
/// </summary>
|
||||||
|
public record OffsetToken : INextPageToken
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Offset in the result set
|
||||||
|
/// </summary>
|
||||||
|
public int Offset { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ctor
|
||||||
|
/// </summary>
|
||||||
|
public OffsetToken(int offset)
|
||||||
|
{
|
||||||
|
Offset = offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using CryptoExchange.Net.Objects;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A shared/common client interface
|
||||||
|
/// </summary>
|
||||||
|
public interface ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Name of the exchange
|
||||||
|
/// </summary>
|
||||||
|
string Exchange { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Which trading modes this client supports
|
||||||
|
/// </summary>
|
||||||
|
TradingMode[] SupportedTradingModes { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether or not API credentials have been configured for this client. Does not check the credentials are actually valid.
|
||||||
|
/// </summary>
|
||||||
|
bool Authenticated { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Format a base and quote asset to an exchange accepted symbol
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="baseAsset">The base asset</param>
|
||||||
|
/// <param name="quoteAsset">The quote asset</param>
|
||||||
|
/// <param name="tradingMode">The trading mode</param>
|
||||||
|
/// <param name="deliverDate">The deliver date for a delivery futures symbol</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
string FormatSymbol(string baseAsset, string quoteAsset, TradingMode tradingMode, DateTime? deliverDate = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Set a default exchange parameter. This can be used instead of passing in an ExchangeParameters object which each request.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="name">Parameter name</param>
|
||||||
|
/// <param name="value">Parameter value</param>
|
||||||
|
void SetDefaultExchangeParameter(string name, object value);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reset the default exchange parameters, resets parameters for all exchanges
|
||||||
|
/// </summary>
|
||||||
|
void ResetDefaultExchangeParameters();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for request funding rate records
|
||||||
|
/// </summary>
|
||||||
|
public interface IFundingRateRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Funding rate request options
|
||||||
|
/// </summary>
|
||||||
|
GetFundingRateHistoryOptions GetFundingRateHistoryOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get funding rate records
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedFundingRate>>> GetFundingRateHistoryAsync(GetFundingRateHistoryRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for placing and managing futures orders
|
||||||
|
/// </summary>
|
||||||
|
public interface IFuturesOrderRestClient : 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
|
||||||
|
/// </summary>
|
||||||
|
IEnumerable<SharedOrderType> FuturesSupportedOrderTypes { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Supported time in force
|
||||||
|
/// </summary>
|
||||||
|
IEnumerable<SharedTimeInForce> FuturesSupportedTimeInForce { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Quantity types support
|
||||||
|
/// </summary>
|
||||||
|
SharedQuantitySupport FuturesSupportedOrderQuantity { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Futures place order request options
|
||||||
|
/// </summary>
|
||||||
|
PlaceFuturesOrderOptions PlaceFuturesOrderOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Place a new futures order
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedId>> PlaceFuturesOrderAsync(PlaceFuturesOrderRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Futures get order request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetOrderRequest> GetFuturesOrderOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get info on a specific futures order
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedFuturesOrder>> GetFuturesOrderAsync(GetOrderRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Futures get open orders request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetOpenOrdersRequest> GetOpenFuturesOrdersOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get info on a open futures orders
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedFuturesOrder>>> GetOpenFuturesOrdersAsync(GetOpenOrdersRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Spot get closed orders request options
|
||||||
|
/// </summary>
|
||||||
|
PaginatedEndpointOptions<GetClosedOrdersRequest> GetClosedFuturesOrdersOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get info on closed futures orders
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedFuturesOrder>>> GetClosedFuturesOrdersAsync(GetClosedOrdersRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Futures get order trades request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetOrderTradesRequest> GetFuturesOrderTradesOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get trades for a specific futures order
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedUserTrade>>> GetFuturesOrderTradesAsync(GetOrderTradesRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Futures user trades request options
|
||||||
|
/// </summary>
|
||||||
|
PaginatedEndpointOptions<GetUserTradesRequest> GetFuturesUserTradesOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get futures user trade records
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedUserTrade>>> GetFuturesUserTradesAsync(GetUserTradesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Futures cancel order request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<CancelOrderRequest> CancelFuturesOrderOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Cancel a futures order
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedId>> CancelFuturesOrderAsync(CancelOrderRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Positions request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetPositionsRequest> GetPositionsOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get open position info
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedPosition>>> GetPositionsAsync(GetPositionsRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Close position order request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<ClosePositionRequest> ClosePositionOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Close a currently open position
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ExchangeWebResult<SharedId>> ClosePositionAsync(ClosePositionRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for request futures symbol info
|
||||||
|
/// </summary>
|
||||||
|
public interface IFuturesSymbolRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Futures symbol request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetSymbolsRequest> GetFuturesSymbolsOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get info on all futures symbols supported on the exchagne
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedFuturesSymbol>>> GetFuturesSymbolsAsync(GetSymbolsRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for requesting ticker info for futures symbols
|
||||||
|
/// </summary>
|
||||||
|
public interface IFuturesTickerRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Futures get ticker request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetTickerRequest> GetFuturesTickerOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get ticker info for a specific futures symbol
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedFuturesTicker>> GetFuturesTickerAsync(GetTickerRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Futures get tickers request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetTickersRequest> GetFuturesTickersOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get ticker info for aall futures symbols
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedFuturesTicker>>> GetFuturesTickersAsync(GetTickersRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for getting the index price klines for a symbol
|
||||||
|
/// </summary>
|
||||||
|
public interface IIndexPriceKlineRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Index price klines request options
|
||||||
|
/// </summary>
|
||||||
|
GetKlinesOptions GetIndexPriceKlinesOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get index price kline/candlestick data
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedFuturesKline>>> GetIndexPriceKlinesAsync(GetKlinesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for managing the leverage of a symbol
|
||||||
|
/// </summary>
|
||||||
|
public interface ILeverageRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// How the leverage setting is configured on the exchange
|
||||||
|
/// </summary>
|
||||||
|
SharedLeverageSettingMode LeverageSettingType { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Leverage request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetLeverageRequest> GetLeverageOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get the current leverage setting for a symbol
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedLeverage>> GetLeverageAsync(GetLeverageRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Leverage set request options
|
||||||
|
/// </summary>
|
||||||
|
SetLeverageOptions SetLeverageOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Set the leverage for a symbol
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedLeverage>> SetLeverageAsync(SetLeverageRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for getting the mark price klines for a symbol
|
||||||
|
/// </summary>
|
||||||
|
public interface IMarkPriceKlineRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Mark price klines request options
|
||||||
|
/// </summary>
|
||||||
|
GetKlinesOptions GetMarkPriceKlinesOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get mark price kline/candlestick data
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedFuturesKline>>> GetMarkPriceKlinesAsync(GetKlinesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for getting the open interest for a symbol
|
||||||
|
/// </summary>
|
||||||
|
public interface IOpenInterestRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Open interest request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetOpenInterestRequest> GetOpenInterestOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get the open interest for a symbol
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedOpenInterest>> GetOpenInterestAsync(GetOpenInterestRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for getting position history
|
||||||
|
/// </summary>
|
||||||
|
public interface IPositionHistoryRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Position history request options
|
||||||
|
/// </summary>
|
||||||
|
GetPositionHistoryOptions GetPositionHistoryOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get position history
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedPositionHistory>>> GetPositionHistoryAsync(GetPositionHistoryRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for managing the position mode setting
|
||||||
|
/// </summary>
|
||||||
|
public interface IPositionModeRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// How the exchange handles setting the position mode
|
||||||
|
/// </summary>
|
||||||
|
SharedPositionModeSelection PositionModeSettingType { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Position mode request options
|
||||||
|
/// </summary>
|
||||||
|
GetPositionModeOptions GetPositionModeOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get the current position mode setting
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedPositionModeResult>> GetPositionModeAsync(GetPositionModeRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Position mode set request options
|
||||||
|
/// </summary>
|
||||||
|
SetPositionModeOptions SetPositionModeOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Set the position mode to a new value
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedPositionModeResult>> SetPositionModeAsync(SetPositionModeRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for requesting asset info
|
||||||
|
/// </summary>
|
||||||
|
public interface IAssetsRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Asset request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetAssetRequest> GetAssetOptions { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get info on a specific asset
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<SharedAsset>> GetAssetAsync(GetAssetRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Assets request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetAssetsRequest> GetAssetsOptions { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get info on all assets the exchange supports
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedAsset>>> GetAssetsAsync(GetAssetsRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for requesting user balance info
|
||||||
|
/// </summary>
|
||||||
|
public interface IBalanceRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Balances request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetBalancesRequest> GetBalancesOptions { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get balances for the user
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedBalance>>> GetBalancesAsync(GetBalancesRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for requesting deposit addresses and deposit records
|
||||||
|
/// </summary>
|
||||||
|
public interface IDepositRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Deposit addresses request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<GetDepositAddressesRequest> GetDepositAddressesOptions { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get deposit addresses for an asset
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedDepositAddress>>> GetDepositAddressesAsync(GetDepositAddressesRequest request, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Deposits request options
|
||||||
|
/// </summary>
|
||||||
|
GetDepositsOptions GetDepositsOptions { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get deposit records
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedDeposit>>> GetDepositsAsync(GetDepositsRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for requesting kline/candlestick data
|
||||||
|
/// </summary>
|
||||||
|
public interface IKlineRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Kline request options
|
||||||
|
/// </summary>
|
||||||
|
GetKlinesOptions GetKlinesOptions { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get kline/candlestick data
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="nextPageToken">The pagination token from the previous request to continue pagination</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ExchangeWebResult<IEnumerable<SharedKline>>> GetKlinesAsync(GetKlinesRequest request, INextPageToken? nextPageToken = null, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace CryptoExchange.Net.SharedApis
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for managing the listen key for user stream updates
|
||||||
|
/// </summary>
|
||||||
|
public interface IListenKeyRestClient : ISharedClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Start listen key request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<StartListenKeyRequest> StartOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Get the listen key which can be used for user data updates on the socket client
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ExchangeWebResult<string>> StartListenKeyAsync(StartListenKeyRequest request, CancellationToken ct = default);
|
||||||
|
/// <summary>
|
||||||
|
/// Keep-alive listen key request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<KeepAliveListenKeyRequest> KeepAliveOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Keep-alive the listen key, needs to be called at a regular interval (typically every 30 minutes)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ExchangeWebResult<string>> KeepAliveListenKeyAsync(KeepAliveListenKeyRequest request, CancellationToken ct = default);
|
||||||
|
/// <summary>
|
||||||
|
/// Stop listen key request options
|
||||||
|
/// </summary>
|
||||||
|
EndpointOptions<StopListenKeyRequest> StopOptions { get; }
|
||||||
|
/// <summary>
|
||||||
|
/// Stop the listen key, updates will no longer be send to the user data stream for this listen key
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">Request info</param>
|
||||||
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ExchangeWebResult<string>> StopListenKeyAsync(StopListenKeyRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user