Skip to content

Commit

Permalink
Updated client order id logic for spot API, added AllowAppendingClien…
Browse files Browse the repository at this point in the history
…tOrderId option
  • Loading branch information
JKorf committed Dec 2, 2024
1 parent b5c987d commit 3fcfea6
Show file tree
Hide file tree
Showing 20 changed files with 100 additions and 44 deletions.
3 changes: 0 additions & 3 deletions HTX.Net/Clients/SpotApi/HTXRestClientSpotApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ internal partial class HTXRestClientSpotApi : RestApiClient, IHTXRestClientSpotA
/// <inheritdoc />
public string ExchangeName => "HTX";

internal readonly string _brokerId;

#region Api clients

/// <inheritdoc />
Expand All @@ -57,7 +55,6 @@ internal HTXRestClientSpotApi(ILogger logger, HttpClient? httpClient, HTXRestOpt
Margin = new HTXRestClientSpotApiMargin(this);
Trading = new HTXRestClientSpotApiTrading(this);

_brokerId = !string.IsNullOrEmpty(options.BrokerId) ? options.BrokerId! : "AA1ef14811";
}
#endregion

Expand Down
21 changes: 14 additions & 7 deletions HTX.Net/Clients/SpotApi/HTXRestClientSpotApiTrading.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public async Task<WebCallResult<long>> PlaceOrderAsync(
};
parameters.AddString("amount", quantity);

clientOrderId ??= ExchangeHelpers.AppendRandomString(_baseClient._brokerId, 64);
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, HTXExchange.ClientOrderId, 64, _baseClient.ClientOptions.AllowAppendingClientOrderId);

parameters.AddOptionalParameter("client-order-id", clientOrderId);
parameters.AddOptionalString("stop-price", stopPrice);
Expand Down Expand Up @@ -84,8 +84,8 @@ public async Task<WebCallResult<IEnumerable<HTXBatchPlaceResult>>> PlaceMultiple
{ "type", orderType }
};
parameters.AddString("amount", order.Quantity);
order.ClientOrderId ??= ExchangeHelpers.AppendRandomString(_baseClient._brokerId, 64);

