Skip to content
This repository has been archived by the owner on Feb 29, 2024. It is now read-only.

autoCxl, bbo-tbt, get positions history #77

Merged
merged 4 commits into from
Dec 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 18 additions & 17 deletions Okex.Net.Examples/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,24 @@ private static void Main(string[] args)
/* Account Endpoints (Signed) */
var account_01 = api.GetAccountBalance();
var account_02 = api.GetAccountPositions();
var account_03 = api.GetAccountPositionRisk();
var account_04 = api.GetBillHistory();
var account_05 = api.GetBillArchive();
var account_06 = api.GetAccountConfiguration();
var account_07 = api.SetAccountPositionMode(OkexPositionMode.LongShortMode);
var account_08 = api.GetAccountLeverage("BTC-USD-211008", OkexMarginMode.Isolated);
var account_09 = api.SetAccountLeverage(30, null, "BTC-USD-211008", OkexMarginMode.Isolated, OkexPositionSide.Long);
var account_10 = api.GetMaximumAmount("BTC-USDT", OkexTradeMode.Isolated);
var account_11 = api.GetMaximumAvailableAmount("BTC-USDT", OkexTradeMode.Isolated);
var account_12 = api.SetMarginAmount("BTC-USDT", OkexPositionSide.Long, OkexMarginAddReduce.Add, 100.0m);
var account_13 = api.GetMaximumLoanAmount("BTC-USDT", OkexMarginMode.Cross);
var account_14 = api.GetFeeRates(OkexInstrumentType.Spot, category: OkexFeeRateCategory.ClassA);
var account_15 = api.GetFeeRates(OkexInstrumentType.Futures, category: OkexFeeRateCategory.ClassA);
var account_16 = api.GetInterestAccrued();
var account_17 = api.GetInterestRate();
var account_18 = api.SetGreeks(OkexGreeksType.GreeksInCoins);
var account_19 = api.GetMaximumWithdrawals();
var account_03 = api.GetAccountPositionsHistory();
var account_04 = api.GetAccountPositionRisk();
var account_05 = api.GetBillHistory();
var account_06 = api.GetBillArchive();
var account_07 = api.GetAccountConfiguration();
var account_08 = api.SetAccountPositionMode(OkexPositionMode.LongShortMode);
var account_09 = api.GetAccountLeverage("BTC-USD-211008", OkexMarginMode.Isolated);
var account_10 = api.SetAccountLeverage(30, null, "BTC-USD-211008", OkexMarginMode.Isolated, OkexPositionSide.Long);
var account_11 = api.GetMaximumAmount("BTC-USDT", OkexTradeMode.Isolated);
var account_12 = api.GetMaximumAvailableAmount("BTC-USDT", OkexTradeMode.Isolated);
var account_13 = api.SetMarginAmount("BTC-USDT", OkexPositionSide.Long, OkexMarginAddReduce.Add, 100.0m);
var account_14 = api.GetMaximumLoanAmount("BTC-USDT", OkexMarginMode.Cross);
var account_15 = api.GetFeeRates(OkexInstrumentType.Spot, category: OkexFeeRateCategory.ClassA);
var account_16 = api.GetFeeRates(OkexInstrumentType.Futures, category: OkexFeeRateCategory.ClassA);
var account_17 = api.GetInterestAccrued();
var account_18 = api.GetInterestRate();
var account_19 = api.SetGreeks(OkexGreeksType.GreeksInCoins);
var account_20 = api.GetMaximumWithdrawals();
#endif

#if FALSE
Expand Down
21 changes: 21 additions & 0 deletions Okex.Net/Converters/ClosingPositionTypeConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using CryptoExchange.Net.Converters;
using Okex.Net.Enums;
using System.Collections.Generic;

namespace Okex.Net.Converters
{
internal class ClosingPositionTypeConverter : BaseConverter<OkexClosingPositionType>
{
public ClosingPositionTypeConverter() : this(true) { }
public ClosingPositionTypeConverter(bool quotes) : base(quotes) { }

protected override List<KeyValuePair<OkexClosingPositionType, string>> Mapping => new List<KeyValuePair<OkexClosingPositionType, string>>
{
new KeyValuePair<OkexClosingPositionType, string>(OkexClosingPositionType.ClosePartially, "1"),
new KeyValuePair<OkexClosingPositionType, string>(OkexClosingPositionType.CloseAll, "2"),
new KeyValuePair<OkexClosingPositionType, string>(OkexClosingPositionType.Liquidation, "3"),
new KeyValuePair<OkexClosingPositionType, string>(OkexClosingPositionType.PartialLiquidation, "4"),
new KeyValuePair<OkexClosingPositionType, string>(OkexClosingPositionType.ADL, "5"),
};
}
}
1 change: 1 addition & 0 deletions Okex.Net/Converters/OrderBookTypeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public OrderBookTypeConverter(bool quotes) : base(quotes) { }
new KeyValuePair<OkexOrderBookType, string>(OkexOrderBookType.OrderBook_5, "books5"),
new KeyValuePair<OkexOrderBookType, string>(OkexOrderBookType.OrderBook_50_l2_TBT, "books50-l2-tbt"),
new KeyValuePair<OkexOrderBookType, string>(OkexOrderBookType.OrderBook_l2_TBT, "books-l2-tbt"),
new KeyValuePair<OkexOrderBookType, string>(OkexOrderBookType.BBO_TBT, "bbo-tbt"),
};
}
}
11 changes: 11 additions & 0 deletions Okex.Net/Enums/OkexClosingPositionType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Okex.Net.Enums
{
public enum OkexClosingPositionType
{
ClosePartially,
CloseAll,
Liquidation,
PartialLiquidation,
ADL
}
}
1 change: 1 addition & 0 deletions Okex.Net/Enums/OkexOrderBookType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public enum OkexOrderBookType
OrderBook_5,
OrderBook_50_l2_TBT,
OrderBook_l2_TBT,
BBO_TBT
}

}
61 changes: 61 additions & 0 deletions Okex.Net/Objects/Account/OkexClosingPosition.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using Newtonsoft.Json;
using Okex.Net.Converters;
using Okex.Net.Enums;
using System;

