Coder Social home page Coder Social logo

okex.net's Introduction

Critical Announcement

It's highly recommended to migrate to OKX.Api in order to get next updates and avoid from CryptoExchange.Net derived errors. It's available on both Github and Nuget

Github Repository: https://github.com/burakoner/OKX.Api

Nuget Package: https://www.nuget.org/packages/OKX.Api

Icon! OKEx.Net

A .Net wrapper for the OKEx API as described on OKEx, including all features the API provides using clear and readable objects.

If you think something is broken, something is missing or have any questions, please open an Issue

CryptoExchange.Net

Implementation is build upon the CryptoExchange.Net library, make sure to also check out the documentation on that: docs

My CryptoExchange.Net implementations:

Image

OKEx

Image

Chiliz

Image

BitMax

Image

BtcTurk

Image

Paribu

Image

Thodex

Image

Coinzo

Image

Tatum

JKorf CryptoExchange.Net implementations:

Image

Binance

Image

Bitfinex

Image

Bittrex

Image

CoinEx

Image

Huobi

Image

Kraken

Image

Kucoin

Implementations from third parties:

Image

Bitmex

Image

Exante

Image

HitBTC

Image

Liquid

Image

LiveCoin

Image

Switcheo

Donations

Donations are greatly appreciated and a motivation to keep improving.

BTC: 33WbRKqt7wXARVdAJSu1G1x3QnbyPtZ2bH
ETH: 0x65b02db9b67b73f5f1e983ae10796f91ded57b64

Installation

Nuget version Nuget downloads Available on Nuget.

PM> Install-Package OKEx.Net

To get started with OKEx.Net first you will need to get the library itself. The easiest way to do this is to install the package into your project using NuGet. Using Visual Studio this can be done in two ways.

Using the package manager

In Visual Studio right click on your solution and select 'Manage NuGet Packages for solution...'. A screen will appear which initially shows the currently installed packages. In the top bit select 'Browse'. This will let you download net package from the NuGet server. In the search box type 'OKEx.Net' and hit enter. The OKEx.Net package should come up in the results. After selecting the package you can then on the right hand side select in which projects in your solution the package should install. After you've selected all project you wish to install and use OKEx.Net in hit 'Install' and the package will be downloaded and added to you projects.

Using the package manager console

In Visual Studio in the top menu select 'Tools' -> 'NuGet Package Manager' -> 'Package Manager Console'. This should open up a command line interface. On top of the interface there is a dropdown menu where you can select the Default Project. This is the project that OKEx.Net will be installed in. After selecting the correct project type Install-Package OKEx.Net in the command line interface. This should install the latest version of the package in your project.

After doing either of above steps you should now be ready to actually start using OKEx.Net.

Getting started

After installing it's time to actually use it. To get started we have to add the OKEx.Net namespace: using Okex.Net;.

OKEx.Net provides two clients to interact with the OKEx API. The OkexClient provides all rest API calls. The OkexSocketClient provides functions to interact with the websocket provided by the OKEx API. Both clients are disposable and as such can be used in a usingstatement.

Rest Api Examples

Public Endpoints (Unsigned)

OkexClient api = new OkexClient();
var public_01 = api.GetInstruments(OkexInstrumentType.Spot);
var public_02 = api.GetInstruments(OkexInstrumentType.Margin);
var public_03 = api.GetInstruments(OkexInstrumentType.Swap);
var public_04 = api.GetInstruments(OkexInstrumentType.Futures);
var public_05 = api.GetInstruments(OkexInstrumentType.Option, "USD");
var public_06 = api.GetDeliveryExerciseHistory(OkexInstrumentType.Futures, "BTC-USD");
var public_07 = api.GetDeliveryExerciseHistory(OkexInstrumentType.Option, "BTC-USD");
var public_08 = api.GetOpenInterests(OkexInstrumentType.Futures);
var public_09 = api.GetOpenInterests(OkexInstrumentType.Option, "BTC-USD");
var public_10 = api.GetOpenInterests(OkexInstrumentType.Swap);
var public_11 = api.GetFundingRates("BTC-USD-SWAP");
var public_12 = api.GetFundingRateHistory("BTC-USD-SWAP");
var public_13 = api.GetLimitPrice("BTC-USD-SWAP");
var public_14 = api.GetOptionMarketData("BTC-USD");
var public_15 = api.GetEstimatedPrice("BTC-USD-211004-41000-C");
var public_16 = api.GetDiscountInfo();
var public_17 = api.GetSystemTime();
var public_18 = api.GetLiquidationOrders(OkexInstrumentType.Futures, underlying: "BTC-USD", alias: OkexInstrumentAlias.Quarter, state: OkexLiquidationState.Unfilled);
var public_19 = api.GetMarkPrices(OkexInstrumentType.Futures);
var public_20 = api.GetPositionTiers(OkexInstrumentType.Futures, OkexMarginMode.Isolated, "BTC-USD");
var public_21 = api.GetInterestRates();
var public_22 = api.GetVIPInterestRates();
var public_23 = api.GetUnderlying(OkexInstrumentType.Futures);
var public_24 = api.GetUnderlying(OkexInstrumentType.Option);
var public_25 = api.GetUnderlying(OkexInstrumentType.Swap);
var public_26 = api.GetInsuranceFund(OkexInstrumentType.Margin, currency:"BTC");
var public_27 = api.UnitConvert( OkexConvertType.CurrencyToContract, instrumentId:"BTC-USD-SWAP", price:35000, size:0.888m);

