
    iO{                       d dl mZ d dlmZ d dlZd dlZd dlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z! d dl"m#Z# d dl"m$Z$ d dl%m&Z& d dl%m'Z' d d	l%m(Z( d d
l%m)Z) d dl%m*Z* d dl%m+Z+ d dl%m,Z, d dl%m-Z- d dl%m.Z. d dl%m/Z/ d dl%m0Z0 d dl%m1Z1 d dl%m2Z2 d dl%m3Z3 d dl%m4Z4 d dl%m5Z5 d dl%m6Z6 d dl%m7Z7 d dl%m8Z8 d dl%m9Z9 d dl%m:Z: d dl;m<Z< d dl=m>Z>  G d dee          Z?dS )     )Exchange)ImplicitAPIN)AccountBalances
Conversion
CurrenciesCurrencyGreeksIntLeverageMarginModificationMarketMarketInterfaceNumOptionOptionChainOrder	OrderBookOrderRequest	OrderSide	OrderTypeStrStringsTickerTickersTradeTradingFeeInterfaceTransactionTransferEntry)List)Any)ExchangeError)AuthenticationError)PermissionDenied)AccountNotEnabled)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidAddress)InvalidOrder)OrderNotFound)CancelPending)ContractUnavailable)NotSupported)NetworkError)RateLimitExceeded)ExchangeNotAvailable)OnMaintenance)InvalidNonce)RequestTimeout)	TICK_SIZE)Precisec                   X	    e Zd Z fdZdi dfdededef fdZd Zdefd	Z	dd
e
dede
de
def
 fdZi fdZi fdZi fdee         fdZi fdee         fdZdefdZi fdZd Zi fdefdZdi fdededefdZddedefdZi fdedefdZdi fdedefdZ ddede!fdZ"ddi fdedededee!         fdZ#ddede$fdZ%d ddi fdedededee$         fd!Z&dddi fde
dedefd"Z'd# Z(d$ Z)d% Z*ddede+fd&Z,i fdede+fd'Z-i fde.fd(Z/i fded)e0fd*Z1i fded)e0fd+Z2di fded,e3d-e4d.e0d/e5f
d0Z6di fded,e3d-e4d.e0d/e5f
d1Z7i fd2ee8         fd3Z9ddi fd4efd5Z:ddi fd4eded,e3d-e4d.e5d/e5fd6Z;di fd4ede
fd7Z<d8 Z=di fde
fd9Z>d: Z?ddede@fd;ZAdi fd4ede
fd<ZBdddi fde
dededee@         fd=ZCdddi fde
dedefd>ZDdddi fde
dededee@         fd?ZEdddi fde
dedefd@ZFdddi fd4ede
dedefdAZGdddi fdBe
dedefdCZHdD ZIddEeJfdFZKddEeJfdGZLi fdBefdHZMi fdBefdIZNdi fdBed.e0fdJZOdddi fdBe
dededeeP         fdKZQdi fd4edBe
fdLZRdddi fdBe
dededeeP         fdMZSdi fd4edBe
fdNZTdO ZUddEeJdePfdPZVi fdedeWfdQZXddeWfdRZYi fdefdSZZdi fdefdTZ[i fdefdUZ\ddefdVZ]i fdBed.e0dWedXede^f
dYZ_ddEeJfdZZ`d[ Zadi fd4edBe
fd\Zbdddi fdBe
dedefd]Zcd^d_i ddfd`ZdddefdaZei fdefdbZfdddi fde
dedefdcZgdi fddede
fdeZhdi fdfeide
fdgZjdi fdhede
fdiZki fdjZli fdBefdkZmddEeJfdlZndm Zodn Zpdddi fdedefdoZqddi fdBededefdpZri fdedesfdqZtddedesfdrZui fdedesfdsZvi fdedesfdtZwi fdefduZxddefdvZyddddi fdBe
de
dedefdwZzddefdxZ{i fdBed.e0fdyZ|i fdBefdzZ}ddEeJfd{Z~i fdefd|Zd}ddi fdededefd~ZddefdZdeif fdZdi fdefdZddZdddi fde
dedefdZd Zd Zi fdZi fdedefdZddefdZdi fded-e4de@fdZi fdedefdZi fdBedefdZddEeJdefdZdi fdeded.e5defdZdi fd4ededed.e5def
dZddeJdeJdefdZi fdefdZd Zddddi fde
d,e
de5de5dees         f
dZ xZS )okxc                 *   |                      t          t          |                                           i dddddddgdd	d
ddddddi dd ddddddddddddddddddddddddddddd dd!di d"dd#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0d d1dd2di d3dd4dd5d d6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBdCdDdi dEddFddGddHddIddJddKddLddMddNddOd dPddQddRddSddTddUdi dVddWddXddYddZdd[d d\dd]dd^dd_dd`ddaddbddcdddd deddfdi dgddhddiddjddkddlddmddnddoddpddqddrddsddtdduddvddwddddddddddddddddxdydzd{d|d}d~ddddddddddddddddiddddddddidddi ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddddddddi ddddddddddddddddɓddɓddɓddɓddɓddɓddɓddɓddɓddɓi ddɓddddddddddddddddddddddddddddɓddɓddɓddddii ddɓddɓddɓddddddɓddɓddddddddddddddddddddi ddddddddddddddd dddddddddddddddddd	d
i ddddddddddddddddddddddddddddddɓddddi ddddɓddd dɓd!dɓd"dɓd#dd$dd%dɓd&dɓd'dɓd(dɓd)dɓd*dɓd+dɓd,dd-di d.dɓd/dd0d1d2d1d3dd4dd5dd6dd7dɓd8dd9dd:dd;dd<dddd=dd>di d?dd@ddAddBddCddDddEddFddGddHddIddJd1dKd1dLd1dMddNddOdi dPddQdɓdRdɓdSdɓdTdɓdUdɓdVdɓdWdɓdXdɓdYddZdd[dd\dd]dɓd^dɓd_dd`dadddad
dddbi dcdɓdddɓdeddfddgdhddɓdidɓdddjdkdldkdmddnddddoddpddqdddi drdsdtddudsdvddwdxdydddzddd{dd|dd}dd~dddddɓddddddi dd
ddddddddddddɓddddddɓddɓddɓddddddddddɓi ddɓddɓddɓd.dddddddddɓddddddddddddddddddi ddddddddddddddddddddddddddddddddddi dddd
dd
ddddddɓddɓddɓddɓddɓddddd[dddddddɓddɓddddddddƐdǜdȜdɜd|                     d˦          |                     d̦          d͜|                     d˦          |                     d̦          d͜|                     dΦ          |                     dϦ          d͜|                     dЦ          |                     dѦ          d͜dҜdddddԜdi dt
          dt
          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt
          dt          dt
          dt          dt          dt
          i dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt          dt
          dt          dt          dt
          dt          dt
          dt
          dt
          i dt          dt          dt          dt          dt          dt          dt          dt
          d t
          dt          dt          dt          dt          dt          dt          dt          dt          i d	t          d
t          dt           dt           dt           dt           dt"          dt          dt$          dt           dt          dt          dt          dt           dt
          dt
          dt
          i dt           dt&          dt&          dt
          dt          dt
          d t          d!t&          d"t&          d#t&          d$t&          d%t           d&t           d't           d(t           d)t           d*t           i d+t           d,t           d-t           d.t           d/t           d0t           d1t           d2t           d3t           d4t           d5t           d6t           d7t           d8t           d9t           d:t           d;t           i d<t           d=t           d>t           d?t          d@t           dAt          dBt           dCt           dDt           dEt           dFt"          dGt           dHt           dIt           dJt           dKt           dLt           i dMt"          dNt           dOt           dPt          dQt"          dRt           dSt           dTt           dUt           dVt           dWt           dXt           dYt           dZt          d[t          d\t           d]t           i d^t           d_t           d`t           dat           dbt           dct           ddt           det           dft           dgt           dht           dit           djt           dkt           dlt           dmt           dnt           i dot           dpt           dqt           drt           dst           dtt           dut           dvt           dwt           dxt           dyt           dzt           d{t           d|t           d}t           d~t           dt           i dt           dt           dt           dt           dt           dt           dt          dt          dt           dt           dt           dt           dt           dt(          dt(          dt(          dt           i dt           dt
          dt
          dt          dt
          dt
          dt*          dt
          dt
          dt"          dt
          dt
          dt
          dt
          dt
          dt
          dt
          i dt
          dt
          dt(          dt          dt          dt          dt
          dt"          dt
          dt
          dt
          dt           dt           dt           dt           dt           dt           i dt           dt           dt
          dt          dt          dt
          dt          dt
          dt
          dt
          dt
          dt          dt          dt
          dt
          dt
          dt
          i dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt
          dt          dt          dt          dt          dt
          dt
          dt
          i dt,          dt          dt
          dt
          dt,          dt
          dt
          dt
          dt
          dt
          dt          dt          dt          dt          dt          dt          dt"          i dt
          dt"          dt
          dt
          dt
          dt
          dt
          dt"          dt
          dt
          dt
          dt
          dt"          dt
          dt           dt"          dt"          i dt          dt          dt          dt
          dt
          dt
          dt
          dt
          dt
          d t
          dt
          dt
          dt
          dt
          dt
          dt          dt          i dt
          d	t          d
t          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt          dt.          dt          t          t          t          t
          t          t          t          dt          t          ddddt          idt0          i ddd d!d"d!d#d$d%d&i d#d'd(d)d*d+d!d!d$d$d,d-d.d/d0d1d2d2d3d4d5d6d7d8d9d:d;d;d<d=d>d?d@dAi dBdCdDdEdFdGdHdIdJdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdYdZd[d\d\d]d^d_d`i dadbdcdddededfdgdhdidjdkdldmdndodpdqdrdsdtdtdudvdwdxdydydzd{d|d}d~di ddddddddddddddddddddddddddddddddddi dddddddddddddddddddddddddddddddddZdyd|dddd|ddddidXddidfddid!ddddTg dâdddNddid_ddid\ddidddid4ddid6ddid d dʜddddddd˜d̐d͐d͐d͐d͐d͐d͐d͐dΜdϐdАdќdҐdӐdԐdՐdՐd֐dҐdӐdԐdՐd֐dלdؐdٜdڐdېdܜdݜ          S (  Nidr:   nameOKX	countriesCNUSversionv5	rateLimitg     Y@proT	certifiedhasCORSspotmarginswapfutureoption	addMargincancelAllOrdersFcancelOrdercancelOrderscloseAllPositionsclosePositioncreateConvertTradecreateDepositAddresscreateMarketBuyOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateOrders$createOrderWithTakeProfitAndStopLosscreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopLossOrdercreateStopMarketOrdercreateStopOrdercreateTakeProfitOrdercreateTrailingPercentOrdercreateTriggerOrder	editOrderfetchAccountsfetchBalancefetchBidsAsksfetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCanceledOrdersfetchClosedOrderfetchClosedOrdersfetchConvertCurrenciesfetchConvertQuotefetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositsWithdrawalsfetchDepositWithdrawFeeemulatedfetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchL3OrderBookfetchLedgerfetchLedgerEntryfetchLeveragefetchLeverageTiersfetchMarginAdjustmentHistoryfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMySettlementHistoryfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenOrderfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchOrderBooksfetchOrdersfetchOrderTradesfetchPermissionsfetchPositionfetchPositionsfetchPositionsForSymbolfetchPositionsRiskfetchPremiumIndexOHLCVfetchSettlementHistoryfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTradingLimitsfetchTransactionFeefetchTransactionFeesfetchTransactionsfetchTransferfetchTransfers)fetchUnderlyingAssetsfetchVolatilityHistoryfetchWithdrawalfetchWithdrawalsfetchWithdrawalWhitelistreduceMarginrepayCrossMarginsetLeverage	setMarginsetMarginModesetPositionModesignIntransferwithdraw
timeframes1m3m5m15m30m1H2H4H6H12H1D1W1M3M)r   r   r   r   r   1h2h4h6h12h1d1wr   r   hostnamezwww.okx.comurlszdhttps://user-images.githubusercontent.com/1294454/152485636-38b19e4a-bece-4dec-979a-5982859ffc04.jpgrestzhttps://{hostname}zhttps://www.okx.comzhttps://www.okx.com/docs-v5/en/z,https://www.okx.com/pages/products/fees.htmlz!https://www.okx.com/join/CCXT2023g?)urldiscount)logoapiwwwdocfeesreferraltestr   getzmarket/books-full   zmarket/tickers   zmarket/tickerzmarket/index-tickerszmarket/booksg      ?zmarket/books-liteg?zmarket/candleszmarket/history-candleszmarket/index-candleszmarket/history-index-candleszmarket/mark-price-candlesz!market/history-mark-price-candleszmarket/tradeszmarket/history-tradesz&market/option/instrument-family-tradeszmarket/platform-24-volume
   zmarket/open-oracle2   zmarket/exchange-rate   zmarket/index-componentszpublic/economic-calendarzmarket/block-tickerszmarket/block-tickerzpublic/block-tradeszpublic/instrumentsz public/delivery-exercise-historyzpublic/open-interestzpublic/funding-ratezpublic/funding-rate-historyzpublic/price-limitzpublic/opt-summaryzpublic/estimated-pricez(public/discount-rate-interest-free-quotazpublic/timezpublic/mark-pricezpublic/position-tierszpublic/interest-rate-loan-quotaz#public/vip-interest-rate-loan-quotazpublic/underlyingzpublic/insurance-fundzpublic/convert-contract-coinzpublic/option-tradeszpublic/instrument-tick-bands   z$rubik/stat/trading-data/support-coinzrubik/stat/taker-volumezrubik/stat/margin/loan-ratioz-rubik/stat/contracts/long-short-account-ratioz)rubik/stat/contracts/open-interest-volumez&rubik/stat/option/open-interest-volumez,rubik/stat/option/open-interest-volume-ratioz-rubik/stat/option/open-interest-volume-expiryz-rubik/stat/option/open-interest-volume-strikez$rubik/stat/option/taker-block-volumezsystem/statuszsprd/spreadsz
sprd/bookszsprd/tickerzsprd/public-tradesztradingBot/grid/ai-paramztradingBot/grid/min-investmentz"tradingBot/public/rsi-back-testingzasset/exchange-listz$finance/staking-defi/eth/apy-historyz$finance/savings/lending-rate-summaryz$finance/savings/lending-rate-historyzfinance/sfp/dcd/productsgUUUUUU?zcopytrading/public-lead-traderszcopytrading/public-weekly-pnlzcopytrading/public-stats)z&copytrading/public-preference-currencyz'copytrading/public-current-subpositionsz'copytrading/public-subpositions-historyzrfq/counterpartieszrfq/maker-instrument-settingszrfq/mmp-configzrfq/rfqsz
rfq/quotesz
rfq/tradeszrfq/public-tradesz
sprd/ordergUUUUUU?zsprd/orders-pendingzsprd/orders-historyzsprd/orders-history-archivezsprd/tradestrade/orderztrade/orders-pendingztrade/orders-historyztrade/orders-history-archiveztrade/fillsztrade/fills-historyg@ztrade/fills-archivetrade/order-algoztrade/orders-algo-pendingztrade/orders-algo-historyz trade/easy-convert-currency-listztrade/easy-convert-historyz#trade/one-click-repay-currency-listztrade/one-click-repay-historyztrade/account-rate-limitzasset/currencieszasset/balanceszasset/non-tradable-assetszasset/asset-valuationzasset/transfer-statezasset/billszasset/deposit-lightning   zasset/deposit-addresszasset/deposit-historyzasset/withdrawal-historyzasset/deposit-withdraw-statuszasset/convert/currencieszasset/convert/currency-pairzasset/convert/historyzasset/monthly-statementzaccount/balancezaccount/positionszaccount/positions-historyd   zaccount/account-position-riskzaccount/billszaccount/bills-archivezaccount/configzaccount/max-sizezaccount/max-avail-sizezaccount/leverage-infozaccount/adjust-leverage-infozaccount/max-loanzaccount/trade-feezaccount/interest-accruedzaccount/interest-ratezaccount/max-withdrawalzaccount/risk-statez)account/quick-margin-borrow-repay-historyzaccount/borrow-repay-historyzaccount/vip-interest-accruedzaccount/vip-interest-deductedzaccount/vip-loan-order-listzaccount/vip-loan-order-detailzaccount/interest-limitszaccount/greekszaccount/position-tierszaccount/mmp-configzusers/subaccount/listzaccount/subaccount/balancesg
@zasset/subaccount/balancesz!account/subaccount/max-withdrawalzasset/subaccount/billsz)asset/subaccount/managed-subaccount-billszusers/entrust-subaccount-listz"account/subaccount/interest-limitsz#tradingBot/grid/orders-algo-pendingz#tradingBot/grid/orders-algo-historyz#tradingBot/grid/orders-algo-detailsztradingBot/grid/sub-ordersztradingBot/grid/positionsztradingBot/signal/signalsz%tradingBot/signal/orders-algo-detailsz%tradingBot/signal/orders-algo-historyztradingBot/signal/positionsz#tradingBot/signal/positions-historyztradingBot/signal/sub-ordersztradingBot/signal/event-historyz(tradingBot/recurring/orders-algo-pendingz(tradingBot/recurring/orders-algo-historyz(tradingBot/recurring/orders-algo-detailsztradingBot/recurring/sub-orderszfinance/savings/balancezfinance/savings/lending-historyzfinance/staking-defi/offersz"finance/staking-defi/orders-activez#finance/staking-defi/orders-historyz finance/staking-defi/eth/balancez0finance/staking-defi/eth/purchase-redeem-historyz copytrading/current-subpositionsz copytrading/subpositions-historyzcopytrading/instrumentsz"copytrading/profit-sharing-detailsz copytrading/total-profit-sharingz-copytrading/unrealized-profit-sharing-detailszcopytrading/copy-settingszcopytrading/batch-leverage-infoz copytrading/current-lead-tradersz copytrading/lead-traders-historyzbroker/nd/infozbroker/nd/subaccount-infozbroker/nd/subaccount/apikey*asset/broker/nd/subaccount-deposit-addressz*asset/broker/nd/subaccount-deposit-historyz-asset/broker/nd/subaccount-withdrawal-historyzbroker/nd/rebate-dailybroker/nd/rebate-per-ordersi,  )finance/sfp/dcd/orderzfinance/sfp/dcd/ordersbroker/fd/rebate-per-orderszbroker/fd/if-rebatezaffiliate/invitee/detailzusers/partner/if-rebatezrfq/create-rfqzrfq/cancel-rfqzrfq/cancel-batch-rfqszrfq/cancel-all-rfqszrfq/execute-quote   zrfq/mmp-resetzrfq/create-quoteg?zrfq/cancel-quotezrfq/cancel-batch-quoteszrfq/cancel-all-quoteszsprd/cancel-orderzsprd/mass-cancelzsprd/amend-ordertrade/batch-ordersg?ztrade/cancel-orderztrade/cancel-batch-ordersztrade/amend-orderztrade/amend-batch-ordersgO贁N{?ztrade/close-positioni  ztrade/cancel-algosztrade/amend-algosztrade/cancel-advance-algosztrade/easy-convertztrade/one-click-repayztrade/mass-cancelztrade/cancel-all-afterzasset/transferzasset/withdrawalzasset/withdrawal-lightningzasset/cancel-withdrawalzasset/convert-dust-assetszasset/convert/estimate-quotezasset/convert/tradezaccount/set-position-modezaccount/set-leveragezaccount/position/margin-balancezaccount/set-greekszaccount/set-isolated-modez!account/quick-margin-borrow-repayzaccount/borrow-repayzaccount/simulated_marginzaccount/position-builderzaccount/set-riskOffset-typezaccount/activate-optionzaccount/set-auto-loanzaccount/set-account-levelzaccount/mmp-resetzusers/subaccount/modify-apikeyzasset/subaccount/transferz!users/subaccount/set-transfer-outz&account/subaccount/set-loan-allocationztradingBot/grid/order-algoz tradingBot/grid/amend-order-algoztradingBot/grid/stop-order-algoztradingBot/grid/close-positionz"tradingBot/grid/cancel-close-orderz%tradingBot/grid/order-instant-triggerztradingBot/grid/withdraw-incomez&tradingBot/grid/compute-margin-balanceztradingBot/grid/margin-balanceztradingBot/signal/create-signalztradingBot/signal/order-algoz!tradingBot/signal/stop-order-algoz tradingBot/signal/margin-balanceztradingBot/signal/amendTPSLz!tradingBot/signal/set-instrumentsz tradingBot/signal/close-positionztradingBot/signal/sub-orderz"tradingBot/signal/cancel-sub-orderztradingBot/recurring/order-algoz%tradingBot/recurring/amend-order-algoz$tradingBot/recurring/stop-order-algoz finance/savings/purchase-redemptz finance/savings/set-lending-ratezfinance/staking-defi/purchase   zfinance/staking-defi/redeemzfinance/staking-defi/cancelz!finance/staking-defi/eth/purchasezfinance/staking-defi/eth/redeemzcopytrading/algo-orderzcopytrading/close-subpositionzcopytrading/set-instrumentszcopytrading/first-copy-settingszcopytrading/amend-copy-settingszcopytrading/stop-copy-tradingzcopytrading/batch-set-leveragezbroker/nd/create-subaccountg      ?zbroker/nd/delete-subaccountz"broker/nd/subaccount/modify-apikeyz"broker/nd/subaccount/delete-apikeyzbroker/nd/set-subaccount-levelz!broker/nd/set-subaccount-fee-ratei  )zbroker/nd/set-subaccount-assetsr   z1asset/broker/nd/modify-subaccount-deposit-addressr   zfinance/sfp/dcd/quoter   zbroker/nd/report-subaccount-ipr   )r   post)publicprivater   z0.0015z0.0010)takermakerz0.0005z0.0002z0.00050z0.00020)tradingrI   rL   rK   requiredCredentials)apiKeysecretpassword
exceptions12500005000150002500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285004450061500625010050101501025010350104501055010650107501085010950110501115011250113501145011551000510015100251003510045100551006510075100851009510105101151012510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510465104751072510735107451090510915109251093510945109551096510985109951100511015110251103511045110551106511075110851109511105111151112511135111551116511175111851119511205112151122511245112551126511275112851129511305113151132511335113451135511365113751138511395115651159511625116351166511745118551201512025120351204512055125051251512525125351254512555125651257512585125951260512615126251263512645126551267512685126951270512715127251273512745127551276512775127851279512805132151322513235132451325513275132851329513305140051401514025140351404514055140651407514085140951410515005150151502515035150651508515095151051511516005160151602516035173251733517345173551736520005400054001551005510155102551035510455111551125511358000580015800258003580045800558006580075810058101581025810358104581055810658107581085810958110581115811258114581155811658117581255812658127581285820058201582025820358204582055820658207582085820958210582115821258213582215822258224582275822858229583005835059000590015910059101591025910359104591055910659107591085910959128592005920159216592605926259300593015931359401595005950159502595035950459505595065950759508596425964360001600026000360004600056000660007600086000960010600116001260013600146001560016)60017600186001963999700107001370016)zInternal Server Errorzserver error)exactbroadhttpExceptions429precisionModesandboxModedefaultNetworkERC20defaultNetworksBTCTRC20)ETHrO  USDTnetworksBitcoinBTCLN	LightningBEP20BSCCRC20CryptoACAAcalaALGOAlgorandBHPAPTAptosARBONEzArbitrum OneAVAXCzAvalanche CAVAXXzAvalanche X-ChainARKARArweaveASTRAstarBCHBitcoinCashBSVz
Bitcoin SVBTMBytomADACardanoCSPRCasperCELOXCHChiaCHZChilizATOMCosmosTRUE	TrueChainDCRDecredDGBDigibyteDOGEDogecoinXECEGLDElrondEOSETCzEthereum ClassicETHWEthereumPowFTMFantomFILFilecoinFLOWFSNFusionONEHarmonyHBARHederaHNTHeliumZENHorizenICXICONICPDfinityIOSTIOTAMIOTAKDAKadenaKARKLAYKlaytnKSMKusamaLSKLiskLTCLitecoinMETISMetisMINAMinaXMRMoneroGLRMMoonbeamMOVR	MoonriverNANONanoNEARNASNebulasNEMzNew Economy MovementNULSOASYSOKCONTOntologyOPTIMISMOptimismLATPlatONDOTPolkadotMATICPolygonRVN	RavencoinXRPRippleSCSiacoinSOLSolanaSTXzl-StacksXLMzStellar LumensXTZTezosTONTHETAThetaVSYSVSYSTEMSWAVESWAXWaxZECZcashZILZilliqaZKSYNC8H)r   r   8hr   5Mr   r  r   timezoneUTCmethodprivateGetAccountPositionsprivatePostTradeBatchOrders!createMarketBuyOrderRequiresPrice)rI   rL   rK   rM   defaultTypeprivateGetAccountBillsprivateGetTradeOrderprivateGetTradeOrdersPending!privatePostTradeCancelBatchOrdersprivateGetTradeOrdersHistory)r   pwd)conditionaltriggerocomove_order_stopicebergtwap618)fundingr   rI   rL   futuresrJ   rK   rM   r  r   )r  r  SPOTMARGINSWAPFUTURESOPTION)rI   rJ   rK   rL   r  rM   r  r  r  r  r  e847386590ce4dBC)r   algoOrderTypesaccountsByTypeaccountsByIdexchangeTypebrokerIdAETWINTOKEN)AEWIN)optionscommonCurrencies)deep_extendsuperr:   describeparse_numberr"   r(   r4   r6   r3   r&   r#   r2   r$   r5   r)   r,   r*   r%   r/   r-   r.   r+   r1   r7   )self	__class__s    \/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/okx.pyr  zokx.describe(   s5   c4 0 0 9 9 ; ; D>
%D>
ED>
 $D>
 t	D>

 D>
 4D>
 D>
  uuu $u 	u
 $u $u Tu "5u tu u $Uu  u %du 'u /u  0!u" t#u u$ %u& 7'u( &t)u* (+u, '-u. &t/u0 (1u2 "43u4 (5u6 -d7u8 %d9u: T;u<  =u> ?u@  AuB &tCuD +DEu u uF )$GuH &tIuJ #DKuL $TMuN )$OuP $TQuR 'SuT (UuV "4WuX YuZ &t[u\ (]u^ 1$_u`  aub +Ecud *:euf +Dgu u uh &tiuj #Dkul *4mun $Uoup tqur "4sut *5uuv +Ewux #Eyuz t{u| #D}u~  u@ %eAuB /CuD +DEuF GuH !$Iu u uJ +EKuL  MuN dOuP $TQuR +DSuT !$UuV "4WuX tYuZ #D[u\ d]u^ !$_u` "5aub ucud #Deuf #Dguh  iuj !$ku u ul *4mun %eoup )%qur )$sut tuuv twux yuz T{u| t}u~ "4u@ #EAuB %eCuD &uEuF 'GuH $UIuJ  KuL !$Mu uN *.*/#'$(,1 $$(#"!%#'  iu u uD>