namespace Okex.Net.Objects.Account
{
public class OkexClosingPosition
{
[JsonProperty("instType"), JsonConverter(typeof(InstrumentTypeConverter))]
public OkexInstrumentType InstrumentType { get; set; }

[JsonProperty("instId")]
public string Instrument { get; set; }

[JsonProperty("mgnMode"), JsonConverter(typeof(MarginModeConverter))]
public OkexMarginMode MarginMode { get; set; }

[JsonProperty("type"), JsonConverter(typeof(ClosingPositionTypeConverter))]
public OkexClosingPositionType Type { get; set; }

[JsonProperty("cTime"), JsonConverter(typeof(OkexTimestampConverter))]
public DateTime CreateTime { get; set; }

[JsonProperty("uTime"), JsonConverter(typeof(OkexTimestampConverter))]
public DateTime UpdateTime { get; set; }

[JsonProperty("openAvgPx")]
public decimal? OpenAveragePrice { get; set; }

[JsonProperty("closeAvgPx")]
public decimal? CloseAveragePrice { get; set; }

[JsonProperty("posId")]
public long? PositionId { get; set; }

[JsonProperty("openMaxPos")]
public decimal? OpenMaxPos { get; set; }

[JsonProperty("closeTotalPos")]
public decimal? CloseTotalPos { get; set; }

[JsonProperty("pnl")]
public decimal? ProfitLoss { get; set; }

[JsonProperty("lever")]
public decimal? Leverage { get; set; }

[JsonProperty("direction"), JsonConverter(typeof(PositionSideConverter))]
public OkexPositionSide Direction { get; set; }

[JsonProperty("triggerPx")]
public decimal? TriggerMarkPrice { get; set; }

[JsonProperty("liqPx")]
public decimal? LiquidationPrice { get; set; }

[JsonProperty("uly")]
public string Underlying { get; set; }
}
}
1 change: 1 addition & 0 deletions Okex.Net/OkexClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ public partial class OkexClient : BaseRestClient
#region Account Endpoints
protected const string Endpoints_V5_Account_Balance = "api/v5/account/balance";
protected const string Endpoints_V5_Account_Positions = "api/v5/account/positions";
protected const string Endpoints_V5_Account_PositionsHistory = "api/v5/account/positions-history";
protected const string Endpoints_V5_Account_PositionRisk = "api/v5/account/account-position-risk";
protected const string Endpoints_V5_Account_Bills = "api/v5/account/bills";
protected const string Endpoints_V5_Account_BillsArchive = "api/v5/account/bills-archive";
Expand Down
69 changes: 68 additions & 1 deletion Okex.Net/OkexClient_Account.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,76 @@ public virtual async Task<WebCallResult<IEnumerable<OkexPosition>>> GetAccountPo
return result.As(result.Data.Data);
}

/// <summary>
/// Retrieve the updated position data for the last 3 months. Return in reverse chronological order using utime.
/// </summary>
/// <param name="instrumentType">Instrument type</param>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="marginMode">Margin mode</param>
/// <param name="type">The type of closing position. It is the latest type if there are several types for the same position.</param>
/// <param name="positionId">Position ID</param>
/// <param name="after">Pagination of data to return records earlier than the requested uTime, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records earlier than the requested uTime, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100. The default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public virtual WebCallResult<IEnumerable<OkexClosingPosition>> GetAccountPositionsHistory(
OkexInstrumentType? instrumentType = null,
string instrumentId = null,
OkexMarginMode? marginMode = null,
OkexClosingPositionType? type = null,
string positionId = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default)
=> GetAccountPositionsHistory_Async(instrumentType, instrumentId, marginMode, type, positionId, after, before, limit, ct).Result;