Market Endpoints (Unsigned)

OkexClient api = new OkexClient();
var market_01 = api.GetTickers(OkexInstrumentType.Spot);
var market_02 = api.GetTicker("BTC-USDT");
var market_03 = api.GetIndexTickers(instrumentId: "BTC-USDT");
var market_04 = api.GetOrderBook("BTC-USDT", 40);
var market_05 = api.GetCandlesticks("BTC-USDT", OkexPeriod.OneHour);
var market_06 = api.GetCandlesticksHistory("BTC-USDT", OkexPeriod.OneHour);
var market_07 = api.GetIndexCandlesticks("BTC-USDT", OkexPeriod.OneHour);
var market_08 = api.GetMarkPriceCandlesticks("BTC-USDT", OkexPeriod.OneHour);
var market_09 = api.GetTrades("BTC-USDT");
var market_10 = api.GetTradesHistory("BTC-USDT");
var market_11 = api.Get24HourVolume();
var market_12 = api.GetOracle();
var market_13 = api.GetIndexComponents("BTC-USDT");
var market_14 = api.GetBlockTickers(OkexInstrumentType.Spot);
var market_15 = api.GetBlockTickers(OkexInstrumentType.Futures);
var market_16 = api.GetBlockTickers(OkexInstrumentType.Option);
var market_17 = api.GetBlockTickers(OkexInstrumentType.Swap);
var market_18 = api.GetBlockTicker("BTC-USDT");
var market_19 = api.GetBlockTrades("BTC-USDT");

Trading Endpoints (Unsigned)

OkexClient api = new OkexClient();
var rubik_01 = api.GetRubikSupportCoin();
var rubik_02 = api.GetRubikTakerVolume("BTC", OkexInstrumentType.Spot);
var rubik_03 = api.GetRubikMarginLendingRatio("BTC", OkexPeriod.OneDay);
var rubik_04 = api.GetRubikLongShortRatio("BTC", OkexPeriod.OneDay);
var rubik_05 = api.GetRubikContractSummary("BTC", OkexPeriod.OneDay);
var rubik_06 = api.GetRubikOptionsSummary("BTC", OkexPeriod.OneDay);
var rubik_07 = api.GetRubikPutCallRatio("BTC", OkexPeriod.OneDay);
var rubik_08 = api.GetRubikInterestVolumeExpiry("BTC", OkexPeriod.OneDay);
var rubik_09 = api.GetRubikInterestVolumeStrike("BTC", "20210623", OkexPeriod.OneDay);
var rubik_10 = api.GetRubikTakerFlow("BTC", OkexPeriod.OneDay);

Account Endpoints (Signed)

OkexClient api = new OkexClient();
api.SetApiCredentials("XXXXXXXX-API-KEY-XXXXXXXX", "XXXXXXXX-API-SECRET-XXXXXXXX", "XXXXXXXX-API-PASSPHRASE-XXXXXXXX");
var account_01 = api.GetAccountBalance();
var account_02 = api.GetAccountPositions();
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();

SubAccount Endpoints (Signed)

OkexClient api = new OkexClient();
api.SetApiCredentials("XXXXXXXX-API-KEY-XXXXXXXX", "XXXXXXXX-API-SECRET-XXXXXXXX", "XXXXXXXX-API-PASSPHRASE-XXXXXXXX");
var subaccount_01 = api.GetSubAccounts();
var subaccount_02 = api.ResetSubAccountApiKey("subAccountName", "apiKey", "apiLabel", true, true, "");
var subaccount_03 = api.GetSubAccountTradingBalances("subAccountName");
var subaccount_04 = api.GetSubAccountFundingBalances("subAccountName");
var subaccount_05 = api.GetSubAccountBills();
var subaccount_06 = api.TransferBetweenSubAccounts("BTC", 0.5m, OkexAccount.Funding, OkexAccount.Unified, "fromSubAccountName", "toSubAccountName");

Funding Endpoints (Signed)

