Skip to content

Commit

Permalink
Client order id update (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
JKorf authored Dec 3, 2024
1 parent f18f297 commit 65d721c
Show file tree
Hide file tree
Showing 21 changed files with 118 additions and 34 deletions.
5 changes: 2 additions & 3 deletions OKX.Net/Clients/UnifiedApi/OKXRestClientUnifiedApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ namespace OKX.Net.Clients.UnifiedApi;
internal partial class OKXRestClientUnifiedApi : RestApiClient, IOKXRestClientUnifiedApi, ISpotClient
{
#region Internal Fields
public new OKXRestOptions ClientOptions => (OKXRestOptions)base.ClientOptions;

private static TimeSyncState _timeSyncState = new("Unified Api");
internal readonly string _ref;

public event Action<OrderId>? OnOrderPlaced;
public event Action<OrderId>? OnOrderCanceled;
Expand All @@ -38,8 +39,6 @@ internal OKXRestClientUnifiedApi(ILogger logger, HttpClient? httpClient, OKXRest
Trading = new OKXRestClientUnifiedApiTrading(this);
SubAccounts = new OKXRestClientUnifiedApiSubAccounts(this);

_ref = !string.IsNullOrEmpty(options.BrokerId) ? options.BrokerId! : "1425d83a94fbBCDE";

if (options.Environment.Name == TradeEnvironmentNames.Testnet)
{
StandardRequestHeaders = new Dictionary<string, string>
Expand Down
40 changes: 30 additions & 10 deletions OKX.Net/Clients/UnifiedApi/OKXRestClientUnifiedApiTrading.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ public virtual async Task<WebCallResult<OKXOrderPlaceResponse>> PlaceOrderAsync(

CancellationToken ct = default)
{
clientOrderId ??= ExchangeHelpers.AppendRandomString(_baseClient._ref, 32);
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection {
{"instId", symbol },
{"sz", quantity.ToString(CultureInfo.InvariantCulture) },
{"tag", _baseClient._ref },
{"tag", OKXExchange.ClientOrderId },
{"clOrdId", clientOrderId },
};
parameters.AddEnum("tdMode", tradeMode ?? Enums.TradeMode.Cash);
Expand All @@ -61,6 +61,11 @@ public virtual async Task<WebCallResult<OKXOrderPlaceResponse>> PlaceOrderAsync(
parameters.AddOptional("stpId", selfTradePreventionId);
parameters.AddOptionalEnum("stpMode", selfTradePreventionMode);

if (attachedAlgoOrders != null)
{
foreach(var attachOrder in attachedAlgoOrders)
attachOrder.ClientOrderId = LibraryHelpers.ApplyBrokerId(attachOrder.ClientOrderId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);
}
parameters.AddOptional("attachAlgoOrds", attachedAlgoOrders?.ToArray());

parameters.AddOptional("tag", tag);
Expand Down Expand Up @@ -118,8 +123,7 @@ public virtual async Task<WebCallResult<OKXCheckOrderResponse>> CheckOrderAsync(
{
var parameters = new ParameterCollection {
{"instId", symbol },
{"sz", quantity.ToString(CultureInfo.InvariantCulture) },
{"tag", _baseClient._ref },
{"sz", quantity.ToString(CultureInfo.InvariantCulture) }
};
parameters.AddEnum("tdMode", tradeMode ?? Enums.TradeMode.Cash);
parameters.AddEnum("side", side);
Expand Down Expand Up @@ -148,8 +152,8 @@ public virtual async Task<WebCallResult<IEnumerable<OKXOrderPlaceResponse>>> Pla
{
foreach (var order in orders)
{
var clientOrderId = order.ClientOrderId ?? ExchangeHelpers.AppendRandomString(_baseClient._ref, 32);
order.Tag = _baseClient._ref;
var clientOrderId = LibraryHelpers.ApplyBrokerId(order.ClientOrderId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);
order.Tag = OKXExchange.ClientOrderId;
order.ClientOrderId = clientOrderId;
}

Expand Down Expand Up @@ -186,6 +190,9 @@ public virtual async Task<WebCallResult<IEnumerable<OKXOrderPlaceResponse>>> Pla
/// <inheritdoc />
public virtual async Task<WebCallResult<OKXOrderCancelResponse>> CancelOrderAsync(string symbol, long? orderId = null, string? clientOrderId = null, CancellationToken ct = default)
{
if (clientOrderId != null)
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection {
{"instId", symbol },
};
Expand Down Expand Up @@ -265,6 +272,9 @@ public virtual async Task<WebCallResult<OKXOrderAmendResponse>> AmendOrderAsync(
TriggerPriceType? newStopLossPriceTriggerType = null,
CancellationToken ct = default)
{
if (clientOrderId != null)
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection
{
{ "instId", symbol },
Expand Down Expand Up @@ -310,11 +320,11 @@ public virtual async Task<WebCallResult<OKXClosePositionResponse>> ClosePosition
string? clientOrderId = null,
CancellationToken ct = default)
{
clientOrderId ??= ExchangeHelpers.AppendRandomString(_baseClient._ref, 32);
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection {
{"instId", symbol },
{"tag", _baseClient._ref },
{"tag", OKXExchange.ClientOrderId },
{"clOrdId", clientOrderId }
};
parameters.AddEnum("mgnMode", marginMode);
Expand All @@ -334,6 +344,9 @@ public virtual async Task<WebCallResult<OKXOrder>> GetOrderDetailsAsync(
string? clientOrderId = null,
CancellationToken ct = default)
{
if (clientOrderId != null)
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection {
{"instId", symbol },
};
Expand Down Expand Up @@ -568,10 +581,11 @@ public virtual async Task<WebCallResult<OKXAlgoOrderResponse>> PlaceAlgoOrderAsy

CancellationToken ct = default)
{
clientOrderId ??= ExchangeHelpers.AppendRandomString(_baseClient._ref, 32);
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection {
{"instId", symbol },
{"tag", _baseClient._ref },
{"tag", OKXExchange.ClientOrderId },
{"clOrdId", clientOrderId }
};
parameters.AddEnum("tdMode", tradeMode);
Expand Down Expand Up @@ -718,6 +732,9 @@ public virtual async Task<WebCallResult<OKXAlgoOrder>> GetAlgoOrderAsync(string?
if ((algoId == null) == (clientAlgoId == null))
throw new ArgumentException("Either algoId or clientAlgoId needs to be provided");

if (clientAlgoId != null)
clientAlgoId = LibraryHelpers.ApplyBrokerId(clientAlgoId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection();
parameters.AddOptional("algoId", algoId);
parameters.AddOptional("algoClOrdId", clientAlgoId);
Expand Down Expand Up @@ -746,6 +763,9 @@ public virtual async Task<WebCallResult<OKXAlgoOrderAmendResponse>> AmendAlgoOrd
if ((algoId == null) == (clientAlgoId == null))
throw new ArgumentException("Either algoId or clientAlgoId needs to be provided");

if (clientAlgoId != null)
clientAlgoId = LibraryHelpers.ApplyBrokerId(clientAlgoId, OKXExchange.ClientOrderId, 32, _baseClient.ClientOptions.AllowAppendingClientOrderId);

var parameters = new ParameterCollection
{
{ "instId", symbol },
Expand Down
5 changes: 2 additions & 3 deletions OKX.Net/Clients/UnifiedApi/OKXSocketClientUnifiedApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,15 @@ internal partial class OKXSocketClientUnifiedApi : SocketApiClient, IOKXSocketCl
private static readonly MessagePath _instTypePath = MessagePath.Get().Property("arg").Property("instType");
private static readonly MessagePath _instFamilyPath = MessagePath.Get().Property("arg").Property("instFamily");

public new OKXSocketOptions ClientOptions => (OKXSocketOptions)base.ClientOptions;

/// <inheritdoc />
public IOKXSocketClientUnifiedApiAccount Account { get; }
/// <inheritdoc />
public IOKXSocketClientUnifiedApiExchangeData ExchangeData { get; }
/// <inheritdoc />
public IOKXSocketClientUnifiedApiTrading Trading { get; }

internal readonly string _ref;
private readonly bool _demoTrading;

#region ctor
Expand All @@ -43,8 +44,6 @@ internal OKXSocketClientUnifiedApi(ILogger logger, OKXSocketOptions options) :
ExchangeData = new OKXSocketClientUnifiedApiExchangeData(logger, this);
Trading = new OKXSocketClientUnifiedApiTrading(logger, this);

_ref = !string.IsNullOrEmpty(options.BrokerId) ? options.BrokerId! : "078ee129065aBCDE";

_demoTrading = options.Environment.Name == TradeEnvironmentNames.Testnet;

RegisterPeriodicQuery("Ping", TimeSpan.FromSeconds(20), x => new OKXPingQuery(), null);
Expand Down
14 changes: 10 additions & 4 deletions OKX.Net/Clients/UnifiedApi/OKXSocketClientUnifiedApiTrading.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ public async Task<CallResult<OKXOrderPlaceResponse>> PlaceOrderAsync(string symb
{ "sz", quantity.ToString(CultureInfo.InvariantCulture) },
};

clientOrderId = clientOrderId ?? ExchangeHelpers.AppendRandomString(_client._ref, 32);
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _client.ClientOptions.AllowAppendingClientOrderId);

parameters.AddOptionalParameter("ccy", asset);
parameters.AddOptionalParameter("clOrdId", clientOrderId);
parameters.AddOptionalParameter("tag", _client._ref);
parameters.AddOptionalParameter("tag", OKXExchange.ClientOrderId);
parameters.AddOptionalParameter("posSide", EnumConverter.GetString(positionSide));
parameters.AddOptionalParameter("px", price?.ToString(CultureInfo.InvariantCulture));
parameters.AddOptionalParameter("reduceOnly", reduceOnly);
Expand All @@ -79,8 +79,8 @@ public async Task<CallResult<IEnumerable<OKXOrderPlaceResponse>>> PlaceMultipleO
{
foreach (var order in orders)
{
order.Tag = _client._ref;
order.ClientOrderId = order.ClientOrderId ?? ExchangeHelpers.AppendRandomString(_client._ref, 32);
order.Tag = OKXExchange.ClientOrderId;
order.ClientOrderId = LibraryHelpers.ApplyBrokerId(order.ClientOrderId, OKXExchange.ClientOrderId, 32, _client.ClientOptions.AllowAppendingClientOrderId);
}

return await _client.QueryInternalAsync<OKXOrderPlaceResponse>(_client.GetUri("/ws/v5/private"), "batch-orders", orders, true, 1, ct).ConfigureAwait(false);
Expand All @@ -89,6 +89,9 @@ public async Task<CallResult<IEnumerable<OKXOrderPlaceResponse>>> PlaceMultipleO
/// <inheritdoc />
public async Task<CallResult<OKXOrderCancelResponse>> CancelOrderAsync(string symbol, string? orderId = null, string? clientOrderId = null, CancellationToken ct = default)
{
if (clientOrderId != null)
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _client.ClientOptions.AllowAppendingClientOrderId);

var parameters = new Dictionary<string, object>()
{
{ "instId", symbol }
Expand Down Expand Up @@ -123,6 +126,9 @@ public virtual async Task<CallResult<OKXOrderAmendResponse>> AmendOrderAsync(
decimal? newPrice = null,
CancellationToken ct = default)
{
if (clientOrderId != null)
clientOrderId = LibraryHelpers.ApplyBrokerId(clientOrderId, OKXExchange.ClientOrderId, 32, _client.ClientOptions.AllowAppendingClientOrderId);

var parameters = new Dictionary<string, object>
{
{ "instId", symbol },
Expand Down
4 changes: 4 additions & 0 deletions OKX.Net/ExtensionMethods/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ public static IServiceCollection AddOKX(
var socketEnvName = options.Socket.Environment?.Name ?? options.Environment?.Name ?? OKXEnvironment.Live.Name;
options.Rest.Environment = OKXEnvironment.GetEnvironmentByName(restEnvName) ?? options.Rest.Environment!;
options.Rest.ApiCredentials = options.Rest.ApiCredentials ?? options.ApiCredentials;
options.Rest.AllowAppendingClientOrderId = options.Rest.AllowAppendingClientOrderId || options.AllowAppendingClientOrderId;
options.Socket.Environment = OKXEnvironment.GetEnvironmentByName(socketEnvName) ?? options.Socket.Environment!;
options.Socket.ApiCredentials = options.Socket.ApiCredentials ?? options.ApiCredentials;
options.Socket.AllowAppendingClientOrderId = options.Socket.AllowAppendingClientOrderId || options.AllowAppendingClientOrderId;


services.AddSingleton(x => Options.Options.Create(options.Rest));
Expand Down Expand Up @@ -70,8 +72,10 @@ public static IServiceCollection AddOKX(

options.Rest.Environment = options.Rest.Environment ?? options.Environment ?? OKXEnvironment.Live;
options.Rest.ApiCredentials = options.Rest.ApiCredentials ?? options.ApiCredentials;
options.Rest.AllowAppendingClientOrderId = options.Rest.AllowAppendingClientOrderId || options.AllowAppendingClientOrderId;
options.Socket.Environment = options.Socket.Environment ?? options.Environment ?? OKXEnvironment.Live;
options.Socket.ApiCredentials = options.Socket.ApiCredentials ?? options.ApiCredentials;
options.Socket.AllowAppendingClientOrderId = options.Socket.AllowAppendingClientOrderId || options.AllowAppendingClientOrderId;

services.AddSingleton(x => Options.Options.Create(options.Rest));
services.AddSingleton(x => Options.Options.Create(options.Socket));
Expand Down
4 changes: 2 additions & 2 deletions OKX.Net/OKX.Net.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
<LangVersion>latest</LangVersion>
Expand Down Expand Up @@ -49,7 +49,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
30 changes: 25 additions & 5 deletions OKX.Net/OKX.Net.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions OKX.Net/OKXExchange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ public static class OKXExchange
"https://www.okx.com/docs-v5/en/"
};

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

/// <summary>
/// Format a base and quote asset to an OKX recognized symbol
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions OKX.Net/Objects/Account/OKXAccountBill.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ public record OKXAccountBill
/// Client order id
/// </summary>
[JsonPropertyName("clOrdId")]
[JsonConverterCtor<ReplaceConverter>($"{OKXExchange.ClientOrderIdPrefix}->")]
public string? ClientOrderId { get; set; }

/// <summary>
Expand Down
Loading

0 comments on commit 65d721c

Please sign in to comment.