|  }D>
\ ]D>
^ ~0 -8F ? #	  0 _D>
B  M+QM(!M (M /	M
 'M ,UM )%M 1!M /M 7M 4QM <QM (M 0M A!M  4R!M" -b#M M$ /%M& 21'M( 3B)M* /+M, .q-M. .q/M0 -a1M2 ;E3M4 /5M6 .q7M8 6q9M: -a;M< -a=M> 1!?M@ CBAMB &qCMD ,QEM M MF 0GMH :2IMJ >rKML ,QMMN 0OMP 7QMR /SMT 7UMV ?WMX 21YMZ 7[M^ H_M` DQaMb A!cMf GgMh HiMj HkM M Ml ?mMn (oMr 'sMt %euMv &qwMx -eyMz 3A{M| 9!}M~ =aM@ .uAMB ?CMD ?EMF ?GMJ 3EKMN :1OMP 8QMR 3ASM MT CDCDCDYM M MObJ,aJ 8J )!	J
 #BJ %bJ %aJ ,QJ %eJ .uJ .uJ 6uJ &uJ  &u!J" /#J$ /%J& 7'J( &u)J J* .s+J, .q-J. +A/J0 4Q1J2 4Q3J4 ;B5J6 5b7J8 >r9J: 8;J< 3A=J@ +EAJB )%CJD 4UEJF 0GJH /IJJ &uKJL 21MJ J JN 0OJP 0QJR 3ESJT 8UJV 3EWJX 6uYJZ 0[J\ 21]J` *1aJb ,QcJd 4SeJf 8gJh (iJj 0kJl )!mJn +AoJp 1!qJ J Jr 0sJt 7uJv +AwJx ,QyJz 3A{J| 0}J~ 1!J@ -aAJB DQCJD 7EJF 7GJH 8IJJ 6qKJL 8MJN 21OJP )!QJR 1!SJ J JT -aUJX 0YJZ 6v[J\ 4V]J^ <Q_J` 1%aJb DUcJd 8eJf =agJj >qkJl >qmJn >qoJp 5aqJr 4QsJt 3AuJv 4QwJx @yJ J Jz @{J| 6q}J~ >qJ@ 7AJB :1CJD CAEJF CAGJH CAIJJ :1KJN 25OJP :5QJR 6vSJT =fUJV >vWJZ ;E[J\ KE]J` ;AaJ J Jb ;AcJd 21eJf =agJh ;AiJj HkJl 4QmJn :1oJp ;AqJr ;AsJv )"wJx 4RyJz 6r{J| Ee}J~ EaJ@ HAJB 1#CJD 6sEJ JF 23237:/04534SJ J JVz(!z )!z 0	z
 .rz ,Rz 8z (z )#z +Cz +Cz 22z 0z %az  ,Q!z" +A#z$ +A%z( &u)z z* -f+z, -e-z. 4V/z0 ,U1z2 3G3z4 /5z6 .v7z8 +A9z: -a;z< ,Q=z> 5a?z@ -bAzB 0CzD ,QEzF 1"GzJ )"KzL +EMz z zN 5aOzP 25QzR 4RSzT 7UzV .qWzX 21Yz\ 4Q]z^ /_z` :1azb -aczd 4Qezf <Qgzh /izj 3Bkzl 3Bmzn 6qozp 21qz z zr 0szt 4Quzv ,Qwzx -cyz| 9"}z~ 4Rz@ <RAzB A!CzF 5aGzH ;AIzJ :1KzL 9!MzN =aOzP @QzR :1SzT A!UzV 9!Wz z zX 9!YzZ :1[z\ 7]z^ <Q_z` ;Aazb 6qczd <Qezf ;Agzh 6qizj =akzl :1mzn @ozp ?qzt ;Euzv ;Ewzx 8yzz 6q{z z z| 6q}z@ <QAzB :1CzF 1!GzH 8IzJ 6qKzL :1MzN :1OzP 8QzR 9!SzV 6tWzX 6qYzZ 6t[z\ =a]z^ =a_z` 9!azb <Qcz zd <@FGMR7<1313:>7<sz z zYG GcY YCD>
v !..x88!..x88 
 "..x88!..x88 
 "..x88!..x88 
 "..y99!..y99  wD>
Z " $ $[D>
d U U 	U
 ZU ]U ZU ^U 1U ZU -U 0U -U ]U .U  ]!U" 1#U$ Z%U& ]'U U( ])U* ]+U, ]-U. ]/U0 ]1U2 ]3U4 ]5U6 ]7U8 Z9U: ];U< 1=U> -?U@ ]AUB ZCUD ]EUF ]GUJ ]KU U UL 0MUN \OUP 0QUR 0SUT 0UUV 0WUX 0YUZ ][U\ ]]U^ -_U` 0aUb 0cUd 0eUf 0gUh ZiUl ZmUn YoU U Up YqUr ZsUt \uUv \wUx \yUz \{U| .}U~ -U@ .AUB \CUD YEUF YGUH YIUJ \KUL ]MUN ]OUP ]QU U UR \SUT 0UUV 0WUX ]YUZ -[U\ ]]U^ Y_U` 0aUb 0cUd 0eUf 0gUh \iUj \kUl \mUn \oUp \qUr \sU U Ut \uUv \wUx \yUz \{U| \}U~ \U@ \AUB \CUD \EUF \GUH \IUJ \KUL \MUN \OUP \QUR \SUT \UU U UV \WUX \YUZ \[U\ Z]U^ \_U` .aUb \cUd \eUf \gUh \iUj .kUl \mUn \oUp \qUr \sUt \uUv \wU U Ux .yUz \{U| \}U~ YU@ .AUB \CUD \EUF \GUH \IUJ \KUL \MUN \OUP \QUR ZSUT ZUUV \WUX \YU U UZ \[U\ \]U^ \_U` \aUb \cUd \eUf \gUh \iUj \kUl \mUn \oUp \qUr \sUt \uUv \wUx \yUz \{U U U| \}U~ \U@ \AUB \CUD \EUF \GUH \IUJ \KUL \MUN \OUP \QUR \SUT \UUV \WUX \YUZ \[U\ \]U U U^ \_U` \aUb \cUd \eUf \gUh \iUj ZkUl ZmUn \oUp \qUr \sUt \uUv \wUx ]yUz ]{U| ]}U~ \U U U@ \AUB ]CUD ]EUF ZGUH ]IUJ ]KUL ]MUN ]OUP ]QUR .SUT ]UUV ]WUX ]YUZ ][U\ ]]U^ ]_U` ]aU U Ub ]cUd ]eUf ]gUh 0iUj 0kUl 0mUn ]oUp .qUt ]uUx ]yUz ]{U~ \U@ \AUB \CUD \EUF \GUH \IU U UJ \KUL \MUP ]QUR 0SUT -UUV ]WUX -YUZ ][U\ ]]U^ ]_U` ]aUb -cUd .eUf ]gUh ]iUj ]kUl ]mU U Un ]oUp ]qUr ]sUt ]uUv ]wUx ]yUz ]{U| ]}U~ ]U@ ]AUB ZCUD ZEUF ZGUH ZIUJ ]KUL ]MUN ]OU U UP ^QUR -SUT ]UUV ]WUX ^YUZ ][U\ ]]U^ ]_U` ]aUb ]cUd 0eUf ZgUh ZiUj ZkUl ZmUn ZoUp .qU U Ur ]sUt .uUx ]yUz ]{U| ]}U~ ]U@	 ]A	UB	 .C	UD	 ]E	UF	 ]G	UH	 ]I	UJ	 ]K	UL	 .M	UN	 ]O	UP	 \Q	UR	 .S	UT	 .U	U U UV	 ZW	UX	 -Y	UZ	 -[	U\	 ]]	U^	 ]_	U`	 ]a	Ub	 ]c	Ud	 ]e	Uf	 ]g	Uh	 ]i	Uj	 ]k	Ul	 ]m	Un	 ]o	Up	 ]q	Ur	 ]s	Ut	 -u	Uv	 Zw	U U Ux	 ]y	U|	 0}	U~	 0	U@
 0A
UB
 0C
UD
 0E
UF
 \G
UH
 0I
UJ
 0K
UL
 0M
UN
 0O
UP
 0Q
UR
 ZS
UT
 ZU
UV
 .W
UX
 \Y