OkexClient api = new OkexClient();
api.SetApiCredentials("XXXXXXXX-API-KEY-XXXXXXXX", "XXXXXXXX-API-SECRET-XXXXXXXX", "XXXXXXXX-API-PASSPHRASE-XXXXXXXX");
var funding_01 = api.GetCurrencies();
var funding_02 = api.GetFundingBalance();
var funding_03 = api.FundTransfer("BTC", 0.5m, OkexTransferType.TransferWithinAccount, OkexAccount.Margin, OkexAccount.Spot);
var funding_04 = api.GetFundingBillDetails("BTC");
var funding_05 = api.GetLightningDeposits("BTC", 0.001m);
var funding_06 = api.GetDepositAddress("BTC");
var funding_07 = api.GetDepositAddress("USDT");
var funding_08 = api.GetDepositHistory("USDT");
var funding_09 = api.Withdraw("USDT", 100.0m, OkexWithdrawalDestination.DigitalCurrencyAddress, "toAddress", "password", 1.0m, "USDT-TRC20");
var funding_10 = api.GetLightningWithdrawals("BTC", "invoice", "password");
var funding_11 = api.GetWithdrawalHistory("USDT");
var funding_12 = api.GetSavingBalances();
var funding_13 = api.SavingPurchaseRedemption("USDT", 10.0m, OkexSavingActionSide.Purchase);

Trade Endpoints (Signed)

OkexClient api = new OkexClient();
api.SetApiCredentials("XXXXXXXX-API-KEY-XXXXXXXX", "XXXXXXXX-API-SECRET-XXXXXXXX", "XXXXXXXX-API-PASSPHRASE-XXXXXXXX");
var trade_01 = api.PlaceOrder("BTC-USDT", OkexTradeMode.Cash, OkexOrderSide.Buy, OkexPositionSide.Long, OkexOrderType.MarketOrder, 0.1m);
var trade_02 = api.PlaceMultipleOrders(new List<OkexOrderPlaceRequest>());
var trade_03 = api.CancelOrder("BTC-USDT");
var trade_04 = api.CancelMultipleOrders(new List<OkexOrderCancelRequest>());
var trade_05 = api.AmendOrder("BTC-USDT");
var trade_06 = api.AmendMultipleOrders(new List<OkexOrderAmendRequest>());
var trade_07 = api.ClosePosition("BTC-USDT", OkexMarginMode.Isolated);
var trade_08 = api.GetOrderDetails("BTC-USDT");
var trade_09 = api.GetOrderList();
var trade_10 = api.GetOrderHistory( OkexInstrumentType.Swap);
var trade_11 = api.GetOrderArchive( OkexInstrumentType.Futures);
var trade_12 = api.GetTransactionHistory();
var trade_13 = api.GetTransactionArchive( OkexInstrumentType.Futures);
var trade_14 = api.PlaceAlgoOrder("BTC-USDT", OkexTradeMode.Isolated, OkexOrderSide.Sell, OkexAlgoOrderType.Conditional, 0.1m);
var trade_15 = api.CancelAlgoOrder(new List<OkexAlgoOrderRequest>());
var trade_16 = api.CancelAdvanceAlgoOrder(new List<OkexAlgoOrderRequest>());
var trade_17 = api.GetAlgoOrderList( OkexAlgoOrderType.OCO);
var trade_18 = api.GetAlgoOrderHistory( OkexAlgoOrderType.Conditional);

Websocket Api Examples

The OKEx.Net socket client provides several socket endpoint to which can be subscribed.

Public Feeds

/* OKEx Socket Client */
var ws = new OkexSocketClient();

/* Sample Pairs */
var sample_pairs = new List<string> { "BTC-USDT", "LTC-USDT", "ETH-USDT", "XRP-USDT", "BCH-USDT", "EOS-USDT", "OKB-USDT", "ETC-USDT", "TRX-USDT", "BSV-USDT", "DASH-USDT", "NEO-USDT", "QTUM-USDT", "XLM-USDT", "ADA-USDT", "AE-USDT", "BLOC-USDT", "EGT-USDT", "IOTA-USDT", "SC-USDT", "WXT-USDT", "ZEC-USDT", };

/* WS Subscriptions */
var subs = new List<UpdateSubscription>();