order.ClientOrderId = LibraryHelpers.ApplyBrokerId(order.ClientOrderId, HTXExchange.ClientOrderId, 64, _baseClient.ClientOptions.AllowAppendingClientOrderId);
parameters.AddOptionalParameter("client-order-id", order.ClientOrderId);
parameters.AddOptionalString("stop-price", order.StopPrice);
parameters.AddOptionalEnum("source", order.Source);
Expand Down Expand Up @@ -180,6 +180,8 @@ public async Task<WebCallResult<long>> CancelOrderAsync(long orderId, Cancellati
/// <inheritdoc />
public async Task<WebCallResult<long>> CancelOrderByClientOrderIdAsync(string clientOrderId, CancellationToken ct = default)
{
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, HTXExchange.ClientOrderId, 64, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection()
{
{ "client-order-id", clientOrderId }
Expand Down Expand Up @@ -239,8 +241,8 @@ public async Task<WebCallResult<HTXBatchCancelResult>> CancelOrdersAsync(IEnumer
throw new ArgumentException("Either orderIds or clientOrderIds should be provided");

var parameters = new ParameterCollection();
parameters.AddOptionalParameter("order-ids", orderIds?.Select(s => s.ToString(CultureInfo.InvariantCulture)));
parameters.AddOptionalParameter("client-order-ids", clientOrderIds?.Select(s => s.ToString(CultureInfo.InvariantCulture)));
parameters.AddOptionalParameter("order-ids", orderIds?.Select(s => s.ToString(CultureInfo.InvariantCulture)).ToArray());
parameters.AddOptionalParameter("client-order-ids", clientOrderIds?.Select(s => LibraryHelpers.ApplyBrokerId(s, HTXExchange.ClientOrderId, 64, _baseClient.ClientOptions.AllowAppendingClientOrderId).ToString(CultureInfo.InvariantCulture)).ToArray());

var request = _definitions.GetOrCreate(HttpMethod.Post, "v1/order/orders/batchcancel", HTXExchange.RateLimiter.EndpointLimit, 1, true,
new SingleLimitGuard(50, TimeSpan.FromSeconds(2), RateLimitWindowType.Sliding, keySelector: SingleLimitGuard.PerApiKey));
Expand Down Expand Up @@ -268,6 +270,8 @@ public async Task<WebCallResult<HTXOrder>> GetOrderAsync(long orderId, Cancellat
/// <inheritdoc />
public async Task<WebCallResult<HTXOrder>> GetOrderByClientOrderIdAsync(string clientOrderId, CancellationToken ct = default)
{
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, HTXExchange.ClientOrderId, 64, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection()
{
{ "clientOrderId", clientOrderId }
Expand Down Expand Up @@ -381,13 +385,14 @@ public async Task<WebCallResult<HTXPlacedConditionalOrder>> PlaceConditionalOrde
{
symbol = symbol.ToLowerInvariant();

clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, HTXExchange.ClientOrderId, 64, _baseClient.ClientOptions.AllowAppendingClientOrderId);
var parameters = new ParameterCollection()
{
{ "accountId", accountId },
{ "symbol", symbol },
{ "orderSide", EnumConverter.GetString(side) },
{ "orderType", EnumConverter.GetString(type) },
{ "clientOrderId", clientOrderId ?? Guid.NewGuid().ToString() }
{ "clientOrderId", clientOrderId }
};
parameters.AddString("stopPrice", stopPrice);

Expand All @@ -411,7 +416,7 @@ public async Task<WebCallResult<HTXConditionalOrderCancelResult>> CancelConditio
{
var parameters = new ParameterCollection()
{
{ "clientOrderIds", clientOrderIds }
{ "clientOrderIds", clientOrderIds.Select(x => LibraryHelpers.ApplyBrokerId(x, HTXExchange.ClientOrderId, 64, _baseClient.ClientOptions.AllowAppendingClientOrderId)).ToArray() }
};

var request = _definitions.GetOrCreate(HttpMethod.Post, $"v2/algo-orders/cancellation", HTXExchange.RateLimiter.EndpointLimit, 1, true,
Expand Down Expand Up @@ -488,6 +493,8 @@ public async Task<WebCallResult<IEnumerable<HTXConditionalOrder>>> GetClosedCond
/// <inheritdoc />
public async Task<WebCallResult<HTXConditionalOrder>> GetConditionalOrderAsync(string clientOrderId, CancellationToken ct = default)
{
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, HTXExchange.ClientOrderId, 64, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection()
{
{ "clientOrderId", clientOrderId }
Expand Down
19 changes: 10 additions & 9 deletions HTX.Net/Clients/SpotApi/HTXSocketClientSpotApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@ internal partial class HTXSocketClientSpotApi : SocketApiClient, IHTXSocketClien
private static readonly MessagePath _channelPath = MessagePath.Get().Property("ch");
private static readonly MessagePath _pingPath = MessagePath.Get().Property("ping");

#region fields
internal readonly string _brokerId;
#endregion
/// <inheritdoc />
public new HTXSocketOptions ClientOptions => (HTXSocketOptions)base.ClientOptions;

#region ctor
internal HTXSocketClientSpotApi(ILogger logger, HTXSocketOptions options)
Expand All @@ -43,8 +42,6 @@ internal HTXSocketClientSpotApi(ILogger logger, HTXSocketOptions options)

RateLimiter = HTXExchange.RateLimiter.SpotConnection;

_brokerId = !string.IsNullOrEmpty(options.BrokerId) ? options.BrokerId! : "AA1ef14811";

SetDedicatedConnection(options.Environment.SocketBaseAddress.AppendPath("ws/trade"), true);
}

Expand Down Expand Up @@ -299,7 +296,7 @@ public async Task<CallResult<string>> PlaceOrderAsync(
var request = new HTXSocketPlaceOrderRequest()
{
AccountId = accountId,
ClientOrderId = clientOrderId ?? ExchangeHelpers.AppendRandomString(_brokerId, 64),
ClientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, HTXExchange.ClientOrderId, 64, ClientOptions.AllowAppendingClientOrderId),
Price = price,
Type = orderType,
Quantity = quantity,
Expand Down Expand Up @@ -333,7 +330,7 @@ public async Task<CallResult<IEnumerable<HTXBatchPlaceResult>>> PlaceMultipleOrd
var parameters = new HTXSocketPlaceOrderRequest()
{
AccountId = long.Parse(order.AccountId),
ClientOrderId = order.ClientOrderId ?? ExchangeHelpers.AppendRandomString(_brokerId, 64),
ClientOrderId = LibraryHelpers.ApplyBrokerId(order.ClientOrderId, HTXExchange.ClientOrderId, 64, ClientOptions.AllowAppendingClientOrderId),
Price = order.Price,
Type = orderType,
Quantity = order.Quantity,
Expand Down Expand Up @@ -429,6 +426,9 @@ public async Task<CallResult> CancelOrdersAsync(
string? clientOrderId = null,
CancellationToken ct = default)
{
if (clientOrderId != null)
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, HTXExchange.ClientOrderId, 64, ClientOptions.AllowAppendingClientOrderId);

var result = await CancelOrdersAsync(orderId == null ? null : [orderId], clientOrderId == null ? null : [clientOrderId], ct).ConfigureAwait(false);
if (!result)
return result.AsDataless();
Expand All @@ -445,9 +445,10 @@ public async Task<CallResult<HTXBatchCancelResult>> CancelOrdersAsync(
IEnumerable<string>? clientOrderIds = null,
CancellationToken ct = default)
{

var parameters = new ParameterCollection();
parameters.AddOptional("order-ids", orderIds);
parameters.AddOptional("client-order-ids", clientOrderIds);
parameters.AddOptional("order-ids", orderIds?.ToArray());
parameters.AddOptional("client-order-ids", clientOrderIds?.Select(x => LibraryHelpers.ApplyBrokerId(x, HTXExchange.ClientOrderId, 64, ClientOptions.AllowAppendingClientOrderId)).ToArray());

var query = new HTXOrderQuery<ParameterCollection, HTXBatchCancelResult>(new HTXSocketOrderRequest<ParameterCollection>
{
Expand Down
3 changes: 0 additions & 3 deletions HTX.Net/Clients/UsdtFutures/HTXRestClientUsdtFuturesApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ internal partial class HTXRestClientUsdtFuturesApi : RestApiClient, IHTXRestClie
/// <inheritdoc />
public string ExchangeName => "HTX";

internal readonly string _brokerId;

#region Api clients

/// <inheritdoc />
Expand All @@ -43,7 +41,6 @@ internal HTXRestClientUsdtFuturesApi(ILogger log, HttpClient? httpClient, HTXRes
SubAccount = new HTXRestClientUsdtFuturesApiSubAccount(this);
Trading = new HTXRestClientUsdtFuturesApiTrading(this);

_brokerId = !string.IsNullOrEmpty(options.BrokerId) ? options.BrokerId! : "AA1ef14811";
}
#endregion

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public async Task<WebCallResult<HTXOrderIds>> PlaceIsolatedMarginOrderAsync(
{ "volume", quantity },
{ "direction", EnumConverter.GetString(side) },
{ "lever_rate", leverageRate },
{ "channel_code", _baseClient._brokerId },
{ "channel_code", HTXExchange.ClientOrderId },
{ "order_price_type", EnumConverter.GetString(orderPriceType) }
};
parameters.AddOptionalParameter("price", price?.ToString(CultureInfo.InvariantCulture));
Expand Down Expand Up @@ -105,7 +105,7 @@ public async Task<WebCallResult<HTXOrderIds>> PlaceCrossMarginOrderAsync(
{ "volume", quantity },
{ "direction", EnumConverter.GetString(side) },
{ "lever_rate", leverageRate },
{ "channel_code", _baseClient._brokerId },
{ "channel_code", HTXExchange.ClientOrderId },
{ "order_price_type", EnumConverter.GetString(orderPriceType) }
};
parameters.AddOptionalParameter("contract_code", contractCode);
Expand Down Expand Up @@ -554,7 +554,7 @@ public async Task<WebCallResult<HTXOrderIds>> PlaceIsolatedMarginTriggerOrderAsy
{
var parameters = new ParameterCollection()
{
{ "channel_code", _baseClient._brokerId }
{ "channel_code", HTXExchange.ClientOrderId }
};
parameters.Add("contract_code", contractCode);
parameters.AddEnum("trigger_type", triggerType);
Expand All @@ -580,7 +580,7 @@ public async Task<WebCallResult<HTXOrderIds>> PlaceCrossMarginTriggerOrderAsync(
{
var parameters = new ParameterCollection()
{
{ "channel_code", _baseClient._brokerId }
{ "channel_code", HTXExchange.ClientOrderId }
};
parameters.AddOptional("contract_code", contractCode);
parameters.AddEnum("trigger_type", triggerType);
Expand Down Expand Up @@ -966,7 +966,7 @@ public async Task<WebCallResult<HTXOrderIds>> PlaceIsolatedMarginTrailingOrderAs
{
var parameters = new ParameterCollection()
{
{ "channel_code", _baseClient._brokerId }
{ "channel_code", HTXExchange.ClientOrderId }
};
parameters.Add("contract_code", contractCode);
parameters.Add("reduce_only", reduceOnly ? 1 : 0);
Expand All @@ -991,7 +991,7 @@ public async Task<WebCallResult<HTXOrderIds>> PlaceCrossMarginTrailingOrderAsync
{
var parameters = new ParameterCollection()
{
{ "channel_code", _baseClient._brokerId }
{ "channel_code", HTXExchange.ClientOrderId }
};
parameters.AddOptional("contract_code", contractCode);
parameters.AddOptional("pair", pair);
Expand Down
2 changes: 1 addition & 1 deletion HTX.Net/HTX.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="CryptoExchange.Net" Version="8.4.0" />
<PackageReference Include="CryptoExchange.Net" Version="8.4.2" />
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
35 changes: 29 additions & 6 deletions HTX.Net/HTX.Net.xml
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,9 @@
<member name="T:HTX.Net.Clients.SpotApi.HTXSocketClientSpotApi">
<inheritdoc />
</member>
<member name="P:HTX.Net.Clients.SpotApi.HTXSocketClientSpotApi.ClientOptions">
<inheritdoc />
</member>
<member name="M:HTX.Net.Clients.SpotApi.HTXSocketClientSpotApi.FormatSymbol(System.String,System.String,CryptoExchange.Net.SharedApis.TradingMode,System.Nullable{System.DateTime})">
<inheritdoc />
</member>
Expand Down Expand Up @@ -17387,6 +17390,16 @@
HTX options
</summary>
</member>
<member name="P:HTX.Net.Objects.Options.HTXOptions.AllowAppendingClientOrderId">
<summary>
Whether to allow the client to adjust the clientOrderId parameter send by the user when placing orders to include a client reference. This reference is used by the exchange to allocate a small percentage of the paid trading fees to developer of this library. Defaults to false.<br />
Note that:<br />
* It does not impact the amount of fees a user pays in any way<br />
* It does not impact functionality. The reference is added just before sending the request and removed again during data deserialization<br />
* It does respect client order id field limitations. For example if the user provided client order id parameter is too long to fit the reference it will not be added<br />
* Toggling this option might fail operations using a clientOrderId parameter for pre-existing orders which were placed before the toggle. Operations on orders placed after the toggle will work as expected. It's adviced to toggle when there are no open orders
</summary>
</member>
<member name="T:HTX.Net.Objects.Options.HTXOrderBookOptions">
<summary>
Options for the HTX SymbolOrderBook
Expand Down Expand Up @@ -17427,14 +17440,19 @@
ctor
</summary>
</member>
<member name="P:HTX.Net.Objects.Options.HTXRestOptions.SignPublicRequests">
<member name="P:HTX.Net.Objects.Options.HTXRestOptions.AllowAppendingClientOrderId">
<summary>
Whether public requests should be signed if ApiCredentials are provided. Needed for accurate rate limiting.
Whether to allow the client to adjust the clientOrderId parameter send by the user when placing orders to include a client reference. This reference is used by the exchange to allocate a small percentage of the paid trading fees to developer of this library. Defaults to false.<br />
Note that:<br />
* It does not impact the amount of fees a user pays in any way<br />
* It does not impact functionality. The reference is added just before sending the request and removed again during data deserialization<br />
* It does respect client order id field limitations. For example if the user provided client order id parameter is too long to fit the reference it will not be added<br />
* Toggling this option might fail operations using a clientOrderId parameter for pre-existing orders which were placed before the toggle. Operations on orders placed after the toggle will work as expected. It's adviced to toggle when there are no open orders
</summary>
</member>
<member name="P:HTX.Net.Objects.Options.HTXRestOptions.BrokerId">
<member name="P:HTX.Net.Objects.Options.HTXRestOptions.SignPublicRequests">
<summary>
Broker id
Whether public requests should be signed if ApiCredentials are provided. Needed for accurate rate limiting.
</summary>
</member>
<member name="P:HTX.Net.Objects.Options.HTXRestOptions.SpotOptions">
Expand Down Expand Up @@ -17462,9 +17480,14 @@
ctor
</summary>
</member>
<member name="P:HTX.Net.Objects.Options.HTXSocketOptions.BrokerId">
<member name="P:HTX.Net.Objects.Options.HTXSocketOptions.AllowAppendingClientOrderId">
<summary>
Broker id
Whether to allow the client to adjust the clientOrderId parameter send by the user when placing orders to include a client reference. This reference is used by the exchange to allocate a small percentage of the paid trading fees to developer of this library. Defaults to false.<br />
Note that:<br />
* It does not impact the amount of fees a user pays in any way<br />
* It does not impact functionality. The reference is added just before sending the request and removed again during data deserialization<br />
* It does respect client order id field limitations. For example if the user provided client order id parameter is too long to fit the reference it will not be added<br />
* Toggling this option might fail operations using a clientOrderId parameter for pre-existing orders which were placed before the toggle. Operations on orders placed after the toggle will work as expected. It's adviced to toggle when there are no open orders
</summary>
</member>
<member name="P:HTX.Net.Objects.Options.HTXSocketOptions.SpotOptions">
Expand Down
3 changes: 3 additions & 0 deletions HTX.Net/HTXExchange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ public static class HTXExchange
"https://www.htx.com/en-us/opend/newApiPages/"
};

internal const string ClientOrderId = "AA1ef14811";
internal const string ClientOrderIdPrefix = ClientOrderId + LibraryHelpers.ClientOrderIdSeperator;

/// <summary>
/// Format a base and quote asset to an HTX recognized symbol
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions HTX.Net/Objects/Models/HTXBatchCancelResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public record HTXFailedCancelResult
/// The id of the failed order
/// </summary>
[JsonPropertyName("client-order-id")]
[JsonConverterCtor<ReplaceConverter>($"{HTXExchange.ClientOrderIdPrefix}->")]
public string? ClientOrderId { get; set; }
}
}
1 change: 1 addition & 0 deletions HTX.Net/Objects/Models/HTXBatchPlaceResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public record HTXBatchPlaceResult
/// Client order id
/// </summary>
[JsonPropertyName("client-order-id")]
[JsonConverterCtor<ReplaceConverter>($"{HTXExchange.ClientOrderIdPrefix}->")]
public string? ClientOrderId { get; set; }
/// <summary>
/// Whether the placement was successful
Expand Down
Loading

0 comments on commit 3fcfea6

Please sign in to comment.