UZ
 1[
U U\
 (''*'''i
U U Un
 .B$8 o
[ [eD>
\ +]D>
b YcD>
dLuL 'L "" #$ $L  l9l[l Ul W	l
 Wl Xl 7l Jl 5l 7l nl ]l 0l 5l  )!l" G#l$ =%l l& <'l( 7)l* 9+l, H-l. F/l0 61l2 83l4 H5l6 K7l8 89l: :;l< J=l> 5?l@ HAlB 5ClD -ElF MGl l lH 8IlJ :KlL FMlN 8OlP 9QlR HSlT 8UlV 9WlX 6YlZ 9[l\ F]l^ G_l` 8alb 5cld Helf 8glh 6il l lj :kll Wmln Folp 8qlr Jslt Kulv Fwlx Fylz 9{l| 1}l~ Fl@ WAlB 5ClD :ElF 
GlH 8IlJ :Kl l lL YMlN ;OlP 8QlR )SlT 8UlV :WlX +YlZ 7[l\ 5]l^ W_l` Jalb Wcld 5elf 7glh 9ilj hkl lLj + """"""""	# 	#-kLB CLJ !:#KLP <QLR 4USLT  D D DULV vWL^ 6 _Lf 4gLl "<$mLr A!sLx &<(yL~ $<&LJ !%	  $(#'+# # #  ## "#" "	# 	# ##! !
 #&"'(&"&"(&! ! /WL L L^ !! !!D>
 D>
 D>
 D D D	    N
methodNamemarketreturnc                     |                      |d          }|                     |d          }|                      |d          }||||d<   t          t          |                               ||||          S )NinstTypetype)safe_stringomitr  r:   handle_market_type_and_params)r  r  r  paramsdefaultValuer  r  r  s          r  r  z!okx.handle_market_type_and_paramso  sy    ##FJ776:..//Lx3%F6NS$==j&RXZfgggr  c                 h    |                      | j        di           }|                     |||          S )Nr  )	safe_dictr	  r  )r  r  exchangeTypess      r  convert_to_instrument_typezokx.convert_to_instrument_typew  s1    t|^RHHtT:::r  symbolc                 0   d}|                     d          }|                     d          }d }|                    d          dk    r|                     |d          }n|                     |d          }|}|                     |d          }|                     |d          }|                     |d          }	|                     |          }
|                     |
          }i d	|dz   |z   dz   |z   dz   |z   dz   |	z   d
|dz   |z   dz   |z   dz   |z   dz   |z   dz   |	z   d|d|d|d|d|d|dddddd dd ddddddddddd|                     d          ||
|	dk    rdnd |                     |          d d d!d d d"d d d"d d d"d#d d$	S )%NUSD-/r   r   r   r   r<   r"  :basequotesettlebaseIdquoteIdsettleIdactiveFr  rM   linearinverserI   rK   rL   TrJ   r   Ccallputamountpriceminmax)r6  r7  cost)	contractcontractSizeexpiryexpiryDatetime
optionTypestrike	precisionlimitsinfo)splitfindr  convert_expire_date	parse8601r  )r  r"  r*  optionParts
symbolBaser)  r+  r>  rA  r@  datetime	timestamps               r  create_expired_option_marketz okx.create_expired_option_market{  s   ll3''\\#&&
;;sb  ##J22DD##K33D!!+q11!!+q11%%k155
++F33NN8,,	+
$*u$s*V3c9FBSH:U+
dSj5(3.7#=FLvUX[[^hh+
 D+
 U	+

 f+
 d+
 u+
 +
 e+
 H+
 d+
 t+
 E+
 E+
 e+
  d!+
" e#+
$  --c22&%/3%6%6&&U''//    
   
     U+
 +
 +
 +	
r  marketId	delimiter
marketTypec                    |d uo1|                     d          dk    p|                     d          dk    }|r|| j        vr|                     |          S t          t          |                               ||||          S )Nz-Cr'  z-P)rF  markets_by_idrM  r  r:   safe_market)r  rN  r  rO  rP  isOptionr  s         r  rS  zokx.safe_market  s    D(hd0C0Cb0H/ghmm\`NaNadfNf 	?X);;;44X>>>S$++HfiTTTr  c                   K   |                      |           d{V }|                     |dg           }t          |          }d|dk    rdnddd|d}t          dt          |                    D ]}||         }|                     |d          }|                     |d          |d	<   |                     |d
          |d<   |dk    rd|d<   ^|dk    rd|d<   j|dk    rd|d<   v|dk    rd|d<   |S )aO  
        the latest known information on the availability of the exchange API
        :see: https://www.okx.com/docs-v5/en/#status-get-status
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        Ndatar   okmaintenance)updatedstatusetar   rD  stateendr[  hrefr   ongoingrZ  	scheduled	completedcanceled)publicGetSystemStatus	safe_listlenranger  safe_integer)	r  r  responserV  
dataLengthupdateieventr\  s	            r  fetch_statuszokx.fetch_status  sJ      33F;;;;;;;;* ~~h33YY
)Qdd]
 
 q#d))$$ 	( 	(AGE$$UG44E --eU;;F5M ,,UF;;F5M	!!#0x  +%%#'x  +%%#'x  *$$#'x r  c                    K   |                      |           d{V }|                     |dg           }|                     |di           }|                     |d          S )ae  
        fetches the current integer timestamp in milliseconds from the exchange server
        :see: https://www.okx.com/docs-v5/en/#public-data-rest-api-get-system-time
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        NrV  r   ts)publicGetPublicTimerd  r  rg  )r  r  rh  rV  firsts        r  
fetch_timezokx.fetch_time  so       11&99999999 ~~h33tQ++  ---r  c           	      P  K   |                      |           d{V }|                     |dg           }g }t          dt          |                    D ]Q}||         }|                     |d          }|                     |d          }|                    ||d|dd           R|S )a  
        fetch all the accounts associated with a profile
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-account-configuration
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
        NrV  r   uidacctLv)r<   r  currencyrD  code)privateGetAccountConfigrd  rf  re  r  append)	r  r  rh  rV  resultrk  account	accountIdr  s	            r  fetch_accountszokx.fetch_accounts  s       55f========( ~~h33q#d))$$ 
	 
	A1gG((%88I##GX66DMM       r  c                   K   |                      | j        dg           }g }g }t          dt          |                    D ]1}|                    |                     ||         |                     2t          j        |  d{V }t          dt          |                    D ]}|                     |||                   }|S )a%  
        retrieves data on all markets for okx
        :see: https://www.okx.com/docs-v5/en/#rest-api-public-data-get-instruments
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r   r   N)	rd  r	  rf  re  ry  fetch_markets_by_typeasynciogatherarray_concat)r  r  typespromisesrz  rk  s         r  fetch_marketszokx.fetch_markets2  s       t|^R@@q#e**%% 	J 	JAOOD66uQxHHIIII 2222222q#h--(( 	< 	<A&&vx{;;FFr  c                    |                      |d          }|                     |d          }|dk    rd}|dk    }|dk    }|dk    }|dk    }|p|p|}|                      |d          }	|                      |d	          }
|                      |d
          }|                     |          }|                      |d          }|C|sA|                    d          }|                      |d          }	|                      |d          }
|                     |	          }|                     |
          }|dz   |z   }d }d }d }|r|dz   |z   }|                     |d          }|r|                     |          }|dz   |z   }na|r_|                      |d          }|                      |d          }|                     |          }|dz   |z   dz   |z   dz   |z   }|dk    rdnd}|                      |d          }|                     | j        |di           }|                      |dd          }t          j	        |d          }| 
                    |d          }|                     |i d|d|d|d|d |d!|	d"|
d#|d$|d|d%|ot          j        |d          d|d|d|d&d'd(|d)|r|
|k    nd |r|	|k    nd |r| 
                    |d*          nd ||                     |          |||                     |d+          | 
                    |d,          |                     |          d-|                     d          |                     |          d.| 
                    |d/          d d.d d d.d |rd n|d.d0|d1
          S )2NinstIdr  r  rL   rI   rK   rM   baseCcyquoteCcy	settleCcyulyr%  r   r   r&  r(  expTimestkoptTypePr4  r3  tickSzr   leverr   maxMktSzr<   r"  r)  r*  r+  r,  r-  r.  r  rJ   r/  Tr<  r0  ctVallistTimelotSzr5  r8  minSz)leverager6  r7  r;  )
r1  r=  r>  r?  rA  r@  createdrB  rC  rD  )r  safe_string_lowersafe_currency_coderE  rg  yymmddsafe_dict_2r   r8   
string_maxsafe_numberextend	string_gtiso8601r  )r  r  r<   r  rI   rL   rK   rM   r<  r,  r-  r.  r+  
underlyingpartsr)  r*  r"  r>  strikePricer@  ymdtickSizer   maxLeveragemaxSpotCosts                             r  parse_marketzokx.parse_marketC  s   d fh//%%fj999D("("+6+V!!&)44""6:66##FK88((22%%fe44
"D"$$S))E%%eQ//F&&ua00G&&v..''00e#
 	Fc\F*F&&vy99F Fkk&))#+ F"..vu==!--fi@@
kk&))#+c1K?#E
R'1S'8'8UUv
##FH55	4B??&&vw<<(c::&&vz::{{4 0"
"0"
f0"
 D0"
 U	0"

 f0"
 f0"
 w0"
 0"
 D0"
 D0"
 dD 1+s C C0"
 D0"
 f0"
 f0"
 d0"
  !0"
" xAw(**T#0"
$ 08A(**TAISD,,VW===t"ll622!$((<<**67;;**844   ,,S11,,[99 
  ++FG<< 
   
  #+<44  $ _0"
 0"
 0"
 0 0 0	r  c           	      (  K   d|                      |          i}|dk    r|                     | j        dddg          }g }t          dt	          |                    D ]K}||         }||d<   |                    |                     |                     ||                               Lt          j	        |  d {V }g }	t          dt	          |                    D ]F}| 
                    ||i           }
|                     |
dg           }|                     |	|          }	G|                     |	          S |                     |                     ||                     d {V }|                     |dg           }|                     |          S )	Nr  rM   defaultUnderlyingBTC-USDzETH-USDr   r  rV  )r!  rd  r	  rf  re  ry  publicGetPublicInstrumentsr  r  r  r  r  parse_markets)r  r  r  requestoptionsUnderlyingr  rk  r  promisesResultmarketsresr	  rh  dataResponses                 r  r  zokx.fetch_markets_by_type  s     77==
 8 $t|=PS\^gRh i iH1c"34455 _ _.q1
!+ ? ?GU[@\@\ ] ]^^^^#*>8#<<<<<<<NG1c.1122 > >nn^Q;;..fb99++GW==%%g...88Wf9U9UVVVVVVVVD ~~h;;!!,///r  c                 <    dddd}|                      |||          S )NrO  OMNIrP  )rT  OmniTRONr  )r  	networkIdnetworksByIds      r  safe_networkzokx.safe_network  s1    
 

 iCCCr  c                   K   |                      | j        dd          }|                     d          r|rdS |                     |           d{V }|                     |dg           }i }|                     |d          }t          |                                          }t          dt          |                    D ]6}||         }	| 
                    |	          }
|
d         }||	         }i }d}d}d}d}t          dt          |                    D ]}||         }|                      |d          }|r|n|}|                      |d	          }|r|n|}|                      |d
          }|r|r|rdnd}|r|n|}|                     |d          }||                    d          dk    r|                    d          }|                     |d|          }|                     ||
d                   }|                     |                     |d                    }||}nt!          j        ||          }||||||                     |d          |                     |          d|                     |d          |                     |d          di|d	||<   |                     |di           }d||	|                     |d          |||d|                     |          ddddi|d||<   8|S )a#  
        fetches all available currencies on an exchange
        :see: https://www.okx.com/docs-v5/en/#rest-api-funding-get-currencies
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        rK  FNrV  ccyr   rw  canDepcanWdcanInternalTchainr%  r   wdTickSzminFeer   minWdmaxWdr8  )	r<   networkr/  depositr   feerB  rC  rD  r=   r6  )rD  rw  r<   r=   r/  r  r   r  rB  rC  rS  )	safe_boolr	  check_required_credentialsprivateGetAssetCurrenciesrd  group_bylistkeysrf  re  safe_currencyr  rF  rE  network_id_to_codeparse_precisionr8   
string_minr  r  r  )r  r  isSandboxModerh  rV  rz  dataByCurrencyIdcurrencyIdsrk  
currencyIdrv  rw  chainsrS  currencyActivedepositEnabledwithdrawEnabledmaxPrecisionjr  
canDepositcanWithdrawr  r/  r  r  	chainPartnetworkCoderB  
firstChains                                 r  fetch_currencieszokx.fetch_currencies  s~      t|]EJJ..u55 	 	4 77????????X ~~h33==u55+002233q#k**++ ?	 ?	A$QJ))*55HF#D%j1FH"N"N#OL1c&kk** " "q	!^^E8<<
0:!O"nnUG<<2="S++O"nnUMBB",XXXSX,2!G ,,UG<<	)	s0C0Cq0H0H%OOC00E $ 0 09 E EI"&"9"9)XfEU"V"VK $ 4 4T5E5EeZ5X5X Y YI#+'0'.'9,	'R'R'#."(#-$/#//x@@%)%6%6y%A%A&'+'7'7w'G'G'+'7'7w'G'G) )# !&- -H[)  266J ((V<<()+!..|<<##  %! F4LL$ r  limitc                 p  K   |                                   d{V  |                     |          }d|d         i}d}|                     |ddd          \  }}|dk    r|d}|d	n|}|||d
<   d}|dk    s|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }|                     |di           }	|                     |	d          }
| 	                    |	||
          S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-order-book
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: 'publicGetMarketBooksFull' or 'publicGetMarketBooks' default is 'publicGetMarketBooks'
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr  r<   r   r  publicGetMarketBookspublicGetMarketBooksFulli  r   szi  rV  r   ro  )
load_marketsr  handle_option_and_paramsr  r  r  rd  r  rg  parse_order_book)r  r"  r  r  r  r  r  rh  rV  rq  rL  s              r  fetch_order_bookzokx.fetch_order_book  s      !!!!!!!!!V$$fTl
 66v?OQY[qrr///EMEE!GDM000eckk!::4;;wPV;W;WXXXXXXXXHH!66t{{7F7S7STTTTTTTTH, ~~h33tQ++%%eT22	$$UFI>>>r  c                 :   |                      |d          }|                     |d          }|                     ||d          }|d         }|                     |d          }|                     |d          }|                     |dd          }|r|                     |d	          nd }	|                     |d
          }
|                     |d          }|                     |d          }|                     i d|d|d|                     |          d|d|d|                     |d          d|                     |d          d|                     |d          d|                     |d          dd d|d|d|dd dd dd dd |
|	|d |          S )!Nro  r  r%  r"  lastopen24hrI   F	volCcy24hvol24hhigh24hlow24hrL  rK  highlowbidbidPx	bidVolumebidSzaskaskPx	askVolumeaskSzvwapopenclosepreviousClosechange
percentageaverage)
baseVolumequoteVolumerD  )rg  r  rS  r  safe_tickerr  )r  tickerr  rL  rN  r"  r  r  rI   r  r  r  r  s                r  parse_tickerzokx.parse_ticker  s<   * %%fd33	##FH55!!(FC88!//	22~~ffe44?CMd&&v{;;;%%fh77
	22vx00 !
f!
!
 Y//!
 D	!

 3!
 4##FG44!
 ))&'::!
 4##FG44!
 ))&'::!
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ %&)!
 !
 !
* +  	r  c                 ^  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     ||          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-ticker
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr  r<   rV  r   )r  r  publicGetMarketTickerr  rd  r  r	  r  r"  r  r  r  rh  rV  rq  s           r  fetch_tickerzokx.fetch_ticker   s       !!!!!!!!!V$$fTl
 33DKK4P4PQQQQQQQQ6 ~~h33tQ++  ///r  symbolsc                 \  K   |                                   d{V  |                     |          }|                     |          }d}|                     d||          \  }}d|                     |          i}|dk    rR|                     | j        dd          }|                     |dd|          }|t          | j	        d	z             ||d<   | 
                    |                     ||                     d{V }|                     |d
g           }	|                     |	|          S )a'  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-tickers
        :param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr   r  rM   r  r  r  rN  zT fetchTickers() requires an underlying uly or marketId parameter for options marketsrV  )r  market_symbolsget_market_from_symbolsr  r!  r  r	  safe_string_2r'   r<   publicGetMarketTickersr  rd  parse_tickers)
r  r  r  r  rP  r  r  r  rh  tickerss
             r  fetch_tickerszokx.fetch_tickers,  sf      !!!!!!!!!%%g..--g66
!??PVX^__
F77
CC
 !! $ 0 0?RT] ^ ^++FE:GXYYJ!'  3I  )I  J  J  J!+44T[[&5Q5QRRRRRRRR6 ..6266!!'7333r  c                    |                      |d          }|                      |d          }|                     ||d          }|d         }|                     |d          }|                     |dd          }|                     |dd	          }|                      |d
          }	|                      |d          }
|                      |d          }d }|Dt	          j        |          }|                      |d          }|                     |          }||d}|                      |d          }|dk    rd}n|dk    rd}|                     |||                     |          |||
d ||	||d |d|          S )NtradeIdr  r%  r"  ro  fillPxpxfillSzr  sideordIdr  feeCcyr;  rv  execTypeTr   Mr   )rD  rL  rK  r"  r<   orderr  takerOrMakerr  r7  r6  r;  r  )	r  rS  rg  r  r8   
string_negr  
safe_trader  )r  trader  r<   rN  r"  rL  r7  r6  r  orderIdfeeCostStringr  feeCostSignedfeeCurrencyIdfeeCurrencyCoder$  s                    r  parse_tradezokx.parse_tradea  s   d eY//##E844!!(FC88!%%eT22	""5(D99##E8T::v..""5'22((66$#.}==M ,,UH==M"55mDDO%+ C ''z::3"LLS  "L"Y//( 
  
   	r  sincec                   K   |                                   d{V  d}|                     |dd          \  }}|r#|                     d||||dddd	  	         d{V S |                     |          }d|d	         i}d}|d
         r0|                     |                     ||                     d{V }n|||d<   d}	|                     |ddd          \  }	}|	dk    r0|                     |                     ||                     d{V }n5|	dk    r/|                     |                     ||                     d{V }|                     |dg           }
| 	                    |
|||          S )a6  
        get the list of most recent trades for a particular symbol
        :see: https://www.okx.com/docs-v5/en/#rest-api-market-data-get-trades
        :see: https://www.okx.com/docs-v5/en/#rest-api-public-data-get-option-trades
        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: *only applies to publicGetMarketHistoryTrades* default False, when True will automatically paginate by calling self endpoint multiple times
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        NFr   paginater  afterr   r  r<   rM   r  r  publicGetMarketTradespublicGetMarketHistoryTradesrV  )
r  r  fetch_paginated_call_cursorr  publicGetPublicOptionTradesr  r2  r3  rd  parse_trades)r  r"  r.  r  r  r0  r  r  rh  r  rV  s              r  fetch_tradeszokx.fetch_trades  s      !!!!!!!!!88PZ[[& 	F99-QVX]_egpry{  BE  F  F  F  F  F  F  F  F  FV$$fTl
 ( 
	a!==dkk'SY>Z>Z[[[[[[[[HH #( F!::6=RZ\sttNFF000!%!;!;DKKQW<X<X!Y!YYYYYYY999!%!B!B4;;wX^C_C_!`!```````F ~~h33  vue<<<r  c           	      T   |                      d|d           }|d         }|dk    rdnd}|                     |d          |                     |d          |                     |d          |                     |d          |                     |d	          |                     ||          gS )
Nr   r   rI   r      r   r   r   r   )r  rg  r  )r  ohlcvr  r  r  volumeIndexs         r  parse_ohlcvzokx.parse_ohlcv  s     00vtLL1v FNNaaeQ''UA&&UA&&UA&&UA&&UK00
 	
r  r   c           	        K   |                                   d{V  |                     |          }d}|                     |dd          \  }}|r!|                     d|||||d           d{V S |                     |d          }|                     |d          }|                     | j        di           }	|                     |	dd          }
|d	}|                     |          }|                     | j	        ||          }|
dk    r|d
k    r||

                                z  }|d         ||d}d}|]|                                 }|dz  }|d|z  z
  }||k     rd}t          |dz
  d          }||d<   |                     |||z            |d<   |                     |d          }|||d<   |                     |d          }|                     |	d|          }|                     |d|          }|                     |d          }|dk    }d}|dk    rc|r1|                     |                     ||                     d{V }n
|                     |                     ||                     d{V }n|dk    rs|d         d         |d<   |r0|                     |                     ||                     d{V }n|                     |                     ||                     d{V }na|r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }|                     |||||          S )a"  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://www.okx.com/docs-v5/en/#rest-api-market-data-get-candlesticks
        :see: https://www.okx.com/docs-v5/en/#rest-api-market-data-get-candlesticks-history
        :see: https://www.okx.com/docs-v5/en/#rest-api-market-data-get-mark-price-candlesticks
        :see: https://www.okx.com/docs-v5/en/#rest-api-market-data-get-mark-price-candlesticks-history
        :see: https://www.okx.com/docs-v5/en/#rest-api-market-data-get-index-candlesticks
        :see: https://www.okx.com/docs-v5/en/#rest-api-market-data-get-index-candlesticks-history
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.price]: "mark" or "index" for mark price and index price candles
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        NFr   r0     r7  r  r  r   i`T  r<   )r  barr  Candlesi  i  HistoryCandlesr   r   beforer1  untilr  markindexrD  
instFamilyr  rV  )r  r  r  "fetch_paginated_call_deterministicr  r  r  r	  parse_timeframer   lowermillisecondsr:  sumrg  &publicGetMarketHistoryMarkPriceCandlesr  publicGetMarketMarkPriceCandles"publicGetMarketHistoryIndexCandlespublicGetMarketIndexCandlespublicGetMarketHistoryCandlespublicGetMarketCandlesrd  parse_ohlcvs)r  r"  	timeframer.  r  r  r  r0  r7  r	  r  durationr?  r  r  nowdurationInMillisecondshistoryBorder	startTimerC  r  isHistoryCandlesrh  rV  s                           r  fetch_ohlcvzokx.fetch_ohlcv  s4     & !!!!!!!!!V$$88zZZ& 	}@@vW\^cenpvx{|||||||||  1167++..|R@@##GZ??=E''	22t	9EEH$5$58>>###CTl
 

  ##%%C%-_"H0F#FGM}$$.EAIq))I )GH#xx/E/MNNGG!!&'22$GGYYvw//F&&wDD<<66** $44F?? d!%!L!LT[[Y`bhMiMi!j!jjjjjjj!%!E!EdkkRY[aFbFb!c!cccccccg &v| <GH `!%!H!HU\^dIeIe!f!fffffff!%!A!A$++gW]B^B^!_!_______ [!%!C!CDKKPWY_D`D`!a!aaaaaaa!%!<!<T[[RX=Y=Y!Z!ZZZZZZZ ~~h33  vy%GGGr  c           
        K   |t          | j        dz             |                                  d{V  d}|                     |dd          \  }}|r!|                     d|||d|d           d{V S |                     |          }d|d	         i}|t          |d
z
  d          |d<   |||d<   |                     |                     ||                     d{V }g }	| 	                    |dg           }
t          dt          |
                    D ]}|
|         }|                     |d          }|	                    ||                     |                     |d                    |                     |d          ||                     |          d           |                     |	d          }|                     ||d         ||          S )a  
        fetches historical funding rate prices
        :see: https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate-history
        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentFr~   r0  r  r   r  r<   r   r   rB  r  rV  fundingTimerealizedRate)rD  r"  fundingRaterL  rK  rL  r"  )r'   r<   r  r  rG  r  r:  !publicGetPublicFundingRateHistoryr  rd  rf  re  rg  ry  safe_symbolr  r  r  sort_byfilter_by_symbol_since_limit)r  r"  r.  r  r  r0  r  r  rh  ratesrV  rk  raterL  sorteds                  r  fetch_funding_rate_historyzokx.fetch_funding_rate_historyu  sL      >#DG.e$efff!!!!!!!!!88AZ\fgg& 	E@@AZ\bdikprvx~  AD  E  E  E  E  E  E  E  E  EV$$fTl
  #EAIq 1 1GH$GG??GU[@\@\]]]]]]]]. ~~h33q#d))$$ 		 		A7D))$>>ILL**4+;+;D(+K+KLL#//nEE& LL33      e[11009I5RWXXXr  c                 b    |dk    r|                      |          S |                     |          S )Nr  )parse_funding_balanceparse_trading_balance)r  r  rh  s      r  parse_balance_by_typezokx.parse_balance_by_type  s5    9--h777--h777r  c                    d|i}|                      |dg           }|                     |di           }|                     |d          }|                      |dg           }t          dt	          |                    D ]}||         }|                     |d          }	|                     |	          }
|                                 }|                     |d          }|                     |d          }||3|                     |d	          |d
<   |                     |d          |d<   n
||d<   ||d
<   |||
<   ||d<   |                     |          |d<   | 	                    |          S )NrD  rV  r   uTimedetailsr  eqavailEqavailBalfree	frozenBalusedtotalrL  rK  )
rd  r  rg  rf  re  r  r  r{  r  safe_balance)r  rh  rz  rV  rq  rL  rm  rk  balancer  rw  r{  rn  ro  s                 r  ri  zokx.parse_trading_balance  sv   (#~~h33tQ++%%eW55	..	266q#g,,'' 	# 	#AajG))'599J**:66DllnnG!!'400B&&w	::G
"&"2"27J"G"G"&"2"27K"H"H#% ")"F4LL'{!\\)44z  (((r  c                    d|i}|                      |dg           }t          dt          |                    D ]}||         }|                     |d          }|                     |          }|                                 }|                     |d          |d<   |                     |d          |d<   |                     |d	          |d
<   |||<   |                     |          S )NrD  rV  r   r  balrt  rp  rq  rr  rs  )rd  rf  re  r  r  r{  ru  )	r  rh  rz  rV  rk  rv  r  rw  r{  s	            r  rh  zokx.parse_funding_balance  s    (#~~h33q#d))$$ 		# 		#A1gG))'599J**:66DllnnG#//??GG"..w
CCGFO"..wDDGFO"F4LL  (((r  c                 $   ||                      d |          |                     t          j        |                     |dd                              |                     t          j        |                     |dd                              d d dS )Nr   makerUr   takerU)rD  r"  r   r   r  	tierBased)r`  r  r8   r%  r  )r  r  r  s      r  parse_trading_feezokx.parse_trading_fee  s     &&tV44&&w'9$:L:LSRY[c:d:d'e'eff&&w'9$:L:LSRY[c:d:d'e'eff
 
 	
r  c                 :  K   |                                   d{V  |                     |          }d|                     |d                   i}|d         r|d         |d<   nG|d         s|d         s|d	         r|d
         dz   |d         z   |d<   nt          | j        dz             |                     |                     ||                     d{V }|                     |dg           }|                     |di           }| 	                    ||          S )ae  
        fetch the trading fees for a market
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-fee-rates
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        Nr  r  rI   r<   r  rK   rL   rM   r,  r%  r-  r  zE fetchTradingFee() supports spot, swap, future or option markets onlyrV  r   )
r  r  r!  r0   r<   privateGetAccountTradeFeer  rd  r  r}  r  s           r  fetch_trading_feezokx.fetch_trading_fee  sL      !!!!!!!!!V$$77vGG
 &> 	r &tGHF^ 	rvh/ 	r6(3C 	r#H-3fY6GGGENNtw)ppqqq77GV8T8TUUUUUUUU& ~~h33tQ++%%eV444r  c                 l  K   |                                   d{V  |                     dd|          \  }}i }d}|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     ||          S )a  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-balance
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-balance
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nrf   r  )r  r  privateGetAssetBalancesr  privateGetAccountBalancerj  )r  r  rP  queryr  rh  s         r  fetch_balancezokx.fetch_balance(	  s       !!!!!!!!! >>~tU[\\
E
 ""!99$++gu:U:UVVVVVVVVHH!::4;;wPU;V;VWWWWWWWWHN ))*h???r  r;  c                    K   |                                   d{V  |                     |          }|d         st          | j        dz             d|d<   d|d<   |                     |dd	|d|           d{V S )
  
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order
        create a market buy order by providing the symbol and cost
        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrI   z: createMarketBuyOrderWithCost() supports spot markets onlyFr  	quote_ccytgtCcyr  buyr  r  r0   r<   create_orderr  r"  r;  r  r  s        r  !create_market_buy_order_with_costz%okx.create_market_buy_order_with_cost	  s       !!!!!!!!!V$$f~ 	gtw)eefff6;23&x&&vxdFSSSSSSSSSr  c                    K   |                                   d{V  |                     |          }|d         st          | j        dz             d|d<   d|d<   |                     |dd	|d|           d{V S )
r  NrI   z; createMarketSellOrderWithCost() supports spot markets onlyFr  r  r  r  sellr  r  s        r  "create_market_sell_order_with_costz&okx.create_market_sell_order_with_cost	  s       !!!!!!!!!V$$f~ 	htw)ffggg6;23&x&&vxtVTTTTTTTTTr  r  r  r6  r7  c                    |                      |          }|d         |||                     ||          d}|d         }	|d         }
|                     |g d          }|                     |dd          }|                     |dd	          }|                     |d
|          }|                     |dd          }|                     |dd          }|                     |d|          }|                     |dd          }|                     |dd          }|                     |d          }|d u}|                     |d          }|d u}|                     |dd          }|d u}|                     | j        ddd          }|                     |dd          }d}|	|dk    rd}n|}|                     |dd          }|	rS|rE|dk    r|d          n|d!         }|                     |d"|          }| 	                    |          |d"<   |r|nd}||d<   n:|
r8|d#         s|d$         r#d } | 
                    |d%d&          \  } }| | |d'<   ||d<   |d(k    }!d}"|                     |!|d)k    |          \  }"}|                     |g d*          }|d+k    p|d,k    }#|d-k    p|d.k    }$|d up|d/k    }%|d up	|d up|d0k    }&|!r|#p|d1k    }'|                     | j        d2d3          }(|                     |d2|(          })|
s|s|)|d2<   |!s|'rd(|d4<   |	r|dk    r|)d5k    rd}*| 
                    |d%d6d          \  }*}|                     |d7d8          }+|                     |d7d8g          }|*rs|W|+T|                     |          },|                     |          }-t          j        |,|-          }.|                     |.          }+n |+t%          | j        d9z             n|+|n|+}+|                     ||+          |d8<   |'r|
rd1|d4<   n|%s|&s|                     ||          |d:<   |"rd)|d4<   n|#r|'sd,|d4<   n|$rd.|d4<   |r!t          j        |d;          }/|/|d<   d<|d4<   n{|s|r|rK|                     |g d=          }0|0t%          | j        d>z             |                     ||0          |d<   |                     |g d?          }1|                     |d@          }2|2h|2dAk    }3|2d(k    }4|3s|4st%          | j        dBz             |3r3|1t%          | j        dCz             |                     ||1          |d<   n-|2d(k    rdD|d<   n!|1|                     ||1          |d<   ndD|d<   |                     |dEdd          }5|5.|5dk    r#|5dFk    r|5dGk    rt%          | j        dHz             |5|d<   |rV|                     |g dI          }6|6t%          | j        dJz             |                     ||6          |d	<   |                     |g dK          }7|                     |d@dL          }8|8m|8dAk    }9|8d(k    }:|9s|:st%          | j        dMz             |9r8|7t%          | j        dNz             |8|dL<   |                     ||7          |d
<   n2|8d(k    rdD|d
<   n&|7dA|dL<   |                     ||7          |d
<   ndD|d
<   |                     |dEdd          };|;.|;dk    r#|;dFk    r|;dGk    rt%          | j        dOz             |;|d<   n|%r<d/|d4<   |                     ||          |dP<   |!rdDn|                     ||          |dQ<   n|&rd0|d4<   |d uo|d u}<|<rdR|d4<   |;|                     ||          |d	<   |dDn|                     ||          |d
<   ||d<   |;|                     ||          |d<   |dDn|                     ||          |d<   ||d<   |=|                     | j        dS          }=|=|=|                                 z   |d<   |=|dT<   n||d<   |                     |ddg          }|                     ||          S )UNr<   )r  r  ordTyper  rI   r<  )triggerPrice	stopPrice	triggerPxtimeInForceGTCtakeProfitPricetpTriggerPxtpOrdPxtpTriggerPxTyper  stopLossPriceslTriggerPxslOrdPxslTriggerPxTypeclOrdIdclientOrderIdstopLoss
takeProfittrailingPercentcallbackRatiodefaultMarginMode
marginModecrosstdModeFcashTrJ   r  r*  r)  r  rK   rL   rX   positionSideposSider  	post_only)rv  r  r  r  r  r  r  r  r  r  r  rJ   r  r  r  IOCiocFOKfokr  r  optimal_limit_iocr  base_ccyr  r  r  r;  r  a   createOrder() requires the price argument with market buy orders to calculate total order cost(amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = False and supply the total cost value in the 'amount' argument or in the 'cost' unified extra parameter or in exchange-specific 'sz' extra parameter(the exchange-specific behaviour)r  100r  )r  r  r  z createOrder() requires a trigger price in params["stopLoss"]["triggerPrice"], or params["stopLoss"]["stopPrice"], or params["stopLoss"]["slTriggerPx"] for a stop loss order)r7  r  r  r  r  zL createOrder() params["stopLoss"]["type"] must be either "limit" or "market"z createOrder() requires a limit price in params["stopLoss"]["price"] or params["stopLoss"]["slOrdPx"] for a stop loss limit order-1triggerPriceTyperE  rD  zT createOrder() stop loss trigger price type must be one of "last", "index" or "mark")r  r  r  z createOrder() requires a trigger price in params["takeProfit"]["triggerPrice"], or params["takeProfit"]["stopPrice"], or params["takeProfit"]["tpTriggerPx"] for a take profit order)r7  r  r  	tpOrdKindzN createOrder() params["takeProfit"]["type"] must be either "limit" or "market"z createOrder() requires a limit price in params["takeProfit"]["price"] or params["takeProfit"]["tpOrdPx"] for a take profit limit orderzV createOrder() take profit trigger price type must be one of "last", "index" or "mark"r  orderPxr  r  tag)r  amount_to_precisionsafe_value_nr  safe_value_2
safe_valuer  r	  r  r  r  handle_post_onlyr  safe_number_2number_to_stringr8   
string_mulr  r,   r<   cost_to_precisionprice_to_precision
string_divuuid16r  )>r  r"  r  r  r6  r7  r  r  r  rI   r<  r  r  r  r  r  r  r  r  r  r  stopLossDefinedr  takeProfitDefinedr  isTrailingPercentOrderr  r  rJ   defaultCurrencyrv  	tradeModer  isMarketOrderpostOnlyr  r  r  r  	marketIOCdefaultTgtCcyr  r  notionalamountStringpriceStringquoteAmountconvertedTrailingPercentstopLossTriggerPricestopLossLimitPricestopLossOrderTypestopLossLimitOrderTypestopLossMarketOrderTypestopLossTriggerPriceTypetakeProfitTriggerPricetakeProfitLimitPricetakeProfitOrderTypetakeProfitLimitOrderTypetakeProfitMarketOrderTypetakeProfitTriggerPriceTypetwoWayConditionr  s>                                                                 r  create_order_requestzokx.create_order_request	  s   V$$Tl  **66::
 
4 f~*%((1[1[1[\\&&v}eDD++F4E}UU//&)U;;**63DfMM))&/=QQ//&)U;;**63DfMM**69oNN??6:66#4/__V\::
't3,,V5FXX!0!< ..t|=PR^`ghh''hGG
"v)=)=FF*J^^FHe<<F 	+ C6:emm&//&QW.++FE?KK!%!8!8!B!B&,8

&I )GH 	+f~ 6!1 6#'+'D'DV]\j'k'k$f+)5GI& *GH(00@SU[\\&6  $s  $s  $s  t  te#7e#7t+C1B$D0moT6QmW[_lWl"*sL8K0K	((xLL!!&(MBB 	'6 	' &GH 	GI 	G!)GI M [((8<5@D@]@]^dfs  vY  [_  A`  A`=5v#11&&$GGH!YYv~>>F8 
N ,'//3/D/DV/L/L.2.C.CE.J.J.5.@{.[.[+/+<+<[+I+I%-".tw  :z  0z  #{  #{  { . /7.>66X$($:$:68$L$LGDM 9X 9%8	" Gk G $ 7 7 F F 	'!,GI 	' 	'!&GI 	'!&GI! R	='.'9/5'Q'Q$'?GO$!2GI N	= 1 N	= J'+'8'8CoCoCo'p'p$'/&tw  2a  (a  b  b  b)-)@)@I])^)^&%)%6%6xAfAfAf%g%g"$($4$4Xv$F$F!$0.?7.J*/@H/L+2 2=T 2*47  6D  ,D  E  E  E/ 2-5".tw  :}  0}  #~  #~  ~151H1HQc1d1dGI..*h66-1	*'3)-)@)@I[)\)\GI&&)-GI&+/+=+=hHZ\mou+v+v(+70F::AY]dAdAd  lD  HN  lN  lN*47  6L  ,L  M  M  M1IG-.  L)-):)::GsGsGs)t)t&)1&tw  2i  (i  j  j  j)-)@)@I_)`)`&'+'8'8ElElEl'm'm$&*&8&8V[&Y&Y#&20Cw0N,1D1P-4 	2?X 	2*47  6F  ,F  G  G  G1 2/7".tw  :C  0C  #D  #D  D3FGK0151H1HQe1f1fGI..,88-1	*)5+2GK()-)@)@I])^)^GI&&)-GI&-1-?-?
L^`qsy-z-z*-92f<<C]ahChCh  pJ  NT  pT  pT*47  6N  ,N  O  O  O1KG-. 	=!*GI#'#:#:6<#P#PGK )6!bD<S<STZ\a<b<bGI 	=!.GI /t ;\-W[B[O  +%*	"*)-)@)@)Y)Y&.5oTTDD[D[\bdkDlDl	"-<)*()-)@)@)W)W&.5oTTDD[D[\bdkDlDl	"-<)* ''jAAH#%-%=	"!)!.GIYYv	?'CDDF{{7F+++r  c                   K   |                                   d{V  |                     |          }|                     ||||||          }|                     | j        dd          }	|                     |d          }
|
dk    s$|
dk    s|
dk    s|dk    s|dk    s|d	k    s|d
k    rd}	|	dk    r#|	dk    r|	dk    rt          | j        dz             |	dk    r|g}d}|	dk    r|                     |           d{V }n=|	dk    r|                     |           d{V }n| 	                    |           d{V }| 
                    |dg           }|                     |di           }|                     ||          }||d<   ||d<   |S )a[	  
        create a trade order
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-multiple-orders
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.reduceOnly]: a mark to reduce the position size for margin, swap and future orders
        :param bool [params.postOnly]: True to place a post only order
        :param dict [params.takeProfit]: *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered(perpetual swap markets only)
        :param float [params.takeProfit.triggerPrice]: take profit trigger price
        :param float [params.takeProfit.price]: used for take profit limit orders, not used for take profit market price orders
        :param str [params.takeProfit.type]: 'market' or 'limit' used to specify the take profit price type
        :param dict [params.stopLoss]: *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered(perpetual swap markets only)
        :param float [params.stopLoss.triggerPrice]: stop loss trigger price
        :param float [params.stopLoss.price]: used for stop loss limit orders, not used for stop loss market price orders
        :param str [params.stopLoss.type]: 'market' or 'limit' used to specify the stop loss price type
        :param str [params.positionSide]: if position mode is one-way: set to 'net', if position mode is hedge-mode: set to 'long' or 'short'
        :param str [params.trailingPercent]: the percent to trail away from the current market price
        :param str [params.tpOrdKind]: 'condition' or 'limit', the default is 'condition'
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrX   r  r  r  r  r  r  r  r  privatePostTradeOrderAlgoprivatePostTradeOrderz createOrder() self.options["createOrder"] must be either privatePostTradeBatchOrders or privatePostTradeOrder or privatePostTradeOrderAlgorV  r   r  r  )r  r  r  r  r	  r"   r<   r  r  r  rd  r  parse_order)r  r"  r  r  r6  r7  r  r  r  r  requestOrdTyperh  rV  rq  r#  s                  r  r  zokx.create_order
  sj     6 !!!!!!!!!V$$++FD$vVV!!$,?\]]))'9==i''^}-L-LR`duRuRu{  DU  |U  |U  [_  ch  [h  [h  nr  v  n  n  EI  MS  ES  ES0F---F>Y4Y4Y`f  kH  aH  aH  +x  !x  y  y  y222 iG,,,!77@@@@@@@@HH222!;;GDDDDDDDDHH!==gFFFFFFFFH~~h33tQ++  //ffr  ordersc           	        K   |                                   d{V  g }t          dt          |                    D ]}||         }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d          }
|                     |di           }|                     ||          }|                     ||||	|
|          }|                    |           | 	                    |           d{V }| 
                    |d	g           }|                     |          S )
a  
        create a list of trade orders
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-multiple-orders
        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   r"  r  r  r6  r7  r  rV  )r  rf  re  r  r  r  r  r  ry  r  rd  parse_orders)r  r  r  ordersRequestsrk  rawOrderrN  r  r  r6  r7  orderParamsextendedParamsorderRequestrh  rV  s                   r  create_orderszokx.create_orders
  sl      !!!!!!!!!q#f++&& 
	0 
	0AayH''(;;H##Hf55D##Hf55D__Xx88FOOHg66E..8R@@K![[f==N44XtT6SXZhiiL!!,////99.IIIIIIII. ~~h33  &&&r  r<   c                    |                      |          }d|d         i}	d }
|dk    s|dk    s|dk    s|dk    s|dk    s|dk    rd	}
|                     |d
d          }||
r||	d<   n||	d
<   n|
r||	d<   n||	d<   |                     |dd          }|                     |d          }|                     |dd          }|                     |dd          }|                     |d          }|                     |dd          }|                     |d          }|                     |d          }|d u}|d u}|
r||t          | j        dz             |X|t          | j        dz             |                     ||          |	d<   |dk    rdn|                     ||          |	d<   ||	d<   |X|t          | j        dz             |                     ||          |	d<   |dk    rdn|                     ||          |	d<   ||	d<   n|?|                     ||          |	d<   |dk    rdn|                     ||          |	d<   ||	d<   |?|                     ||          |	d<   |dk    rdn|                     ||          |	d<   ||	d<   |r|                     |d          }|                     |d           }|                     |d!          }|                     ||          |	d<   |dk    rdn|                     ||          |	d<   ||	d<   |r|                     |d          }|                     |d           }|                     |d!          }|d"k    r|nd#|	d$<   |                     ||          |	d<   |dk    rdn|                     ||          |	d<   ||	d<   ||                     ||          |	d%<   |
s||                     ||          |	d&<   | 	                    |g d'          }| 
                    |	|          S )(Nr  r<   r  r  r  r  r  r  Tr  r  algoClOrdIdalgoIdr  r  newSlTriggerPx
newSlOrdPxnewSlTriggerPxTyper  r  newTpTriggerPx
newTpOrdPxnewTpTriggerPxTyper  r  z\ editOrder() requires a stopLossPrice or takeProfitPrice parameter for editing an algo orderzF editOrder() requires a newSlOrdPx parameter for editing an algo orderr  r  zF editOrder() requires a newTpOrdPx parameter for editing an algo orderr  r7  r  r  	conditionnewTpOrdKindnewSznewPx)r  r  r  r  r  r  )r  r  r  r  r  r(   r<   r  r  r  r  )r  r<   r"  r  r  r6  r7  r  r  r  isAlgoOrderr  r  r  r  r  r  r  r  r  r  r  stopLossTypetakeProfitTypes                           r  edit_order_requestzokx.edit_order_request
  sN   V$$fTl
 I4=#8#8dFW>W>W]aej]j]jpt  yB  qB  qB  HL  PV  HV  HVK**69oNN$ 3)6&&%2	"" &$&!!#% #00JZ[[==#'#3#3F<PRX#Y#Y !%!2!26;LN^!_!_//&,??%)%5%5f>RTZ%[%["??6:66__V\::
#4/'t3 &	K$,3I3Q   ,J  "J  K  K  K#/ ($TW/w%wxxx,0,C,CFL`,a,a()151A1AH_H_`fhuHvHv%0H,-%1"*$TW/w%wxxx,0,C,CFLb,c,c()151A1AH_H_`fhwHxHx%0J,-#/,0,C,CFL`,a,a()151A1AH_H_`fhuHvHv%0H,-%1,0,C,CFLb,c,c()151A1AH_H_`fhwHxHx%0J,- I'+x'P'P$ $' B B#//&AA,0,C,CFL`,a,a()1=1I1IPTPgPghnp}P~P~%0H,-  K)-^)T)T&"&//*g"F"F!%!1!1*f!E!E=Kw=V=V..]h',0,C,CFLb,c,c()1?81K1KRVRiRijp  sB  SC  SC%0J,-#77GGGG 	J #'#:#:65#I#I 6#}#}#}~~{{7F+++r  c           	      P  K   |                                   d{V  |                     |          }|                     |||||||          }	d}
|dk    s|dk    s|dk    s|dk    s|dk    s|dk    rd}
d}|
r0|                     |                     |	|                     d{V }n/|                     |                     |	|                     d{V }|                     |d	g           }|                     |d
i           }|                     ||          }||d<   ||d<   |S )a!
  
        edit a trade order
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-amend-order
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-amend-algo-order
        :param str id: order id
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of the currency you want to trade in units of the base currency
        :param float [price]: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: client order id, uses id if not passed
        :param float [params.stopLossPrice]: stop loss trigger price
        :param float [params.newSlOrdPx]: the stop loss order price, set to stopLossPrice if the type is market
        :param str [params.newSlTriggerPxType]: 'last', 'index' or 'mark' used to specify the stop loss trigger price type, default is 'last'
        :param float [params.takeProfitPrice]: take profit trigger price
        :param float [params.newTpOrdPx]: the take profit order price, set to takeProfitPrice if the type is market
        :param str [params.newTpTriggerPxType]: 'last', 'index' or 'mark' used to specify the take profit trigger price type, default is 'last'
        :param dict [params.stopLoss]: *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
        :param float [params.stopLoss.triggerPrice]: stop loss trigger price
        :param float [params.stopLoss.price]: used for stop loss limit orders, not used for stop loss market price orders
        :param str [params.stopLoss.type]: 'market' or 'limit' used to specify the stop loss price type
        :param dict [params.takeProfit]: *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
        :param float [params.takeProfit.triggerPrice]: take profit trigger price
        :param float [params.takeProfit.price]: used for take profit limit orders, not used for take profit market price orders
        :param str [params.takeProfit.type]: 'market' or 'limit' used to specify the take profit price type
        :param str [params.newTpOrdKind]: 'condition' or 'limit', the default is 'condition'
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  r  r  r  r  TrV  r   r  r  )	r  r  r  privatePostTradeAmendAlgosr  privatePostTradeAmendOrderrd  r  r  )r  r<   r"  r  r  r6  r7  r  r  r  r  rh  rV  rq  r#  s                  r  
edit_orderzokx.edit_orderD  s     < !!!!!!!!!V$$))"fdD&%QWXXI4=#8#8dFW>W>W]aej]j]jpt  yB  qB  qB  HL  PV  HV  HVK 	[!<<T[[RX=Y=YZZZZZZZZHH!<<T[[RX=Y=YZZZZZZZZH  ~~h33tQ++  //ffr  c                   K   |t          | j        dz             |                     |dd          }|                     |dd          }|s|r4|                     |g||           d{V }|                     |d          S |                                  d{V  |                     |          }d|d	         i}|                     |d
d          }	|	|	|d
<   n||d<   | 	                    |d
dg          }
| 
                    |                     ||
                     d{V }|                     |dg           }|                     |d          }|                     ||          S )a  
        cancels an open order
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-order
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.trigger]: True if trigger orders
        :param boolean [params.trailing]: set to True if you want to cancel a trailing order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nz) cancelOrder() requires a symbol argumentstopr  trailingFr   r  r<   r  r  r  rV  )r'   r<   r  r  cancel_ordersr  r  r  r  r  privatePostTradeCancelOrderr  r  r  )r  r<   r"  r  r  r  
orderInnerr  r  r  r  rh  rV  r#  s                 r  cancel_orderzokx.cancel_order  s      >#DG.Y$YZZZ  ;;>>&*e<< 	28 	2#112$GGGGGGGGJ??:q111!!!!!!!!!V$$fTl

 **69oNN$!.GI!GG		&9o">??99$++gu:U:UVVVVVVVVx44tQ''v...r  c                 ^    |*t          |t                    r|                    d          S |S )zq
         * @ignore
        :param string[]|str ids: order ids
        :returns str[]: list of order ids
        N,)
isinstancestrrE  )r  idss     r  	parse_idszokx.parse_ids  s,     OC!5!5O99S>>!Jr  c                 8  K   |t          | j        dz             |                                  d{V  |                     |          }g }|                     | j        di           }|                     |dd          }|                     |d|          }|                     |                     |dd                    }	|                     |                     |d                    }
|                     |d	d
          }| 	                    |dd          }|s|rd}|	|                     |          }|
Dt          dt          |
                    D ]&}|                    |
|         |d         d           't          dt          |                    D ]O}|s|r%|                    ||         |d         d           +|                    ||         |d         d           PnDt          dt          |	                    D ]&}|                    |d         |	|         d           'd}|dk    r|                     |           d{V }n|                     |           d{V }|                     |dg           }|                     ||dd|          S )a  
        cancel multiple orders
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-multiple-orders
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order
        :param str[] ids: order ids
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.trigger]: whether the order is a stop/trigger order
        :param boolean [params.trailing]: set to True if you want to cancel trailing orders
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nz* cancelOrders() requires a symbol argumentrQ   r  r  r  r  r  r  r  r  FprivatePostTradeCancelAlgosr   r<   )r  r  )r  r  )r  r  rV  )r'   r<   r  r  r  r	  r  r  r  r  rf  re  ry  r  r  rd  r  )r  r  r"  r  r  r  r	  defaultMethodr  clientOrderIdsalgoIdsr  r  rk  rh  
ordersDatas                   r  r	  zokx.cancel_orders  s      >#DG.Z$Z[[[!!!!!!!!!V$$//$,CC(((<_``!!&(MBB(9(9&)_(](]^^..!B!BCC  ;;>>&*e<< 	38 	32F!..%%C"q#g,,//  ANN")!*"(,$ $     1c#hh'' 
 
 	t 	NN"%a&"(,$ $    
 NN!$Q"(,$ $    
 1c.1122  $Tl-a0        222!==gFFFFFFFFHH!CCGLLLLLLLLH< ^^Hfb99
  VT4HHHr  c                 B    ddddddd}|                      |||          S )Nrb  r  closed)rb  order_failedlivepartially_filledfilled	effectiver  r  rZ  statusess      r  parse_order_statuszokx.parse_order_status  s:    "& &!
 
 &&999r  c                 n   |                      |d          }|H|dk    rB|                     |                      |d          |                      |d          d|d          S |                     |dd          }|                     |d          }|                     |d	          }|                     |d
          }|                      |d          }|                      |d          }	d }
d }|	dk    rd}
d}	n|	dk    rd}d}	n
|	dk    rd}d}	|                      |d          }|                     ||          }|                     ||d          }|                      |d          }|                     |dd          }|                      |d          }|                     |                      |d                    }|                      |d          }d }d }|                      | j        dd          }|                      |d|          }|                      |d          }|dk    r)|	d k    r#|d!k    r|d"k    r|                      |d#          }n|                      |d#          }d }|Wt          j	        |          }|                      |d$          }| 
                    |          }|                     |          |d%}|                      |d          }|t          |          d&k     rd }|                     |d'd(          }|                     |d)d*          }|                     |d+d,g          }|                      |d-          } d.}!|!| d/k    }!|                     i d0|d1|d2|d3|d4|                     |          d5|d6|d7|d8|	d9|d:|
d|d;|d<|d=|d>|d?|||||d ||d |!d@	|          S )ANsCode0r  r  rejected)r<   r  rZ  rD  r  cTimerl  fillTimer  r  r  Tr  r  r  r  r  r  r%  	accFillSzr  ordPxavgPxr\  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  moveTriggerPx
reduceOnlyFtruerD  r<   r  rL  rK  lastTradeTimestamplastUpdateTimestampr"  r  r  r  r7  r  r  r  r  )	r  r;  r6  r  	remainingrZ  r  tradesr-  )r  
safe_orderr  rg  rS  r`  r"  r	  r8   r%  r  r  re  r  safe_number_nr  )"r  r#  r  scoder<   rL  r0  r/  r  r  r  r  rN  r"  r  r7  r  rZ  r)  r6  r;  r  r  r  r  r*  r+  r,  r  r  r  r  reduceOnlyRawr-  s"                                     r  r  zokx.parse_order  s   T   00ESLL??&&ug66!%!1!1%!C!C$	$ $    x99%%eW55	"//w??!..ujAAv..y11;HDDU]]KDDU]]KD##E844!!(F33!!(FC88!!%55""5$88""5'22(()9)9%)I)IJJ((66 ((xLL!!%=AA##E:66EMM 0 0x67I7IPVZePePe##E400DD %%eT22F$#.}==M ,,UH==M"55mDDO))-88+ C ((	::%C,>,>,B,B M**5-KK,,UM9MM&&u{O.LMM	((==
!'61J  
E 
" 
 ] 
 	 

 Y// 
 !"4 
 "#6 
 f 
 D 
 ; 
  
 D 
 U 
 ] 
  
  ! 
" I# 
$ $5 
  
  
6 7  	r  c                 \  K   |t          | j        dz             |                                  d{V  |                     |          }d|d         i}|                     |dd          }|                     | j        di           }|                     |dd	          }|                     |d|          }	|                     |d
d          }
|
rd}	|||d<   n||d<   n|||d<   n||d<   | 	                    |g d          }d}|	dk    r0| 
                    |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }|                     |d          }|                     ||          S )a   
        fetch an order by the id
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-details
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-details
        :param str id: the order id
        :param str symbol: unified market symbol
        :param dict [params]: extra and exchange specific parameters
        :param boolean [params.trigger]: True if fetching trigger orders
        :returns: `an order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nz( fetchOrder() requires a symbol argumentr  r<   r  r  r   r  r  r  r  privateGetTradeOrderAlgor  r  r  )r  r  r  r  r  rV  r   )r'   r<   r  r  r  r  r	  r  r  r  r8  r  r  r  r  )r  r<   r"  r  r  r  r  r	  r  r  r  r  rh  rV  r#  s                  r  fetch_orderzokx.fetch_order  s      >#DG.X$XYYY!!!!!!!!!V$$fTl
 **69oNN//$,bAA(((<RSS!!&(MBB  ;; 
	&/F()6&&$&!!(%2	""#% 		&"["["[\\///!::4;;wPU;V;VWWWWWWWWHH!66t{{7E7R7RSSSSSSSSHB x44tQ''v...r  c                   K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |||d<   |                     | j        di           }|                     | j        di           }	|                     |d	d
          }
|                     |d	|
          }|                     |d          }|                     |dd          }|                     |dd          }|s|s||	v rd}|rd|d<   n	|r|d|d<   | 	                    |g d          }d}|dk    r0| 
                    |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        fetch all unfilled currently open orders
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-list
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-list
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.stop]: True if fetching trigger or conditional orders
        :param str [params.ordType]: "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"
        :param str [params.algoId]: Algo ID "'433845797218942976'"
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :param boolean [params.trailing]: set to True if you want to fetch trailing orders
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NFr   r0  r<   r  r  r   r  r  r  r  r  r   privateGetTradeOrdersAlgoPendingr  r  r  r  r  rV  )r  r  fetch_paginated_call_dynamicr  r  r	  r  r  r  r  r;  r  r  rd  r  )r  r"  r.  r  r  r0  r  r  r	  r   r  r  r  r  r  r  rh  rV  s                     r  fetch_open_orderszokx.fetch_open_orderso  s}       !!!!!!!!!88ART^__& 	l::;LfV[]bdjkkkkkkkkk	
 [[((F &tGH$GG//$,0A2FF7GLL(((<Z[[!!&(MBB""6955  ;;>>&*e<< 	8t 	8> 9 97F 	+!2GI 	+w!*GI		&"K"K"KLL777!BB4;;wX]C^C^________HH!>>t{{7TY?Z?Z[[[[[[[[H@ ~~h33  vue<<<r  c                   K   |                                   d{V  i }d}| |                     |          }|d         |d<   d}d}|                     d||          \  }}|                     |          |d<   |||d<   d|d<   |                     | j        di           }	|                     | j        d	i           }
|                     |	d
d          }|                     |d
|          }|                     |d          }|                     |dd          }|                     |dd          }|rd}d|d<   n|s||
v rQd}|                     |d          }|||d<   | 	                    |d          }|r|t          | j        dz             n=|||d<   |                     |dd          }|||d<   | 	                    |ddg          }| 	                    |g d          }d}|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )aj  
        fetches information on multiple canceled orders made by the user
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-7-days
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-history
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: timestamp in ms of the earliest order, default is None
        :param int [limit]: max number of orders to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.stop]: True if fetching trigger or conditional orders
        :param str [params.ordType]: "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"
        :param str [params.algoId]: Algo ID "'433845797218942976'"
        :param int [params.until]: timestamp in ms to fetch orders for
        :param boolean [params.trailing]: set to True if you want to fetch trailing orders
        :returns dict: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr<   r  rk   r  r  rb  r\  r   r  r  r  r  r  r  F privateGetTradeOrdersAlgoHistoryr  r  z fetchCanceledOrders() requires an "ordType" string parameter, "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"begintillrC  r]  r<  rV  )r  r  r  r!  r  r	  r  r  r  r  r'   r<   safe_integer_2r@  r  r  rd  r  )r  r"  r.  r  r  r  r  r  r  r	  r   r  r  r  r  r  r  rC  sendrh  rV  s                        r  fetch_canceled_orderszokx.fetch_canceled_orders	  s       !!!!!!!!!

 [[((F &tGH889NPVX^__e"==dCC
$GG%//$,0ErJJ7GLL(((<Z[[!!&(MBB""6955  ;;>>&*e<< 	<7F!2GI 	<g//7F%%fh77F!$*!6844 A?+DG  7@  -@  A  A  A #( ''vw??E !&		%'6):;;yy I I IJJ777!BB4;;wX\C]C]^^^^^^^^HH!>>t{{7TX?Y?YZZZZZZZZHH ~~h33  vue<<<r  c                 \  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   d}d}	|                     d||          \  }}	|                     |          |d<   |||d<   |                     | j        di           }
|                     | j        d	i           }|                     |
d
d          }|                     |d
|          }|                     |d          }| 	                    |dd          }| 
                    |dd          }|s|s||v rd}d|d<   |rd|d<   nL|r|d|d<   nB|||d<   |                     |	dd          }|||d<   |                     |	ddg          }	d|d<   |                     |	g d          }d}|dk    r0|                     |                     ||                     d{V }ne|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        fetches information on multiple closed orders made by the user
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-7-days
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-history
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-3-months
        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.trigger]: True if fetching trigger or conditional orders
        :param str [params.ordType]: "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"
        :param str [params.algoId]: Algo ID "'433845797218942976'"
        :param int [params.until]: timestamp in ms to fetch orders for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :param str [params.method]: method to be used, either 'privateGetTradeOrdersHistory', 'privateGetTradeOrdersHistoryArchive' or 'privateGetTradeOrdersAlgoHistory' default is 'privateGetTradeOrdersHistory'
        :param boolean [params.trailing]: set to True if you want to fetch trailing orders
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NFrm   r0  r<   r  r  r  r   r  r  r  r  r  r  r@  r  r\  r  rA  rB  rC  r]  r  r<  #privateGetTradeOrdersHistoryArchiverV  )r  r  r=  r  r  r!  r  r	  r  safe_bool_2r  rC  r  r@  r  rG  r  rd  r  )r  r"  r.  r  r  r0  r  r  r  r  r	  r   r  r  r  r  r  rC  rD  rh  rV  s                        r  fetch_closed_orderszokx.fetch_closed_orders  sd     & !!!!!!!!!88ATV`aa& 	n::;NPVX]_dflmmmmmmmmm

 [[((F &tGH889LfV\]]e"==dCC
$GG../BBGG6FKK(((<Z[[!!&(MBB""6955	::>>&*e<< 	+t 	+> 9 97F*GG 	(!2GI 
	(%.	" #( ''vw??E !&		%'6):;;'GGyy I I IJJ777!BB4;;wX\C]C]^^^^^^^^HH<<<!EEdkkRY[_F`F`aaaaaaaaHH!>>t{{7TX?Y?YZZZZZZZZH@ ~~h33  vue<<<r  c                 v  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |||d<   |                     d||          \  }}|                     d||          \  }}	|                     |          |d	<   ||||d
<   |                     |                     ||	                     d{V }
| 	                    |
dg           }| 
                    |||||	          S )ar  
        fetch all trades made by the user
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-months
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: Timestamp in ms of the latest time to retrieve trades for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        NFr   r0  r<   r  rA  r]  r  r  rV  )r  r  r=  r  handle_until_optionr  r!  privateGetTradeFillsHistoryr  rd  r6  )r  r"  r.  r  r  r0  r  r  r  r  rh  rV  s               r  fetch_my_tradeszokx.fetch_my_tradesd  s      !!!!!!!!!88R\]]& 	j::?FTY[`bhiiiiiiiii
 [[((F &tGH$GG225'6JJ88&RXYYe"==dCC
EM$GG99$++gu:U:UVVVVVVVV4 ~~h33  vueUCCCr  c           	      r   K   d|i}|                      ||||                     ||                     d{V S )aC  
        fetch all the trades made from a single order
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-months
        :param str id: order id
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        r  N)rM  r  )r  r<   r"  r.  r  r  r  s          r  fetch_order_tradeszokx.fetch_order_trades  sQ       R
 ))&%GU[@\@\]]]]]]]]]r  rw  c                   K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S |                     | j        di           }|                     |d          }|                     |d|          }|                     |d          }i }d}	|                     d|          \  }	}|	|                     |d          }	|dk    r|	|	|d<   |                     dd|          \  }
}|
| 	                    |
          |d<   |||d	<   d}| | 
                    |          }|d
         |d<   |                     d||          \  }}d}|dk    r0|                     |                     ||                     d{V }ne|dk    r0|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :see: https://www.okx.com/docs-v5/en/#rest-api-account-get-bills-details-last-7-days
        :see: https://www.okx.com/docs-v5/en/#rest-api-account-get-bills-details-last-3-months
        :see: https://www.okx.com/docs-v5/en/#rest-api-funding-asset-bills-details
        :param str code: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entrys to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated'
        :param int [params.until]: the latest time in ms to fetch entries for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger-structure>`
        NFr   r0  r  mgnModeprivateGetAssetBillsr  r  r<   r  r]  privateGetAccountBillsArchiverV  )r  r  r=  r  r	  r  r  handle_margin_mode_and_paramsr  r!  rv  rK  rS  r  rR  r  rd  parse_ledger)r  rw  r.  r  r  r0  r	  r  r  r  r  r  rv  rh  rV  s                  r  fetch_ledgerzokx.fetch_ledger  s      !!!!!!!!!88PZ[[& 	f::=$PUW\^deeeeeeeee..}bAA!!'844!!&(F;;68,,
 
!??vVV
F))&)<<J+++%%/	"88fUUe"&"A"A$"G"GGJ$GG}}T**H%d^GEN225'6JJ444!??GUZ@[@[\\\\\\\\HH---!66t{{7E7R7RSSSSSSSSHH!88We9T9TUUUUUUUUHb ~~h33  x>>>r  c                 L    dddddddddddd}|                      |||          S )Nr   r'  rebater  )r   r   345r  7891011r  )r  r  r  s      r  parse_ledger_entry_typezokx.parse_ledger_entry_type*  sI    
 
 tT222r  rv  c                    |                      |d          }d }|                      |d          }d }|                     |                      |d                    }|                     |                      |d          |          }|                      |d          }	|                     |	          }
|                     |d          }|                      |d          }d }|*|                     t          j        |                    |d}d }|                      |d	          }|                     |          }d
}|                      |d          }|                     |d d          }||||                     |          |||||||
||||dS )NbillIdr  r  r  balChgro  r  r  rx  rW  r  r%  )r<   rD  rL  rK  r{  referenceIdreferenceAccountr  rv  r"  r6  rB  r1  rZ  r  )	r  ra  r  r  rg  r8   r%  r`  r  )r  itemrv  r<   r{  re  rf  r  rw  r  r6  rL  r)  r  rB  afterStringr1  rZ  rN  r"  s                       r  parse_ledger_entryzokx.parse_ledger_entry:  s   J dH--&&tW55++D,<,<T6,J,JKK&&t'7'7e'D'DhOO''h77""<00%%dD11	((u55$))'*<]*K*KLL  C &&tU33!!+..##D(33!!(D#66"Y//& 0
 
 	
r  c                    |                      |d          }|                     |g d          }|-|                     |di           }|                      |d          }|                      |d          }|                     ||          }|d         }|                      |d          }|                     |di           }	|                     |	d	          }
|                     |
|          }|d
k    r|                     |
dd
          }|                      |d          }|                     ||          }|                     |           |||||dS )Naddr)r  pmtIdmemoaddrExcommentr  rw  r  rS  r<   zUSDT-PolygonzUSDT-Polygon-Bridger  )rv  addressr  r  rD  )r  safe_string_nr  r  index_byr  r  check_address)r  depositAddressrv  rp  r  rn  r  rw  r  rS  r  networkDatar  r  s                 r  parse_deposit_addresszokx.parse_deposit_address  sk   : "">6::  1I1I1IJJ;__^XrBBF""6955C%%ne<<
%%j(;;  99??8Z<<}}Xt44oolE::T N""++L:OQ_``K"";	::--gt<<7###""
 
 	
r  c                   K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     |dd          }|                     ||d         gd          }|                     |d	          S )
a  
        fetch a dictionary of addresses for a currency, indexed by network
        :see: https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-deposit-address
        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `address structures <https://docs.ccxt.com/#/?id=address-structure>` indexed by the network
        Nr  r<   rV  selectedTrw  Fr  )r  rv  privateGetAssetDepositAddressr  rd  	filter_byparse_deposit_addressesrr  )	r  rw  r  rv  r  rh  rV  filteredparseds	            r  "fetch_deposit_addresses_by_networkz&okx.fetch_deposit_addresses_by_network  s       !!!!!!!!!==&&8D>
 ;;DKKQW<X<XYYYYYYYY, ~~h33>>$
D99--h&9I8JERR}}VY///r  c                   K   |                      |d          }|                     | j        di           }|                     |||          }|                     |d          }|                     ||           d{V }d}||                     ||          }||                     |||          }|                     ||          }||                     | j        dd          }	|                     ||	          }|St          |                                          }
|                     |
d          }|t          | j	        dz   |z             |S |                     ||          }| t          | j	        dz   |z   d	z   |z             |S )
a  
        fetch the deposit address for a currency associated with self account
        :see: https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-deposit-address
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r  rS  NrL  rM  r   z7 fetchDepositAddress() cannot find deposit address for z# fetchDepositAddress() cannot find z deposit address for )
safe_string_upperr  r	  r  r  r~  r  valuesr+   r<   )r  rw  r  
rawNetworkrS  r  rh  rz  aliasrL  r  s              r  fetch_deposit_addresszokx.fetch_deposit_address  s      ++FI>>
??4<R@@""8ZDD69--@@vNNNNNNNN?__Xt44F~((4>>599>%)%5%5dlDTV]%^%^N!__X~FFF~!%hoo&7&7!8!8!%!;!;!>"0;t1tw{1{"|"||M733> +P!PSZ!Z]t!tw{!{|||r  c                   K   |                      ||          \  }}|                     |           |                                  d{V  |                     |          }|t	          |          dk    r|dz   |z   }|d         |d|                     |          d}|                     |d          }|l|                     | j        di           }	|                     |	|	                                |          }|d         d	z   |z   |d
<   | 
                    |d          }|                     |d          }
|
|                                  d{V }|                     | j        |          | _        |                     |d         |                     |          i           }|                     |d          }
|
t          | j        dz             |                     |
          |d<   | 
                    |dg          }|                     |                     ||                     d{V }|                     |dg           }|                     |d          }|                     ||          S )a  
        make a withdrawal
        :see: https://www.okx.com/docs-v5/en/#funding-account-rest-api-withdrawal
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr   r(  r<   rZ  )r  toAddrdestamtr  rS  r%  r  r  u    withdraw() requires a "fee" string parameter, network transaction fee must be ≥ 0. Withdrawals to OKCoin or OKX are fee-free, please set "0". Withdrawing to external digital asset address requires network transaction fee.rV  )handle_withdraw_tag_and_paramsrs  r  rv  re  r  r  r  r	  upperr  r  r  
currenciesr  r'   r<   privatePostAssetWithdrawalr  rd  parse_transaction)r  rw  r6  rp  r  r  rv  r  r  rS  r  r  targetNetworkr  rh  rV  transactions                    r  r   zokx.withdraw/  s      99#vFFV7###!!!!!!!!!==&&O#c((Q,,mc)GD>((00	
 
 ""6955~~dlJCCH&&x'JJG'~3g=GGYYvy11Fvu--;#4466666666J"..t
KKDO NN8J+?AXAXY`AaAaceffM""=%88C{'  3U  )U  V  V  V..s33		&5'**88We9T9TUUUUUUUU ~~h33nnT1--%%k8<<<r  c                 0  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |t	          |dz
  d          |d	<   |||d
<   |                     d||          \  }}|                     |                     ||                     d{V }|                     |dg           }	| 	                    |	||||          S )aZ  
        fetch all deposits made to an account
        :see: https://www.okx.com/docs-v5/en/#rest-api-funding-get-deposit-history
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        NFrw   r0  r<   r  r   r   rB  r  r1  rV  )
r  r  r=  rv  r:  rK  privateGetAssetDepositHistoryr  rd  parse_transactions
r  rw  r.  r  r  r0  r  rv  rh  rV  s
             r  fetch_depositszokx.fetch_depositsh  sk      !!!!!!!!!88R\]]& 	h::?DRWY^`fggggggggg
 }}T**H%d^GEN #EAIq 1 1GH$GG227GVLL;;DKKQW<X<XYYYYYYYYN ~~h33&&tXueVLLLr  c                 n  K   |                                   d{V  d|i}d}| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     |d          }|                     |di           }|                     ||          S )a  
        fetch data on a currency deposit via the deposit id
        :see: https://www.okx.com/docs-v5/en/#rest-api-funding-get-deposit-history
        :param str id: deposit id
        :param str code: filter by currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        NdepIdr<   r  rV  r   )r  rv  r  r  r  r  r  )	r  r<   rw  r  r  rv  rh  rV  r  s	            r  fetch_depositzokx.fetch_deposit  s       !!!!!!!!!R
 }}T**H%d^GEN;;DKKQW<X<XYYYYYYYYx00..q"--%%gx888r  c                 0  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S i }d}| |                     |          }|d         |d<   |t	          |dz
  d          |d	<   |||d
<   |                     d||          \  }}|                     |                     ||                     d{V }|                     |dg           }	| 	                    |	||||          S )ah  
        fetch all withdrawals made from an account
        :see: https://www.okx.com/docs-v5/en/#rest-api-funding-get-withdrawal-history
        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        NFr   r0  r<   r  r   r   rB  r  r1  rV  )
r  r  r=  rv  r:  rK   privateGetAssetWithdrawalHistoryr  rd  r  r  s
             r  fetch_withdrawalszokx.fetch_withdrawals  sl      !!!!!!!!!88ASU_``& 	k::;MtUZ\acijjjjjjjjj
 }}T**H%d^GEN #EAIq 1 1GH$GG227GVLL>>t{{7TZ?[?[\\\\\\\\> ~~h33&&tXueVLLLr  c                 n  K   |                                   d{V  d|i}d}| |                     |          }|d         |d<   |                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     |          S )a  
        fetch data on a currency withdrawal via the withdrawal id
        :see: https://www.okx.com/docs-v5/en/#rest-api-funding-get-withdrawal-history
        :param str id: withdrawal id
        :param str code: unified currency code of the currency withdrawn, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        NwdIdr<   r  rV  r   )r  rv  r  r  rd  r  r  )	r  r<   rw  r  r  rv  rh  rV  
withdrawals	            r  fetch_withdrawalzokx.fetch_withdrawal  s       !!!!!!!!!B
 }}T**H%d^GEN>>t{{7TZ?[?[\\\\\\\\, ~~h33^^D!R00
%%j111r  c                     i ddddddddddd	d
dddddddddddddddddddddd}|                      |||          S )Nz-3pendingz-2rb  r  failedr%  r   r   rW  rY  rZ  r[  r  r\  r]  r^  r_  121516r  r   s      r  parse_transaction_statuszokx.parse_transaction_status7  s    0
)
*
 (
 	

 
 
 
 
 
 
 
 
 
 )
 )
  )!
" )#
& &&999r  c                 <   d }d }|                      |d          }|                      |d          }|                      |d          }|}|                     |dd          }	|                     |d|	          }	|d}|}n|                      |d          }d	}|                      |d
          }
|                     |
          }|                     |d          }|                     |                      |d                    }|                      |d          }|                     |d          }d }|d	k    rd}n|                     |d          }i d|d|d|d|dd d|d|d|dd d|	d|	d|d|dd d|d|d |                     |          d d ||d!d"S )#Nr  fromtor  rm  rl  r  r  r  r  r  r\  txIdro  r   r  rD  r<   rv  r6  r  addressFrom	addressTorp  tagFromtagTorZ  r  rY  txidrL  rK  )rv  r;  )internalro  r  )r  r  r  r  r  rg  r  )r  r  rv  r  r<   withdrawalIdr  r  rp  r  r  rw  r6  rZ  r  rL  feeCosts                    r  r  zokx.parse_transactiond  sj   P ''V<<&&{F;;$$[$77	"";v>>"";??#DBB !!+w77BD%%k599
&&z22!!+u55..t/?/?W/U/UVVV44%%k488	9GG&&{E::G
K
"
 
 f	

 t
 ;
 
 w
 t
 U
 5
 f
 D
 t
 D
  !
" Y//#
$   )
 
 
 	
r  c                   K   |                                   d{V  d}|                     d|          \  }}||                     |dd          }|dk    r|dk    rt          | j        dz             |                     |          }|d         |d}|                     |                     ||                     d{V }|                     |d	g           }| 	                    ||          S )
a  
        fetch the set leverage for a market
        :see: https://www.okx.com/docs-v5/en/#rest-api-account-get-leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated'
        :returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
        Nr   rQ  r  isolatedzV fetchLeverage() requires a marginMode parameter that must be either cross or isolatedr<   r  rQ  rV  )
r  rT  r  r(   r<   r  privateGetAccountLeverageInfor  rd  parse_leverage)r  r"  r  r  r  r  rh  rV  s           r  fetch_leveragezokx.fetch_leverage  s'      !!!!!!!!!
!??QWXX
F))&)WEEJ'!!
j(@(@TW'  A  A  AV$$Tl!
 
 ;;DKKQW<X<XYYYYYYYY ~~h33""4000r  c                    d }d }d }d }t          dt          |                    D ]}||         }|                     |d          }|                     |d          }|                     |d          }	|	dk    r|                     |d          }i|	dk    r|                     |d          }|                     |d          }|                     |d          }||                     ||          |||dS )	Nr   rQ  r  r  longr  short)rD  r"  r  longLeverageshortLeverage)rf  re  r  r  rg  r`  )
r  r  r  rN  r  r  r  rk  entryr  s
             r  r  zokx.parse_leverage  s   
q#h--(( 	B 	BAQKE//yAAJ''x88H11%CCLv%%#00@@(( $ 1 1% A A#00@@ $ 1 1% A A&&x88$(*
 
 	
r  c                   K   |                                   d{V  |                     |          }|                     d||          \  }}d|d         i}||                     |          |d<   |                     |                     ||                     d{V }|                     |dg           }|                     |d          }	|	dS |                     |	|          S )a  
        fetch data on a single open contract trade position
        :see: https://www.okx.com/docs-v5/en/#rest-api-account-get-positions
        :param str symbol: unified market symbol of the market the position is held in, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.instType]: MARGIN, SWAP, FUTURES, OPTION
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nr   r  r<   r  rV  r   )	r  r  r  r!  r  r  rd  r  parse_position)
r  r"  r  r  r  r  r  rh  rV  positions
             r  fetch_positionzokx.fetch_position  s
      !!!!!!!!!V$$88&RXYYe fTl

 "&"A"A$"G"GGJ88We9T9TUUUUUUUU^ ~~h33>>$**4""8V444r  c                   K   |                                   d{V  i }|g }t          dt          |                    D ]:}||         }|                     |          }|                    |d                    ;t          |          }|dk    rd                    |          |d<   |                     | j        di           }	|                     |	dd          }
d}|
d	k    r0| 	                    | 
                    ||                     d{V }n/|                     | 
                    ||                     d{V }|                     |d
g           }g }t          dt          |                    D ]0}|                    |                     ||                              1|                     |d|d          S )a   
        :see: https://www.okx.com/docs-v5/en/#rest-api-account-get-positions
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions-history history
        fetch all open positions
        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.instType]: MARGIN, SWAP, FUTURES, OPTION
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nr   r<   r  r  r   r  r  !privateGetAccountPositionsHistoryrV  r"  F)r  rf  re  r  ry  joinr  r	  r  r  r  r  rd  r  filter_by_array_positions)r  r  r  r  	marketIdsrk  r  r  marketIdsLengthfetchPositionsOptionsr  rh  	positionsrz  s                 r  fetch_positionszokx.fetch_positionsI  s      !!!!!!!!!

 I1c'll++ / /
U++  ....!)nnO""$'HHY$7$7! $t|=Mr R R!!"7C_``888!CCDKKPWY_D`D`aaaaaaaaHH!<<T[[RX=Y=YZZZZZZZZH^ NN8VR88	q#i..)) 	= 	=AMM$--il;;<<<<--fhOOOr  c                 @   K   |                      |g|           d{V S )a  
        :see: https://www.okx.com/docs-v5/en/#rest-api-account-get-positions
        fetch all open positions for specific symbol
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.instType]: MARGIN(if needed)
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        N)r  )r  r"  r  s      r  fetch_positions_for_symbolzokx.fetch_positions_for_symbol  s2       ))6(F;;;;;;;;;r  c                 >
   |                      |d          }|                     ||          }|d         }|                      |d          }t          j        |          }|                     |dd          }|dk    }|                     |          }	|d         r\|dk    r=|                      |d          }
|                     |
          }||d	         |k    rd
nd}||                      |d          }n:|8|dk    r2t          j        |d          rd
}nt          j        |d          rd}nd }| 	                    |d          }| 
                    |          }|                      |d          }|                      |d          }|d         r(t          j        t          j        ||          |          }|                     |          }|                      |d          }d }|                     |dd          }|                      |d          }|                      |d          }d }d }|dk    r,|                      |d          }t          j        ||          }n1|dk    r+t          j        d|          }|                      |d          }|                      |d          }|                     |          }t          j        ||          }|*|                     t          j        ||d                    }n|t          j        ||          }d}|                     t          j        t          j        ||          dd                    }| 	                    |d          }|                      |d          }|                     t          j        |d                    }|                     |d           } |                     t          j        ||d                    }!|                     i d!|d"|                      |d#          d|d$|d%|d&|d'|                     |          d(|                     |          d)| 	                    |d)          d*|d+|	d|d,|                     |          d-| 	                    |d.          d/|d0|d1| |                     |           |                     |d2          |||                     |          |                     |          |                     |          |                     |          |!d d d3          S )4Nr  r"  posr  	directionnetrJ   posCcyr)  r  r  r%  r=  markPxnotionalUsdr1  rQ  r+  	openAvgPxuplr  r  imrr  r   mmrr   z0.00005liqPxuplRatior  r'  rD  r<   posIdr  r  liquidationPrice
entryPriceunrealizedPnlrealizedPnlr  	contracts	markPrice	lastPrice
closeAvgPxr  hedgedrL  rl  )rK  r0  maintenanceMarginmaintenanceMarginPercentage
collateralinitialMargininitialMarginPercentager  marginRatior  r  )r  rS  r8   
string_absr  r  r  r  	string_ltr  r  r  r  
string_addrg  safe_positionr  )"r  r  r  rN  r"  r  contractsAbsr  r  r  r  parsedCurrencyr=  contractSizeStringmarkPriceStringnotionalStringr  r  initialMarginStringentryPriceStringunrealizedPnlStringleverageStringr  collateralStringmaintenanceMarginStringr  !maintenanceMarginPercentageStringrounderr  r  percentageStringr  rL  r  s"                                     r  r  zokx.parse_position  s   F ##Hh77!!(F33!x//)#..!!(I{CC%%l33	( 	$u}}))(H==!%!8!8!@!@!-&,Vn&F&F66WD|''+>>5==(c22 $% *344 $&#''??!22<@@**8X>>))(MBB) 	w$/0B<Qc0d0dfuvvN$$^44%%h	::
"--hMM"..x??))(G<<"&  "&"2"28U"C"C&12EGZ[[:%%&-&8n&M&M##//(CC"&"2"28U"C"C --.EFF,3,>?VXf,g,g)"*&*&7&78JK^`npq8r8r&s&s## (")"45Ln"]"]&*&7&78J7K]^  BI  LJ  LJ  LO  QR  9S  9S  'T  'T#++Hg>>++HjAA&&w'9:JE'R'RSS
%%h88	''(:;RTdfg(h(hii!! #
H#
$""8W55#
 f#
 	#

 *#
  0#
 $++,<==#
 T../BCC#
 4++HmDD#
 *#
 #
 L#
 **?;;#
 ))(LAA#
 D#
  f!#
" ##
$ Y//#'#4#4Xw#G#G!2+F++,<==!../BCC'+'8'89P'Q'Q)).99&!#9#
 #
 #
   	r  fromAccount	toAccountc                 4  K   |                                   d{V  |                     |          }|                     | j        di           }|                     |||          }|                     |||          }	|d         |                     ||          d||	d}
|dk    r?d|
d<   |	|
d	<   |                     |d
d          |
d
<   |                     |dd          |
d<   nD|	dk    r>d|
d<   ||
d	<   |                     |d
d          |
d
<   |                     |dd          |
d<   |                     |                     |
|                     d{V }|                     |dg           }|                     |di           }| 	                    ||          S )a!  
        transfer currency internally between wallets on the same account
        :see: https://www.okx.com/docs-v5/en/#rest-api-funding-funds-transfer
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nr  r<   r%  )r  r  r  r  r  masterr   r  subAcctr  r  r  r   rV  r   )
r  rv  r  r	  r  currency_to_precisionprivatePostAssetTransferr  rd  parse_transfer)r  rw  r6  r  r  r  rv  r  fromIdtoIdr  rh  rV  rawTransfers                 r  r   zokx.transferF  s      !!!!!!!!!==&&6FKK!!.+{KK	9EED>--dF;;

 

 X!GFO!%GI"..vvsCCGFO ,,VT3??GDMMX!GFO!'GI"..vvsCCGFO ,,VT3??GDM66t{{7F7S7STTTTTTTT  ~~h33nnT1b11"";999r  c                    |                      |dd          }|                     |d          }|                     ||          }|                     |d          }|                     |d          }|                     |d          }|                     | j        di           }	|                     |d          }
|                     |d	          }|'|                     t          j	        |                    }|||
| 
                    |
          |||                     |	|          |                     |	|          |                     |                     |d
                    d	S )NtransIdrc  r  r  r  r  r  ro  r  r\  )	rD  r<   rL  rK  rv  r6  r  r  rZ  )r  r  r  r  r  r	  rg  r  r8   r  r  parse_transfer_status)r  r   rv  r<   r  rw  r6  fromAccountIdtoAccountIdr  rL  balanceChanges               r  r  zokx.parse_transfer  s^   j )X>>%%h66
&&z8<<!!(E22((6::&&x66~~dlNBGG%%h55	((488$&&w'9-'H'HIIF"Y//++L-HH)),DD001A1A(G1T1TUU

 

 
	
r  c                 8    ddi}|                      |||          S )NsuccessrW  r  r   s      r  r	  zokx.parse_transfer_status  s(    t
 &&999r  c                 $  K   |                                   d {V  d|i}|                     |                     ||                     d {V }|                     |dg           }|                     |d          }|                     |          S )Nr  rV  r   )r  privateGetAssetTransferStater  rd  r  r  )r  r<   rw  r  r  rh  rV  r   s           r  fetch_transferzokx.fetch_transfer  s      !!!!!!!!!r
 ::4;;wPV;W;WXXXXXXXX* ~~h33>>$**""8,,,r  c                 d  K   |                                   d{V  d}ddi}| |                     |          }|d         |d<   |||d<   |||d<   |                     |                     ||                     d{V }|                     |dg           }|                     |||||          S )	aY  
        fetch a history of internal transfers made on an account
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-3-months
        :param str code: unified currency code of the currency transferred
        :param int [since]: the earliest time in ms to fetch transfers for
        :param int [limit]: the maximum number of transfers structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transfer structures <https://docs.ccxt.com/#/?id=transfer-structure>`
        Nr  r   r<   r  rA  r  rV  )r  rv  rS  r  rd  parse_transfers)	r  rw  r.  r  r  rv  r  rh  	transferss	            r  fetch_transferszokx.fetch_transfers  s       !!!!!!!!!C
 }}T**H%d^GEN$GG$GG;;DKKQW<X<XYYYYYYYYB NN8VR88	##IxvNNNr  r   GETc                 .   t          |t                    }d| j        z   dz   |                     ||          z   }|                     ||                     |                    }	|                     | j        d         d                   |z   }
|dk    r|	r|
d|                     |	          z   z  }
n|dk    r| 	                                 |dk    r|d	k    s|d
k    s|dk    r| 
                    | j        dd          }t          |t                    ret          dt          |                    D ]F}||         }| 
                    |d          }|$||                                 z   |d<   ||d<   |||<   Gn7| 
                    |d          }|||                                 z   |d<   ||d<   |                     |                                           }| j        | j        |d}||z   |z   }|dk    r%|	r"d|                     |	          z   }|
|z  }
||z  }n#|s|	r|                     |	          }||z  }d|d<   |                     |                     |          |                     | j                  t.          j        d          }||d<   |
|||dS )Nz/api/r&  r   r   r   ?r   POSTr   r   r   r  r  r   r  r  )zOK-ACCESS-KEYzOK-ACCESS-PASSPHRASEzOK-ACCESS-TIMESTAMPr  zapplication/jsonzContent-Typebase64zOK-ACCESS-SIGN)r   r  bodyheaders)r  r  rB   implode_paramsr  extract_paramsimplode_hostnamer   	urlencoder  r  r	  rf  re  r  r  rJ  r   r   jsonhmacencoder   hashlibsha256)r  pathr   r  r  r  r  isArrayr  r  r   r  rk  r  r  rL  authurlencodedQuery	signatures                      r  signzokx.sign*  s   VT**DL(3.1D1DT61R1RR		&$"5"5d";";<<##DIe$4V$<==G(?? 3sT^^E2222I++---T-A%A%ATM_E_E_cgkxcxcx++DL*FXYYfd++ 1"1c&kk22 . . &q	(,(8(8	(J(J(0/7$++--/GE),+3E%L(-F1I. %)$4$4VY$G$GM$,,4t{{}},Dy)(0uT%6%6%8%899I!%(,'0 G v%/D ,&)DNN5,A,A&AO?*CO+D !e !99U++DDLD*<'		$++d"3"3T[[5M5Mw~_ghhI(1G$%fdwOOOr  c                    |                      |d          }|                     |d          }|                     ||          }|                     |d          }|                      |d          }i d|d|dd dd d	|                     d
          dd dd dd d|                     |d          d|d|                     |          d|d|d|                     |          dd dd dd S )NnextFundingTimer  nextFundingRater\  rD  r"  r  
indexPriceinterestRater%  estimatedSettlePricerL  rK  r^  fundingTimestampfundingDatetimenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetime)rg  r  r`  r  r  r  )r  r<  r  nextFundingRateTimestamprN  r"  r.  r\  s           r  parse_funding_ratezokx.parse_funding_rate]  sz    $(#4#4X?P#Q#Q ##Hh77!!(F33**85FGG''-@@
H
f
 
 $	

 D--c22
 #D
 
 
 4++HmDD
 
 t||K88
 
 #$<
 "4<<0H#I#I
 "4
  '!
" &t#
 	
r  c                   K   |                                   d{V  |                     |          }|d         st          | j        dz             d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     ||          S )aq  
        fetch the current funding rate
        :see: https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        NrK   z2 fetchFundingRate() is only valid for swap marketsr  r<   rV  r   )	r  r  r"   r<   publicGetPublicFundingRater  rd  r  r:  )r  r"  r  r  r  rh  rV  r  s           r  fetch_funding_ratezokx.fetch_funding_rate  s       !!!!!!!!!V$$f~ 	`*^ ^___fTl
 88Wf9U9UVVVVVVVV" ~~h33tQ++&&uf555r  c                 N  K   |                                   d{V  ddi}|t          |          |d<   d}|N|                     |          }|d         }|d         r)|d         rd|d<   |d	         |d
<   nd|d<   |d         |d
<   |                     d||          \  }}|dk    r|                     |          |d<   |                     |                     ||                     d{V }	|                     |	dg           }
g }t          dt          |
                    D ]}|
|         }| 
                    |d          }|                     |d          }|                     |          }|                     |d
          }|                     |          }|                    ||d         |||                     |          |                     |d          |                     |d          d           |                     |d          }|                     ||||          S )a]  
        fetch the history of funding payments paid and received on self account
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-3-months
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
        Nr  r]  r  r"  r<  r0  ctTyper-  r  r1  r,  r|   rK   r  rV  r   ro  r  rc  rd  )rD  r"  rw  rL  rK  r<   r6  rL  )r  r  r  r  r!  rS  r  rd  rf  re  rg  r  rS  r  ry  r  r  ra  rb  )r  r"  r.  r  r  r  r  r  r  rh  rV  rz  rk  r  rL  r  marketInnerr  rw  re  s                       r  fetch_funding_historyzokx.fetch_funding_history  s|      !!!!!!!!! CK
X "5zzGG[[((FH%Fj! 6(# 6(0GH%%+I%6GENN(1GH%%+H%5GEN889NPVX^__e6>>"&"A"A$"G"GGJ;;DKKQV<W<WXXXXXXXX2 ~~h33q#d))$$ 	 	AGE))%66I%%eX66F**622K))%77J**:66DMM%h/& LL33&&uh77**5(;;      fk2200NNNr  r  c                   K   |t          | j        dz             |dk     s|dk    rt          | j        dz             |                                  d{V  |                     |          }d}|                     d|          \  }}||                     |dd          }|dk    r|d	k    rt          | j        d
z             |||d         d}|                     |d          }|d	k    rB|t          | j        dz             |dk    r#|dk    r|dk    rt          | j        dz             |                     |                     ||                     d{V }|S )a%  
        set the level of leverage for a market
        :see: https://www.okx.com/docs-v5/en/#rest-api-account-set-leverage
        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated'
        :param str [params.posSide]: 'long' or 'short' for isolated margin long/short mode on futures and swap markets
        :returns dict: response from the exchange
        Nz) setLeverage() requires a symbol argumentr   }   z3 setLeverage() leverage should be between 1 and 125r   rQ  r  r  zT setLeverage() requires a marginMode parameter that must be either cross or isolatedr<   r  rQ  r  r  z> setLeverage() requires a posSide argument for isolated marginr  r  r  zR setLeverage() requires the posSide argument to be either "long", "short" or "net")	r'   r<   r(   r  r  rT  r  privatePostAccountSetLeverager  )	r  r  r"  r  r  r  r  r  rh  s	            r  set_leveragezokx.set_leverage?  s      >#DG.Y$YZZZ qLLhnnTW'\\]]]!!!!!!!!!V$$
!??vVV
F))&)WEEJ'!!
j(@(@TW'}}~~~!Tl
 

 ""6955##'2r(rsss&  W%7%7Gu<L<L +!  A  A  A;;DKKQW<X<XYYYYYYYY r  r  c                    K   d}|rd}nd}d|i}|                      |                     ||                     d{V }|S )a  
        set hedged to True or False for a market
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-set-position-mode
        :param bool hedged: set to True to use long_short_mode, False for net_mode
        :param str symbol: not used by okx setPositionMode
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        Nlong_short_modenet_modeposMode)!privatePostAccountSetPositionModer  )r  r  r"  r  	hedgeModer  rh  s          r  set_position_modezokx.set_position_modet  sj       	 	#)II"Iy
 ??GU[@\@\]]]]]]]] r  r  c                 $  K   |t          | j        dz             |                                }|dk    r|dk    rt          | j        dz             |                                  d{V  |                     |          }|                     |dd          }||dk     s|d	k    rt          | j        d
z             |                     |dg          }|||d         d}|                     | 	                    ||                     d{V }|S )a  
        set margin mode to 'cross' or 'isolated'
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-set-leverage
        :param str marginMode: 'cross' or 'isolated'
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.leverage]: leverage
        :returns dict: response from the exchange
        Nz+ setMarginMode() requires a symbol argumentr  r  z< setMarginMode() marginMode must be either cross or isolatedr  r  r   rC  z< setMarginMode() params["lever"] should be between 1 and 125r<   rD  )
r'   r<   rI  r(   r  r  rC  r  rE  r  )r  r  r"  r  r  r  r  rh  s           r  set_margin_modezokx.set_margin_mode  sC      >#DG.[$[\\\  %%''
'!!
j(@(@TW'eefff!!!!!!!!!V$$##FGZ@@MuqyyeckkTW'eefff6J<00!Tl
 

 ;;DKKQW<X<XYYYYYYYY r  c                 B  K   |                                   d{V  |                     |           d{V }|                     |dg           }g }t          dt	          |                    D ]0}|                    |                     ||                              1|S )a_  
        fetch the borrow interest rates of all currencies
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-interest-rate
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `borrow rate structures <https://docs.ccxt.com/#/?id=borrow-rate-structure>`
        NrV  r   )r  privateGetAccountInterestRaterd  rf  re  ry  parse_borrow_rate)r  r  rh  rV  rc  rk  s         r  fetch_cross_borrow_rateszokx.fetch_cross_borrow_rates  s       !!!!!!!!!;;FCCCCCCCC ~~h33q#d))$$ 	: 	:ALL//Q889999r  c                 \  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     |          S )a  
        fetch the rate of interest to borrow a currency for margin trading
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-interest-rate
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `borrow rate structure <https://docs.ccxt.com/#/?id=borrow-rate-structure>`
        Nr  r<   rV  r   )r  rv  rQ  r  rd  r  rR  )r  rw  r  rv  r  rh  rV  rd  s           r  fetch_cross_borrow_ratezokx.fetch_cross_borrow_rate  s       !!!!!!!!!==&&8D>
 ;;DKKQW<X<XYYYYYYYY ~~h33~~dAr**%%d+++r  c                     |                      |d          }|                     |d          }|                     |          |                     |dd          d||                     |          |dS )Nr  ro  r0  rd  i \&)rv  rd  periodrL  rK  rD  )r  rg  r  r  r  )r  rD  rv  r  rL  s        r  rR  zokx.parse_borrow_rate  s{     tU++%%dD11	//44&&t^VDD"Y//
 
 	
r  c                 "   i }t          dt          |                    D ]}||         }|                     |                     |d                    }||                     ||          r9||vrg ||<   |                     |          }	||                             |	           t          |                                          }
t          dt          |
                    D ]+}|
|         }| 	                    ||         |||          ||<   ,|S )Nr   r  )
rf  re  r  r  in_arrayrR  ry  r  r  filter_by_currency_since_limit)r  rh  codesr.  r  borrowRateHistoriesrk  rg  rw  borrowRateStructurer  s              r  parse_borrow_rate_historieszokx.parse_borrow_rate_histories  s*    !q#h--(( 	F 	FAA;D**4+;+;D%+H+HIID}dE : :} 33302'-&*&<&<T&B&B##D)001DEEE',,..//q#d))$$ 	{ 	{A7D(,(K(KL_`dLegkmrty(z(z%%""r  c                    g }t          dt          |                    D ]4}||         }|                     |          }|                    |           5|                     |d          }	|                     |	|||          S )Nr   rL  )rf  re  rR  ry  ra  rZ  )
r  rh  rw  r.  r  rz  rk  rg  
borrowRatere  s
             r  parse_borrow_rate_historyzokx.parse_borrow_rate_history)  s    q#h--(( 	& 	&AA;D//55JMM*%%%%fk222264NNNr  c                   K   |                                   d{V  i }|||d<   |||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        retrieves a history of a multiple currencies borrow interest rate at specific time slots, returns all currencies if no symbols passed, default is None
        :see: https://www.okx.com/docs-v5/en/#financial-product-savings-get-public-borrow-history-public
        :param str[]|None codes: list of unified currency codes, default is None
        :param int [since]: timestamp in ms of the earliest borrowRate, default is None
        :param int [limit]: max number of borrow rate prices to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `borrow rate structures <https://docs.ccxt.com/#/?id=borrow-rate-structure>` indexed by the market symbol
        NrB  r  rV  )r  )publicGetFinanceSavingsLendingRateHistoryr  rd  r^  )r  r[  r.  r  r  r  rh  rV  s           r  fetch_borrow_rate_historieszokx.fetch_borrow_rate_histories2  s       !!!!!!!!!
  %GH$GGGGT[]cHdHdeeeeeeee ~~h33//eUEJJJr  c                 P  K   |                                   d{V  |                     |          }d|d         i}|||d<   |||d<   |                     |                     ||                     d{V }|                     |dg           }|                     ||||          S )a  
        retrieves a history of a currencies borrow interest rate at specific time slots
        :see: https://www.okx.com/docs-v5/en/#financial-product-savings-get-public-borrow-history-public
        :param str code: unified currency code
        :param int [since]: timestamp for the earliest borrow rate
        :param int [limit]: the maximum number of `borrow rate structures <https://docs.ccxt.com/#/?id=borrow-rate-structure>` to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of `borrow rate structures <https://docs.ccxt.com/#/?id=borrow-rate-structure>`
        Nr  r<   rB  r  rV  )r  rv  rc  r  rd  ra  )	r  rw  r.  r  r  rv  r  rh  rV  s	            r  fetch_borrow_rate_historyzokx.fetch_borrow_rate_historyY  s       !!!!!!!!!==&&8D>
  %GH$GGGGT[]cHdHdeeeeeeee ~~h33--dD%GGGr  c                 (  K   |                                   d {V  |                     |          }|                     |dd          }|                     |dg          }|d         |||d}|                     |                     ||                     d {V }|                     |dg           }	|                     |	di           }
|                     |d          }|                     |                     |
|          d|d	k    rd
ndi          S )Nr  r  r<   )r  r  r  r  rV  r   rw  rZ  r%  rW  r  )	r  r  r  r  'privatePostAccountPositionMarginBalancer  rd  r  parse_margin_modification)r  r"  r6  r  r  r  r  r  rh  rV  r  	errorCodes               r  modify_margin_helperzokx.modify_margin_helper  s<     !!!!!!!!!V$$""69e<<6I;//Tl	
 
 EEdkkRY[aFbFbcccccccc ~~h33tQ++$$Xv66	{{499%HHyC//ddhK
   	r  c                    |                      |dd          }|                     |d          }d }|dk    rt          j        |d          rdnd}n|}t          j        |          }|                     |d          }|                     ||          }|d	         r|d
         n|d         }	|                     |d          }
||d         |d|                     |          |	d d |
|                     |
          d
S )Nr  	posBalChgr  r  r%  addreducer  r1  r)  r*  ro  r"  r  )
rD  r"  r  r  r6  rw  rt  rZ  rL  rK  )	r  r  r8   r  r  rS  rg  r  r  )r  rV  r  	amountRawtypeRawr  r6  rN  responseMarketrw  rL  s              r  ri  zokx.parse_margin_modification  s   ` &&tUK@@	""400c>>#-i==K558DDD#I..##D(33))(F;;)7	)B_~f%%W^H_%%dD11	$X.$''//"Y//
 
 	
r  c                 B   K   |                      ||d|           d{V S )a  
        remove margin from a position
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-increase-decrease-margin
        :param str symbol: unified market symbol
        :param float amount: the amount of margin to remove
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=reduce-margin-structure>`
        ro  Nrk  r  r"  r6  r  s       r  reduce_marginzokx.reduce_margin  s4       ..vvxPPPPPPPPPr  c                 B   K   |                      ||d|           d{V S )a  
        add margin
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-increase-decrease-margin
        :param str symbol: unified market symbol
        :param float amount: amount of margin to add
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin structure <https://docs.ccxt.com/#/?id=add-margin-structure>`
        rn  Nrt  ru  s       r  
add_marginzokx.add_margin  s4       ..vvufMMMMMMMMMr  c                 x  K   |                                   d{V  |                     |          }|d         rdn|                     |d                   }|                     |d         d          }|s |dk    rt	          | j        dz   |z             d}|                     d|          \  }}||                     |d	d
          }|||d}|dk    r|d         |d<   |                     |                     ||                     d{V }| 	                    |dg           }	| 
                    |	|          S )a  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market
        :see: https://www.okx.com/docs-v5/en/#rest-api-public-data-get-position-tiers
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.marginMode]: 'cross' or 'isolated'
        :returns dict: a `leverage tiers structure <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`
        NrI   r  r  rD  r  z< fetchMarketLeverageTiers() cannot fetch leverage tiers for r   r  r  )r  r  r  r<   r  rV  )r  r  r!  r  r(   r<   rT  publicGetPublicPositionTiersr  rd  parse_market_leverage_tiers)
r  r"  r  r  r  r  r  r  rh  rV  s
             r  fetch_market_leverage_tierszokx.fetch_market_leverage_tiers  sz      !!!!!!!!!V$$!&>^xxt/N/NvV\~/^/^vf~u55 	tx +i!ilr!rsss
!??@Z\bcc
F))&(GDDJ 
 

 8 &tGH::4;;wPV;W;WXXXXXXXX, ~~h33//f===r  c                 h   g }t          dt          |                    D ]}||         }|                    |                     |d          |d         |                     |d          |                     |d          |                     |d          |                     |d          |d           |S )	z}
         * @ignore
        :param dict info: Exchange response for 1 market
        :param dict market: CCXT market
        r   tierr*  r  maxSzr  maxLever)r~  rv  minNotionalmaxNotionalmaintenanceMarginRater  rD  )rf  re  ry  rg  r  )r  rD  r  tiersrk  r~  s         r  r{  zokx.parse_market_leverage_tiers5  s    0 q#d))$$ 
	 
	A7DLL))$77"7O#//g>>#//g>>)-)9)9$)F)F#//jAA      r  c                 >  K   |                                   d{V  d}|                     d|          \  }}||                     |dd          }d|i}d}| |                     |          }	|	d         |d<   ||dz
  |d<   |||d	<   | |                     |          }|d         |d
<   |                     |                     ||                     d{V }
|                     |
dg           }|                     |          }| 	                    ||||          S )a  
        fetch the interest owed by the user for borrowing currency for margin trading
        :see: https://www.okx.com/docs-v5/en/#rest-api-account-get-interest-accrued-data
        :param str code: the unified currency code for the currency of the interest
        :param str symbol: the market symbol of an isolated margin market, if None, the interest for cross margin markets is returned
        :param int [since]: timestamp in ms of the earliest time to receive interest records for
        :param int [limit]: the number of `borrow interest structures <https://docs.ccxt.com/#/?id=borrow-interest-structure>` to retrieve
        :param dict [params]: exchange specific parameters
        :param int [params.type]: Loan type 1 - VIP loans 2 - Market loans *Default is Market loans*
        :param str [params.marginMode]: 'cross' or 'isolated'
        :returns dict[]: An list of `borrow interest structures <https://docs.ccxt.com/#/?id=borrow-interest-structure>`
        Nrh   rQ  r  r<   r  r   rB  r  r  rV  )
r  rT  r  rv  r   privateGetAccountInterestAccruedr  rd  parse_borrow_interestsrZ  )r  rw  r"  r.  r  r  r  r  r  rv  rh  rV  interests                r  fetch_borrow_interestzokx.fetch_borrow_interest[  sb      !!!!!!!!!
!??@UW]^^
F))&)WEEJz
 }}T**H%d^GEN %	GH$GG[[((F &tGH>>t{{7TZ?[?[\\\\\\\\( ~~h33..t44228T5%PPPr  c           
         |                      |d          }||                     ||          }|                     |d          }|                      |d          |                      |d          |                     |                      |d                    |                     |d          |                     |d          |                     |d          ||                     |          |d		S )
Nr  ro  r"  rQ  r  r  r0  liab)	r"  r  rv  r  r0  amountBorrowedrL  rK  rD  )r  rS  rg  r  r  r  )r  rD  r  r  rL  s        r  parse_borrow_interestzokx.parse_borrow_interest  s    !!$11%%ff55F%%dD11	&&vx88**4;;//0@0@u0M0MNN((z:: ,,T>BB"..tV<<"Y//

 

 
	
r  c                   K   |                                   d{V  |                     |          }|d         |                     ||          dd}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     ||          S )a  
        create a loan to borrow margin(need to be VIP 5 and above)
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-vip-loans-borrow-and-repay
        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        Nr<   borrow)r  r  r  rV  r   )r  rv  r  privatePostAccountBorrowRepayr  rd  r  parse_margin_loan)	r  rw  r6  r  rv  r  rh  rV  loans	            r  borrow_cross_marginzokx.borrow_cross_margin  s       !!!!!!!!!==&&D>--dF;;
 

 ;;DKKQW<X<XYYYYYYYY  ~~h33~~dAr**%%dH555r  c                   K   |                                   d{V  |                     |dd          }|                     |d          }|t          | j        dz             |                     |          }|d         |                     ||          d|d}|                     |                     ||                     d{V }| 	                    |dg           }| 
                    |di           }	|                     |	|          S )	a#  
        repay borrowed margin and interest
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-vip-loans-borrow-and-repay
        :param str code: unified currency code of the currency to repay
        :param float amount: the amount to repay
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.id]: the order ID of borrowing, it is necessary while repaying
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        Nr<   r  z, repayCrossMargin() requires an id parameterrepay)r  r  r  r  rV  r   )r  r  r  r'   r<   rv  r  r  r  rd  r  r  )
r  rw  r6  r  r<   rv  r  rh  rV  r  s
             r  repay_cross_marginzokx.repay_cross_margin  s&      !!!!!!!!!g6664((:#DG.\$\]]]==&&D>--dF;;	
 
 ;;DKKQW<X<XYYYYYYYY  ~~h33~~dAr**%%dH555r  c                     |                      |d          }d |                     ||          |                     |d          d d d |dS )Nr  r  )r<   rv  r6  r"  rL  rK  rD  )r  r  r  )r  rD  rv  r  s       r  r  zokx.parse_margin_loan  s]     %%dE22
//
HEE&&tU33
 
 	
r  c                   K   |                                   d{V  |                     |          }|d         st          | j        dz             |                     |d                   }|                     |d         d          }|||d         d}|                     |                     ||                     d{V }|                     |d	g           }| 	                    |d
         |          S )an  
        Retrieves the open interest of a currency
        :see: https://www.okx.com/docs-v5/en/#rest-api-public-data-get-open-interest
        :param str symbol: Unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict} an open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure:
        Nr<  z3 fetchOpenInterest() supports contract markets onlyr  rD  r  r<   )r  r  r  rV  r   )
r  r  r(   r<   r!  r  publicGetPublicOpenInterestr  rd  parse_open_interest)	r  r"  r  r  r  r  r  rh  rV  s	            r  fetch_open_interestzokx.fetch_open_interest	  s      !!!!!!!!!V$$j! 	^TW'\\]]]..vf~>>vf~u55Tl
 

 99$++gv:V:VWWWWWWWW  ~~h33''Q888r  r   c                   K   |                      | j        di           }|                      |di           }|                     |||          }|dk    r#|dk    r|dk    rt          | j        dz             |                                  d{V  d}d}	|| j        v s	|| j        v r|                     |          }	|	d         }n| 	                    |          }
|
d	         }||d
}d}d}| 
                    d|	|          \  }}|dk    r0|                     |                     ||                     d{V }nl|||d<   |                     |dd          }|||d<   |                     |ddg          }|                     |                     ||                     d{V }|                     |dg           }|                     |d||          S )ab  
        Retrieves the open interest history of a currency
        :see: https://www.okx.com/docs-v5/en/#rest-api-trading-data-get-contracts-open-interest-and-volume
        :see: https://www.okx.com/docs-v5/en/#rest-api-trading-data-get-options-open-interest-and-volume
        :param str symbol: Unified CCXT currency code or unified symbol
        :param str timeframe: "5m", "1h", or "1d" for option only "1d" or "8h"
        :param int [since]: The time in ms of the earliest record to retrieve unix timestamp
        :param int [limit]: Not used by okx, but parsed internally by CCXT
        :param dict [params]: Exchange specific parameters
        :param int [params.until]: The time in ms of the latest record to retrieve unix timestamp
        :returns: An array of `open interest structures <https://docs.ccxt.com/#/?id=open-interest-structure>`
        r   r   r   r   r   zF fetchOpenInterestHistory cannot only use the 5m, 1h, and 1d timeframeNr,  r<   )r  rW  rM   rA  rB  rC  r]  rV  )r  r	  r  r(   r<   r  r  rR  r  rv  r  *publicGetRubikStatOptionOpenInterestVolumer  rC  r  -publicGetRubikStatContractsOpenInterestVolumerd  parse_open_interests)r  r"  rS  r.  r  r  r	  r   r  r  rv  r  r  rh  rC  rV  s                   r  fetch_open_interest_historyzokx.fetch_open_interest_history/  s5      ../I2NN^^G\2>>
$$ZIFF	d!2!2yD7H7HTW'ooppp!!!!!!!!!
dl""$2D(D(D[[((F)JJ}}V,,H!$J
 
 99:TV\^deef8!LLT[[Y`bhMiMijjjjjjjjHH #( ''@@E !&6GV+<==!OOPTP[P[\cekPlPlmmmmmmmmH ~~h33((tUEBBBr  c                    |                      |d          }|                     ||          }|                     |d          }|                     |d|          }d }d }d }d }	|                      | j        d          }
t	          |t
                    r`|
dk    r-|                     |d          }|                     |d          }no|                     |d          }	|                     |d          }nB|                     |d          }|                     |d	          }|                     |d          }	|                     |                     |          ||||	|| 	                    |          |d
|          S )Nr  ro  r   r  rM   r   r   oiCcyoi)r"  r  r  openInterestAmountopenInterestValuerL  rK  rD  )
r  rS  rg  r	  r  r  r  safe_open_interestr`  r  )r  r  r  r<   timerL  r  r  r  r  r  s              r  r  zokx.parse_open_interestm  s   ( h11!!"f--  400%%h488	
! m<<h%% 
	Dx%)%5%5h%B%B"!--h::

$($4$4Xq$A$A!"..x;;))(G<<J!%!1!1(D!A!A $ 0 07 C C&&&&r**$&"4!2"Y//	(
 	(
 	 	 		r  enablec                     t          t          |                               |           || j        d<   |rd| j        d<   d S d| j        v r"|                     | j        d          | _        d S d S )NrK  r   zx-simulated-trading)r  r:   set_sandbox_moder	  r  r  )r  r  r  s     r  r  zokx.set_sandbox_mode  sz    c4))&111&,]# 	J25DL.///"dl2299T\3HIIDLLL 32r  r[  c                    K   |                                   d{V  |                     |           d{V }|                     |d          }|                     ||          S )au  
        fetch deposit and withdraw fees
        :see: https://www.okx.com/docs-v5/en/#rest-api-funding-get-currencies
        :param str[]|None codes: list of unified currency codes
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `fees structures <https://docs.ccxt.com/#/?id=fee-structure>`
        NrV  )r  r  rd  parse_deposit_withdraw_fees)r  r[  r  rh  rV  s        r  fetch_deposit_withdraw_feeszokx.fetch_deposit_withdraw_fees  s}       !!!!!!!!!77????????X ~~h////e<<<r  c                    i }|                      |          }t          dt          |                    D ]}||         }|                     |d          }|                     |          }||                     ||          r|                     ||          }	|	|                     i           ||<   |||         d         |<   |                     |d          }
|
                    d          }|                     |d          }| 	                    |d          }||dnd d	}d d d	}| 
                    ||          }||d
||         d         |<    t          |                                          }t          dt          |                    D ]>}||         }|                     |          }|                     ||         |          ||<   ?|S )Nr   r  rD  r  r%  r   r  F)r  r  )r   r  rS  )market_codesrf  re  r  r  rY  r  deposit_withdraw_feerE  r  r  r  r  rv  $assign_default_deposit_withdraw_fees)r  rh  r[  currencyIdKeydepositWithdrawFeesrk  feeInfor  rw  depositWithdrawFeer  
chainSplitr  withdrawFeewithdrawResultdepositResultr  depositWithdrawCodesrv  s                      r  r  zokx.parse_deposit_withdraw_fees  s   , !!!%((q#h--(( 	 	AqkG))'599J**:66D4==u#=#=%)__5H$%O%O"%-040I0I"0M0M'-@G#D)&1*=(('::"[[--
 OOJ::	"..wAA&,7,C%%$" "
  "&! ! #55iFF .,F F#D)*5kB  $$7$<$<$>$>??q#23344 	w 	wA'*D}}T**H(,(Q(QRefjRkmu(v(v%%""r  c                   K   |t          | j        dz             |                                  d{V  |                     |          }d}|                     d||          \  }}|dk    r|dk    rt          | j        dz             |                     |          |d         dz   |d	         z   d
}||dz
  |d<   |||d<   |                     |                     ||                     d{V }| 	                    |dg           }	| 
                    |	|          }
|                     |
d          }|                     ||d         ||          S )a  
        fetches historical settlement records
        :see: https://www.okx.com/docs-v5/en/#rest-api-public-data-get-delivery-exercise-history
        :param str symbol: unified market symbol to fetch the settlement history for
        :param int [since]: timestamp in ms
        :param int [limit]: number of records
        :param dict [params]: exchange specific params
        :returns dict[]: a list of `settlement history objects <https://docs.ccxt.com/#/?id=settlement-history-structure>`
        Nz4 fetchSettlementHistory() requires a symbol argumentr   rL   rM   zC fetchSettlementHistory() supports futures and options markets onlyr,  r%  r-  )r  r  r   rB  r  rV  rL  r"  )r'   r<   r  r  r  r0   r!  &publicGetPublicDeliveryExerciseHistoryr  rd  parse_settlementsra  rb  )r  r"  r.  r  r  r  r  r  rh  rV  settlementsre  s               r  fetch_settlement_historyzokx.fetch_settlement_history  s      >#DG.d$deee!!!!!!!!!V$$99:RTZ\bccf8 0 0tw)nnooo77==(#c)F9,==
 
  %	GH$GGDDT[[QXZ`EaEabbbbbbbb& ~~h33,,T6::k;77009I5RWXXXr  c                     |                      |d          }||                     ||          |                     |d          d d dS )NinsIdr  )rD  r"  r7  rL  rK  )r  r`  r  )r  
settlementr  rN  s       r  parse_settlementzokx.parse_settlementK  sW     ##J88&&x88%%j$77
 
 	
r  c                    g }t          dt          |                    D ]}||         }|                     |d          }|                     |dg           }t          dt          |                    D ]]}|                     ||         |          }	|                    |                     |	||                     |          d                     ^|S )Nr   ro  rm  )rL  rK  )rf  re  rg  rd  r  ry  r  r  )
r  r  r  rz  rk  r  rL  rm  r  r  s
             r  r  zokx.parse_settlements\  s     q#k**++ 		 		ANE))%66InnUIr::G1c'll++  !2271:vFF
dkk*!* $Y 7 77 7       r  c                   K   |                                   d{V  d}|                     dd|          \  }}||dk    rd}|dk    r#|dk    r|dk    rt          | j        dz             d|                     |          i}|                     |                     ||                     d{V }|                     |d	g           }|d
         S )a  
        fetches the market ids of underlying assets for a specific contract market type
        :see: https://www.okx.com/docs-v5/en/#public-data-rest-api-get-underlying
        :param dict [params]: exchange specific params
        :param str [params.type]: the contract market type, 'option', 'swap' or 'future', the default is 'option'
        :returns dict[]: a list of `underlying assets <https://docs.ccxt.com/#/?id=underlying-assets-structure>`
        Nr   rI   rM   rK   rL   z7 fetchUnderlyingAssets() supports contract markets onlyr  rV  r   )r  r  r0   r<   r!  publicGetPublicUnderlyingr  rd  )r  r  rP  r  rh  underlyingss         r  fetch_underlying_assetszokx.fetch_underlying_assetsv  s      !!!!!!!!!
!??@WY]_eff
FJ&$8$8!J(""v)=)=JRZDZDZtw)bbccc77
CC
 77GV8T8TUUUUUUUU nnXvr::1~r  c                 J  K   |                                   d{V  |                     |          }|d         }|                    d          }|d         d         |d         d         |                     |d          d}|                     |                     ||                     d{V }|                     |d	g           }t          d
t          |                    D ]>}	||	         }
|                     |
d          }||k    r| 	                    |
|          c S ?dS )a  
        fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract
        :see: https://www.okx.com/docs-v5/en/#public-data-rest-api-get-option-market-data
        :param str symbol: unified symbol of the market to fetch greeks for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `greeks structure <https://docs.ccxt.com/#/?id=greeks-structure>`
        Nr<   r%  rD  r  rF  r   )r  rF  r  rV  r   r  )
r  r  rE  r  publicGetPublicOptSummaryr  rd  rf  re  parse_greeks)r  r"  r  r  rN  rI  r  rh  rV  rk  r  entryMarketIds               r  fetch_greekszokx.fetch_greeks  sH      !!!!!!!!!V$$$<nnS))&>%( .6''Q77
 

 77GV8T8TUUUUUUUU< ~~h33q#d))$$ 	8 	8AGE ,,UH==M((((77777 )tr  c                 8   |                      |d          }|                     |d          }|                     ||          }i d|d|d|                     |          d|                     |d          d|                     |d          d|                     |d          d	|                     |d	          d
d dd dd d|                     |d          d|                     |d          d|                     |d          dd dd dd dd d |dS )Nro  r  r"  rL  rK  deltagammathetavegarhobidSizeaskSizebidImpliedVolatilitybidVolaskImpliedVolatilityaskVolmarkImpliedVolatilitymarkVolbidPriceaskPricer  r  )underlyingPricerD  )rg  r  r`  r  r  )r  greeksr  rL  rN  r"  s         r  r  zokx.parse_greeks  s   0 %%fd33	##FH55!!(F33
f

 Y//
 T%%fg66	

 T%%fg66
 T%%fg66
 D$$VV44
 4
 t
 t
 #D$4$4VX$F$F
 #D$4$4VX$F$F
 $T%5%5fi%H%H
 
 
  !
" #
$  $'
 
 
 	
r  c                 ~  K   |                                   d{V  |                     |          }|                     |d          }|                     |d          }d}|                     d|d          \  }}|d         |d}||dk    rd	|d
<   n|dk    rd|d
<   n||d
<   |||d<   | |                     |          }	|	d         |d<   |                     |                     ||                     d{V }
|                     |
dg           }|                     |d          }| 	                    ||          S )ad  
        closes open positions for a market
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-close-positions
        :param str symbol: Unified CCXT market symbol
        :param str [side]: 'buy' or 'sell', leave in net mode
        :param dict [params]: extra parameters specific to the okx api endpoint
        :param str [params.clientOrderId]: a unique identifier for the order
        :param str [params.marginMode]: 'cross' or 'isolated', default is 'cross
        :param str [params.code]: *required in the case of closing cross MARGIN position for Single-currency margin* margin currency
         *
         * EXCHANGE SPECIFIC PARAMETERS
        :param boolean [params.autoCxl]: whether any pending orders for closing out needs to be automatically canceled when close position via a market order. False or True, the default is False
        :param str [params.tag]: order tag a combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters
        :returns dict[]: `A list of position structures <https://docs.ccxt.com/#/?id=position-structure>`
        Nr  rw  rS   r  r<   r  r  r  r  r  r  r  r  rV  r   )
r  r  r  rT  rv  privatePostTradeClosePositionr  rd  r  r  )r  r"  r  r  r  r  rw  r  r  rv  rh  rV  r#  s                r  close_positionzokx.close_position   s       !!!!!!!!!V$$((AA//
!??QWY`aa
FTl!
 
 %+	""%,	""%)	"$!.GI}}T**H%d^GEN;;DKKQW<X<XYYYYYYYY$ ~~h33tQ''v...r  c                 `  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     |d|          S )a  
        fetches option data that is commonly found in an option chain
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-ticker
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `option chain structure <https://docs.ccxt.com/#/?id=option-chain-structure>`
        Nr  r<   rV  r   )r  r  r  r  rd  r  parse_option)r  r"  r  r  r  rh  rz  r  s           r  fetch_optionzokx.fetch_option<  s       !!!!!!!!!V$$fTl
 33DKK4P4PQQQQQQQQ6 &"55vq"--  f555r  c                 :  K   |                                   d{V  |                     |          }|d         dz   dd}|                     |                     ||                     d{V }|                     |dg           }|                     |dd          S )a*  
        fetches data for an underlying asset that is commonly found in an option chain
        :see: https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-tickers
        :param str currency: base currency to fetch an option chain for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.uly]: the underlying asset, can be obtained from fetchUnderlyingAssets()
        :returns dict: a list of `option chain structures <https://docs.ccxt.com/#/?id=option-chain-structure>`
        Nrw  z-USDr  )r  r  rV  r  )r  rv  r  r  rd  parse_option_chain)r  rw  r  rv  r  rh  rz  s          r  fetch_option_chainzokx.fetch_option_chainh  s       !!!!!!!!!==&&F#f, 
 
 44T[[&5Q5QRRRRRRRR6 &"55&&vtX>>>r  c                    |                      |d          }|                     ||          }|                     |d          }i d|dd d|d         d|d|                     |          dd d	d d
|                     |d          d|                     |d          dd dd d|                     |d          dd dd dd d|                     |d          dd S )Nr  ro  rD  rv  r"  rL  rK  impliedVolatilityopenInterestr  r  r  r  midPricer  r  r  r  r  r  r  r  r  )r  rS  rg  r  r  )r  r  rv  r  rN  rL  s         r  r  zokx.parse_option  sf   * ##E844!!(F33%%eT22	
E

 fX&
 	

 Y//
  
 D
 ((88
 ((88
 
 
 ))%88
 t
 d
 $
  $**5+>>!
" 4#
 	
r  fromCodetoCodec                 t  K   |                                   d{V  |                                |                                |                                |                     |          dd}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }|                     |d|          }	|                     |	          }
|                     |d|          }|                     |          }| 	                    ||
|          S )aP  
        fetch a quote for converting from one currency to another
        :see: https://www.okx.com/docs-v5/en/#funding-account-rest-api-estimate-quote
        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float [amount]: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        Nr  )r  r  rfqSzCcyrfqSzr  rV  r   r  r  )
r  r  r  $privatePostAssetConvertEstimateQuoter  rd  r  r  rv  parse_conversion)r  r  r  r6  r  r  rh  rV  rz  fromCurrencyIdfromCurrencytoCurrencyId
toCurrencys                r  fetch_convert_quotezokx.fetch_convert_quote  s;      !!!!!!!!!~~'' ((**622
 
 BB4;;wX^C_C_````````0 ~~h33a,,))&)XFF}}^44''
FCC]]<00
$$V\:FFFr  c                 
  K   |                                   d{V  |||||                     |          dd}|                     |                     ||                     d{V }|                     |dg           }|                     |di           }	|                     |	d|          }
|                     |
          }|                     |	d|          }|                     |          }|                     |	||          S )a{  
        convert from one currency to another
        :see: https://www.okx.com/docs-v5/en/#funding-account-rest-api-convert-trade
        :param str id: the id of the trade that you want to make
        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float [amount]: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        Nr  )r-  r  r  szCcyr  r  rV  r   r  r  )	r  r  privatePostAssetConvertTrader  rd  r  r  rv  r  )r  r<   r  r  r6  r  r  rh  rV  rz  r  r  r  r  s                 r  create_convert_tradezokx.create_convert_trade  s"      !!!!!!!!!''//
 
 ::4;;wPV;W;WXXXXXXXX. ~~h33a,,))&)XFF}}^44''
FCC]]<00
$$V\:FFFr  r  r  c                    |                      |dd          }|                     |d          }|                     ||          }|                     |d          }|                     ||          }|||                     |          |                     |g d          ||                     |dd          ||                     |dd	          |                     |d
d          d d
S )N	quoteTimero  r  r  )clQReqIdr  r-  baseSz
fillBaseSzquoteSzfillQuoteSzcnvtPxr  )
rD  rL  rK  r<   r  
fromAmountr  toAmountr7  r  )rC  r  r  r  rq  r  )	r  
conversionr  r  rL  fromCoinr  r  r  s	            r  r  zokx.parse_conversion&  s    J ''
KFF	##J	::**8\BBj*55((Z88"Y//$$Z1S1S1STT$,,Z<PP **:y-PP''
HhGG
 
 	
r  c                   K   |                                   d{V  |                     |           d{V }i }|                     |dg           }t          dt	          |                    D ]}}||         }|                     |d          }|                     |          }|||dddddddd|                     |d          |                     |d          dddddddddd	||<   ~|S )
a:  
        fetches all available currencies that can be converted
        :see: https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-convert-currencies
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        NrV  r   r  r9  r:  r8  )r6  r   r  )rD  r<   rw  rS  r  r=   r/  r  r   r  rB  rC  r  )r   privateGetAssetConvertCurrenciesrd  rf  re  r  r  r  )	r  r  rh  rz  rV  rk  r  r<   rw  s	            r  fetch_convert_currencieszokx.fetch_convert_currencies]  s\      !!!!!!!!!>>vFFFFFFFF ~~h33q#d))$$ 	 	AGE!!%//B**2..D  !  $//u==#//u== 
  $#! !
  $#      5 F4LL8 r  c
                 ,   |sd S |                      |d          }
|
dk    r|
dk    r| j        dz   |z   }|                     |dg           }t          dt	          |                    D ]z}||         }|                      |d          }|                      |d          }|                     | j        d	         ||           |                     | j        d
         ||           {|                     | j        d	         |
|           t          |          d S )Nrw  r%  r    rV  r   r$  sMsgrF  rG  )	r  r<   rd  rf  re  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr"   )r  httpCodereasonr   r  r  r  rh  requestHeadersrequestBodyrw  feedbackrV  rk  errorrj  messages                    r  handle_errorszokx.handle_errors  s&    	4* &11CKKdckkw}t+H>>(FB77D1c$ii(( b bQ ,,UG<<	**5&9944T_W5MyZbccc44T_W5MwX`aaaa001I4QYZZZ)))tr  c                 N  K   |                                   d{V  |                     |d          }|t          | j        dz             |dk    }|rdnd}|r|rd}nt	          | j        dz   |z             |d	d
}	|                     |d          }
|                     |d          }|||	d<   |||	d<   |
|
|	d<   d}|                                 }|dz
  }|dz
  }|||k    r0|                     | 	                    |	|                     d{V }nM||k    r0| 
                    | 	                    |	|                     d{V }nt	          | j        dz             |                     |d          }|                     |          }|                     ||||          S )a  
        fetches the history of margin added or reduced from contract isolated positions
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-7-days
        :see: https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-3-months
        :param str [symbol]: not used by okx fetchMarginAdjustmentHistory
        :param str [type]: "add" or "reduce"
        :param dict params: extra parameters specific to the exchange api endpoint
        :param boolean [params.auto]: True if fetching auto margin increases
        :returns dict[]: a list of `margin structures <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        Nautoz8 fetchMarginAdjustmentHistory() requires a type argumentrn  160161162z* cannot fetch margin adjustments for type r  )subTyperQ  rC  rX  r  endTimei $l    X zS fetchMarginAdjustmentHistory() cannot fetch margin adjustments older than 3 monthsrV  )r  r  r'   r<   r(   rg  r  rJ  r  r  rS  rd  parse_margin_modificationsrb  )r  r"  r  r.  r  r  r  isAddr  r  rC  rh  rU  
oneWeekAgothreeMonthsAgorV  modificationss                    r  fetch_margin_adjustment_historyz#okx.fetch_margin_adjustment_history  s      !!!!!!!!!~~ff--<#DG.h$hiii +%%e 	` ` +W!WZ^!^___!
 
 !!&'2267++#(GK $GG!&GI!!9_
z)Muz11!88Wf9U9UVVVVVVVVHH^##!??GU[@\@\]]]]]]]]HHTW'||}}}V ~~h//77==00uUUUr  )NNNN)N)NN)__name__
__module____qualname__r  r  r   r!   r  r!  rM  r   r   rS  rm  rr  r    r   r}  r  r  r  r  r   r  r   r   r  r   r	  r  r   r   r  r   r-  r7  r  r<  rZ  rf  rj  ri  rh  r   r}  r  r   r  floatr  r  r   r   r   r  r  r   r  r  r  r  r  r	  r"  r   r  r9  r>  rE  rI  rM  rO  rV  ra  r	   ri  rv  r~  r  r   r   r  r  r  r  r  r  r   r  r  r  r  r  r  r   r   r  r	  r  r  r+  r:  r=  rA  rF  boolrM  rO  rS  rU  rR  r^  ra  rd  rf  r   rk  ri  rv  rx  r|  r{  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
   r  r  r  r   r  r   r  r  r   r  r  r  r  r  r%  __classcell__)r  s   @r  r:   r:   &   s       E E E E EN" OS[]lp h h hV hux h h h h h h; ; ;;
3 ;
 ;
 ;
 ;
zU UC U URU Ujm U  zI U U U U U U )+ 2 2 2 2h ') . . . .* +- ( (g ( ( ( (T *,  V    "Kf K K K KZ 8: 50 50 50 50nD D D -/ C C: C C C CJ @DB 3? 3?S 3? 3?S\ 3? 3? 3? 3?j5 56 5V 5 5 5 5n 68 *0 *0 *0F *0 *0 *0 *0X 6:" 34 347 34 34 34 34 34jX X X5 X X X Xt <@d[] D= D= D=S D= D=bfglbm D= D= D= D=L
 
 
4 
 
 
 
4 8<$]ajl XH XH XHC XHWZ XHquvzq{ XH XH XH XHt >BPTcgpr >Y >Ys >Y# >Y]` >Y >Y >Y >Y@8 8 8) ) )2) ) )
 
V 
?R 
 
 
 
0 ;= +5 +5c +5AT +5 +5 +5 +5Z *, x@ x@ x@ x@ x@ x@t XZ T Tc T T T T T" Y[ U Us U% U U U U" os{} M, M,3 M,i M,y M,Z_ M,hk M, M, M, M,^ mqy{ 5 5 5I 5Y 5X] 5fi 5 5 5 5n FH ,' ,'$|*< ,' ,' ,' ,'\ FJQU^` J, J,S J, J, J, J,X fjx|  FH = =3 = =9 =I =_b =ru = = = =~ 9=R $/ $/S $/# $/ $/ $/ $/L	 	 	 6:" WI WIs WI WI WI WIr	: 	: 	:F F F5 F F F FP 8<B M/ M/C M/ M/ M/ M/ M/^ 59tZ^gi X= X=c X= X=TW X=nrsxny X= X= X= X=t 9=4^bkm k= k=# k=S k=X[ k= k= k= k=Z 7;\`ik l= l= l=3 l=VY l=ptuzp{ l= l= l= l=\ 37TX\eg @D @DC @Ds @DRU @D @D @D @DD ?CQUdhqs ^ ^3 ^ ^3 ^^a ^ ^ ^ ^( .2SW`b n? n?s n?# n?S n? n? n? n?`3 3 3 K
 K
 K
 K
 K
 K
Z]
 ]
h ]
 ]
 ]
 ]
~ JL &0 &0S &0 &0 &0 &0P =?      B EIQS 7= 7=3 7= 7= 7= 7= 7=r 04$UYbd IM IM IMC IMs IMimnyiz IM IM IM IMV 8<B 9 9c 9 9 9 9 9, 37TX\eg AM AMC AMs AMRU AMlpq|l} AM AM AM AMF ;?r )2 )2 )2C )2 )2 )2 )2V+: +: +:Z[
 [
x [
; [
 [
 [
 [
z 8: %1 %13 %1h %1 %1 %1 %1N
 
x 
 
 
 
2 8: F5 F53 F5 F5 F5 F5P 8<B RP RPW RP RP RP RPh DF 	< 	<s 	< 	< 	< 	<\ \v \ \ \ \| ac 7: 7:3 7: 7:C 7:TW 7:gt 7: 7: 7: 7:rJ
 J
 J
 J
 J
 J
X: : : 9=R - -s -# - - - -> 154VZce 8O 8O# 8OS 8OPS 8O 8O 8O 8Ot &eBSW 1P 1P 1P 1Pf&
 &
6 &
 &
 &
 &
P <> "6 "6s "6 "6 "6 "6H 9=4^bkm TO TO# TOS TOX[ TO TO TO TOl ?C2 3 33 3 3 3 3 3j CGr  d C    > DHPR + + +S + + + +Z 57    6 ?A , ,# , , , ,>
 
 
 
 
 
(# # #6O O O 7;\`ik %K %K3 %KVY %K %K %K %KN GKY]fh &H &HC &H &HSV &H &H &H &HP LN   Rd    BG
 G
f G
HZ G
 G
 G
 G
R ?A 	Q 	Q# 	QEW 	Q 	Q 	Q 	Q <> 	N 	Ns 	NBT 	N 	N 	N 	N EG 2> 2> 2> 2> 2> 2>h$ $ $ $ $ $L 7;$]apt} 6Q 6Q 6QC 6QWZ 6Qjm 6Q 6Q 6Q 6Qp
 
& 
 
 
 
" JL "6 "6c "65 "6 "6 "6 "6H BD (6 (6S (6 (6 (6 (6T
 
 
 
 
 
. =? $9 $9 $9 $9 $9 $9L HLZ^mqz| <C <C <CTW <Cgj <C <C <C <C|1 1F 1 1 1 1fJt J J J J J J BFb 6= 6=w 6= 6= 6= 6=p7# 7# 7# 7#r <@daenp 0Y 0YS 0Y 0Y[^ 0Y 0Y 0Y 0Yd
 
 
"  4 46        D 68 5 5 5F 5 5 5 5n/
 /
6 /
 /
 /
 /
b CGr :/ :/3 :/i :/V[ :/ :/ :/ :/x 68 *6 *6 *6F *6 *6 *6 *6X :< +? +?S +? +? +? +? +?Z*
 *
H *
V *
 *
 *
 *
X SW_a 0G 0G# 0Gs 0GC 0Gfp 0G 0G 0G 0Gd ]aik 1G 1GS 1GC 1G 1GVY 1Gpz 1G 1G 1G 1Gf5
 5
 5
V^ 5
jt 5
 5
 5
 5
n 57 8 8: 8 8 8 8t# # #J CGTXgkz~  HJ XV XVC XVc XVad XVtw XV  OS  Tf  Og XV XV XV XV XV XV XV XVr  r:   )@ ccxt.async_support.base.exchanger   ccxt.abstract.okxr   r  r$  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr    r!   ccxt.base.errorsr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   ccxt.base.decimal_to_precisionr7   ccxt.base.preciser8   r:    r  r  <module>r4     s   6 5 5 5 5 5 ) ) ) ) ) )   {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {  {             * * * * * * 0 0 0 0 0 0 - - - - - - . . . . . . - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . + + + + + + ) ) ) ) ) ) * * * * * * * * * * * * 0 0 0 0 0 0 ) ) ) ) ) ) ) ) ) ) ) ) . . . . . . 1 1 1 1 1 1 * * * * * * ) ) ) ) ) ) + + + + + + 4 4 4 4 4 4 % % % % % %nsV nsV nsV nsV nsV(K nsV nsV nsV nsV nsVr  