// TODO: Get positions history
/// <summary>
/// Retrieve the updated position data for the last 3 months. Return in reverse chronological order using utime.
/// </summary>
/// <param name="instrumentType">Instrument type</param>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="marginMode">Margin mode</param>
/// <param name="type">The type of closing position. It is the latest type if there are several types for the same position.</param>
/// <param name="positionId">Position ID</param>
/// <param name="after">Pagination of data to return records earlier than the requested uTime, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="before">Pagination of data to return records earlier than the requested uTime, Unix timestamp format in milliseconds, e.g. 1597026383085</param>
/// <param name="limit">Number of results per request. The maximum is 100. The default is 100.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public virtual async Task<WebCallResult<IEnumerable<OkexClosingPosition>>> GetAccountPositionsHistory_Async(
OkexInstrumentType? instrumentType = null,
string instrumentId = null,
OkexMarginMode? marginMode = null,
OkexClosingPositionType? type = null,
string positionId = null,
long? after = null,
long? before = null,
int limit = 100,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object>();
if (instrumentType.HasValue)
parameters.AddOptionalParameter("instType", JsonConvert.SerializeObject(instrumentType, new InstrumentTypeConverter(false)));
parameters.AddOptionalParameter("instId", instrumentId);
if (marginMode != null)
parameters.AddOptionalParameter("mgnMode", JsonConvert.SerializeObject(marginMode, new MarginModeConverter(false)));
if (type != null)
parameters.AddOptionalParameter("type", JsonConvert.SerializeObject(type, new ClosingPositionTypeConverter(false)));
parameters.AddOptionalParameter("posId", positionId);
parameters.AddOptionalParameter("after", after?.ToString());
parameters.AddOptionalParameter("before", before?.ToString());
parameters.AddOptionalParameter("limit", limit.ToString());

var result = await UnifiedApi.ExecuteAsync<OkexRestApiResponse<IEnumerable<OkexClosingPosition>>>(UnifiedApi.GetUri(Endpoints_V5_Account_PositionsHistory), HttpMethod.Get, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return result.AsError<IEnumerable<OkexClosingPosition>>(new OkexRestApiError(result.Error.Code, result.Error.Message, result.Error.Data));
if (result.Data.ErrorCode > 0) return result.AsError<IEnumerable<OkexClosingPosition>>(new OkexRestApiError(result.Data.ErrorCode, result.Data.ErrorMessage, null));

return result.As(result.Data.Data);
}

/// <summary>
/// Get account and position risk
Expand Down
9 changes: 8 additions & 1 deletion Okex.Net/OkexClient_Trade.cs
Original file line number Diff line number Diff line change
Expand Up @@ -297,29 +297,33 @@ public virtual async Task<WebCallResult<IEnumerable<OkexOrderAmendResponse>>> Am
/// <param name="marginMode">Margin Mode</param>
/// <param name="positionSide">Position Side</param>
/// <param name="currency">Currency</param>
/// <param name="autoCxl">Whether any pending orders for closing out needs to be automatically canceled when close position via a market order.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual WebCallResult<OkexClosePositionResponse> ClosePosition(
string instrumentId,
OkexMarginMode marginMode,
OkexPositionSide? positionSide = null,
string currency = null,
bool? autoCxl = null,
CancellationToken ct = default)
=> ClosePositionAsync(instrumentId, marginMode, positionSide, currency, ct).Result;
=> ClosePositionAsync(instrumentId, marginMode, positionSide, currency, autoCxl, ct).Result;
/// <summary>
/// Close all positions of an instrument via a market order.
/// </summary>
/// <param name="instrumentId">Instrument ID</param>
/// <param name="marginMode">Margin Mode</param>
/// <param name="positionSide">Position Side</param>
/// <param name="currency">Currency</param>
/// <param name="autoCxl">Whether any pending orders for closing out needs to be automatically canceled when close position via a market order.</param>
/// <param name="ct">Cancellation Token</param>
/// <returns></returns>
public virtual async Task<WebCallResult<OkexClosePositionResponse>> ClosePositionAsync(
string instrumentId,
OkexMarginMode marginMode,
OkexPositionSide? positionSide = null,
string currency = null,
bool? autoCxl = null,
CancellationToken ct = default)
{
var parameters = new Dictionary<string, object> {
Expand All @@ -330,6 +334,9 @@ public virtual async Task<WebCallResult<OkexClosePositionResponse>> ClosePositio
parameters.AddOptionalParameter("posSide", JsonConvert.SerializeObject(positionSide, new PositionSideConverter(false)));
parameters.AddOptionalParameter("ccy", currency);

if (autoCxl.HasValue)
parameters.AddOptionalParameter("autoCxl", autoCxl);

var result = await UnifiedApi.ExecuteAsync<OkexRestApiResponse<IEnumerable<OkexClosePositionResponse>>>(UnifiedApi.GetUri(Endpoints_V5_Trade_ClosePosition), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false);
if (!result.Success) return result.AsError<OkexClosePositionResponse>(new OkexRestApiError(result.Error.Code, result.Error.Message, result.Error.Data));
if (result.Data.ErrorCode > 0) return result.AsError<OkexClosePositionResponse>(new OkexRestApiError(result.Data.ErrorCode, result.Data.ErrorMessage, null));
Expand Down