/* Instruments (Public) */
ws.SubscribeToInstruments(OkexInstrumentType.Spot, (data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

/* Tickers (Public) */
foreach (var pair in sample_pairs)
{
    var subscription = ws.SubscribeToTickers(pair, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
    subs.Add(subscription.Data);
}

/* Unsubscribe */
foreach (var sub in subs)
{
    _ = ws.UnsubscribeAsync(sub);
}

/* Interests (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToInterests(pair, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Candlesticks (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToCandlesticks(pair, OkexPeriod.FiveMinutes, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Trades (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToTrades(pair, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Estimated Price (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToTrades(pair, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Mark Price (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToMarkPrice(pair, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Mark Price Candlesticks (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToMarkPriceCandlesticks(pair, OkexPeriod.FiveMinutes, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Limit Price (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToPriceLimit(pair, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Order Book (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToOrderBook(pair, OkexOrderBookType.OrderBook, (data) =>
    {
        if (data != null && data.Asks != null && data.Asks.Count() > 0 && data.Bids != null && data.Bids.Count() > 0)
        {
            // ... Your logic here
        }
    });
}

/* Option Summary (Public) */
ws.SubscribeToOptionSummary("USD", (data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

/* Funding Rates (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToFundingRates(pair, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Index Candlesticks (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToIndexCandlesticks(pair, OkexPeriod.FiveMinutes, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* Index Tickers (Public) */
foreach (var pair in sample_pairs)
{
    ws.SubscribeToIndexTickers(pair, (data) =>
    {
        if (data != null)
        {
            // ... Your logic here
        }
    });
}

/* System Status (Public) */
ws.SubscribeToSystemStatus((data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

Private Feeds

/* OKEx Socket Client */
var ws = new OkexSocketClient();
ws.SetApiCredentials("XXXXXXXX-API-KEY-XXXXXXXX", "XXXXXXXX-API-SECRET-XXXXXXXX", "XXXXXXXX-API-PASSPHRASE-XXXXXXXX");

/* Account Updates (Private) */
ws.SubscribeToAccountUpdates((data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

/* Position Updates (Private) */
ws.SubscribeToPositionUpdates(OkexInstrumentType.Futures, "INSTRUMENT", "UNDERLYING", (data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

/* Balance And Position Updates (Private) */
ws.SubscribeToBalanceAndPositionUpdates((data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

/* Order Updates (Private) */
ws.SubscribeToOrderUpdates(OkexInstrumentType.Futures, "INSTRUMENT", "UNDERLYING", (data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

/* Algo Order Updates (Private) */
ws.SubscribeToAlgoOrderUpdates(OkexInstrumentType.Futures, "INSTRUMENT", "UNDERLYING", (data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

/* Advance Algo Order Updates (Private) */
ws.SubscribeToAdvanceAlgoOrderUpdates(OkexInstrumentType.Futures, "INSTRUMENT", "UNDERLYING", (data) =>
{
    if (data != null)
    {
        // ... Your logic here
    }
});

Release Notes

Please refer to VERSION file.

okex.net's People

Contributors

alanthinker avatar burakoner avatar ivanov-as avatar saiswj avatar sheldon1310 avatar tekr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

okex.net's Issues

Error Code: 3

When i run this project, in most cases got the error msg:
{3: Server error: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。 }

how can i tuning it ?

Invalid sing

Hello, sometimes an invalid sign error occurs when making requests and then continues to work as usual.

OkexSocketClient is not working using DemoTradingService

Hi Burakoner. How are you? it's me again...

I don't know if I'm doing something wrong.., but this method "ws.SubscribeToOrderUpdates(OkexInstrumentType.Spot" doesn't work using DemoTradingService."
var ws = new OkexSocketClient(new Okex.Net.CoreObjects.OkexSocketClientOptions()
{
AutoReconnect = true,
DemoTradingService = demoTrading,
LogLevel = LogLevel.Debug,
ReconnectInterval = new TimeSpan(0, 1, 0),
SocketResponseTimeout = new TimeSpan(0, 0, 30),
SocketNoDataTimeout = new TimeSpan(0, 0, 30),
});
ws.SetApiCredentials(apiKey,apiSecret,apiPhrase);
ws.SubscribeToOrderUpdates(OkexInstrumentType.Spot, "INSTRUMENT", "UNDERLYING", (data) =>
{
if (data != null)
{
Console.WriteLine(" Updated something ");
}
});
await Task.Delay(10000);
..... put the order.....
I'm placing the order normal using api.PlaceOrder
Thanks.

Api V5 e çıkmış

Selamlar,

Api V5 çıkmış. Response class yapıları ve endpointlerde değişiklik yapmışlar.

Incorrect URLs for some endpoints

Hi! I'm not sure if some endpoints changed their URL at some point, but they now seem to be different than what's in the code. For example:

Endpoint Client Code OKX Documentation
Get sub-account balance api/v5/users/subaccount/balances /api/v5/account/subaccount/balances
History of sub-account transfer api/v5/users/subaccount/bills /api/v5/asset/subaccount/bills
Master accounts manage the transfers between sub-accounts api/v5/users/subaccount/transfer /api/v5/asset/subaccount/transfer

There may be others. Requesting these endpoints from the client returns a 404.

SubscribeToOrderUpdates - Messages not handled.

Is there any way the following error can be fixed. Can you point me in the right direction, please.

I've subscribed to order updates using SubscribeToOrderUpdates but each time there's an update it shows in the log a warning the message has not been handled.

2022/07/22 02:10:26:020 | Warning | OKEx WS Api | Socket 1 Message not handled:

{
  "arg": {
    "channel": "orders",
    "instType": "SWAP",
    "instId": "GODS-USDT-SWAP",
    "uid": "111111111111"
  },
  "data": [
    {
      "accFillSz": "1",
      "amendResult": "",
      "avgPx": "0.4643",
      "cTime": "1658452225477",
      "category": "normal",
      "ccy": "",
      "clOrdId": "",
      "code": "0",
      "execType": "T",
      "fee": "-0.00023215",
      "feeCcy": "USDT",
      "fillFee": "-0.00023215",
      "fillFeeCcy": "USDT",
      "fillNotionalUsd": "0.4643",
      "fillPx": "0.4643",
      "fillSz": "1",
      "fillTime": "1658452225480",
      "instId": "GODS-USDT-SWAP",
      "instType": "SWAP",
      "lever": "20",
      "msg": "",
      "notionalUsd": "0.4643",
      "ordId": "470517968441606146",
      "ordType": "market",
      "pnl": "0",
      "posSide": "long",
      "px": "",
      "rebate": "0",
      "rebateCcy": "USDT",
      "reduceOnly": "false",
      "reqId": "",
      "side": "buy",
      "slOrdPx": "",
      "slTriggerPx": "",
      "slTriggerPxType": "last",
      "source": "",
      "state": "filled",
      "sz": "1",
      "tag": "",
      "tdMode": "cross",
      "tgtCcy": "",
      "tpOrdPx": "",
      "tpTriggerPx": "",
      "tpTriggerPxType": "last",
      "tradeId": "16669343",
      "uTime": "1658452225483"
    }
  ]
}

FundTransfer doesn't work

execuse me.
accounting the okex document,if i want transfer Funding account to Trading account,like this:
Transfer 1.5 USDT from funding account to Trading account when current account is master-account
POST /api/v5/asset/transfer
body
{
"ccy":"USDT",
"amt":"1.5",
"from":"6",
"to":"18"
}

but in FundTransfer parameter OkexAccount ,there is no 18 Trading account. how can i solve this problem?

okex software

is there any software that works the same as this code?
finally, I couldn't understand code and couldn't use it!

How to calculate order size?

Could you please explain to me how I can calculate the order size ?
The other question, how I can set the leverage?

For example, I want to order Ethereum :
price : 2789
leverage : 40
amount: 300 USDT

Incorrect deserialisation of perpetual swap positions

As detailed here, the side of a position is returned as either 'long' or short'.

However OkexSwapPosition.Side is currently of type OkexSwapOrderSide, which is deserialised from the string values 'buy' and 'sell'. As such the values are not deserialised correctly (for short positions), leading to incorrect position results.

Following the pattern of OkexSwapTransaction.Direction, I believe that OkexSwapPosition.Side should be renamed to OkexSwapPosition.Direction and changed to be of type OkexSwapDirection.

System.MissingMethodException

Hi,
when i test, it throws an excepption. I run it on windows 10 .net 5.

using (OkexClient client = new OkexClient())
{
    client.SetApiCredentials(account.AKey, account.SKey, account.Pass);
    var tickers = client.Spot_GetAllTickers(); // throw an exception
}

System.MissingMethodException
HResult=0x80131513
Message=Method not found: 'System.Threading.Tasks.Task1<CryptoExchange.Net.Objects.WebCallResult1<!!0>> CryptoExchange.Net.RestClient.SendRequest(System.Uri, System.Net.Http.HttpMethod, System.Threading.CancellationToken, System.Collections.Generic.Dictionary2<System.String,System.Object>, Boolean, Boolean, System.Nullable1<CryptoExchange.Net.Objects.PostParameters>, System.Nullable1<CryptoExchange.Net.Objects.ArrayParametersSerialization>, Int32)'. Source=Okex.Net StackTrace: at Okex.Net.OkexClient.<Spot_GetAllTickers_Async>d__267.MoveNext() at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.Start[TStateMachine](TStateMachine& stateMachine)
at Okex.Net.OkexClient.Spot_GetAllTickers_Async(CancellationToken ct)
at Okex.Net.OkexClient.Spot_GetAllTickers(CancellationToken ct)
at Assets.OApi.SyncAccount(Account account, Dictionary`2 prices) in C:\Dex\Assets\OApi.cs:line 25
at Assets.Program.Main(String[] args) in C:\Dex\Assets\Program.cs:line 34

Structure to use for Futures trading

I want to use it, but it is a title bit difficult to understand how it works.
Why it has different structure than other component (binance.net)?

There is any clear example to use for Futures?

Deserialize JsonSerializationException in OkexFundingAssetInformation

Hi i got an error in the Funding_GetAllCurrencies_Async function "Deserialize JsonSerializationException: Error converting value {null} to type 'System.Decimal'. Path '[25].min_withdrawal', line 1, position 3003." Decision this problem is to make a nullable decimal in the "MinWithdrawalAmount" property.

New v5 apiKey.

Hi,
I have this error:
"30016: Please change to port v1 when you are using v1 apiKey. If you wish to use port v3, please register a v3 apiKey"
My apiKey version is v5 and I can't create v3 apiKey. Please help me.
Thx.

GetOrderDetails

GetOrderDetails获取订单详情中返回参数QuantityType为空字符串的时候没办法转换成枚举报NULL

auth reconnect bug

connection will not authenticate when connection reconnected.the origin code is bellow

 protected virtual async Task<CallResult<bool>> OkexAuthenticateSocket(SocketConnection s)
        {
            // Check Point
            if (s.Authenticated)
                return new CallResult<bool>(true, null);

            // Check Point
            if (Key == null || Secret == null || PassPhrase == null)
                return new CallResult<bool>(false, new NoApiCredentialsError());

because the package CryptoExchange.net will not set Authenticated=false.that's say Authenticated is awalys true..
we can also think, the field Authenticated just say the connection need auth

PrivatWebsocket instantly closes

Hello, I ran in to a problem while receiving data from privat websockets.

While the public websocket stays open and works as expected the privat websocket instantly closes.

The Login args are in my case filled.

Here are some Debug logs:
2020.04.25 13:20:10:412 | Debug | Socket 2 sending data: {"op":"login","args":[" "," "," "]}
2020.04.25 13:20:10:642 | Debug | Socket 2 received data: {"event":"login","success":true}
2020.04.25 13:20:10:645 | Debug | Socket 2 sending data: {"op":"subscribe","args":["spot/account:OKB"]}
2020.04.25 13:20:10:869 | Debug | Socket 2 received data: {"event":"subscribe","channel":"spot/account:OKB"}
2020.04.25 13:20:10:872 | Debug | Subscription completed
2020.04.25 13:20:10:874 | Debug | Disposing socket client, closing all subscriptions
2020.04.25 13:20:10:876 | Debug | Closing all 1 subscriptions
2020.04.25 13:20:10:879 | Debug | Socket 2 closing
2020.04.25 13:20:11:097 | Info | Socket 2 closed

Authenticated websocket handler not working.

I am having trouble using the websocket to get order and position updates. I can see the data showing up in the debug output but it is never being sent to the callback. I have only tested on swap markets. I confirmed the issue is happening when using the demo example code as well. It seems to be having issues handling the pong messages as well. Here is a shortened version of what I am seeing in the output.

2022/04/27 17:44:58:230 | Error | OKEx WS Api | Deserialize JsonReaderException: Unexpected character encountered while parsing value: p. Path '', line 0, position 0., Path: , LineNumber: 0, LinePosition: 0. Data: pong

2022/04/27 17:39:29:524 | Warning | OKEx WS Api | Socket 1 Message not handled: pong
2022/04/27 17:39:31:810 | Warning | OKEx WS Api | Socket 1 Message not handled: {
"arg": {
"channel": "positions",

OkexAccountPositionRiskPositionData.MarginMode owned a wrong json property name.

    public class OkexAccountPositionRiskPositionData
    {
        [JsonProperty("ccy")]
        public string Currency { get; set; }

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

        [JsonProperty("instType"), JsonConverter(typeof(InstrumentTypeConverter))]
        public OkexInstrumentType InstrumentType { get; set; }

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

        [JsonProperty("notionalCcy")]
        public decimal? NotionalCcy { get; set; }

        [JsonProperty("notionalUsd")]
        public decimal? NotionalUsd { get; set; }

        [JsonProperty("pos")]
        public decimal? Quantity { get; set; }

        [JsonProperty("posCcy")]
        public string PositionCurrency { get; set; }

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

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

MarginMode got a wrong JsonPropertyAttribute named "instType" which should be "mgnMode".

Deserialise error on Options_GetPositions_Async

var posResp = await OKex.Options_GetPositions_Async("UNDERLYING HERE");

posResp.success is then false with the error message:

Deserialize JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Okex.Net.RestObjects.OkexOptionsPositions' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.

Issue in Future_PlaceOrder_Async

When I place an order on the exchange, I get an error: Illegal parameter, code : 30024.
Parameters for placing an order:
{
"instrument_id": "LINK-USDT-210326",
"match_price": 0,
"order_type": "4",
"size": 1,
"type": "1"
}. Exchange only accepts string

OKEx.NET depends on an older version of CryptoExchange.Net.

CryptoExchange.Net does not respect semantic versioning because there are breaking changes from 3.0.5 to 3.0.14. This renders OKEx.NET unusable if the assembly corresponding to the 3.0.14 NuGet package is loaded, as might happen if one depends also on Binance.NET 6.0.2.

I am working on updating the package and fixing the breaking changes. I will submit a pull request.

Get Candlesticks History

I need to use candles to get ema200,sma100,... so it seems there is limitation for 100 records.
Could you please tell me how I can get more than 100?

for (int i = 1; i < 4; i++)
                { 
                    var result = client.GetCandlesticksHistory(symbolName, (OkexPeriod)interval, after  , before  ); 
                    if (result.Success)
                    {
                        foreach (var k in result.Data)
                        {
                            var n = new Quote()
                            {
                                Date = k.Time,
                                Open = k.Open,
                                Close = k.Close,
                                High = k.High,
                                Low = k.Low,
                                Volume = k.Close
                            };
                            allCandles.Add(n);
                        }
                    }
                    before += 99;
                    after += 99; ;
                }

use demo api

I have tried to connect to demo API, but it doesn't work, there is configuration I have to set?

Even i created new API but still i get this error:
50101: Broker id of APIKey does not match current environment.

Algo emirlerde sorun var.

"Swap_AlgoPlaceOrder_Async" metodunda parametre olarak ikisinde de "order_type" alınmış. Oysaki "type" verisi isteniyor ve bu bilgi oraya gönderiliyor. Burada bir düzeltme yaparak devam etmek istedim ama mevcuttaki tüm parametrelere karşılık girsem de eksik parametre var hatası almaktan kurtulamadım.

SubscribeToIndexTickers

SubscribeToIndexTickers 返回的实体对象不对 public virtual CallResult SubscribeToIndexTickers(string intrumentId, Action onData); 应该返回OkexIndexTicker这个吧

Ping timeout for websocket

I have code similar to this:

var OKexWS = new OkexSocketClient(new Okex.Net.CoreObjects.OkexSocketClientOptions()
            {
                AutoReconnect = true,
                ReconnectInterval=new TimeSpan(0,1,0),
                SocketResponseTimeout= new TimeSpan(0, 0, 30),
                SocketNoDataTimeout = new TimeSpan(0, 0, 30),
            }) ;

var pong = await OKexWS.PingAsync();

I am getting a failed pong with the error message of "No response on query received"
From what I can see the requests times out.

Is this an issue or am I doing something wrong?

Margin Endpoints

Hi there,

I saw that the Margin Endpoints are already in OkexClient.cs but not implemented yet.
Is this project still under development and is Margin Endpoints to be implemented ?

Great Work,

Regards,

PlaceOrder 下单都是报错{1: Operation failed. }

OkexClient api = new OkexClient();
api.SetApiCredentials("XXXXXXXX-API-KEY-XXXXXXXX", "XXXXXXXX-API-SECRET-XXXXXXXX", "XXXXXXXX-API-PASSPHRASE-XXXXXXXX");
var trade_01 = api.PlaceOrder("BTC-USDT", OkexTradeMode.Cash, OkexOrderSide.Buy, OkexPositionSide.Long, OkexOrderType.MarketOrder, 0.1m);
用你的demo也是一样

question about 2 request

/* First of all, thank you for this class library :)
I need you to find two methods. (of course, if implemented.)

  1. i want to get list of all assets in spot and futures market;
  2. and i want get candle details (Klines) of some currencies as BTCUSDT
    */

v5 support missing

Hello,

Since this lib doesn't support v5 and json structures are different, is there a plan to create v5 lib?
Thanks

Acess to Demo trading using OkexClient

Please, Could you help me to acess Demo trade and make a SPOT order using:
OkexClient api = new OkexClient(new Okex.Net.CoreObjects.OkexRestClientOptions {
LogLevel = LogLevel.Debug,
BaseAddress = baseUrl,
});
var trade_01 = api.PlaceOrder("BTC-USDT", OkexTradeMode.Cash, OkexOrderSide.Buy, OkexPositionSide.Long, OkexOrderType.MarketOrder, 0.1m);

What the adress /baseUrl that I can use to acess the Demo trading ?

GetAlgoOrderList error to set ActualSide

i want to remove all algo orders, it seems there is an issue in converting. Could you please have a look at it?

api.GetAlgoOrderList(OkexAlgoOrderType.OCO,instrumentId:preOrder.Symbol );

But i got this error:

{: [115] Deserialize JsonSerializationException: Error setting value to 'ActualSide' on 'Okex.Net.RestObjects.Trade.OkexAlgoOrder'. data: {
  "code": "0",
  "data": [
    {
      "activePx": "",
      "activePxType": "",
      "actualPx": "",
      "actualSide": "",
      "actualSz": "0",
      "algoId": "432333195139489792",
      "cTime": "1649348266083",
      "callbackRatio": "",
      "callbackSpread": "",
      "ccy": "",
      "ctVal": "0.1",
      "instId": "ETH-USDT-SWAP",
      "instType": "SWAP",
      "last": "3210.29",
      "lever": "20",
      "moveTriggerPx": "",
      "notionalUsd": "",
      "ordId": "0",
      "ordPx": "",
      "ordType": "oco",
      "posSide": "short",
      "pxLimit": "",
      "pxSpread": "",
      "pxVar": "",
      "side": "buy",
      "slOrdPx": "-1",
      "slTriggerPx": "3223.14",
      "slTriggerPxType": "last",
      "state": "live",
      "sz": "19",
      "szLimit": "",
      "tag": "",
      "tdMode": "isolated",
      "tgtCcy": "",
      "timeInterval": "",
      "tpOrdPx": "-1",
      "tpTriggerPx": "3176.89",
      "tpTriggerPxType": "last",
      "triggerPx": "",
      "triggerPxType": "",
      "triggerTime": "",
      "uly": "ETH-USDT"
    }
  ],
  "msg": ""
} {
  "code": "0",
  "data": [
    {
      "activePx": "",
      "activePxType": "",
      "actualPx": "",
      "actualSide": "",
      "actualSz": "0",
      "algoId": "432333195139489792",
      "cTime": "1649348266083",
      "callbackRatio": "",
      "callbackSpread": "",
      "ccy": "",
      "ctVal": "0.1",
      "instId": "ETH-USDT-SWAP",
      "instType": "SWAP",
      "last": "3210.29",
      "lever": "20",
      "moveTriggerPx": "",
      "notionalUsd": "",
      "ordId": "0",
      "ordPx": "",
      "ordType": "oco",
      "posSide": "short",
      "pxLimit": "",
      "pxSpread": "",
      "pxVar": "",
      "side": "buy",
      "slOrdPx": "-1",
      "slTriggerPx": "3223.14",
      "slTriggerPxType": "last",
      "state": "live",
      "sz": "19",
      "szLimit": "",
      "tag": "",
      "tdMode": "isolated",
      "tgtCcy": "",
      "timeInterval": "",
      "tpOrdPx": "-1",
      "tpTriggerPx": "3176.89",
      "tpTriggerPxType": "last",
      "triggerPx": "",
      "triggerPxType": "",
      "triggerTime": "",
      "uly": "ETH-USDT"
    }
  ],
  "msg": ""
}}

A josn parsing error problem

The same json attribute posSide appears in line 37 and line 49 in the OkexOrder.cn file, which causes it to not work properly during parsing. Please fix it as soon as possible.

pong json read error

okex.net version 5.1.2
newtonsoft.json version 13.0.1
error occured when recieve websocket message

2021-11-30 11:13:34:989 | Error | OKEx WS Api | Deserialize JsonReaderException: Unexpected character encountered while parsing value: p. Path '', line 0, position 0., Path: , LineNumber: 0, LinePosition: 0. Data: pong
2021-11-30 11:13:35:005 | Warning | OKEx WS Api | Socket 4 Message not handled: pong
2021-11-30 11:13:35:006 | Error | OKEx WS Api | Deserialize JsonReaderException: Unexpected character encountered while parsing value: p. Path '', line 0, position 0., Path: , LineNumber: 0, LinePosition: 0. Data: pong
예외 발생: 'System.InvalidOperationException'(Newtonsoft.Json.dll)
2021-11-30 11:13:35:051 | Error | OKEx WS Api | Socket 5 unhandled exception during message processing: InvalidOperationException - Cannot access child value on Newtonsoft.Json.Linq.JValue.
at Newtonsoft.Json.Linq.JToken.get_Item(Object key)
at Okex.Net.OkexSocketClient.OkexHandleSubscriptionResponse(SocketConnection s, SocketSubscription subscription, Object request, JToken message, CallResult1& callResult) at CryptoExchange.Net.SocketClient.<>c__DisplayClass62_0.<SubscribeAndWaitAsync>b__0(JToken data) at CryptoExchange.Net.Sockets.PendingRequest.CheckData(JToken data) at CryptoExchange.Net.Sockets.SocketConnection.ProcessMessage(String data) at CryptoExchange.Net.Sockets.CryptoExchangeWebSocketClient.Handle[T](List1 handlers, T data)
at CryptoExchange.Net.Sockets.CryptoExchangeWebSocketClient.HandleMessage(Byte[] data, Int32 offset, Int32 count, WebSocketMessageType messageType)

Heavy CPU usage in websocket handler

Thanks for this great library. I was able to use it to quickly add OkEx support to a market data depth capture system.

However I observed very high CPU usage when recording order books for ~20 instruments (keeping in mind OkEx has hundreds of instruments). Profiling showed that almost a quarter of all CPU time is spent in OkexSocketClient.OkexMessageMatchesHandler(); this method looks very ripe for some optimisation, so I'll have a crack at it.

Attached is the profiling output with the method above highlighted.

MatchesHanderCost

It's better to add "instId" in class OkexOrderBook for subscription identity.

In the docs, after u subscribe the "books" channel success, it will push:

{
    "arg": {
        "channel": "books",
        "instId": "BTC-USDT"
    },
    "action": "snapshot",
    "data": [{
        "asks": [
            ["8476.98", "415", "0", "13"],
            ["8477", "7", "0", "2"],
            ["8477.34", "85", "0", "1"],
            ["8477.56", "1", "0", "1"],
            ["8505.84", "8", "0", "1"],
            ["8506.37", "85", "0", "1"],
            ["8506.49", "2", "0", "1"],
            ["8506.96", "100", "0", "2"]
        ],
        "bids": [
            ["8476.97", "256", "0", "12"],
            ["8475.55", "101", "0", "1"],
            ["8475.54", "100", "0", "1"],
            ["8475.3", "1", "0", "1"],
            ["8447.32", "6", "0", "1"],
            ["8447.02", "246", "0", "1"],
            ["8446.83", "24", "0", "1"],
            ["8446", "95", "0", "3"]
        ],
        "ts": "1597026383085",
        "checksum": -855196043
    }]
}

And there is no "arg" property in class OkexOrderBook:

namespace Okex.Net.RestObjects.Market
{
    public class OkexOrderBook
    {
        public OkexOrderBook();

        [JsonProperty("asks")]
        public IEnumerable<OkexOrderBookRow> Asks { get; set; }
        [JsonProperty("bids")]
        public IEnumerable<OkexOrderBookRow> Bids { get; set; }
        [JsonConverter(typeof(OkexTimestampConverter))]
        [JsonProperty("ts")]
        public DateTime Time { get; set; }
        [JsonProperty("action")]
        public string Action { get; set; }
        [JsonProperty("checksum")]
        public long? Checksum { get; set; }
    }
}

In fact, “instId” is really useful for identify different data push.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.