
    !:h)                    (   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!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/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< d dl/m=Z= d dl/m>Z> d dl/m?Z? d dl/m@Z@ d dl/mAZA d dl/mBZB d dl/mCZC d dl/mDZD d dl/mEZE d dl/mFZF d dl/mGZG d dlHmIZI d dlJmKZK  G d  d!ee      ZLy)"    )Exchange)ImplicitAPIN)&AccountAnyBalancesBorrowInterest
ConversionCrossBorrowRateCrossBorrowRates
CurrenciesCurrencyDepositAddressGreeksIntLedgerEntryLeverageLeverageTierLongShortRatioMarginModificationMarketNumOptionOptionChainOrder	OrderBookOrderRequestCancellationRequest	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateTradeTradingFeeInterfaceTransactionMarketInterfaceTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountNotEnabled)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)OperationRejected)ManualInteractionNeeded)InsufficientFunds)InvalidAddress)InvalidOrder)OrderNotFound)ContractUnavailable)NotSupported)NetworkError)DDoSProtection)RateLimitExceeded)ExchangeNotAvailable)OnMaintenance)InvalidNonce)RequestTimeout)CancelPending)	TICK_SIZE)Precisec                   D    e Zd Zdef 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efdZi fdee   fdZd Zi fdee   fdZdedefdZi f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defdZi fdedefdZdi fd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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de.fd+Z/i fdede.fd,Z0i fde1fd-Z2i fded.e3fd/Z4i fded.e3fd0Z5di fded1e6d2e7d3e3d4e8f
d5Z9di fded1e6d2e7d3e3d4e8f
d6Z:i fd7ee;   fd8Z<ddi fd9efd:Z=ddi fd9eded1e6d2e7d3e8d4e8fd;Z>di fd9ede
fd<Z?d= Z@di fde
fd>ZAi fd7eeB   fd?ZCi fd@efdAZDdBe
fdCZEddDededeFfdEZGdi fd9ede
fdFZHdddi fde
d!ededeeF   fdGZIdddi fde
d!edefdHZJdddi fde
d!ededeeF   fdIZKdddi fde
d!edefdJZLdddi fd9ede
d!edefdKZMdddi fdLe
d!ededeeN   fdMZOdN ZPddOedPeQdeNfdQZRddPeQdeSfdRZTi fdLedeeS   fdSZUi fdLedeSfdTZVdi fdLed3e3dUedeWfdVZXdddi fdLe
d!ededeeW   fdWZYdi fd9edLe
fdXZZdddi fdLe
d!ededeeW   fdYZ[di fd9edLe
fdZZ\dBe
fd[Z]dd\edPeQdeWfd]Z^i fdede_fd^Z`dd_edede_fd`Zai fdefdaZbdi fdedeec   fdbZdi fdefdcZedddedefdeZfi fdLed3e3dfedgedegf
dhZhddiedPeQdegfdjZidBe
de
fdkZjdi fd9edLe
degfdlZkdddi fdLe
d!ededeeg   fdmZldndoi ddfdpZmddedenfdqZodr Zpi fdedenfdsZqi fdedenfdtZrdddi fde
d!edefduZsdi fd_ede
fdvZtdi fde
fdwZudi fdxevde
fdyZwdi fdzede
fd{Zxi fdeyfd|Zzi fdLede{fd}Z|ddPeQfd~Z}d Z~dddi fd!edefdZddi fdLed!edefdZi fdedefdZddededefdZi fded3e3defdZi fded3e3defdZi fdedee   fdZddedee   fdZddddi fdLe
de
d!ededee   f
dZddededefdZi fdLed3e3fdZi fdLefdZddPeQfdZi fdefdZdddi fded!edefdZddefdZdevf 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ZddededefdZdi fded2e7deFfdZi fdedefdZi fdLedefdZddedPeQdedefdZdi fdeded3e8defdZdi fd9ededed3e8def
dZdi fd9edLe
defdZdddi fdLe
d!ededee   fdZddedeQdeQdefdZi fdefdZdedededededefdZddddi fde
d1e
d!e8de8dee   f
dZdddi fded!ededeec   fdZddddi fde
de
d!ededee   f
dZddededefdZ xZS )okxreturnc                 -   | j                  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dBddCdi dDddEddFdG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dodGdpddqddrddsddtdduddvddwdi dxddyddzdd{dd|dd}dd~ddddddddddddddddddddddddddddddd	dddddddddddddddd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dddddddddddddi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d0dړd1dd2dd3dd4dړd5dd6dړd7dړd8dړd9dd:dd;dړd<dړd=dړd>dړd?dړi d@dړdAdړdBddCddDdړdEdړdFddGddHddIdړdJdړdKddLddMddNddOddPdi dQddRddSdړdTddUddVddWddXddYddddZdd[dd\dd]dd^dd_dd`di daddbddcdddddeddfddgddhddiddjddkddldmdnddoddpddqddrdړi dsdړdtdړdudړdvdړdwdړdxdړdydړdzdd{dd|dd}dd~dړddړdd+dddddddddddڐdi ddړddړddddddddړddړdd+ddddddddddddddddddi dd dddd dddd ddddddddddddddddddddddړddi ddddddddddddddd&dddړddddddړddړddړddddddi ddddړddړddړddړdDd+ddddddddd/d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ddmddmddmddddddddi ddddddړddړddړddړddړddddd|dddddddړddړddd}dddddddddddd| j	                  d      | j	                  d      d| j	                  d      | j	                  d      d| j	                  d       | j	                  d      d| j	                  d      | j	                  d      dddddddd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        d/t        d0t        d1t        d2t
        d3t
        d4t        d5t        d6t        d7t        d8t        d9t        d:t        i d;t         d<t         d=t        d>t"        d?t"        d@t"        dAt"        dBt$        dCt        dDt&        dEt"        dFt         dGt         dHt         dIt"        dJt
        dKt
        i dLt
        dMt"        dNt(        dOt(        dPt
        dQt        dRt
        dSt         dTt(        dUt(        dVt(        dWt(        dXt"        dYt"        dZt"        d[t"        d\t"        i d]t"        d^t"        d_t"        d`t"        dat"        dbt"        dct"        ddt"        det"        dft"        dgt"        dht"        dit"        djt"        dkt"        dlt"        dmt"        i dnt"        dot"        dpt"        dqt"        drt        dst"        dtt        dut"        dvt"        dwt"        dxt"        dyt$        dzt"        d{t"        d|t"        d}t"        d~t"        i dt"        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
        dt
        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        d.t        d/t        d0t
        d1t
        d2t
        d3t
        d4t0        d5t$        d6t0        d7t0        d8t        d9t
        i d:t
        d;t
        d<t
        d=t
        d>t
        d?t
        d@t
        dAt        dBt
        dCt
        dDt
        dEt
        dFt
        dGt        dHt
        dIt        dJt        i dKt        dLt        dMt        dNt        dOt        dPt        dQt        dRt        dSt        dTt        dUt        dVt        dWt2        dXt        dYt        dZt        d[t        i d\t
        d]t&        d^t        d_t4        d`t        dat
        dbt        dct6        ddt8        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|t2        d}t        t        t        t        d~t        t        ddddt        idt:        i dddddddd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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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dddddddddddd	idbd
didpddid#dddd\g ddddddddTddididdidfddidddiddi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'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.didd/d+d0dd1ddddd2dd+dddd3d dd+d/d4d dddd5dd+d6d7	d8d9id8d9id8d9id:d8d9id8d9id:d;d<d=d>d?      S (@  NidrG   nameOKX	countriesCNUSversionv5	rateLimitg     Y@proT	certifiedhasCORSspotmarginswapfutureoption	addMargincancelAllOrdersFcancelAllOrdersAftercancelOrdercancelOrderscancelOrdersForSymbols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fetchConvertTradefetchConvertTradeHistoryfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositsWithdrawalsfetchDepositWithdrawFeeemulatedfetchDepositWithdrawFeesfetchFundingHistoryfetchFundingIntervalfetchFundingIntervalsfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchL3OrderBookfetchLedgerfetchLedgerEntryfetchLeveragefetchLeverageTiersfetchLongShortRatiofetchLongShortRatioHistoryfetchMarginAdjustmentHistoryfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMarkPricefetchMarkPricesfetchMySettlementHistoryfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenOrderfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchOrderBooksfetchOrdersfetchOrderTradesfetchPositionfetchPositionHistoryfetchPositionsfetchPositionsForSymbolfetchPositionsHistoryfetchPositionsRiskfetchPremiumIndexOHLCVfetchSettlementHistoryfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTradingLimitsfetchTransactionFeefetchTransactionFeesfetchTransactionsfetchTransferfetchTransfersfetchUnderlyingAssetsfetchVolatilityHistoryfetchWithdrawalfetchWithdrawalsfetchWithdrawalWhitelistreduceMargin)	repayCrossMarginsandbox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-ratioz6rubik/stat/contracts/long-short-account-ratio-contractz)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market/sprd-tickerzmarket/sprd-candleszmarket/sprd-history-candlesztradingBot/grid/ai-paramztradingBot/grid/min-investmentz"tradingBot/public/rsi-back-testingzasset/exchange-listz$finance/staking-defi/eth/apy-historyz$finance/staking-defi/sol/apy-historyz$finance/savings/lending-rate-summaryg
@gUUUUUU?)z$finance/savings/lending-rate-historyz!finance/fixed-loan/lending-offersz&finance/fixed-loan/lending-apy-historyz)finance/fixed-loan/pending-lending-volumezfinance/sfp/dcd/productszcopytrading/public-lead-traderszcopytrading/public-weekly-pnlzcopytrading/public-statsz&copytrading/public-preference-currencyz'copytrading/public-current-subpositionsz'copytrading/public-subpositions-historyzsupport/announcements-typesz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-currency-list-v2ztrade/one-click-repay-historyz trade/one-click-repay-history-v2z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/instrumentszaccount/balancezaccount/positionszaccount/positions-historyd   zaccount/account-position-riskzaccount/billszaccount/bills-archivezaccount/bills-history-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"account/fixed-loan/borrowing-limitz"account/fixed-loan/borrowing-quotez(account/fixed-loan/borrowing-orders-listz account/spot-manual-borrow-repayzaccount/set-auto-repayz!account/spot-borrow-repay-historyzaccount/move-positions-historyzusers/subaccount/listzaccount/subaccount/balanceszasset/subaccount/balancesz!account/subaccount/max-withdrawalzasset/subaccount/billsz)asset/subaccount/managed-subaccount-billszusers/entrust-subaccount-listz"account/subaccount/interest-limitszusers/subaccount/apikeyz#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%finance/staking-defi/eth/product-info   z finance/staking-defi/sol/balancez0finance/staking-defi/sol/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/apikeyz*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-orders,  finance/sfp/dcd/orderzfinance/sfp/dcd/orders)broker/fd/rebate-per-orderszbroker/fd/if-rebatezaffiliate/invitee/detailzusers/partner/if-rebatezsupport/announcementsz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-orderzsprd/cancel-all-after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/one-click-repay-v2z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"account/fixed-loan/borrowing-orderz(account/fixed-loan/amend-borrowing-orderz"account/fixed-loan/manual-reborrowz(account/fixed-loan/repay-borrowing-orderi@ zaccount/move-positionszusers/subaccount/modify-apikeyzasset/subaccount/transferz!users/subaccount/set-transfer-outz&account/subaccount/set-loan-allocationz"users/subaccount/create-subaccountz"users/subaccount/subaccount-apikeyzusers/subaccount/delete-apikeyz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/grid/adjust-investmentz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/purchasezfinance/staking-defi/redeemzfinance/staking-defi/cancelz!finance/staking-defi/eth/purchasezfinance/staking-defi/eth/redeemz!finance/staking-defi/sol/purchasezfinance/staking-defi/sol/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-ratezbroker/nd/set-subaccount-assetsz1asset/broker/nd/modify-subaccount-deposit-addressi  )r  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)tradingrW   rZ   rY   requiredCredentials)apiKeysecretpassword
exceptions124088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540085400954011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5941059411594125941359414595005950159502595035950459505595065950759508595155951659517595185951959642596436000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032639996400064001640026400370010700137001670060700617006270064700657006670067100940014002400340044005)400640074008)zInternal Server Errorzserver error)exactbroadhttpExceptions429precisionModesandboxModedefaultNetworkERC20defaultNetworksBTCTRC20)ETHr  USDTnetworksBitcoinBTCLN	LightningBTCLIGHTNINGBEP20BSCBRC20CRC20CryptoACAAcalaALGOAlgorandAPTAptosSCROLLScrollARBONEzArbitrum OneAVAXCzAvalanche C-ChainAVAXXzAvalanche X-ChainBASEBaseSUI	ZKSYNCERAz
zkSync EraLINEALineaARArweaveASTRAstarBCHBitcoinCashBSVz
Bitcoin SVADACardanoCSPRCasperCELOXCHChiaATOMCosmosDGBDigibyteDOGEDogecoinEGLDElrondCFXConfluxEOSCOREETCzEthereum ClassicETHWEthereumPowFILFilecoinONEHarmonyHBARHederaICXICONICPDfinityIOSTIOTAMIOTAKLAYKlaytnKSMKusamaLSKLiskLTCLitecoinMETISMetisMINAMinaGLRMMoonbeamMOVR	MoonriverNANONanoNEARNULSOASYS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WaxZilliqa)THETAWAXZIL8H)r   r   8hr   5Mr   r  r   timezoneUTCmethodprivateGetAccountPositionsprivatePostTradeBatchOrders!createMarketBuyOrderRequiresPrice)rW   rZ   rY   r[   timeDifferencer   adjustForTimeDifferencedefaultTypeprivateGetAccountBillsprivateGetTradeOrderprivateGetTradeOrdersPending!privatePostTradeCancelBatchOrdersprivateGetTradeOrdersHistory)r  pwd)conditionaltriggerocomove_order_stopicebergtwap618)fundingr  rW   rZ   futuresrX   rY   r[   r-  r  )r+  r,  SPOTMARGINSWAPFUTURESOPTION)rW   rX   rY   rZ   r.  r[   r/  r0  r1  r2  r3  e847386590ce4dBC)r{   r}   r   algoOrderTypesaccountsByTypeaccountsByIdexchangeTypebrokerId)lastmarkindex)triggerPriceTypeprice)IOCFOKPOGTD)
marginModetriggerPricer=  triggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingr)  leverageselfTradePreventionmarketBuyByCostmarketBuyRequiresPricemaxZ   i'  )rC  daysBacklimit	untilDayssymbolRequired)rC  r&  rK  rU  )rC  rS  r&  rK  rU  gUUUUUU?)rC  rS  rR  daysBackCanceledrT  r&  rK  rU  )rS  
historical)	r   rh   ri   r   r   r   r   r}   r   extendsdefault)linearinverse)rY  rW   rY   rZ   AETWINTOKEN)AEWIN)optionsfeaturescommonCurrencies)deep_extendsuperrG   describeparse_numberr,   r5   r2   r@   rB   r?   r0   r-   r>   r.   rA   r3   r8   r6   r/   r:   r9   rC   r7   r4   r<   r=   r1   r;   rD   )self	__class__s    P/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/async_support/okx.pyre  zokx.describe*   s>9   c4 9 ; T>
%T>
ET>
 $T>
 t	T>

 T>
 4T>
 T>
  AAA $A 	A
 $A $A TA "5A 'A tA A )$A $UA  A %dA  '!A" /#A$ 0%A& t'A( )A* 7+A, &t-A. (/A0 '1A2 &t3A4 (5A6 "47A8 (9A: -d;A< %d=A> T?A@  AAB CAD  EAF &tGAH +DIAJ )$KAL &tMAN #DOAP $TQAR )$SAT $TUAV $TWAX +DYAZ '[A\ (]A^ "4_A` aAb &tcAd (eAf 1$gAh  iAj +EkAl *:mAn +DoAp &tqAr 'sAt (uAv #DwAx *4yAz $U{A| t}A~ "4A@ *5AAB +ECAD #EEAF tGAH #DIAJ  KAL %eMAN &uOAP -dQAR /SAT +DUAV WAX !$YAZ !$[A\ "4]A^ +E_A`  aAb dcAd $TeAf +DgAh !$iAj "4kAl tmAn #DoAp dqAr !$sAt "5uAv uwAx #DyAz  {A| '
}A~ !$A@ *4AAB (CAD %eEAF )%GAH )$IAJ tKAL tMAN OAP TQAR tSAT "4UAV #EWAX %eYAZ &u[A\ ']A^ $U_A`  aAb !$cAd (eAf )%gAh "4iAj #DkAl +EmAn oAp %)#"!%#'  AAT>
T UT>
t uT>
v ~0 -8F ? #	 0wT>
Z  V+QV(!V (V /	V
 'V ,UV )%V 1!V /V 7V 4QV <QV (V 0V A!V  4R!V" -b#V$ /%V& 21'V( 3B)V* /+V, .q-V. .q/V0 -a1V2 ;E3V4 /5V6 .q7V8 6q9V: -a;V< -a=V> 1!?V@ CBAVB &qCVD ,QEVF 0GVH :2IVJ >rKVL ,QMVN 0OVP 7QVR /SVT 7UVV ?WVX 21YVZ 7[V^ H_V` QRSaVb DQcVd A!eVh GiVj HkVl HmVn ?oVp (qVt 'uVv %ewVx &qyVz -e{V| -a}V~ .qV@ 6qAVB 3ACVD 9!EVF =aGVH .uIVJ ?KVL ?MVN ?OVP AF=CBHEK49;<9:45BCCDCD79kVXtZ,aZ 8Z )!	Z
 #BZ %bZ %aZ ,QZ %eZ .uZ .uZ 6uZ &uZ  &u!Z" /#Z$ /%Z& 7'Z( &u)Z* .s+Z, .q-Z. +A/Z0 4Q1Z2 4Q3Z4 ;B5Z6 5b7Z8 >r9Z: A";Z< 8=Z> ;B?Z@ 3AAZD +EEZF )%GZH 4UIZJ 0KZL /MZN &uOZP 21QZR 0SZT 0UZV 3EWZX 8YZZ 3E[Z\ 6u]Z^ 0_Z` 21aZd .qeZf *1gZh ,QiZj 4SkZl 8mZn (oZp 0qZr 8sZt )!uZv +AwZx 1!yZz 0{Z| 7}Z~ +AZ@ ,QAZB 3ACZD 0EZF 1!GZH -aIZJ DQKZL 7MZN 7OZP 8QZR 6qSZT 8UZV 21WZX )!YZZ 1![Z\ -a]Z^ =a_Z` =aaZb CAcZd ;BeZf 1!gZh <QiZj 9"kZn 0oZp 6vqZr 4VsZt <QuZv 1%wZx DUyZz 8{Z| =a}Z~ 22ZB >qCZD >qEZF >qGZH 5aIZJ 4QKZL 3AMZN 4QOZP @QZR @SZT 6qUZV >qWZX 7YZZ :1[Z\ CA]Z^ CA_Z` CAaZb :1cZf 25gZh :5iZj 6vkZl =fmZn >voZr ;EsZt KEuZv @wZx ;EyZz KE{Z~ ;AZ@ ;AAZB 21CZD =aEZF ;AGZH HIZJ 4QKZL :1MZN ;AOZP ;AQZT )"UZV 4RWZX 6rYZZ Ee[Z\ Ea]Z^ H_Z` 1#aZb 6scZd 0eZf 1!gZh 8;/0453412sZvH(!H )!H 0	H
 .rH ,RH 8H (H )#H +CH +CH 22H 0H %aH  ,Q!H" +A#H$ +A%H& 0'H* &u+H, -f-H. -e/H0 4V1H2 ,U3H4 3G5H6 /7H8 .v9H: +A;H< -a=H> ,Q?H@ 5aAHB -bCHD 0EHF 3BGHH ,QIHJ 1"KHN )"OHP +EQHR 5aSHT 25UHV 4RWHX 7YHZ .q[H\ 21]H` 4QaHb /cHd :1eHf -agHh 4QiHj <QkHl /mHn 3BoHp 3BqHr 6qsHt 21uHv 0wHx 4QyHz ,Q{H| -c}H~ =aH@ CAAHB =aCHD CAEHF 8GHH 1"IHL 9"MHN 4ROHP <RQHR A!SHT =bUHV =bWHX 9"YH\ 5a]H^ ;A_H` :1aHb 9!cHd =aeHf @gHh :1iHj A!kHl 9!mHn 9!oHp <QqHr :1sHt 7uHv <QwHx ;AyHz 6q{H| <Q}H~ ;AH@ 6qAHB =aCHD :1EHF @GHH ?IHL ;EMHN ;EOHP 8QHR 6qSHT 6qUHX <QYHZ :1[H\ <Q]H^ :1_Hb 1!cHd 8eHf 6qgHh :1iHj :1kHl 8mHn 9!oHr 6tsHt 6quHv 6twHx =ayHz =a{H| 9!}H~ <QH@ :4AHB EaCHD LUEHF 8=1313:>7<OHyeu@[T>
\ !..x8!..x8
 "..x8!..x8
 "..x8!..x8
 "..y9!..y9]T>
@ " $AT>
J D D 	D
 3D ZD ]D ZD ^D 1D ZD -D 0D -D ]D  .!D" ]#D$ 1%D& Z'D( ])D* ]+D, ]-D. ]/D0 ]1D2 ]3D4 ]5D6 ]7D8 ]9D: Z;D< ]=D> 1?D@ -ADB ]CDD ZEDF ]GDH ]IDL ]MDN 0ODP \QDR 0SDT 0UDV 0WDX 0YDZ 0[D\ ]]D^ ]_D` -aDb 0cDd 0eDf 0gDh 0iDj ZkDn ZoDp YqDr YsDt ZuDv \wDx \yDz \{D| \}D~ .D@ -ADB .CDD \EDF YGDH YIDJ YKDL \MDN ]ODP ]QDR ]SDT \UDV 0WDX 0YDZ ][D\ -]D^ ]_D` YaDb 0cDd 0eDf 0gDh 0iDj \kDl \mDn \oDp \qDr \sDt \uDv \wDx \yDz \{D| \}D~ \D@ \ADB \CDD \EDF \GDH \IDJ \KDL \MDN \ODP \QDR \SDT \UDV \WDX \YDZ \[D\ \]D^ Z_D` \aDb .cDd \eDf \gDh \iDj \kDl .mDn \oDp \qDr \sDt \uDv \wDx \yDz .{D| \}D~ \D@ YADB .CDD \EDF \GDH \IDJ \KDL \MDN \ODP \QDR \SDT ZUDV ZWDX \YDZ \[D\ \]D^ \_D` \aDb \cDd \eDf \gDh \iDj \kDl \mDn \oDp \qDr \sDt \uDv \wDx \yDz \{D| \}D~ \D@ \ADB \CDD \EDF \GDH \IDJ \KDL \MDN \ODP \QDR \SDT \UDV \WDX \YDZ \[D\ \]D^ \_D` \aDb \cDd \eDf \gDh \iDj \kDl ZmDn ZoDp \qDr \sDt \uDv \wDx \yDz ]{D| ]}D~ ]D@ \ADB \CDD ]EDF ]GDH ZIDJ ]KDL ]MDN ]ODP ]QDR ]SDT .UDV ]WDX ]YDZ ][D\ ]]D^ ]_D` ]aDb ]cDd ]eDf ]gDh ]iDj 0kDl 0mDn 0oDp ]qDr .sDv ]wDz ]{D| ]}D~ \D@ \ADB \CDF \GDH \IDJ \KDL \MDN \ODP \QDR \SDT \UDX ]YDZ 0[D\ -]D^ ]_D` -aDb ]cDd ]eDf ]gDh ]iDj -kDl .mDn ]oDp ]qDr ]sDt ]uDv ]wDx ]yDz ]{D| ]}D~ ]D@ ]ADB ]CDD ]EDF ]GDH ]IDJ ZKDL ZMDN ZODP ZQDR ]SDT ]UDV ]WDX ^YDZ -[D\ ]]D^ ]_D` ^aDb ]cDd ]eDf ]gDh ]iDj ]kDl 0mDn ZoDp ZqDr ZsDt ZuDv ZwDx .yDz ]{D| .}D@	 ]A	DB	 ]C	DD	 ]E	DF	 ]G	DH	 ]I	DJ	 .K	DL	 ]M	DN	 ]O	DP	 ]Q	DR	 ]S	DT	 .U	DV	 ]W	DX	 \Y	DZ	 .[	D\	 .]	D^	 Z_	D`	 -a	Db	 -c	Dd	 ]e	Df	 ]g	Dh	 ]i	Dj	 ]k	Dl	 .m	Dn	 .o	Dp	 .q	Dr	 .s	Dt	 Zu	Dv	 ]w	Dx	 ]y	Dz	 ]{	D|	 ]}	D~	 ]	D@
 ]A
DB
 ]C
DD
 ]E
DF
 -G
DH
 ]I
DJ
 ]K
DL
 ]M
DN
 ]O
DP
 ]Q
DR
 ZS
DT
 ]U
DX
 0Y
DZ
 0[
D\
 0]
D^
 0_
D`
 0a
Db
 \c
Dd
 0e
Df
 0g
Dh
 0i
Dj
 0k
Dl
 0m
Dn
 Zo
Dp
 Zq
Dr
 .s
Dt
 \u
Dv
 1w
Dx
 Zy
Dz
 Z{
D|
 Z}
D~
 ]
D@ .ADB 0CDD ^EDF 0GDH ]IDJ 0KDL .MDN \ODP .QDR .SDT 0UDV 0WDX ]YDZ Z[D\ Z]D^ Z_D` .aDb ZcDd ZeDf ZgDh ZiDj ZkDl ZmDn ZoDp ZqDr ZsDt ZuDv JwDx /yDz J{D| -}D~ LD@ 0ADB '/-GDL .B$8MJKT>
` +aT>
f YgT>
h[u[ '[ "" #$[  y9y[y #Ky U	y
 Wy Wy Wy Xy 7y Jy 7y hy ny 0y 0y  F!y" 5#y$  %y& W'y( ))y* G+y, =-y. </y0 91y2 H3y4 F5y6 67y: H;y< :=y> J?y@ HAyB 9CyD 5EyF FGyH -IyJ MKyN :OyP 9QyR HSyT 6UyV 9WyX FYyZ G[y\ H]y^ 8_y` 6ayb :cyd Weyf Fgyh Jiyj Kkyl Fmyn Foyp Fqyr Wsyt :uyv 
wyz 8{y| :}y~ Yy@ ;AyB 8CyD )EyF 8GyH :IyJ +KyL 7MyN 5OyP % $Uy[D + """"""""	#-E[\ ][d !:#e[j <k[l 4Um[n  Do[p !!q[r *5s[t vu[| 6 }[D 4E[J "<$K[P A!Q[X <( <& !%	 $(#'+# #  ## "#" "	# ##!
 #&"'(&"&"(&! /u[|  $&*(,$($(%)-
 -2)-+/ )-(,)-1
 &*7 $(#'"&#(	( #'$(#'$)/3+/27? $D r% ',$&!$%**/& ',#'$(*.	# ',!$#'$(*/( $(&+!$$&,2%)#'$(*/	* "%&)#KIV y
 "9 "9 	 "9 "9 	m^B !!_(T>
 T T	    N
methodNamemarketc                     | j                  |d      }| j                  |d      }| j                  |d      }||||d<   t        t        |   ||||      S )NinstTypetype)safe_stringomitrd  rG   handle_market_type_and_params)rg  rk  rl  paramsdefaultValuern  ro  rh  s          ri  rr  z!okx.handle_market_type_and_paramsA  sd    ##FJ76:./Lx3%F6NS$=j&RXZfggrj  c                 b    | j                  | j                  di       }| j                  |||      S )Nr8  )	safe_dictr`  rp  )rg  ro  exchangeTypess      ri  convert_to_instrument_typezokx.convert_to_instrument_typeI  s-    t||^RHtT::rj  symbolc                    d}|j                  d      }|j                  d      }d }|j                  d      dkD  r| j                  |d      }n| j                  |d      }|}| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |      }
| j	                  |
      }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| j                  d      ||
|	dk(  rdnd | j                  |      d d d!d d d"d d d"d d d"d#d d$	S )%NUSD-/r   r   r  r   rJ   ry  :basequotesettlebaseIdquoteIdsettleIdactiveFro  r[   rZ  r[  rW   rY   rZ   TrX   r  Ccallputamountr>  minrP  )r  r>  cost)	contractcontractSizeexpiryexpiryDatetime
optionTypestrike	precisionlimitsinfo)splitfindrp  convert_expire_date	parse8601rf  )rg  ry  r  optionParts
symbolBaser  r  r  r  r  datetime	timestamps               ri  create_expired_option_marketz okx.create_expired_option_marketM  sW   ll3'\\#&
;;sb ##J2D##K3D!!+q1!!+q1%%k15
++F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&%/3%6&U''/  
  
   U+
 +	
rj  marketId	delimiter
marketTypec                     |d uxr* |j                  d      dkD  xs |j                  d      dkD  }|r|| j                  vr| j                  |      S t        t        |   ||||      S )Nz-Cr~  z-P)r  markets_by_idr  rd  rG   safe_market)rg  r  rl  r  r  isOptionrh  s         ri  r  zokx.safe_market  sn    D(hd0Cb0H/ghmm\`NadfNfX););;44X>>S$+HfiTTrj  c                   K   | j                  |       d{   }| j                  |dg       }t        |      }d|dk(  rdnddd|d}t        dt        |            D ]o  }||   }| j	                  |d      }| j                  |d      |d	<   | j	                  |d
      |d<   |dk(  rd|d<   O|dk(  rd|d<   Z|dk(  rd|d<   e|dk(  skd|d<   q |S 7 w)aK  
        the latest known information on the availability of the exchange API

        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   r  stateendr  hrefr   ongoingr  	scheduled	completedcanceled)publicGetSystemStatus	safe_listlenrangerp  safe_integer)	rg  rs  responser  
dataLengthupdateieventr  s	            ri  fetch_statuszokx.fetch_status  s     33F;;* ~~h3Y
)Qd]
 q#d)$ 	(AGE$$UG4E --eU;F5M ,,UF;F5M	!#0x +%#'x +%#'x *$#'x 	( W <s   CCB0C	
Cc                    K   | j                  |       d{   }| j                  |dg       }| j                  |di       }| j                  |d      S 7 <w)aa  
        fetches the current integer timestamp in milliseconds from the exchange server

        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
        Nr  r   ts)publicGetPublicTimer  rv  r  )rg  rs  r  r  firsts        ri  
fetch_timezokx.fetch_time  sY      11&99 ~~h3tQ+  -- :s   AA=Ac           	      "  K   | j                  |       d{   }| j                  |dg       }g }t        dt        |            D ]B  }||   }| j	                  |d      }| j	                  |d      }|j                  ||d|dd       D |S 7 uw)a|  
        fetch all the accounts associated with a profile

        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
        Nr  r   uidacctLv)rJ   ro  currencyr  code)privateGetAccountConfigr  r  r  rp  append)	rg  rs  r  r  resultr  account	accountIdro  s	            ri  fetch_accountszokx.fetch_accounts  s      55f==( ~~h3q#d)$ 
	A1gG((%8I##GX6DMM  	
	 C >s   BBA6Bc                 B    | j                         | j                  d   z
  S )Nr  )millisecondsr`  )rg  s    ri  noncez	okx.nonce
  s       "T\\2B%CCCrj  c                   K   | j                   d   r| j                          d{    | j                  | j                   dg       }g }g }t        dt	        |            D ]&  }|j                  | j                  ||   |             ( t        j                  |  d{   }t        dt	        |            D ]  }| j                  |||         } |S 7 7 7w)a!  
        retrieves data on all markets for okx

        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  Nr   r   )
r`  load_time_differencer  r  r  r  fetch_markets_by_typeasynciogatherarray_concat)rg  rs  typespromisesr  r  s         ri  fetch_marketszokx.fetch_markets  s      <<12++---t||^R@q#e*% 	JAOOD66uQxHI	J 22q#h-( 	<A&&vx{;F	< . 3s"   #CCA8CC6CCc                 V   | j                  |d      }| j                  |d      }|dk(  rd}|dk(  }|dk(  }|dk(  }|dk(  }|xs |xs |}| j                  |dd	      }	| j                  |d
d	      }
| j                  |d      }| j                  |      }| j                  |d      }|7|s5|j                  d      }| j                  |d      }	| j                  |d      }
| j                  |	      }| j                  |
      }|dz   |z   }d }d }d }|r||dz   |z   }|r.| j	                  |d      }|| j                  |      }|dz   |z   }nh|rf| j	                  |d      }| j                  |d      }| j                  |d      }|.| j                  |      }|dz   |z   dz   |z   dz   |z   }|dk(  rdnd}| j                  | j                  |di       }| j                  |dd      }t        j                  |d      }| j                  |d      }| j                  |i d|d|d|d|d |d!|	d"|
d#|d$|d|d%|xr t        j                  |d      d|d|d|d&d'd(|d)|r|
|k(  nd |r|	|k(  nd |r| j                  |d*      nd || j                  |      | j                  |      || j	                  |d+      | j                  |d,      | j                  |d-      d.| j                  d      | j                  |      d/| j                  |d0      d d/d d d/d |rd n|d/d1|d2
      S )3NinstIdrn  r.  rZ   rW   rY   r[   baseCcy quoteCcy	settleCcyulyr|  r   r   r}  r  expTimestkoptTypePr  r  r  leverr  maxMktSzrJ   ry  r  r  r  r  r  r  ro  rX   r  Tr  rZ  ctVallistTimelotSztickSzr  r  minSz)rL  r  r>  r  )
r[  r  r  r  r  r  createdr  r  r  )rp  safe_string_lowersafe_currency_coder  r  yymmddsafe_dict_2r   rE   
string_maxsafe_numberextend	string_gtiso8601rf  )rg  rl  rJ   ro  rW   rZ   rY   r[   r  r  r  r  r  
underlyingpartsr  r  ry  r  strikePricer  ymdr   maxLeveragemaxSpotCosts                            ri  parse_marketzokx.parse_market"  s:   d fh/%%fj99D("("+6+V!!&)R8""6:r:##FK8((2%%fe4
"D$$S)E%%eQ/F&&ua0G&&v.''0e#
!#.**69=%++f-C#c\C/F**69="..vu=!--fi@
%++f-C#c\C/#5CcIJVF+5+<6J		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 1+s C0"
 D0"
 f0"
 f0"
 d0"
  !0"
" xw(*T#0"
$ 08(*TAID,,VW=t"ll62''4$((<**67;))&(;  ,,S1,,[9
  ++FG<
  
  #+4$ _0"
 0 0	rj  c           	        K   d| j                  |      i}|dk(  r| j                  | j                  dddg      }g }t        dt	        |            D ]<  }||   }||d<   |j                  | j                  | j                  ||                   > t        j                  |  d {   }g }	t        dt	        |            D ]:  }| j                  ||i       }
| j                  |
dg       }| j                  |	|      }	< | j                  |	      S | j                  | j                  ||             d {   }| j                  |dg       }| j                  |      S 7 7 *w)	Nrn  r[   defaultUnderlyingBTC-USDzETH-USDr   r  r  )rx  r  r`  r  r  r  publicGetPublicInstrumentsr  r  r  rv  r  parse_markets)rg  ro  rs  requestoptionsUnderlyingr  r  r  promisesResultmarketsresr`  r  dataResponses                 ri  r  zokx.fetch_markets_by_type  sl    77=
 8 $t||=PS\^gRh iH1c"345 _.q1
!+ ? ?GU[@\ ]^_ $+>>8#<<NG1c.12 >nn^Q;..fb9++GW=> %%g..88Wf9UVVD ~~h;!!,//U = Ws%   B#E %E&BE 3E4)E E c                 f  K   | j                  | j                  dd      }| j                  d      r|ry| j                  |       d{   }| j	                  |dg       }i }| j                  |d      }t        |j                               }t        dt        |            D ]  }||   }	| j                  |	      }
|
d   }||	   }i }d}t        |      }t        d|      D ]  }||   }| j                  |d	d
      }|d
k(  rd}|j                  d      }| j                  |d      }dj                  |      }| j                  ||
d         }||d| j                  |d      | j                  |d      | j!                  |d      | j#                  | j%                  | j                  |d                  d| j!                  |d      | j!                  |d      di|d	||<    | j'                  |di       }| j)                  |||	| j                  |d      dddddddddi||d      ||<    |S 7 w)a  
        fetches all available currencies on an exchange

        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
        r  FNr  ccyr   r  cryptochainr  fiatr|  r   canDepcanWdfeewdTickSzr   minWdmaxWdr  )	rJ   networkr  depositr   r  r  r  r  rK   r  )r  r  rJ   rK   r  r  r   r  r  r  ro  r  )	safe_boolr`  check_required_credentialsprivateGetAssetCurrenciesr  group_bylistkeysr  r  safe_currencyrp  r  array_slicejoinnetwork_id_to_coder  rf  parse_precisionrv  safe_currency_structure)rg  rs  isSandboxModer  r  r  dataByCurrencyIdcurrencyIdsr  
currencyIdr  r  chainsr  ro  chainsLengthjr  	networkIdidPartsr  	chainPartnetworkCode
firstChains                           ri  fetch_currencieszokx.fetch_currencies  s~     t||]EJ..u5 77??X ~~h3==u5+0023q#k*+ 6	A$QJ))*5HF#D%j1FHDv;L1l+ q	 ,,UGR@	?!D#//#.((!4HHUO	"55i&AQR#*"#~~eX> $ug >++E59!%!2!243G3GHXHXY^`jHk3l!m"#'#3#3E7#C#'#3#3E7#C% ")%6 26J77 ((V< !## $#9 F4LI6	n O @s   AH1H.	G&H1rS  c                 (  K   | j                          d{    | j                  |      }d|d   i}d}| j                  |ddd      \  }}|dk(  r|d}|d	n|}|||d
<   d}|dk(  s|dkD  r*| j                  | j	                  ||             d{   }n)| j                  | j	                  ||             d{   }| j                  |dg       }| j                  |di       }	| j                  |	d      }
| j                  |	||
      S 7 7 {7 Sw)a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        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  rJ   r   r  publicGetMarketBookspublicGetMarketBooksFulli  r  szi  r  r   r  )
load_marketsrl  handle_option_and_paramsr3  r  r2  r  rv  r  parse_order_book)rg  ry  rS  rs  rl  r  r  r  r  r  r  s              ri  fetch_order_bookzokx.fetch_order_bookg  s7     !!!V$fTl
 66v?OQY[qr//EMEE!GDM00eck!::4;;wPV;WXXH!66t{{7F7STTH, ~~h3tQ+%%eT2	$$UFI>>S 	" YTs5   DDA;DD)D<D=ADDDtickerc           
         | j                  |d      }| j                  |d      }| j                  ||d      }|d   }| j                  |d      }| j                  |d      }| j                  |dd      }|r| j                  |d	      nd }	| j                  |d
      }
| j                  |d      }| j                  |d      }| j	                  i d|d|d| j                  |      d|d|d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      dd d|d|d|dd dd dd dd |
|	| j                  |d       | j                  |d!      |d"|      S )#Nr  r  r|  ry  r:  open24hrW   F	volCcy24hvol24hhigh24hlow24hr  r  highlowbidbidPx	bidVolumebidSzaskaskPx	askVolumeaskSzvwapopenclosepreviousClosechange
percentageaveragemarkPxidxPx)
baseVolumequoteVolume	markPrice
indexPricer  )r  rp  r  r  safe_tickerr  )rg  r9  rl  r  r  ry  r:  rK  rW   rT  rS  r@  rA  s                ri  parse_tickerzokx.parse_ticker  s   L %%fd3	##FH5!!(FC8!/	2~~ffe4?Cd&&v{;%%fh7
	2vx0 !
f!
!
 Y/!
 D	!

 3!
 4##FG4!
 ))&':!
 4##FG4!
 ))&':!
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ %&))&(;**67;-!
. / 	rj  c                 4  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }| j                  ||      S 7 }7 >w)a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        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  rJ   r  r   )r5  rl  publicGetMarketTickerr  r  rv  rX  rg  ry  rs  rl  r  r  r  r  s           ri  fetch_tickerzokx.fetch_ticker  s      !!!V$fTl
 33DKK4PQQ6 ~~h3tQ+  //E 	"
 Rs"   BBA BB=BBsymbolsc                 "  K   | j                          d{    | j                  |      }| j                  |      }d}| j                  d||      \  }}d| j	                  |      i}|dk(  rP| j                  | j                  dd      }| j                  |dd|      }|t        | j                  d	z         ||d<   | j                  | j                  ||             d{   }| j                  |d
g       }	| j                  |	|      S 7 7 +w)a#  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        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   rn  r[   r  r  r  r  zT fetchTickers() requires an underlying uly or marketId parameter for options marketsr  )r5  market_symbolsget_market_from_symbolsrr  rx  rp  r`  safe_string_2r1   rJ   publicGetMarketTickersr  r  parse_tickers
rg  r]  rs  rl  r  r  r  r'  r  tickerss
             ri  fetch_tickerszokx.fetch_tickers  s/     !!!%%g.--g6
!??PVX^_
F77
C
 ! $ 0 0?RT] ^++FE:GXYJ!'  3I  )I  J  J!+44T[[&5QRR6 ..626!!'733W 	" S"   DDC
D!D"*DDc                 ,  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |d      }| j                  | j                  |d      |      S 7 y7 :w)a  
        fetches mark price for the market

        https://www.okx.com/docs-v5/en/#public-data-rest-api-get-mark-price

        :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 dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr  rJ   r  r   )r5  rl  publicGetPublicMarkPricer  r  rX  rv  )rg  ry  rs  rl  r  r  r  s          ri  fetch_mark_pricezokx.fetch_mark_priceM  s      !!!V$fTl
 66t{{7F7STT ~~h/  a!8&AA+ 	"
 Us"   BBA BB9BBc                 $  K   | j                          d{    | j                  |      }| j                  |      }d}| j                  d||d      \  }}d| j	                  |      i}|dk(  rP| j                  | j                  dd      }| j                  |dd	|      }|t        | j                  d
z         ||d<   | j                  | j                  ||             d{   }| j                  |dg       }	| j                  |	|      S 7 7 +w)a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://www.okx.com/docs-v5/en/#public-data-rest-api-get-mark-price

        :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   rY   rn  r[   r  r  r  r  zW fetchMarkPrices() requires an underlying uly or marketId parameter for options marketsr  )r5  r_  r`  rr  rx  rp  r`  ra  r1   rJ   ri  r  r  rc  rd  s
             ri  fetch_mark_priceszokx.fetch_mark_pricesn  s/     !!!%%g.--g6
!??PVX^`fg
F77
C
 ! $ 0 0?RT] ^++FE:GXYJ!'  3L  )L  M  M!+66t{{7F7STT..626!!'733# 	" Us"   DDCD"D#*DDtradec                 x   | j                  |d      }| j                  |d      }| j                  ||d      }|d   }| j                  |d      }| j                  |dd      }| j                  |dd	      }| j                  |d
      }	| j                  |d      }
| j                  |d      }d }|=t	        j
                  |      }| j                  |d      }| j                  |      }||d}| j                  |d      }|dk(  rd}n|dk(  rd}| j                  ||| j                  |      |||
d ||	||d |d|      S )NtradeIdr  r|  ry  r  fillPxpxfillSzr4  sideordIdr  feeCcyr  r  execTypeTr  Mr  )r  r  r  ry  rJ   orderro  takerOrMakerrs  r>  r  r  r  )	rp  r  r  ra  rE   
string_negr  
safe_trader  )rg  rm  rl  rJ   r  ry  r  r>  r  rs  orderIdfeeCostStringr  feeCostSignedfeeCurrencyIdfeeCurrencyCoder{  s                    ri  parse_tradezokx.parse_trade  sz   d eY/##E84!!(FC8!%%eT2	""5(D9##E8T:v.""5'2((6$#..}=M ,,UH=M"55mDO%+C ''z:3"LS "L"Y/( 
  	rj  sincec                   K   | j                          d{    d}| j                  |dd      \  }}|r!| j                  d||||dddd	       d{   S | j                  |      }d|d	   i}d}|d
   r*| j	                  | j                  ||             d{   }n}|||d<   d}	| j                  |ddd      \  }	}|	dk(  r*| j                  | j                  ||             d{   }n.|	dk(  r)| j                  | j                  ||             d{   }| j                  |dg       }
| j                  |
|||      S 7 -7 7 7 a7 4w)a  
        get the list of most recent trades for a particular symbol

        https://www.okx.com/docs-v5/en/#rest-api-market-data-get-trades
        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 str [params.method]: 'publicGetMarketTrades' or 'publicGetMarketHistoryTrades' default is 'publicGetMarketTrades'
        :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   paginatero  afterr  r  rJ   r[   rS  r  publicGetMarketTradespublicGetMarketHistoryTradesr  )
r5  r6  fetch_paginated_call_cursorrl  publicGetPublicOptionTradesr  r  r  r  parse_trades)rg  ry  r  rS  rs  r  rl  r  r  r  r  s              ri  fetch_tradeszokx.fetch_trades  s     !!!88PZ[&99-QVX]_egpry{  BE  F  F  FV$fTl
 (!==dkk'SY>Z[[H #( F!::6=RZ\stNFF00!%!;!;DKKQW<X!YY99!%!B!B4;;wX^C_!``F ~~h3  vue<<q 	" F \ Z`sY   EE:EEAEEAE(E
).EE,EEE
EEc           	         | j                  d|d       }|d   }|dk(  rdnd}| j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d	      | j                  ||      gS )
Nr   r   rW   r     r   r   r  r   )rr  r  r  )rg  ohlcvrl  r	  ro  volumeIndexs         ri  parse_ohlcvzokx.parse_ohlcv.	  s     00vtL1v FNaeQ'UA&UA&UA&UA&UK0
 	
rj  r   c           	      v  K   | j                          d{    | j                  |      }d}| j                  |dd      \  }}|r| j                  d|||||d       d{   S | j	                  |d      }| j                  |d      }| j                  | j                  di       }	| j	                  |	dd      }
|d	}nt        |d
      }| j                  |      }| j	                  | j                  ||      }|
dk(  r|dk\  r||
j                         z  }|d   ||d}d}|\| j                         }|dz  }|d|z  z
  }||k  rd}t        |d	      }t        |dz
  d      }||d<   | j                  |||z        |d<   | j                  |d      }|||d<   | j                  |d      }| j	                  |	d|      }| j	                  |d|      }| j                  |d      }|dk(  }d}|dk(  rV|r*| j!                  | j#                  ||             d{   }n| j%                  | j#                  ||             d{   }n|dk(  ra|d   d   |d<   |r*| j'                  | j#                  ||             d{   }n| j)                  | j#                  ||             d{   }nU|r*| j+                  | j#                  ||             d{   }n)| j-                  | j#                  ||             d{   }| j/                  |dg       }| j1                  |||||      S 7 7 7 7 7 7 7 e7 =w)a   
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://www.okx.com/docs-v5/en/#rest-api-market-data-get-candlesticks
        https://www.okx.com/docs-v5/en/#rest-api-market-data-get-candlesticks-history
        https://www.okx.com/docs-v5/en/#rest-api-market-data-get-mark-price-candlesticks
        https://www.okx.com/docs-v5/en/#rest-api-market-data-get-mark-price-candlesticks-history
        https://www.okx.com/docs-v5/en/#rest-api-market-data-get-index-candlesticks
        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   r     r>  r  r  r  r  i`T  rJ   )r  barrS  Candles  i  HistoryCandlesr   r   beforer  untilro  r;  r<  r  
instFamilyr  r  )r5  rl  r6  "fetch_paginated_call_deterministicrp  rq  rv  r`  r  parse_timeframer   lowerr  rP  sumr  &publicGetMarketHistoryMarkPriceCandlesr  publicGetMarketMarkPriceCandles"publicGetMarketHistoryIndexCandlespublicGetMarketIndexCandlespublicGetMarketHistoryCandlespublicGetMarketCandlesr  parse_ohlcvs)rg  ry  	timeframer  rS  rs  rl  r  r>  r`  r  durationr  r  r  nowdurationInMillisecondshistoryBorder	startTimer  ro  isHistoryCandlesr  r  s                           ri  fetch_ohlcvzokx.fetch_ohlcvH	  sm    * !!!V$88zZ&@@vW\^cenpvx{|||  167+..|R@##GZ?=EsOE''	2t	9EH$58>>##CTl

  ##%C%-_"H0F#FGM}$.E3EAIq)I )GH#xx/E/MNGG!!&'2$GGYYvw/F&&wD<66* $44F?!%!L!LT[[Y`bhMi!jj!%!E!EdkkRY[aFb!ccg &v| <GH!%!H!HU\^dIe!ff!%!A!A$++gW]B^!__!%!C!CDKKPWY_D`!aa!%!<!<T[[RX=Y!ZZ ~~h3  vy%GGQ 	"
 }R kc g_ bZs   L9L&A	L9 L)!F2L9L,)L9=L/>;L99L1:)L9#L3$+L9L5)L99L7:-L9)L9,L9/L91L93L95L97L9c           
      0  K   |t        | j                  dz         | j                          d{    d}| j                  |dd      \  }}|r| j	                  d|||d|d       d{   S | j                  |      }d|d	   i}|t        |d
z
  d      |d<   |||d<   | j                  | j                  ||             d{   }g }	| j                  |dg       }
t        dt        |
            D ]n  }|
|   }| j                  |d      }|	j                  || j                  | j                  |d            | j!                  |d      || j#                  |      d       p | j%                  |	d      }| j'                  ||d   ||      S 7 ^7 (7 έw)a  
        fetches historical funding rate prices

        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   r  r  r  r  rJ   r   r   r  rS  r  fundingTimerealizedRate)r  ry  fundingRater  r  r  ry  )r1   rJ   r5  r6  r  rl  rP  !publicGetPublicFundingRateHistoryr  r  r  r  r  r  safe_symbolrp  r  r  sort_byfilter_by_symbol_since_limit)rg  ry  r  rS  rs  r  rl  r  r  ratesr  r  rater  sorteds                  ri  fetch_funding_rate_historyzokx.fetch_funding_rate_history	  s     >#DGG.e$eff!!!88AZ\fg&@@AZ\bdikprvx~  AD  E  E  EV$fTl
  #EAIq 1GH$GG??GU[@\]]. ~~h3q#d)$ 		A7D))$>ILL**4+;+;D(+KL#//nE& LL3 		 e[1009I5RWXXc 	" E ^s5   .FF8F)F*AFFC	FFFc                 P    |dk(  r| j                  |      S | j                  |      S )Nr-  )parse_funding_balanceparse_trading_balance)rg  ro  r  s      ri  parse_balance_by_typezokx.parse_balance_by_type	  s,    9--h77--h77rj  c                 \   d|i}| j                  |dg       }| j                  |di       }| j                  |d      }| j                  |dg       }t        dt	        |            D ]  }||   }| j                  |d      }	| j                  |	      }
| j                         }| j                  |d      }| j                  |d      }||+| j                  |d	      |d
<   | j                  |d      |d<   n
||d<   ||d
<   |||
<    ||d<   | j                  |      |d<   | j                  |      S )Nr  r  r   uTimedetailsr  eqavailEqavailBalfree	frozenBalusedtotalr  r  )
r  rv  r  r  r  rp  r  r  r  safe_balance)rg  r  r  r  r  r  r  r  balancer'  r  r  r  r  s                 ri  r  zokx.parse_trading_balance	  sI   )~~h3tQ+%%eW5	..	26q#g,' 	#AajG))'59J**:6DllnG!!'40B&&w	:G
"&"2"27J"G"&"2"27K"H#% ")"F4L	# ({!\\)4z  ((rj  c                 ~   d|i}| j                  |dg       }t        dt        |            D ]~  }||   }| j                  |d      }| j	                  |      }| j                         }| j                  |d      |d<   | j                  |d      |d<   | j                  |d	      |d
<   |||<    | j                  |      S )Nr  r  r   r  balr  r  r  r  r  )r  r  r  rp  r  r  r  )	rg  r  r  r  r  r  r'  r  r  s	            ri  r  zokx.parse_funding_balance
  s    )~~h3q#d)$ 		#A1gG))'59J**:6DllnG#//?GG"..w
CGFO"..wDGFO"F4L		#   ((rj  r  c                     || j                  d |      | j                  t        j                  | j	                  |dd                  | j                  t        j                  | j	                  |dd                  d d dS )Nr  makerUr  takerU)r  ry  r  r  rO  	tierBased)r  rf  rE   r|  ra  )rg  r  rl  s      ri  parse_trading_feezokx.parse_trading_fee
  s{     &&tV4&&w'9'9$:L:LSRY[c:d'ef&&w'9'9$:L:LSRY[c:d'ef
 	
rj  c                   K   | j                          d{    | j                  |      }d| j                  |d         i}|d   r	|d   |d<   n9|d   s
|d   s|d	   r|d
   dz   |d   z   |d<   nt        | j                  dz         | j                  | j                  ||             d{   }| j                  |dg       }| j                  |di       }| j                  ||      S 7 7 >w)aa  
        fetch the trading fees for a market

        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>`
        Nrn  ro  rW   rJ   r  rY   rZ   r[   r  r|  r  r  zE fetchTradingFee() supports spot, swap, future or option markets onlyr  r   )
r5  rl  rx  r;   rJ   privateGetAccountTradeFeer  r  rv  r  r[  s           ri  fetch_trading_feezokx.fetch_trading_fee/
  s     !!!V$77vG
 &> &tGHF^vh/6(3C#H-3fY6GGGENtww)ppqq77GV8TUU& ~~h3tQ+%%eV44G 	" Vs"   C.C*BC.-C,.=C.,C.c                 N  K   | j                          d{    | j                  dd|      \  }}i }d}|dk(  r*| j                  | j                  ||             d{   }n)| j	                  | j                  ||             d{   }| j                  ||      S 7 7 B7 w)a  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-balance
        https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-balance

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: wallet type, ['funding' or 'trading'] default is 'trading'
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nrv   r-  )r5  rr  privateGetAssetBalancesr  privateGetAccountBalancer  )rg  rs  r  queryr  r  s         ri  fetch_balancezokx.fetch_balance^
  s      !!! >>~tU[\
E
 "!99$++gu:UVVH!::4;;wPU;VWWHN ))*h??a 	" WWs4   B%BAB%B!)B%B#	B%!B%#B%r  c                   K   | j                          d{    | j                  |      }|d   st        | j                  dz         ddd}| j	                  |dd|d| j                  ||             d{   S 7 e7 w)	  

        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>`
        NrW   z: createMarketBuyOrderWithCost() supports spot markets onlyF	quote_ccyr  tgtCcyrl  buyr5  rl  r;   rJ   create_orderr  rg  ry  r  rs  rl  reqs         ri  !create_market_buy_order_with_costz%okx.create_market_buy_order_with_cost
  s      !!!V$f~tww)eeff16!
 &&vxdDKKX[]cLdeee 	" f"   B A<A B 7A>8B >B c                   K   | j                          d{    | j                  |      }|d   st        | j                  dz         ddd}| j	                  |dd|d| j                  ||             d{   S 7 e7 w)	r  NrW   z; createMarketSellOrderWithCost() supports spot markets onlyFr  r  rl  sellr  r  s         ri  "create_market_sell_order_with_costz&okx.create_market_sell_order_with_cost
  s      !!!V$f~tww)ffgg16!
 &&vxtT[[Y\^dMefff 	" gr  ro  rs  r  r>  c                    | j                  |      }|d   ||| j                  ||      d}|d   }	|d   }
| j                  |g d      }| j                  |dd      }| j	                  |dd	      }| j                  |d
|      }| j                  |dd      }| j	                  |dd      }| j                  |d|      }| j                  |dd      }| j                  |dd      }| j                  |d      }|d u}| j                  |d      }|d u}| j                  |dd      }|d u}|d uxs |dk(  }| j                  |dd      }| j                  | j                  ddd      }| j                  |dd      }d}||dk7  rd}n|}| j                  |d d      }|	rD|r6|d!k(  r|d"   n|d#   }| j                  |d$|      } | j                  |       |d$<   |r|nd}!|!|d<   n|
r|d%   s|d&   rvd }"| j                  |d'd(      \  }"}|"|"|d)<   nVd }#| j                  |d'd*      \  }#}|#r<|d!k(  }$|d uxs |d uxs |}%|%r|$rd+nd,|d)<   |r| j                  |d      }n	|$rd,nd+|d)<   ||d<   |d-k(  }&d}'| j                  |&|d.k(  |      \  }'}| j                  |g d/      }|d0k(  xs |d1k(  }(|d2k(  xs |d3k(  })|d uxs |d uxs |d4k(  }*|&xr |(xs |d5k(  }+| j                  | j                  d6d7      },| j                  |d6|,      }-|
s|s|-|d6<   |&s|+rd-|d8<   |	r|d!k(  r|-d9k(  rd}.| j                  |d'd:d      \  }.}| j                  |d;d<      }/| j                  |d;d<g      }|.rh|L|/j| j                  |      }0| j                  |      }1t        j                   |0|1      }2| j#                  |2      }/n |/t%        | j&                  d=z         |/|n|/}/| j)                  ||/      |d<<   |+r!|
rd5|d8<   n|s|*s| j+                  ||      |d><   |'rd.|d8<   n|(r|+sd1|d8<   n|)rd3|d8<   |r"t        j,                  |d?      }3|3|d<   d@|d8<   n-|s|rl|r-| j                  |g dA      }4|4t%        | j&                  dBz         | j+                  ||4      |d<   | j                  |g dC      }5| j                  |dD      }6|6c|6dEk(  }7|6d-k(  }8|7s|8st%        | j&                  dFz         |7r0|5t%        | j&                  dGz         | j+                  ||5      |d<   n(|6d-k(  r#dH|d<   n|5| j+                  ||5      |d<   ndH|d<   | j                  |dIdd      }9|9,|9dk7  r"|9dJk7  r|9dKk7  rt%        | j&                  dLz         |9|d<   |r| j                  |g dM      }:|:t%        | j&                  dNz         | j+                  ||:      |d	<   | j                  |g dO      };| j                  |dDdP      }<|<h|<dEk(  }=|<d-k(  }>|=s|>st%        | j&                  dQz         |=r5|;t%        | j&                  dRz         |<|dP<   | j+                  ||;      |d
<   n-|<d-k(  r(dH|d
<   n"|;dE|dP<   | j+                  ||;      |d
<   ndH|d
<   | j                  |dIdd      }?|?|?dk7  r"|?dJk7  r|?dKk7  rt%        | j&                  dSz         |?|d<   n|r4d|d8<   | j+                  ||      |dT<   |&rdHn| j+                  ||      |dU<   n|*rd4|d8<   |d uxr |d u}@|@rdV|d8<   |5| j+                  ||      |d	<   dH}A|| j+                  ||      }AA|d
<   ||d<   |5| j+                  ||      |d<   dH}B|| j+                  ||      }BB|d<   ||d<   |:| j                  | j                  dW      }C|C5C| j/                         z   |d<   |C|dX<   n||d<   | j                  |ddg      }| j1                  ||      S )YNrJ   )r  rs  ordTyper4  rW   r  )rD  	stopPrice	triggerPxrI  GTCrG  tpTriggerPxtpOrdPxtpTriggerPxTyper:  rF  slTriggerPxslOrdPxslTriggerPxTypeclOrdIdclientOrderIdstopLoss
takeProfittrailingPercentcallbackRatior&  
reduceOnlyFdefaultMarginModerC  crosstdModecashTrX   r  r  r  r  rY   rZ   rh   positionSideposSiderJ  shortlongrl  	post_only)r  r  rC  rI  r  rD  r  rF  rG  r  r  rX   r  r  r  r?  iocr@  fokr%  optimal_limit_iocr  base_ccyr  r  r  r  r4  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)rq  100r(  )rD  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)r>  rF  r  ro  rS  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-1r=  r<  r;  zT createOrder() stop loss trigger price type must be one of "last", "index" or "mark")rD  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)r>  rG  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'  r9  tag)rl  amount_to_precisionsafe_value_nrp  safe_value_2
safe_valuera  r`  r  r  r6  rq  handle_post_onlysafe_number_2number_to_stringrE   
string_mulrf  r8   rJ   cost_to_precisionprice_to_precision
string_divuuid16r  )Drg  ry  ro  rs  r  r>  rs  rl  r  rW   r  rD  rI  rG  r  r  rF  r  r  r  r  stopLossDefinedr  takeProfitDefinedr  isTrailingPercentOrderr&  isReduceOnlyr  rC  rX   defaultCurrencyr  	tradeModer  rJ  isBuyisProtectiveisMarketOrderpostOnlyr  r  r%  	marketIOCdefaultTgtCcyr  r  notionalamountStringpriceStringquoteAmountconvertedTrailingPercentstopLossTriggerPricestopLossLimitPricestopLossOrderTypestopLossLimitOrderTypestopLossMarketOrderTypestopLossTriggerPriceTypetakeProfitTriggerPricetakeProfitLimitPricetakeProfitOrderTypetakeProfitLimitOrderTypetakeProfitMarketOrderTypetakeProfitTriggerPriceTypetwoWayCondition
tpOrdPxReq
slOrdPxReqr9  sD                                                                       ri  create_order_requestzokx.create_order_request  s[
   V$Tl  **66:
4 f~*%((1[\&&v}eD++F4E}U//&)U;**63DfM))&/=Q//&)U;**63DfM**69oN??6:6#4/__V\:
't3,,V5FX!0!<t+C1Bv|UC ..t||=PR^`gh''hG
"v)=F*J^^FHe<F6:em&/&QW.++FE?K!%!8!8!B&,
&I )GHf~!1#'+'D'DV]\j'k$f+)5GI&!F%)%B%B6=Zb%cNFF!%(7t(C's^bIb'sgs' =BvGI.+)-6<)H;@gGI. *GH(00@SU[\&6  $s  te#7e#7$D0moT6QmW[_lWl"*sL8K0K	((xL!!&(MB6 &GHI!)GI [(8<5@D@]@]^dfs  vY  [_  A`=5v#11&&$GH!YYv~>F8 ,'//3/D/DV/L.2.C.CE.J.5.@.@{.[+/+<+<[+I%-".tww  :z  0z  #{  {.6.>6X$($:$:68$LGDMX%8	"k $ 7 7 F!,GI!&GI!&GI!'.'9'9/5'Q$'?GO$!2GI 1'+'8'8Co'p$'/&tww  2a  (a  b  b)-)@)@I])^&%)%6%6xAf%g"$($4$4Xv$F!$0.?7.J*/@H/L+2=T*477  6D  ,D  E  E/-5".tww  :}  0}  #~  ~151H1HQc1dGI.*h6-1	*'3)-)@)@I[)\GI&)-GI&+/+=+=hHZ\mou+v(+70F:AY]dAd  lD  HN  lN*477  6L  ,L  M  M1IG-. )-):)::Gs)t&)1&tww  2i  (i  j  j)-)@)@I_)`&'+'8'8El'm$&*&8&8V[&Y#&20Cw0N,1D1P-4?X*477  6F  ,F  G  G1/7".tww  :C  0C  #D  D3FGK0151H1HQe1fGI.,8-1	*)5+2GK()-)@)@I])^GI&)-GI&-1-?-?
L^`qsy-z*-92f<C]ahCh  pJ  NT  pT*477  6N  ,N  O  O1KG-.!*GI#'#:#:6<#PGK )6D<S<STZ\a<bGI!.GI /t ;\-W[B[O %*	"*)-)@)@)Y&!
&!%!8!8!IJ%/	"-<)*()-)@)@)W&!
&!%!8!8!IJ%/	"-<)* ''jAH#%-%=	"!)!.GIYYv	?'CDF{{7F++rj  c                   K   | j                          d{    | j                  |      }| j                  ||||||      }| j                  | j                  dd      }	| j                  |d      }
|
dk(  s|
dk(  s|
dk(  s|dk(  s|dk(  s
|d	k(  s|d
k(  rd}	|	dk7  r"|	dk7  r|	dk7  rt        | j                  dz         |	dk(  r|g}d}|	dk(  r| j                  |       d{   }n8|	dk(  r| j                  |       d{   }n| j                  |       d{   }| j                  |dg       }| j                  |di       }| j                  ||      }||d<   ||d<   |S 7 L7 7 g7 Ow)a	
  
        create a trade order

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order
        https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-multiple-orders
        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 fulfilled, 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'
        :param bool [params.hedged]: *swap and future only* True for hedged mode, False for one way mode
        :param str [params.marginMode]: 'cross' or 'isolated', the default is 'cross'
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nrh   r  r  r&  r%  r(  r'  r)  r*  privatePostTradeOrderAlgoprivatePostTradeOrderz createOrder() self.options["createOrder"] must be either privatePostTradeBatchOrders or privatePostTradeOrder or privatePostTradeOrderAlgor  r   ro  rs  )r5  rl  r9  rp  r`  r,   rJ   r<  r;  r  r  rv  parse_order)rg  ry  ro  rs  r  r>  rs  rl  r  r  requestOrdTyper  r  r  rz  s                  ri  r  zokx.create_order  s    > !!!V$++FD$vV!!$,,?\]))'9=i'^}-LR`duRu{  DU  |U  [_  ch  [h  nr  v  n  EI  MS  ES0F--F>Y4Y`f  kH  aH  +x  !x  y  y22 iG,,!77@@H22!;;GDDH!==gFFH~~h3tQ+  /ff5 	"  ADFsG   E+E"C	E+ E%!E+?E' E+E)A	E+%E+'E+)E+ordersc           	      L  K   | j                          d{    g }t        dt        |            D ]  }||   }| j                  |d      }| j                  |d      }| j                  |d      }| j	                  |d      }	| j	                  |d      }
| j                  |di       }| j                  ||      }| j                  ||||	|
|      }|j                  |        | j                  |       d{   }| j                  |d	g       }| j                  |      S 7 	7 +w)
a  
        create a list of trade orders

        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
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   ry  ro  rs  r  r>  rs  r  )r5  r  r  rp  r  rv  r  r9  r  r  r  parse_orders)rg  r?  rs  ordersRequestsr  rawOrderr  ro  rs  r  r>  orderParamsextendedParamsorderRequestr  r  s                   ri  create_orderszokx.create_orders$  s+     !!!q#f+& 
	0AayH''(;H##Hf5D##Hf5D__Xx8FOOHg6E..8R@K![[f=N44XtT6SXZhiL!!,/
	0 99.II. ~~h3  &&K 	" Js"   D$DCD$6D"7)D$"D$rJ   c                    | j                  |      }d|d   i}	d }
|dk(  s|dk(  s|dk(  s|dk(  s
|dk(  s|dk(  rd	}
| j                  |d
d      }||
r||	d<   n||	d
<   n|
r||	d<   n||	d<   | j                  |dd      }| j                  |d      }| j	                  |dd      }| j                  |dd      }| j                  |d      }| j	                  |dd      }| j                  |d      }| j                  |d      }|d u}|d u}|
r||t        | j                  dz         |P|t        | j                  dz         | j                  ||      |	d<   |dk(  rdn| j                  ||      |	d<   ||	d<   ||t        | j                  dz         | j                  ||      |	d<   |dk(  rdn| j                  ||      |	d<   ||	d<   nX|6| j                  ||      |	d<   |dk(  rdn| j                  ||      |	d<   ||	d<   |6| j                  ||      |	d<   |dk(  rdn| j                  ||      |	d<   ||	d<   |rl| j                  |d      }| j                  |d       }| j	                  |d!      }| j                  ||      |	d<   |dk(  rdn| j                  ||      |	d<   ||	d<   |rx| j                  |d      }| j                  |d       }| j	                  |d!      }|d"k(  r|nd#|	d$<   | j                  ||      |	d<   |dk(  rdn| j                  ||      |	d<   ||	d<   || j                  ||      |	d%<   |
s|| j                  ||      |	d&<   | j                  |g d'      }| j                  |	|      S )(Nr  rJ   r&  r%  r(  r'  r)  r*  Tr  r  algoClOrdIdalgoIdrt  rF  newSlTriggerPx
newSlOrdPxnewSlTriggerPxTyper:  rG  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 orderrl  r	  zF editOrder() requires a newTpOrdPx parameter for editing an algo orderrD  r>  ro  rS  	conditionnewTpOrdKindnewSznewPx)r  r  rG  rF  r  r  r"  )rl  ra  r  r  rp  r2   rJ   r  r  rq  r  )rg  rJ   ry  ro  rs  r  r>  rs  rl  r  isAlgoOrderr  r*  rF  r/  r0  rG  r5  r  r  r  r  stopLossTypetakeProfitTypes                           ri  edit_order_requestzokx.edit_order_requestU  s{   V$fTl
 I4=#8dFW>W]aej]jpt  yB  qB  HL  PV  HVK**69oN$)6&%2	"$&!#% #00JZ[=#'#3#3F<PRX#Y !%!2!26;LN^!_//&,?%)%5%5f>RTZ%["??6:6__V\:
#4/'t3$,3I3Q   ,J  "J  K  K#/ ($TWW/w%wxx,0,C,CFL`,a()151AH_H_`fhuHv%0H,-%1"*$TWW/w%wxx,0,C,CFLb,c()151AH_H_`fhwHx%0J,-#/,0,C,CFL`,a()151AH_H_`fhuHv%0H,-%1,0,C,CFLb,c()151AH_H_`fhwHx%0J,-'+x'P$ $' B#//&A,0,C,CFL`,a()1=1IPTPgPghnp}P~%0H,- )-^)T&"&//*g"F!%!1!1*f!E=Kw=V.]h',0,C,CFLb,c()1?81KRVRiRijp  sB  SC%0J,-#77GGG #'#:#:65#I 6  $J  K{{7F++rj  c           	        K   | j                          d{    | j                  |      }| j                  |||||||      }	d}
|dk(  s|dk(  s|dk(  s|dk(  s
|dk(  s|dk(  rd}
d}|
r*| j                  | j	                  |	|             d{   }n)| j                  | j	                  |	|             d{   }| j                  |d	g       }| j                  |d
i       }| j                  ||      }||d<   ||d<   |S 7 7 t7 Lw)a
  
        edit a trade order

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-amend-order
        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 fulfilled, 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*  Tr  r   ro  rs  )	r5  rl  rX  privatePostTradeAmendAlgosr  privatePostTradeAmendOrderr  rv  r=  )rg  rJ   ry  ro  rs  r  r>  rs  rl  r  rU  r  r  r  rz  s                  ri  
edit_orderzokx.edit_order  s;    @ !!!V$))"fdD&%QWXI4=#8dFW>W]aej]jpt  yB  qB  HL  PV  HVK!<<T[[RX=YZZH!<<T[[RX=YZZH  ~~h3tQ+  /ff? 	" [Zs5   DD A6DD)D7D8A	DDDc                   K   |t        | j                  dz         | j                  |dd      }| j                  |dd      }|s|r.| j	                  |g||       d{   }| j                  |d      S | j                          d{    | j                  |      }d|d	   i}| j                  |d
d      }	|	|	|d
<   n||d<   | j                  |d
dg      }
| j                  | j                  ||
             d{   }| j                  |dg       }| j                  |d      }| j                  ||      S 7 7 7 ?w)a  
        cancels an open order

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-order
        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&  rK  Fr   r  rJ   r  r  rt  r  )r1   rJ   r  r  cancel_ordersr  r5  rl  ra  rq  privatePostTradeCancelOrderr  rv  r=  )rg  rJ   ry  rs  r&  rK  
orderInnerrl  r  r  r  r  r  rz  s                 ri  cancel_orderzokx.cancel_order  sP     >#DGG.Y$YZZ##FFI>>>&*e<h#112$GGJ??:q11!!!V$fTl

 **69oN$!.GI!GG		&9o">?99$++gu:UVVx4tQ'v..' H! Ws7   AD?D9)D?D;	A4D?=D=><D?;D?=D?c                 L    |!t        |t              r|j                  d      S |S )zg
 @ignore
        :param string[]|str ids: order ids
        :returns str[]: list of order ids
        ,)
isinstancestrr  )rg  idss     ri  	parse_idszokx.parse_ids
  s%     OC!599S>!Jrj  c                 l  K   |t        | j                  dz         | j                          d{    | j                  |      }g }| j	                  | j
                  di       }| j                  |dd      }| j                  |d|      }| j                  | j                  |dd            }	| j                  | j	                  |d            }
| j                  |d	d
      }| j                  |dd      }|s|rd}|	| j                  |      }|
4t        dt        |
            D ]  }|j                  |
|   |d   d        t        dt        |            D ];  }|s|r|j                  ||   |d   d       "|j                  ||   |d   d       = n4t        dt        |	            D ]  }|j                  |d   |	|   d        d}|dk(  r| j                  |       d{   }n| j                  |       d{   }| j                  |dg       }| j!                  ||dd|      S 7 7 I7 1w)a  
        cancel multiple orders

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-multiple-orders
        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 argumentr`   r  r"  r  r  rJ  r^  r&  rK  FprivatePostTradeCancelAlgosr   rJ   )rJ  r  )rt  r  )r  r  r  )r1   rJ   r5  rl  r  r`  rp  rh  r  r  r  r  r  rj  r"  r  rA  )rg  rg  ry  rs  rl  r  r`  defaultMethodr  clientOrderIdsalgoIdsr&  rK  r  r  
ordersDatas                   ri  r_  zokx.cancel_orders  sR     >#DGG.Z$Z[[!!!V$//$,,C(((<_`!!&(MB(9(9&)_(]^..!BC##FFI>>>&*e<h2F!..%C"q#g,/ ANN")!*"(,$ 
 1c#h' 
wNN"%a&"(,$ 
 NN!$Q"(,$ 
 1c.12 $Tl-a0  
 22!==gFFH!CCGLLH< ^^Hfb9
  VT4HHQ 	"N GLs4   .H4H-F5H4&H0'H4 H2-H40H42H4c                   K   | j                          d{    g }| j                  | j                  di       }| j                  |dd      }| j                  |d|      }| j	                  |dd      }| j                  |dd      }|xs |}	|	rd	}t        d
t        |            D ]{  }
||
   }| j                  |d      }| j                  |dd      }| j                  |d      }| j                  |      }d}|	rd}n|d}d|d   i}||n|||<   |j                  |       } d}|d	k(  r| j                  |       d{   }n| j                  |       d{   }| j                  |dg       }| j                  |ddd|      S 7 o7 I7 1w)a5  
        cancel multiple orders for multiple symbols

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-multiple-orders
        https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order

        :param CancellationRequest[] orders: each order should contain the parameters required by cancelOrder namely id and symbol, example [{"id": "a", "symbol": "BTC/USDT"}, {"id": "b", "symbol": "ETH/USDT"}]
        :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>`
        Nr`   r  r"  r^  r&  rK  Frj  r   rJ   r  r  ry  rt  rJ  r  r  )r5  rv  r`  rp  safe_bool_2r  r  r  ra  rl  r  rj  r"  r  rA  )rg  r?  rs  r  r`  rk  r  r&  rK  isStopOrTrailingr  rz  rJ   r  ry  rl  idKeyrequestItemr  rn  s                       ri  cancel_orders_for_symbolszokx.cancel_orders_for_symbolsp  s     !!!..~rB(((<_`!!&(MB""669=>>&*e<".h2Fq#f+& 	(A1IE!!%.B ..uiQM%%eX6F[[(FE *!&,!K 4A3LSUKNN;'	(  22!==gFFH!CCGLLH< ^^Hfb9
  T4vFF{ 	"8 GLs4   FFD'F>F?FF
-FF
Ftimeoutc                    K   | j                          d{    d|dkD  r| j                  |dz        ndi}| j                  | j                  ||             d{   }|S 7 L7 w)au  
        dead man's switch, cancel all orders after the given timeout

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-all-after

        :param number timeout: time in milliseconds, 0 represents cancel the timer
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: the api result
        NtimeOutr   r  )r5  parse_to_intprivatePostTradeCancelAllAfterr  )rg  ru  rs  r  r  s        ri  cancel_all_orders_afterzokx.cancel_all_orders_after  sq      !!!Wq[t((48q
 <<T[[RX=YZZ # 	" [s"   A'A#AA'A%A'%A'r  c                 :    ddddddd}| j                  |||      S )Nr  rK  closed)r  order_failedlivepartially_filledfilled	effectiverp  rg  r  statusess      ri  parse_order_statuszokx.parse_order_status  s2    "& &!
 &&99rj  rz  c                 H   | j                  |d      }|;|dk7  r6| j                  | j                  |d      | j                  |d      d|d      S | j                  |dd      }| j                  |d      }| j                  |d	      }| j                  |d
      }| j                  |d      }| j                  |d      }	d }
d }|	dk(  rd}
d}	n|	dk(  rd}d}	n	|	dk(  rd}d}	| j                  |d      }| j	                  ||      }| j                  ||d      }| j                  |d      }| j                  |dd      }| j                  |d      }| j                  | j                  |d            }| j                  |d      }d }d }| j                  | j                  dd      }| j                  |d|      }| j                  |d      }|dk(  r"|	d k(  r|d!k(  r|d"k(  r| j                  |d#      }n| j                  |d#      }d }|Lt        j                  |      }| j                  |d$      }| j                  |      }| j                  |      |d%}| j                  |d      }|t        |      d&k  rd }| j                  |d'd(      }| j                  |d)d*      }| j                  |d+      }d,} | |d-k(  } | j                  i d.|d/|d0|d1|d2| j                  |      d3|d4|d5|d6|	d7|d8|
d|d9|d:|d;|d<| j                  |d=d>g      d?||||d ||d | d@|      S )ANsCode0rt  r  rejected)rJ   r  r  r  rJ  cTimer  fillTimers  r  r  TrS  r  r@  r  r?  r  r|  	accFillSzrq  ordPxavgPxr  r  r  r  rn  r  rl  r/  r  r4  ru  rv  r   r  r  r  r  r  Ftruer  rJ   r  r  r  lastTradeTimestamplastUpdateTimestampry  ro  rI  r"  r>  rF  rG  rD  r  moveTriggerPxrP  )r  r  r  	remainingr  r  tradesr  )rp  
safe_orderra  r  r  r  r  r`  rE   r|  r  rf  r  r  r  safe_number_n)!rg  rz  rl  scoderJ   r  r  r  rs  ro  r"  rI  r  ry  r  r>  rP  r  r  r  r  r$  r  rn  r  r  r  r  r  rF  rG  reduceOnlyRawr  s!                                    ri  r=  zokx.parse_order  s*   T   0ESL??&&ug6!%!1!1%!C$	$   x9%%eW5	"//w?!..ujAv.y1;HDU]KDU]KD##E84!!(F3!!(FC8!!%5""5$8""5'2(()9)9%)IJ((6 ((xL!!%=A##E:6EM 0x67IPVZePe##E40D %%eT2F$#..}=M ,,UH=M"55mDO))-8+C ((	:%C,>,B M**5-K,,UM9M((=
!'61J  
E 
" 
 ] 
 	 

 Y/ 
 !"4 
 "#6 
 f 
 D 
 ; 
  
 D 
 U 
 ] 
  
  D..u{O6TU! 
" w# 
$ $3 
4 5 	rj  c                   K   |t        | j                  dz         | j                          d{    | j                  |      }d|d   i}| j	                  |dd      }| j                  | j                  di       }| j                  |dd	      }| j                  |d|      }	| j                  |d
d      }
|
rd}	|||d<   n||d<   n|||d<   n||d<   | j                  |g d      }d}|	dk(  r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |dg       }| j                  |d      }| j                  ||      S 7 J7 h7 @w)a  
        fetch an order by the id

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-details
        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  rJ   r  r  r   r  r   r^  r&  privateGetTradeOrderAlgorI  rJ  rt  )r  r  r  r^  r&  r  r   )r1   rJ   r5  rl  ra  r  r`  rp  r  rq  r  r  r   rv  r=  )rg  rJ   ry  rs  rl  r  r  r`  rk  r  r&  r  r  r  rz  s                  ri  fetch_orderzokx.fetch_order  s     >#DGG.X$XYY!!!V$fTl
 **69oN//$,,bA(((<RS!!&(MB##FFI>/F()6&$&!(%2	"#% 		&"[\//!::4;;wPU;VWWH!66t{{7E7RSSHB x4tQ'v..A 	"6 XSs4   .FE:C#FE=)F>E??<F=F?Fc                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S i }d}|| j                  |      }|d   |d<   |||d<   | j	                  | j
                  di       }| j	                  | j
                  di       }	| j                  |d	d
      }
| j                  |d	|
      }| j                  |d      }| j                  |dd      }| j                  |dd      }|s|s||	v rd}|rd|d<   n	|r|d|d<   | j                  |g d      }d}|dk(  r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |dg       }| j                  ||||      S 7 7 v7 [7 3w)a  
        fetch all unfilled currently open orders

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-list
        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.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 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   r  rJ   r  rS  r5  r  r!  r  r^  r&  rK   privateGetTradeOrdersAlgoPendingr(  r  r^  r&  rK  r  )r5  r6  fetch_paginated_call_dynamicrl  r  r`  rp  r  r  rq  r  r  r!  r  rA  )rg  ry  r  rS  rs  r  r  rl  r`  r5  rk  r  r  r&  rK  r  r  r  s                     ri  fetch_open_orderszokx.fetch_open_orders;  s    $ !!!88ART^_&::;LfV[]bdjkkk	
 [[(F &tGH$GG//$,,0A2F7GL(((<Z[!!&(MB""695##FFI>>>&*e<w7n#<7F!2GI'/!*GI		&"KL77!BB4;;wX]C^__H!>>t{{7TY?Z[[H@ ~~h3  vue<<Q 	" lB `[sF   G
G 6G
GDG
*G+)G
G,G
G
G
G
c                 l  K   | j                          d{    i }d}|| j                  |      }|d   |d<   d}d}| j                  d||      \  }}| j                  |      |d<   |||d<   d|d<   | j	                  | j
                  di       }	| j	                  | j
                  d	i       }
| j                  |	d
d      }| j                  |d
|      }| j                  |d      }| j                  |dd      }| j                  |dd      }|rd}d|d<   n|s||
v rId}| j                  |d      }|||d<   | j                  |d      }|rM|Kt        | j                  dz         |||d<   | j                  |d      }|||d<   | j                  |dg      }| j                  |g d      }d}|dk(  r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j!                  |dg       }| j#                  ||||      S 7 7 X7 0w)ac  
        fetches information on multiple canceled orders made by the user

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-7-days
        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.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.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>`
        NrJ   r  r{   rn  rS  r  r  r5  r  r#  r  r^  r&  rK  F privateGetTradeOrdersAlgoHistoryr(  rJ  z fetchCanceledOrders() requires an "ordType" string parameter, "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"beginr  r  r  r  )r5  rl  rr  rx  r  r`  rp  r  r  rq  r1   rJ   r  r  r  r#  r  rA  )rg  ry  r  rS  rs  r  rl  ro  r  r`  r5  rk  r  r  r&  rK  rJ  r  sendr  r  s                        ri  fetch_canceled_orderszokx.fetch_canceled_orders  s    $ !!!

 [[(F &tGH889NPVX^_e"==dC
$GG%//$,,0ErJ7GL(((<Z[!!&(MB""695##FFI>>>&*e<7F!2GIN27F%%fh7F!$*!684?+DGG  7@  -@  A  A #( %%eW5E !&		%'3yy IJ77!BB4;;wX\C]^^H!>>t{{7TX?YZZHH ~~h3  vue<<w 	"h _Zs4   H4H-G H4H0)H4H2,H40H42H4c                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S i }d}|| j                  |      }|d   |d<   d}d}	| j	                  d||      \  }}	| j                  |      |d<   |||d<   | j                  | j                  di       }
| j                  | j                  d	i       }| j                  |
d
d      }| j                  |d
|      }| j                  |d      }| j                  |dd      }| j                  |dd      }|s|s||v rd}d|d<   |rd|d<   nB|r|>d|d<   n8|||d<   | j                  |	d      }|||d<   | j                  |	dg      }	d|d<   | j                  |	g d      }d}|dk(  r*| j                  | j                  ||             d{   }nX|dk(  r*| j                  | j                  ||             d{   }n)| j!                  | j                  ||             d{   }| j#                  |dg       }| j%                  ||||      S 7 E7 7 7 ]7 5w)a  
        fetches information on multiple closed orders made by the user

        https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-7-days
        https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-history
        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>`
        NFr}   r  rJ   r  rn  rS  r5  r  r#  r  r^  r&  rK  r  r  r  r(  r  r  r  r  r  #privateGetTradeOrdersHistoryArchiver  )r5  r6  r  rl  rr  rx  rv  r`  rp  rp  r  r  rq  r  r  r  r#  r  rA  )rg  ry  r  rS  rs  r  r  rl  ro  r  r`  r5  rk  r  r  r&  rK  r  r  r  r  s                        ri  fetch_closed_orderszokx.fetch_closed_orders  s    * !!!88ATV`a&::;NPVX]_dflmmm

 [[(F &tGH889LfV\]e"==dC
$GG../BBG6FK(((<Z[!!&(MB""695""669=>>&*e<w7n#<7F*GG!2GI%.	" #( %%eW5E !&		%'3'GGyy IJ77!BB4;;wX\C]^^H<<!EEdkkRY[_F`aaH!>>t{{7TX?YZZH@ ~~h3  vue<<s 	" n` _aZsX   I'I6I'IFI'I!.I'I#)I'/I%0,I'I'!I'#I'%I'c                 4  K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S i }d}|| j                  |      }|d   |d<   |||d<   | j	                  d||      \  }}| j                  d||      \  }}	| j                  |      |d	<   ||||d
<   | j                  | j                  ||	             d{   }
| j                  |
dg       }| j                  |||||	      S 7 7 7 0w)an  
        fetch all trades made by the user

        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   r  rJ   r  r  r  rn  rS  r  )r5  r6  r  rl  handle_until_optionrr  rx  privateGetTradeFillsHistoryr  r  r  )rg  ry  r  rS  rs  r  r  rl  ro  r  r  r  s               ri  fetch_my_tradeszokx.fetch_my_trades6  sT     !!!88R\]&::?FTY[`bhiii
 [[(F &tGH$GG225'6J88&RXYe"==dC
EM$GG99$++gu:UVV4 ~~h3  vueUCCi 	" j* Ws4   DD6DDBD%D&-DDDc           	      n   K   d|i}| j                  |||| j                  ||             d{   S 7 w)a?  
        fetch all the trades made from a single order

        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>`
        rt  N)r  r  )rg  rJ   ry  r  rS  rs  r  s          ri  fetch_order_tradeszokx.fetch_order_tradesz  s?      R
 ))&%GU[@\]]]]s   ,535r  c                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S | j                  | j                  di       }| j                  |d      }| j                  |d|      }| j                  |d      }i }d}	| j                  d|      \  }	}|	| j                  |d      }	|dk7  r|	|	|d<   | j                  dd|      \  }
}|
| j                  |
      |d<   |||d	<   d}|| j                  |      }|d
   |d<   | j                  d||      \  }}d}|dk(  r*| j                  | j                  ||             d{   }nX|dk(  r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j!                  |dg       }| j#                  ||||      S 7 7 7 7 ]7 5w)a  
        fetch the history of changes, actions done by the user or operations that altered balance of the user

        https://www.okx.com/docs-v5/en/#rest-api-account-get-bills-details-last-7-days
        https://www.okx.com/docs-v5/en/#rest-api-account-get-bills-details-last-3-months
        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 entries 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 [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        NFr   r  r  mgnModeprivateGetAssetBillsrn  rS  rJ   r  r  privateGetAccountBillsArchiver  )r5  r6  r  rv  r`  rp  rq  handle_margin_mode_and_paramsrr  rx  r  r  r  r  r  r  r  parse_ledger)rg  r  r  rS  rs  r  r`  r  r  rC  ro  r  r  r  r  s                  ri  fetch_ledgerzokx.fetch_ledger  s9    " !!!88PZ[&::=$PUW\^deee..}bA!!'84!!&(F;68,
 
!??vV
F))&)<J++%%/	"88fUe"&"A"A$"GGJ$GG}}T*H%d^GEN225'6J44!??GUZ@[\\H--!66t{{7E7RSSH!88We9TUUHb ~~h3  x>> 	" fJ ]SUsX   HG56HG8D"H0G;1.HG= )H	G?
,H8H;H=H?Hc                 D    dddddddddddd}| j                  |||      S )Nr   rm  rebater  )r  r  345r+  7891011r  )rg  ro  r  s      ri  parse_ledger_entry_typezokx.parse_ledger_entry_type  sA    
 tT22rj  itemr  c                 v   | j                  |d      }| j                  ||      }| j                  ||      }| j                  |d      }| j                  |d      }d }|'| j	                  t        j                  |            |d}| j                  |d      }| j                  |d d      }	| j                  || j                  |d      || j                  |      d | j                  |d      d | j                  | j                  |d	            ||	| j                  |d
      d | j                  |d      d|d|      S )Nr  r  r  rv  r  r|  billIdrt  ro  balChgr  r  )r  rJ   r  r  r  referenceIdreferenceAccountro  r  ry  r  r  r  r  r  )rp  r  r  r  rf  rE   r|  r  safe_ledger_entryr  r  r  )
rg  r  r  r'  r  r  r  r  r  ry  s
             ri  parse_ledger_entryzokx.parse_ledger_entry  sT   J %%dE2
&&z8<%%j(;%%dD1	((u5$))'*<*<]*KL C ##D(3!!(D#6%%""42"Y/++D': $001A1A$1OP&&tX6%%dE2'
  ! 	rj  c                 *   | j                  |d      }| j                  |g d      }|%| j                  |di       }| j                  |d      }| j                  |d      }| j                  ||      }|d   }| j                  |d      }| j                  |di       }	| j	                  |	d	      }
| j                  |
|      }|d
k(  r| j                  |
dd
      }| j                  |d      }| j                  ||      }| j                  |       |||||dS )Naddr)r  pmtIdmemoaddrExcommentr  r  r  r  rJ   zUSDT-PolygonzUSDT-Polygon-Bridger  )r  r  r  addressr  )rp  safe_string_nr  r  index_byr  r!  check_address)rg  depositAddressr  r  r  r  r'  r  r  r  networksByIdnetworkDatar  r.  s                 ri  parse_deposit_addresszokx.parse_deposit_addressV  s0   : "">6:  1IJ;__^XrBF""695C%%ne<
%%j(;  9??8Z<}}Xt4oolE:T N"++L:OQ_`K"";	:--gt<7#""
 	
rj  c                 b  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |dd      }| j                  ||d   gd      }| j                  |d	      S 7 7 Uw)
a  
        fetch a dictionary of addresses for a currency, indexed by network

        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  rJ   r  selectedTr  Fr  )r5  r  privateGetAssetDepositAddressr  r  	filter_byparse_deposit_addressesr  )	rg  r  rs  r  r  r  r  filteredparseds	            ri  "fetch_deposit_addresses_by_networkz&okx.fetch_deposit_addresses_by_network  s      !!!==&8D>
 ;;DKKQW<XYY, ~~h3>>$
D9--h&9I8JER}}VY//= 	"
 Zs#   B/B+A B/B-AB/-B/c                 &  K   | j                          d{    | j                  |d      }| j                  |d      }| j                  |      }| j	                  ||      }| j                  ||       d{   }|7| j                  ||      }|!t        | j                  dz   |z   dz   |z         |S | j	                  ||      }||v r||   S t        |j                               }| j                  |d      }	| j                  ||	      S 7 7 w)a  
        fetch the deposit address for a currency associated with self account

        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
        :param str [params.network]: the network name for the deposit address
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        Nr  z# fetchDepositAddress() cannot find z deposit address for r   )r5  rp  rq  r  r!  r  rv  r7   rJ   r  r  )
rg  r  rs  
rawNetworkr  r  r  codeNetworkr  r  s
             ri  fetch_deposit_addresszokx.fetch_deposit_address  s$     !!!%%fi8
69-&&t,))*d;@@vNN^^Hg6F~$TWW/T%TW^%^ax%x{%  A  AM--dD9("K((HMMO$  q)~~h..# 	"
 Os#   DDA D7D8BDDr  c                 H  K   | j                  ||      \  }}| j                  |       | j                          d{    | j                  |      }|t	        |      dkD  r|dz   |z   }|d   |d| j                  |      d}| j                  |d      }|^| j                  | j                  di       }	| j                  |	|j                         |      }|d   d	z   |z   |d
<   | j                  |d      }| j                  |d      }
|
| j                          d{   }| j                  | j                  |      | _        | j                  |d   | j                  |      i       }| j                  |d      }
|
t        | j                   dz         | j                  |
      |d<   | j                  |dg      }| j#                  | j%                  ||             d{   }| j'                  |dg       }| j                  |d      }| j)                  ||      S 7 7 7 Aw)a  
        make a withdrawal

        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  rJ   r  )r  toAddrdestamtr  r  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.r  )handle_withdraw_tag_and_paramsr  r5  r  r  r  rp  rv  r`  upperrq  r0  rc  
currenciesr!  r1   rJ   privatePostAssetWithdrawalr  r  parse_transaction)rg  r  r  r  r  rs  r  r  r  r  r  r  targetNetworkr  r  r  transactions                    ri  r   zokx.withdraw  s'     99#vFV7#!!!==&O#c(Q,mc)GD>((0	
 ""695~~dllJCH&&x'JG'~3g=GGYYvy1Fvu-;#4466J"..t
KDO NN8J+?AXAXY`AacefM""=%8C{'  3U  )U  V  V..s3		&5'*88We9TUU ~~h3nnT1-%%k8<<U 	"$ 7 Vs5   :H"HCH"HCH"H <H"H" H"c                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S i }d}|| j                  |      }|d   |d<   |t	        |dz
  d      |d	<   |||d
<   | j                  d||      \  }}| j                  | j                  ||             d{   }| j                  |dg       }	| j                  |	||||      S 7 7 7 0w)aV  
        fetch all deposits made to an account

        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>`
        NFr   r  rJ   r  r   r   r  rS  r  r  )
r5  r6  r  r  rP  r  privateGetAssetDepositHistoryr  r  parse_transactions
rg  r  r  rS  rs  r  r  r  r  r  s
             ri  fetch_depositszokx.fetch_deposits8  s.     !!!88R\]&::?DRWY^`fggg
 }}T*H%d^GEN #EAIq 1GH$GG227GVL;;DKKQW<XYYN ~~h3&&tXueVLL{ 	" h" Z4   C9C36C9C5A8C9C7-C95C97C9c                 D  K   | j                          d{    d|i}d}|| j                  |      }|d   |d<   | j                  | j                  ||             d{   }| j	                  |d      }| j                  |di       }| j                  ||      S 7 7 =w)a  
        fetch data on a currency deposit via the deposit id

        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depIdrJ   r  r  r   )r5  r  r  r  r  rv  r  )	rg  rJ   r  rs  r  r  r  r  r  s	            ri  fetch_depositzokx.fetch_deposit  s      !!!R
 }}T*H%d^GEN;;DKKQW<XYYx0..q"-%%gx88 	" Z"   B BA	B  B!<B B c                   K   | j                          d{    d}| j                  |dd      \  }}|r| j                  d||||       d{   S i }d}|| j                  |      }|d   |d<   |t	        |dz
  d      |d	<   |||d
<   | j                  d||      \  }}| j                  | j                  ||             d{   }| j                  |dg       }	| j                  |	||||      S 7 7 7 0w)ad  
        fetch all withdrawals made from an account

        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   r  rJ   r  r   r   r  rS  r  r  )
r5  r6  r  r  rP  r   privateGetAssetWithdrawalHistoryr  r  r  r  s
             ri  fetch_withdrawalszokx.fetch_withdrawals  s/     !!!88ASU_`&::;MtUZ\acijjj
 }}T*H%d^GEN #EAIq 1GH$GG227GVL>>t{{7TZ?[\\> ~~h3&&tXueVLLk 	" k" ]r  c                 D  K   | j                          d{    d|i}d}|| j                  |      }|d   |d<   | j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }| j                  |      S 7 7 =w)a  
        fetch data on a currency withdrawal via the withdrawal id

        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wdIdrJ   r  r  r   )r5  r  r  r  r  rv  r  )	rg  rJ   r  rs  r  r  r  r  
withdrawals	            ri  fetch_withdrawalzokx.fetch_withdrawal  s      !!!B
 }}T*H%d^GEN>>t{{7TZ?[\\, ~~h3^^D!R0
%%j11A 	" ]r  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}| j                  |||      S )Nz-3pendingz-2r  r	  failedr  r  r  r  r  r  r  r+  r  r  r  r  121516r  r  s      ri  parse_transaction_statuszokx.parse_transaction_status  s    0
)
*
 (
 	

 
 
 
 
 
 
 
 
 
 )
 )
  )!
" )#
& &&99rj  r  c                    d }d }| j                  |d      }| j                  |d      }| j                  |d      }|}| j                  |dd      }	| j                  |d|	      }	|d}|}n| j                  |d      }d	}| j                  |d
      }
| j                  |
      }| j                  |d      }| j	                  | j                  |d            }| j                  |d      }| j                  |d      }d }|d	k(  rd}n| j                  |d      }i d|d|d|d|dd d|d|d|dd d|	d|	d|d|dd d|d|d | j                  |      d d ||d!d"S )#Nr  fromtor  r  r  r  r  r  r  r  r  txIdr  r   r  r  rJ   r  r  r  addressFrom	addressTor  tagFromtagTor  ro  r  txidr  r  )r  r  )internalr  r  )rp  ra  r  r  r  r  r  )rg  r  r  ro  rJ   withdrawalIdr
  r  r  r  r'  r  r  r  r  r  feeCosts                    ri  r  zokx.parse_transaction<  s'   P ''V<&&{F;$$[$7	"";v>"";?#DB !!+w7BD%%k59
&&z2!!+u5..t/?/?W/UVV4%%k48	9G&&{E:G
K
"
 
 f	

 t
 ;
 
 w
 t
 U
 5
 f
 D
 t
 D
  !
" Y/#
$  )
 	
rj  c                   K   | j                          d{    d}| j                  d|      \  }}|| j                  |dd      }|dk7  r|dk7  rt        | j                  dz         | j                  |      }|d   |d}| j                  | j                  ||             d{   }| j                  |d	g       }| j                  ||      S 7 7 +w)
a  
        fetch the set leverage for a market

        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   r  r  isolatedzV fetchLeverage() requires a marginMode parameter that must be either cross or isolatedrJ   r  r  r  )
r5  r  rp  r2   rJ   rl  privateGetAccountLeverageInfor  r  parse_leverage)rg  ry  rs  rC  rl  r  r  r  s           ri  fetch_leveragezokx.fetch_leverage  s      !!!
!??QWX
F))&)WEJ'!
j(@TWW'  A  AV$Tl!
 ;;DKKQW<XYY ~~h3""4009 	" Zs"   CCBC&C'*CCrL  c                    d }d }d }d }t        dt        |            D ]  }||   }| j                  |d      }| j                  |d      }| j                  |d      }	|	dk(  r| j	                  |d      }V|	dk(  r| j	                  |d      }n| j	                  |d      }| j	                  |d      } || j                  ||      |||dS )	Nr   r  r  r   r  r  r  )r  ry  rC  longLeverageshortLeverage)r  r  r  rp  r  r  )
rg  rL  rl  r  rC  r  r  r  entryr  s
             ri  r  zokx.parse_leverage  s    
q#h-( 	BAQKE//yAJ''x8H11%CLv%#00@( $ 1 1% A#00@ $ 1 1% A	B &&x8$(*
 	
rj  c                   K   | j                          d{    | j                  |      }| j                  d||      \  }}d|d   i}|| j                  |      |d<   | j	                  | j                  ||             d{   }| j                  |dg       }| j                  |d      }	|	y| j                  |	|      S 7 7 @w)a  
        fetch data on a single open contract trade position

        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  rJ   rn  r  r   )	r5  rl  rr  rx  r  r  r  rv  parse_position)
rg  ry  rs  rl  ro  r  r  r  r  positions
             ri  fetch_positionzokx.fetch_position  s      !!!V$88&RXYe fTl

 "&"A"A$"GGJ88We9TUU^ ~~h3>>$*""8V44{ 	" Vs"   CCA,CC?CCc                 "  K   | j                          d{    i }|jg }t        dt        |            D ],  }||   }| j                  |      }|j	                  |d          . t        |      }|dkD  rdj                  |      |d<   | j                  | j                  di       }	| j                  |	dd      }
d}|
d	k(  r*| j                  | j                  ||             d{   }n)| j                  | j                  ||             d{   }| j                  |d
g       }g }t        dt        |            D ]%  }|j	                  | j                  ||                ' | j                  |d| j                  |      d      S 7 r7 7 ~w)a  

        https://www.okx.com/docs-v5/en/#rest-api-account-get-positions
        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   rJ   rd  r  r   r  r  !privateGetAccountPositionsHistoryr  ry  F)r5  r  r  rl  r  r   rv  r`  rp  r!  r  r  r  r  filter_by_array_positionsr_  )rg  r]  rs  r  	marketIdsr  r  rl  marketIdsLengthfetchPositionsOptionsr  r  	positionsr  s                 ri  fetch_positionszokx.fetch_positions%  s     !!!

 I1c'l+ /
U+  ./ ")nO"$'HHY$7! $t||=Mr R!!"7C_`88!CCDKKPWY_D`aaH!<<T[[RX=YZZH^ NN8VR8	q#i.) 	=AMM$--il;<	=--fh@S@ST[@\^cddQ 	"& bZs5   FFCF$F%)FFA:FFFc                 D   K   | j                  |g|       d{   S 7 w)a  

        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'  rg  ry  rs  s      ri  fetch_positions_for_symbolzokx.fetch_positions_for_symbol{  s#      ))6(F;;;;s     r  c                    | j                  |d      }| j                  ||d d      }|d   }| j                  |d      }t        j                  |      }| j	                  |dd      }|dk7  }| j                  |      }	|d   rK|dk(  r1| j                  |d	      }
| j                  |
      }||d
   |k(  rdnd}|N| j                  |d      }n;|9|dk(  r4t        j                  |d      rd}nt        j                  |d      rd}nd }| j                  |d      }| j                  |      }| j                  |d      }| j                  |d      }|d   r*t        j                  t        j                  ||      |      }| j                  |      }| j                  |d      }d }| j	                  |dd      }| j                  |d      }| j                  |d      }d }d }|dk(  r)| j                  |d      }t        j                  ||      }n-|dk(  r(t        j                  d|      }| j                  |d      }| j                  |d      }| j                  |      }t        j                  ||      }|'| j                  t        j                  ||d            }n|t        j                  ||      }d}| j                  t        j                  t        j                  ||      dd            }| j                  |d      }| j                  |d      }| j                  t        j                  |d             }| j                  |d!      } | j                  t        j                  ||d            }!| j                  i d"|d#| j                  |d$      d|d%|d&|d'|d(| j                  |      d)| j                  |      d*| j                  |d*      d+|d,|	d|d-| j                  |      d.| j                  |d/      d0|d1|d2| | j!                  |       | j                  |d3      ||| j                  |      | j                  |      | j                  |      | j                  |      |!d d d4      S )5Nr  r  ry  posr   	directionnetrX   posCcyr  r  r  r  r  rQ  notionalUsdr[  r  r  	openAvgPxuplr  r  imrr  r  mmrr   z0.00005liqPxuplRatior  r  r  rJ   posIdr%  rC  liquidationPrice
entryPriceunrealizedPnlrealizedPnlrO  	contractsrU  	lastPrice
closeAvgPxrs  rJ  r  r  )r  r  maintenanceMarginmaintenanceMarginPercentage
collateralinitialMargininitialMarginPercentagerL  marginRatiorF  rG  )rp  r  rE   
string_absra  rf  r  r  	string_ltr  r  r  r  
string_addr  safe_positionr  )"rg  r  rl  r  ry  r,  contractsAbsrs  rJ  r<  r/  parsedCurrencyr  contractSizeStringmarkPriceStringnotionalStringr%  rC  initialMarginStringentryPriceStringunrealizedPnlStringleverageStringrC  collateralStringmaintenanceMarginStringr?  !maintenanceMarginPercentageStringrounderr@  r8  percentageStringrO  r  rD  s"                                     ri  r  zokx.parse_position  s6   F ##Hh7!!(FD*E!x/))#.!!(I{C%%l3	(u}))(H=!%!8!8!@!-&,Vn&F6WD|''+>5=((c2% **34&#''?!22<@**8X>))(MB)$//0B0B<Qc0dfuvN$$^4%%h	:
"--hM"..x?))(G<"& "&"2"28U"C&112EGZ[:%&-&8&8n&M##//(C"&"2"28U"C --.EF,3,>,>?VXf,g)"*&*&7&78J8JK^`npq8r&s# (")"4"45Ln"]&*&7&78J8J7K]K]^  BI  LJ  LO  QR  9S  'T#++Hg>++HjA&&w'9'9:JE'RS
%%h8	''(:(:;RTdfg(hi!! #
H#
$""8W5#
 f#
 	#

 *#
  0#
 $++,<=#
 T../BC#
 4++HmD#
 *#
 #
 L#
 **?;#
 ))(LA#
 D#
  f!#
" ##
$ Y/#'#4#4Xw#G!2+F++,<=!../BC'+'8'89P'Q)).9&!#9#
  	rj  fromAccount	toAccountc                   K   | j                          d{    | j                  |      }| j                  | j                  di       }| j	                  |||      }| j	                  |||      }	|d   | j                  ||      d||	d}
|dk(  r7d|
d<   |	|
d	<   | j	                  |d
d      |
d
<   | j	                  |dd      |
d<   n;|	dk(  r6d|
d<   ||
d	<   | j	                  |d
d      |
d
<   | j	                  |dd      |
d<   | j                  | j                  |
|             d{   }| j                  |dg       }| j                  |di       }| j                  ||      S 7 L7 ?w)a  
        transfer currency internally between wallets on the same account

        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>`
        Nr6  rJ   r  )r  r  ro  r  r  masterr  ro  subAcctr  r+  r  r  r  r   )
r5  r  rv  r`  rp  currency_to_precisionprivatePostAssetTransferr  r  parse_transfer)rg  r  r  rW  rX  rs  r  r6  fromIdtoIdr  r  r  rawTransfers                 ri  r   zokx.transfer&  s     !!!==&6FK!!.+{K	9ED>--dF;

 X!GFO!%GI"..vvsCGFO ,,VT3?GDMX!GFO!'GI"..vvsCGFO ,,VT3?GDM66t{{7F7STT  ~~h3nnT1b1"";99Y 	"4 Us"   E'E"DE'%E%&=E'%E'r   c                 ^   | j                  |dd      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j	                  | j
                  di       }	| j                  |d      }
| j                  |d	      }|$| j                  t        j                  |            }|||
| j                  |
      ||| j                  |	|      | j                  |	|      | j                  | j                  |d
            d	S )NtransIdr  r  r  r  r  r7  r  r4  r  )	r  rJ   r  r  r  r  rW  rX  r  )ra  rp  r  r  rv  r`  r  rf  rE   rE  r  parse_transfer_status)rg  r   r  rJ   r'  r  r  fromAccountIdtoAccountIdr7  r  balanceChanges               ri  r^  zokx.parse_transfera  s.   j )X>%%h6
&&z8<!!(E2((6:&&x6~~dllNBG%%h5	((48$&&w'9'9-'HIF"Y/++L-H)),D001A1A(G1TU

 
	
rj  c                 0    ddi}| j                  |||      S )Nsuccessr  r  r  s      ri  rd  zokx.parse_transfer_status  s%    t
 &&99rj  c                   K   | j                          d {    d|i}| j                  | j                  ||             d {   }| j                  |dg       }| j	                  |d      }| j                  |      S 7 g7 <w)Nrc  r  r   )r5  privateGetAssetTransferStater  r  rv  r^  )rg  rJ   r  rs  r  r  r  r   s           ri  fetch_transferzokx.fetch_transfer  s     !!!r
 ::4;;wPV;WXX* ~~h3>>$*""8,,9 	"
 Ys!   BA>,BB ;B Bc                 B  K   | j                          d{    d}ddi}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j                  ||             d{   }| j	                  |dg       }| j                  |||||      S 7 7 .w)	aU  
        fetch a history of internal transfers made on an account

        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>`
        Nro  r  rJ   r  r  rS  r  )r5  r  r  r  r  parse_transfers)	rg  r  r  rS  rs  r  r  r  	transferss	            ri  fetch_transferszokx.fetch_transfers  s      !!!C
 }}T*H%d^GEN$GG$GG;;DKKQW<XYYB NN8VR8	##IxvNN] 	" Zs"   BBAB.B/-BBr  GETc                    t        |t              }d| j                  z   dz   | j                  ||      z   }| j	                  || j                  |            }	| j                  | j                  d   d         |z   }
|dk(  r|	r|
d| j                  |	      z   z  }
n|dk(  r| j                          |dk(  r|d	k(  s
|d
k(  s|dk(  r| j                  | j                  dd      }t        |t              rUt        dt        |            D ]<  }||   }| j                  |d      }||| j                         z   |d<   ||d<   |||<   > n/| j                  |d      }||| j                         z   |d<   ||d<   | j                  | j!                               }| j"                  | j$                  |d}||z   |z   }|dk(  r!|	r>d| j                  |	      z   }|
|z  }
||z  }n|s|	r| j'                  |	      }||z  }d|d<   | j)                  | j+                  |      | j+                  | j,                        t.        j0                  d      }||d<   |
|||dS )Nz/api/r}  r   r   r  ?r  POSTr
  r  r   r9  r4  r   r  r  )zOK-ACCESS-KEYzOK-ACCESS-PASSPHRASEzOK-ACCESS-TIMESTAMPrq  zapplication/jsonzContent-Typebase64zOK-ACCESS-SIGN)r   r  bodyheaders)re  r  rP   implode_paramsrq  extract_paramsimplode_hostnamer   	urlencoder  rp  r`  r  r  r  r  r  r  r  jsonhmacencoder  hashlibsha256)rg  pathr   r  rs  rw  rv  isArrayr  r  r   r9  r  r  r  r  authurlencodedQuery	signatures                      ri  signzokx.sign  sb   VT*DLL(3.1D1DT61RR		&$"5"5d";<##DIIe$4V$<=G(?sT^^E222I++-T-A%ATM_E_cgkxcx++DLL*FXYfd+"1c&k2 . &q	(,(8(8	(J(0/7$++-/GE),+3E%L(-F1I. %)$4$4VY$GM$,,4t{{},Dy)(0uTZZ\2I!%(,'0G v%/D&)DNN5,A&AO?*CO+De99U+DDLD*<'		$++d"3T[[5Mw~~_ghI(1G$%fdwOOrj  c                 4   | j                  |d      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	t	        j
                  |	|      }
i d|d|dd dd d	| j                  d
      dd dd dd d| j                  |d      d|d| j                  |      d|d|d| j                  |      dd dd dd d| j                  |
      iS )NnextFundingTimer  nextFundingRater  r  ry  rU  rV  interestRater  estimatedSettlePricer  r  r  fundingTimestampfundingDatetimenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)	r  rp  r  r  rE   
string_subrf  r  parse_funding_interval)rg  r  rl  nextFundingRateTimestampr  ry  r  r  fundingTimeStringnextFundingTimeStringmillisecondsIntervals              ri  parse_funding_ratezokx.parse_funding_rateA  s   : $(#4#4X?P#Q ##Hh7!!(F3**85FG''-@ ,,X}E $ 0 0;L M&112GIZ[
H
f
 
 $	

 D--c2
 #D
 
 
 4++HmD
 
 t||K8
 
 #$<
 "4<<0H#I
 "4
  '!
" &t#
$ 334HI%
 	
rj  c                 8    dddddd}| j                  |||      S )Nr   r   r  16h24h)360000014400000288000005760000086400000r  )rg  r  	intervalss      ri  r  zokx.parse_funding_interval}  s/    
	 	8X>>rj  c                 B   K   | j                  ||       d{   S 7 w)av  
        fetch the current funding rate interval

        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>`
        N)fetch_funding_rater)  s      ri  fetch_funding_intervalzokx.fetch_funding_interval  s!      ,,VV<<<<s   c                 n  K   | j                          d{    | j                  |      }|d   st        | j                  dz         d|d   i}| j	                  | j                  ||             d{   }| j                  |dg       }| j                  |di       }| j                  ||      S 7 7 >w)am  
        fetch the current funding rate

        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>`
        NrY   z2 fetchFundingRate() is only valid for swap marketsr  rJ   r  r   )	r5  rl  r,   rJ   publicGetPublicFundingRater  r  rv  r  )rg  ry  rs  rl  r  r  r  r  s           ri  r  zokx.fetch_funding_rate  s      !!!V$f~*^ ^__fTl
 88Wf9UVV" ~~h3tQ+&&uf555 	" Ws"   B5B1AB54B35=B53B5c                   K   | j                          d{    ddi}|t        |      |d<   d}|;| j                  |      }|d   }|d   r |d   rd|d<   |d	   |d
<   nd|d<   |d   |d
<   | j                  d||      \  }}|dk(  r| j	                  |      |d<   | j                  | j                  ||             d{   }	| j                  |	dg       }
g }t        dt        |
            D ]  }|
|   }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d
      }| j                  |      }|j                  ||d   ||| j                  |      | j                  |d      | j!                  |d      d        | j#                  |d      }| j%                  ||||      S 7 7 w)aY  
        fetch the history of funding payments paid and received on self account

        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>`
        Nro  r  rS  ry  r  rZ  ctTyper  r  r[  r  r   rY   rn  r  r   r  r  r  r  )r  ry  r  r  r  rJ   r  r  )r5  rf  rl  rr  rx  r  r  r  r  r  r  rp  r  r  r  r  r  r  r  )rg  ry  r  rS  rs  r  rl  ro  r  r  r  r  r  r  r  r  marketInnerr'  r  r  s                       ri  fetch_funding_historyzokx.fetch_funding_history  s     !!! CK
X "5zGG[[(FH%Fj!(#(0GH%%+I%6GEN(1GH%%+H%5GEN889NPVX^_e6>"&"A"A$"GGJ;;DKKQV<WXX2 ~~h3q#d)$ 	AGE))%6I%%eX6F**62K))%7J**:6DMM%h/& LL3&&uh7**5(; 	  fk200NNU 	"| Ys#   G	GB*G	GDG	G	c                 h  K   |t        | j                  dz         |dk  s|dkD  rt        | j                  dz         | j                          d{    | j	                  |      }d}| j                  d|      \  }}|| j                  |dd      }|dk7  r|d	k7  rt        | j                  d
z         |||d   d}| j                  |dd      }|d	k(  r,|dk7  r"|dk7  r|dk7  rt        | j                  dz         ||d<   | j                  | j                  ||             d{   }|S 7 7 w)a<  
        set the level of leverage for a market

        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' or 'net' for isolated margin long/short mode on futures and swap markets, default is 'net'
        :returns dict: response from the exchange
        Nz) setLeverage() requires a symbol argumentr   }   z3 setLeverage() leverage should be between 1 and 125r   r  r  r  zT setLeverage() requires a marginMode parameter that must be either cross or isolatedrJ   r  r  r  r   r.  r  r  zR setLeverage() requires the posSide argument to be either "long", "short" or "net")	r1   rJ   r2   r5  rl  r  rp  privatePostAccountSetLeverager  )	rg  rL  ry  rs  rl  rC  r  r   r  s	            ri  set_leveragezokx.set_leverageQ  s`     >#DGG.Y$YZZ qLhnTWW'\\]]!!!V$
!??vV
F))&)WEJ'!
j(@TWW'}}~~!Tl

 ""69e<#& W%7Gu<L +!  A  A!(GI;;DKKQW<XYY C 	"$ Zs%   AD2D.CD2'D0(D20D2c                   K   | j                          d{   }t        |      }d}|dkD  ru| j                  |d      }|<| j                  |d      }t	        | j
                  dz   dj                  |      z         | j                  |d      }| j                  ||      }n|d   }|d   }	| j                  |	d	      }
|
d
k(  }|	|dS 7 w)at  

        https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-account-configuration

        fetchs the position mode, hedged or one way, hedged for binance is set identically for all linear markets or all inverse markets
        :param str symbol: unified symbol of the market to fetch the order book for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.accountId]: if you have multiple accounts, you must specify the account id to fetch the position mode
        :returns dict: an object detailing whether the market is in hedged or one-way mode
        Nr   r  rJ   z fetchPositionMode() can not detect position mode, because you have multiple accounts. Set params["accountId"] to desired id from: z, r   r  posModelong_short_mode)r  rJ  )	r  r  rp  get_list_from_object_valuesr,   rJ   r   r  rv  )rg  ry  rs  accountslengthselectedAccountr  
accountIdsr7  mainAccountr  isHedgeds               ri  fetch_position_modezokx.fetch_position_mode  s     ,,..XA:((=I !==hM
#DGG  /t  %t  w{  w@  w@  AK  wL  %L  M  M#}}Xt<"&..y"I&qkO%f-"";	://
 	
! /s   C
CB2C
rJ  c                 ~   K   d}|rd}nd}d|i}| j                  | j                  ||             d{   }|S 7 w)a  
        set hedged to True or False for a market

        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
        Nr  net_moder  )!privatePostAccountSetPositionModer  )rg  rJ  ry  rs  	hedgeModer  r  s          ri  set_position_modezokx.set_position_mode  sT      	)I"Iy
 ??GU[@\]]  ^s   2=;=rC  c                   K   |t        | j                  dz         |j                         }|dk7  r|dk7  rt        | j                  dz         | j	                          d{    | j                  |      }| j                  |dd      }|
|dk  s|d	kD  rt        | j                  d
z         | j                  |dg      }|||d   d}| j                  | j                  ||             d{   }|S 7 7 w)a  
        set margin mode to 'cross' or 'isolated'

        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  rL  r   r  z< setMarginMode() params["lever"] should be between 1 and 125rJ   r  )
r1   rJ   r  r2   r5  rl  safe_integer_2rq  r  r  )rg  rC  ry  rs  rl  r  r  r  s           ri  set_margin_modezokx.set_margin_mode  s
     >#DGG.[$[\\  %%'
'!
j(@TWW'eeff!!!V$##FGZ@MuqyeckTWW'eeff6J<0!Tl

 ;;DKKQW<XYY 5 	" Zs%   A C:"C6#BC:/C80C:8C:c                   K   | j                          d{    | j                  |       d{   }| j                  |dg       }g }t        dt	        |            D ]%  }|j                  | j                  ||                ' |S 7 q7 Zw)a[  
        fetch the borrow interest rates of all currencies

        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>`
        Nr  r   )r5  privateGetAccountInterestRater  r  r  r  parse_borrow_rate)rg  rs  r  r  r  r  s         ri  fetch_cross_borrow_rateszokx.fetch_cross_borrow_rates  s      !!!;;FCC ~~h3q#d)$ 	:ALL//Q89	:% 	"Cs    BBBB
AB
Bc                 2  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }| j                  |      S 7 |7 =w)a  
        fetch the rate of interest to borrow a currency for margin trading

        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  rJ   r  r   )r5  r  r  r  r  rv  r  )rg  r  rs  r  r  r  r  r  s           ri  fetch_cross_borrow_ratezokx.fetch_cross_borrow_rate  s      !!!==&8D>
 ;;DKKQW<XYY ~~h3~~dAr*%%d+++ 	"
 Zs"   BBA BB<BBc                     | j                  |d      }| j                  |d      }| j                  |      | j                  |dd      d|| j	                  |      |dS )Nr  r  r  r  i \&)r  r  periodr  r  r  )rp  r  r  r  r  )rg  r  r  r  r  s        ri  r  zokx.parse_borrow_rate5  sg     tU+%%dD1	//4&&t^VD"Y/
 	
rj  c                    i }t        dt        |            D ]m  }||   }| j                  | j                  |d            }|| j	                  ||      s>||vrg ||<   | j                  |      }	||   }
|
j                  |	       o t        |j                               }t        dt        |            D ]!  }||   }| j                  ||   |||      ||<   # |S )Nr   r  )
r  r  r  rp  in_arrayr  r  r  r  filter_by_currency_since_limit)rg  r  codesr  rS  borrowRateHistoriesr  r  r  borrowRateStructureborrrowRateCoder  s               ri  parse_borrow_rate_historieszokx.parse_borrow_rate_historiesI  s    %'q#h-( 	<AA;D**4+;+;D%+HID}dE : 3302'-&*&<&<T&B#"5d";&&':;	< ',,./q#d)$ 	{A7D(,(K(KL_`dLegkmrty(z%	{ #"rj  c                   K   | j                          d{    i }|||d<   |||d<   | j                  | j                  ||             d{   }| j                  |dg       }| j	                  ||||      S 7 d7 -w)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

        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
        Nr  rS  r  )r5  )publicGetFinanceSavingsLendingRateHistoryr  r  r  )rg  r  r  rS  rs  r  r  r  s           ri  fetch_borrow_rate_historieszokx.fetch_borrow_rate_historiese  s      !!!
  %GH$GGGGT[]cHdee ~~h3//eUEJJ7 	" fs!   A?A;8A?A=,A?=A?c                 .  K   | j                          d{    | j                  |      }d|d   i}|||d<   |||d<   | j                  | j                  ||             d{   }| j	                  |dg       }| j                  ||||      S 7 z7 -w)a  
        retrieves a history of a currencies borrow interest rate at specific time slots

        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  rJ   r  rS  r  )r5  r  r  r  r  parse_borrow_rate_history)	rg  r  r  rS  rs  r  r  r  r  s	            ri  fetch_borrow_rate_historyzokx.fetch_borrow_rate_history  s      !!!==&8D>
  %GH$GGGGT[]cHdee ~~h3--dD%GG9 	" fs"   BBAB%B&,BBc                   K   | j                          d {    | j                  |      }| j                  |dd      }| j                  |dg      }|d   |||d}| j	                  | j                  ||             d {   }| j                  |dg       }	| j                  |	di       }
| j                  |d      }| j                  | j                  |
|      d|d	k(  rd
i      S di      S 7 7 nw)Nr   r.  rJ   )r  r  ro  r   r  r   r  r  r  r  r  )	r5  rl  rp  rq  'privatePostAccountPositionMarginBalancer  r  rv  parse_margin_modification)rg  ry  r  ro  rs  rl  r   r  r  r  r  	errorCodes               ri  modify_margin_helperzokx.modify_margin_helper  s    !!!V$""69e<6I;/Tl	
 EEdkkRY[aFbcc ~~h3tQ+$$Xv6	{{499%HyC/dK
  	6>K
  	9 	" ds#   C1C-A)C1 C/A-C1/C1r  c                    | j                  |dd      }| j                  |d      }d }|dk(  rt        j                  |d      rdnd}n|}t        j                  |      }| j                  |d      }| j                  ||      }|d	   r|d
   n|d   }	| j                  |d      }
||d   |d| j                  |      |	d d |
| j                  |
      d
S )Nr  	posBalChgro  r+  r  addreducer  r[  r  r  r  ry  r  )
r  ry  ro  rC  r  r  r  r  r  r  )	ra  rp  rE   r  rE  r  r  rf  r  )rg  r  rl  	amountRawtypeRawro  r  r  responseMarketr  r  s              ri  r  zokx.parse_margin_modification  s    ` &&tUK@	""40c>#--i=58DD##I.##D(3))(F;)7	)B~f%W^H_%%dD1	$X.$''/"Y/
 	
rj  c                 F   K   | j                  ||d|       d{   S 7 w)a  
        remove margin from a position

        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>`
        r  Nr  rg  ry  r  rs  s       ri  reduce_marginzokx.reduce_margin"  s%      ..vvxPPPP   !!c                 F   K   | j                  ||d|       d{   S 7 w)a  
        add margin

        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>`
        r  Nr  r  s       ri  
add_marginzokx.add_margin/  s%      ..vvufMMMMr  c                 "  K   | j                          d{    | j                  |      }|d   rdn| j                  |d         }| j                  |d   d      }|s |dk7  rt	        | j
                  dz   |z         d}| j                  d|      \  }}|| j                  |d	d
      }|||d}|dk(  r|d   |d<   | j                  | j                  ||             d{   }| j                  |dg       }	| j                  |	|      S 7 7 +w)a  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market

        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>`
        NrW   r0  ro  r  r  z< fetchMarketLeverageTiers() cannot fetch leverage tiers for r   r  r  )rn  r  r  rJ   r  r  )r5  rl  rx  rp  r2   rJ   r  publicGetPublicPositionTiersr  r  parse_market_leverage_tiers)
rg  ry  rs  rl  ro  r  rC  r  r  r  s
             ri  fetch_market_leverage_tierszokx.fetch_market_leverage_tiers<  s4     !!!V$!&>xt/N/NvV\~/^vf~u5x +i!ilr!rss
!??@Z\bc
F))&(GDJ 

 8 &tGH::4;;wPV;WXX, ~~h3//f==S 	"$ Yrg  c                 f   g }t        dt        |            D ]  }||   }| j                  |d      }|j                  | j	                  |d      | j                  ||      |d   | j                  |d      | j                  |d      | j                  |d      | j                  |d      |d	        |S )
zs
 @ignore
        :param dict info: Exchange response for 1 market
        :param dict market: CCXT market
        r   r  tierr  r  maxSzr4  maxLever)r  ry  r  minNotionalmaxNotionalmaintenanceMarginRater  r  )r  r  rp  r  r  r  r  )rg  r  rl  tiersr  r  r  s          ri  r  zokx.parse_market_leverage_tiersr  s    0 q#d)$ 	A7D''h7HLL))$7**8V<"7O#//g>#//g>)-)9)9$)F#//jA	 		 rj  c                   K   | j                          d{    d}| j                  d|      \  }}|| j                  |dd      }d|i}d}|| j                  |      }	|	d   |d<   ||dz
  |d<   |||d	<   || j	                  |      }|d   |d
<   | j                  | j                  ||             d{   }
| j                  |
dg       }| j                  |      }| j                  ||||      S 7 7 >w)a  
        fetch the interest owed by the user for borrowing currency for margin trading

        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>`
        Nrx   r  r  rJ   r  r   r  rS  r  r  )
r5  r  rp  r  rl   privateGetAccountInterestAccruedr  r  parse_borrow_interestsr  )rg  r  ry  r  rS  rs  rC  r  rl  r  r  r  interests                ri  fetch_borrow_interestzokx.fetch_borrow_interest  s3     !!!
!??@UW]^
F))&)WEJz
 }}T*H%d^GEN %	GH$GG[[(F &tGH>>t{{7TZ?[\\( ~~h3..t4228T5%PPS 	"& ]s"   C9C5B!C98C79=C97C9r  c                    | j                  |d      }|| j                  ||      }| j                  |d      }|| j                  |d      | j                  | j                  |d            | j	                  |d      | j	                  |d      | j	                  |d      | j                  |d      || j                  |      d		S )
Nr  r  ry  r  r  r  liabr  )	r  ry  r  r  r  amountBorrowedrC  r  r  )rp  r  r  r  r  r  )rg  r  rl  r  r  s        ri  parse_borrow_interestzokx.parse_borrow_interest  s    !!$1%%ff5F%%dD1	&&vx8//0@0@u0MN((z: ,,T>B"..tV<**4;"Y/

 
	
rj  c                 X  K   | j                          d{    | j                  |      }|d   | j                  ||      dd}| j                  | j	                  ||             d{   }| j                  |dg       }| j                  |di       }| j                  ||      S 7 7 >w)a  
        create a loan to borrow margin(need to be VIP 5 and above)

        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>`
        NrJ   borrow)r  r  rs  r  r   )r5  r  r\  privatePostAccountBorrowRepayr  r  rv  parse_margin_loan)	rg  r  r  rs  r  r  r  r  loans	            ri  borrow_cross_marginzokx.borrow_cross_margin  s      !!!==&D>--dF;

 ;;DKKQW<XYY  ~~h3~~dAr*%%dH553 	" Zs"   B*B&AB*)B(*=B*(B*c                   K   | j                          d{    | j                  |dd      }| j                  |d      }|t        | j                  dz         | j                  |      }|d   | j                  ||      d|d}| j                  | j                  ||             d{   }| j                  |dg       }| j                  |di       }	| j                  |	|      S 7 7 >w)	a  
        repay borrowed margin and interest

        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>`
        NrJ   rt  z, repayCrossMargin() requires an id parameterrepay)r  r  rs  rt  r  r   )r5  ra  rq  r1   rJ   r  r\  r  r  r  rv  r  )
rg  r  r  rs  rJ   r  r  r  r  r  s
             ri  repay_cross_marginzokx.repay_cross_margin  s      !!!g664(:#DGG.\$\]]==&D>--dF;	
 ;;DKKQW<XYY  ~~h3~~dAr*%%dH55= 	" Zs"   C*C&BC*)C(*=C*(C*c                 z    | j                  |d      }d | j                  ||      | j                  |d      d d d |dS )Nr  r  )rJ   r  r  ry  r  r  r  )rp  r  r  )rg  r  r  r'  s       ri  r  zokx.parse_margin_loan7  sO     %%dE2
//
HE&&tU3
 	
rj  c                   K   | j                          d{    | j                  |      }|d   st        | j                  dz         | j	                  |d         }| j                  |d   d      }|||d   d}| j                  | j                  ||             d{   }| j                  |d	g       }| j                  |d
   |      S 7 7 .w)aj  
        Retrieves the open interest of a currency

        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 onlyro  r  r  rJ   )rn  r  r  r  r   )
r5  rl  r2   rJ   rx  rp  publicGetPublicOpenInterestr  r  parse_open_interest)	rg  ry  rs  rl  ro  r  r  r  r  s	            ri  fetch_open_interestzokx.fetch_open_interestN  s      !!!V$j!TWW'\\]]..vf~>vf~u5Tl

 99$++gv:VWW  ~~h3''Q889 	" Xs"   CCBCC -CCr   c                 X  K   | j                  | j                  di       }| j                  |di       }| j                  |||      }|dk7  r"|dk7  r|dk7  rt        | j                  dz         | j                          d{    d}d}	|| j                  v s|| j                  v r| j                  |      }	|	d   }n| j                  |      }
|
d	   }||d
}d}d}| j                  d|	|      \  }}|dk(  r*| j                  | j                  ||             d{   }n\|||d<   | j                  |d      }|||d<   | j                  |dg      }| j                  | j                  ||             d{   }| j!                  |dg       }| j#                  |d||      S 7 #7 7 0w)aX  
        Retrieves the open interest history of a currency

        https://www.okx.com/docs-v5/en/#rest-api-trading-data-get-contracts-open-interest-and-volume
        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  rJ   )r  r  r[   r  r  r  r  )rv  r`  rp  r2   rJ   r5  r  r  rl  r  rr  *publicGetRubikStatOptionOpenInterestVolumer  r  rq  -publicGetRubikStatContractsOpenInterestVolumer  parse_open_interests_history)rg  ry  r  r  rS  rs  r`  r   r'  rl  r  r  ro  r  r  r  s                   ri  fetch_open_interest_historyzokx.fetch_open_interest_historyv  s     ../I2N^^G\2>
$$ZIF	d!2yD7HTWW'oopp!!!
dll"$2D2D(D[[(F)J}}V,H!$J
 99:TV\^def8!LLT[[Y`bhMijjH #( %%fg6E !&6G95!OOPTP[P[\cekPlmmH ~~h300tUEJJU 	"$ k ns8   A>F* F#BF*F&AF*7F(8,F*&F*(F*c                 x   | j                  |d      }| j                  ||      }| j                  |d      }| j                  |d|      }d }d }d }d }	| j                  | j                  d      }
t	        |t
              rO|
dk(  r%| j                  |d      }| j                  |d      }n[| j                  |d      }	| j                  |d      }n6| j                  |d      }| j                  |d	      }| j                  |d
      }	| j                  | j                  |      ||||	|| j                  |      |d|      S )Nr  r  r   r  r[   r   r   oiCcyoioiUsd)ry  rS  rT  openInterestAmountopenInterestValuer  r  r  )
rp  r  r  r`  re  r  r  safe_open_interestr  r  )rg  r  rl  rJ   timer  rS  rT  r  r  ro  s              ri  r  zokx.parse_open_interest  sW   * h1!!"f-  40%%h48	
! m<h%x%)%5%5h%B"!--h:
$($4$4Xq$A!"..x;))(G<J!%!1!1(D!A $ 0 07 C&&&&r*$&"4!2"Y/	(
 	 		rj  enablec                     t         t        |   |       || j                  d<   |rd| j                  d<   y d| j                  v r"| j                  | j                  d      | _        y y )Nr  r  zx-simulated-trading)rd  rG   set_sandbox_moder`  rw  rq  )rg  r  rh  s     ri  r   zokx.set_sandbox_mode  sZ    c4)&1&,]#25DLL./"dll299T\\3HIDL 3rj  r  c                 .  K   | j                          d{    i }|%| j                  |      }dj                  |      |d<   | j                  | j	                  ||             d{   }| j                  |d      }| j                  ||      S 7 z7 *w)aq  
        fetch deposit and withdraw fees

        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>`
        Nrd  r  r  )r5  currency_idsr   r  r  r  parse_deposit_withdraw_fees)rg  r  rs  r  rg  r  r  s          ri  fetch_deposit_withdraw_feeszokx.fetch_deposit_withdraw_fees  s      !!!##E*C XXc]GEN77GV8TUUX ~~h///e<<e 	"
 Vs"   BBAB(B))BBc                    i }| j                  |      }t        dt        |            D ]  }||   }| j                  |d      }| j	                  |      }|| j                  ||      s@| j                  ||      }	|	| j                  i       ||<   |||   d   |<   | j                  |d      }
|
|
j                  d      }| j                  |d      }| j                  |d      }||dnd d	}d d d	}| j                  ||      }||d
||   d   |<    t        |j                               }t        dt        |            D ]0  }||   }| j                  |      }| j                  ||   |      ||<   2 |S )Nr   r  r  r  r|  r   r  F)r  rO  )r   r  r  )market_codesr  r  rp  r  r  r  deposit_withdraw_feer  r  r!  r  r  r  $assign_default_deposit_withdraw_fees)rg  r  r  currencyIdKeydepositWithdrawFeesr  feeInfor'  r  depositWithdrawFeer  
chainSplitr+  withdrawFeewithdrawResultdepositResultr.  depositWithdrawCodesr  s                      ri  r#  zokx.parse_deposit_withdraw_fees0  s   , %'!!%(q#h-( 	AqkG))'59J**:6D4==u#=%)__5H$%O"%-040I0I"0M'-@G#D)&1*=((':="[[-
 OOJ:	"..w>&,7,C%$(
  "&' #55iF .,F#D)*5kB1	8  $$7$<$<$>?q#234 	wA'*D}}T*H(,(Q(QRefjRkmu(v%	w #"rj  c                 \  K   |t        | j                  dz         | j                          d{    | j                  |      }d}| j	                  d||      \  }}|dk7  r|dk7  rt        | j                  dz         | j                  |      |d   dz   |d	   z   d
}||dz
  |d<   |||d<   | j                  | j                  ||             d{   }| j                  |dg       }	| j                  |	|      }
| j                  |
d      }| j                  ||d   ||      S 7 7 Tw)a  
        fetches historical settlement records

        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   rZ   r[   zC fetchSettlementHistory() supports futures and options markets onlyr  r|  r  )rn  r  r   r  rS  r  r  ry  )r1   rJ   r5  rl  rr  r;   rx  &publicGetPublicDeliveryExerciseHistoryr  r  parse_settlementsr  r  )rg  ry  r  rS  rs  rl  ro  r  r  r  settlementsr  s               ri  fetch_settlement_historyzokx.fetch_settlement_historyk  sX     >#DGG.d$dee!!!V$99:RTZ\bcf8 0tww)nnoo77=(#c)F9,==
  %	GH$GGDDT[[QXZ`Eabb& ~~h3,,T6:k;7009I5RWXXI 	" cs#   .D,D(B$D,D*AD,*D,c                 v    | j                  |d      }|| j                  ||      | j                  |d      d d dS )NinsIdrq  )r  ry  r>  r  r  )rp  r  r  )rg  
settlementrl  r  s       ri  parse_settlementzokx.parse_settlement  sI     ##J8&&x8%%j$7
 	
rj  c                 V   g }t        dt        |            D ]  }||   }| j                  |d      }| j                  |dg       }t        dt        |            D ]J  }| j	                  ||   |      }	|j                  | j                  |	|| j                  |      d             L  |S )Nr   r  r  )r  r  )r  r  r  r  r:  r  r  r  )
rg  r5  rl  r  r  r  r  r  r*  r9  s
             ri  r4  zokx.parse_settlements  s     q#k*+ 		ANE))%6InnUIr:G1c'l+ !2271:vF
dkk*!* $Y 77  			 rj  c                 z  K   | j                          d{    d}| j                  dd|      \  }}||dk(  rd}|dk7  r"|dk7  r|dk7  rt        | j                  dz         d| j	                  |      i}| j                  | j                  ||             d{   }| j                  |d	g       }|d
   S 7 7 w)a  
        fetches the market ids of underlying assets for a specific contract market type

        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   rW   r[   rY   rZ   z7 fetchUnderlyingAssets() supports contract markets onlyrn  r  r   )r5  rr  r;   rJ   rx  publicGetPublicUnderlyingr  r  )rg  rs  r  r  r  underlyingss         ri  fetch_underlying_assetszokx.fetch_underlying_assets  s      !!!
!??@WY]_ef
FJ&$8!J("v)=JRZDZtww)bbcc77
C
 77GV8TUU nnXvr:1~1 	" Vs"   B;B7BB;B9B;9B;c                   K   | j                          d{    | j                  |      }|d   }|j                  d      }|d   d   |d   d   | j                  |d      d}| j	                  | j                  ||             d{   }| j                  |d	g       }t        d
t        |            D ]2  }	||	   }
| j                  |
d      }||k(  s | j                  |
|      c S  y7 7 dw)a  
        fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract

        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>`
        NrJ   r|  r  r  r  r   )r  r  r  r  r   r  )
r5  rl  r  rp  publicGetPublicOptSummaryr  r  r  r  parse_greeks)rg  ry  rs  rl  r  r  r  r  r  r  r  entryMarketIds               ri  fetch_greekszokx.fetch_greeks  s     !!!V$$<nnS)&>%( .6''Q7

 77GV8TUU< ~~h3q#d)$ 	8AGE ,,UH=M(((77		8
 [ 	" Vs)   C/C+A1C/C-	AC/C/-C/greeksc                    | j                  |d      }| j                  |d      }| j                  ||      }i d|d|d| j                  |      d| j	                  |d      d| j	                  |d      d| j	                  |d      d	| j	                  |d	      d
d dd dd d| j	                  |d      d| j	                  |d      d| j	                  |d      dd dd dd dd d |dS )Nr  r  ry  r  r  deltagammathetavegarhobidSizeaskSizebidImpliedVolatilitybidVolaskImpliedVolatilityaskVolmarkImpliedVolatilitymarkVolbidPriceaskPricerU  r=  )underlyingPricer  )r  rp  r  r  r  )rg  rE  rl  r  r  ry  s         ri  rB  zokx.parse_greeks'  s}   0 %%fd3	##FH5!!(F3
f

 Y/
 T%%fg6	

 T%%fg6
 T%%fg6
 D$$VV4
 4
 t
 t
 #D$4$4VX$F
 #D$4$4VX$F
 $T%5%5fi%H
 
 
  !
" #
$  $'
 	
rj  c                 *  K   | j                          d{    | j                  |      }| j                  |d      }| j                  |d      }d}| j                  d|d      \  }}|d   |d}||dk(  rd	|d
<   n|dk(  rd|d
<   n||d
<   |||d<   || j	                  |      }	|	d   |d<   | j                  | j                  ||             d{   }
| j                  |
dg       }| j                  |d      }| j                  ||      S 7 7 =w)aL  
        closes open positions for a market

        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  r  rc   r  rJ   r  r  r  r   r  r  r  r  r  r   )
r5  rl  rp  r  r  privatePostTradeClosePositionr  r  rv  r=  )rg  ry  rs  rs  rl  r  r  rC  r  r  r  r  rz  s                ri  close_positionzokx.close_positionX  sE    $ !!!V$((A/
!??QWY`a
FTl!
 %+	"%,	"%)	"$!.GI}}T*H%d^GEN;;DKKQW<XYY$ ~~h3tQ'v..U 	", Zs"   DDB<DD<DDc                 6  K   | j                          d{    | j                  |      }d|d   i}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }| j                  |d|      S 7 ~7 ?w)a  
        fetches option data that is commonly found in an option chain

        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  rJ   r  r   )r5  rl  rZ  r  r  rv  parse_option)rg  ry  rs  rl  r  r  r  r  s           ri  fetch_optionzokx.fetch_option  s      !!!V$fTl
 33DKK4PQQ6 &"5vq"-  f55E 	"
 Rs"   BBA BB>BBc                   K   | j                          d{    | j                  |      }|d   dz   dd}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |dd      S 7 o7 ,w)a"  
        fetches data for an underlying asset that is commonly found in an option chain

        https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-tickers

        :param str code: 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>`
        Nr  z-USDr3  )r  rn  r  r  )r5  r  rb  r  r  parse_option_chain)rg  r  rs  r  r  r  r  s          ri  fetch_option_chainzokx.fetch_option_chain  s      !!!==&F#f, 
 44T[[&5QRR6 &"5&&vtX>>E 	" Ss"   B
BAB
B+B
B
r  c                 |   | j                  |d      }| j                  ||      }| j                  |d      }i d|dd d|d   d|d| j                  |      dd d	d d
| j	                  |d      d| j	                  |d      dd dd d| j	                  |d      dd dd dd d| j	                  |d      dd S )Nr  r  r  r  ry  r  r  impliedVolatilityopenInterestrT  rC  rU  rG  midPricerU  r=  r:  rV  rN  rO  rS  r<  rT  )rp  r  r  r  r  )rg  r  r  rl  r  r  s         ri  r[  zokx.parse_option  sN   * ##E84!!(F3%%eT2	
E

 fX&
 	

 Y/
  
 D
 ((8
 ((8
 
 
 ))%8
 t
 d
 $
  $**5+>!
" 4#
 	
rj  fromCodetoCodec                   K   | j                          d{    |j                         |j                         |j                         | j                  |      dd}| j                  | j	                  ||             d{   }| j                  |dg       }| j                  |di       }| j                  |d|      }	| j                  |	      }
| j                  |d|      }| j                  |      }| j                  ||
|      S 7 7 w)aL  
        fetch a quote for converting from one currency to another

        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rfqSzrs  r  r   r  r  )
r5  r  r  $privatePostAssetConvertEstimateQuoter  r  rv  rp  r  parse_conversion)rg  rd  re  r  rs  r  r  r  r  fromCurrencyIdfromCurrencytoCurrencyId
toCurrencys                ri  fetch_convert_quotezokx.fetch_convert_quote  s      !!!~~' (**62
 BB4;;wX^C_``0 ~~h3a,))&)XF}}^4''
FC]]<0
$$V\:FFM 	" as#   D
DA)D
 DBD
D
c                   K   | j                          d{    ||||| j                  |      dd}| j                  | j                  ||             d{   }| j	                  |dg       }| j                  |di       }	| j                  |	d|      }
| j                  |
      }| j                  |	d|      }| j                  |      }| j                  |	||      S 7 7 w)aw  
        convert from one currency to another

        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  szCcyr4  rs  r  r   r  r  )	r5  r  privatePostAssetConvertTrader  r  rv  rp  r  rj  )rg  rJ   rd  re  r  rs  r  r  r  r  rk  rl  rm  rn  s                 ri  create_convert_tradezokx.create_convert_tradeS  s      !!!''/
 ::4;;wPV;WXX. ~~h3a,))&)XF}}^4''
FC]]<0
$$V\:FFM 	" Ys#   C!CA C!CBC!C!c                   K   | j                          d{    d|i}| j                  | j                  ||             d{   }| j                  |dg       }| j	                  |di       }| j                  |d      }| j                  |d      }	d}
d}|| j                  |      }
|	| j                  |	      }| j                  ||
|      S 7 7 w)a  
        fetch the data for a conversion trade

        https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-convert-history

        :param str id: the id of the trade that you want to fetch
        :param str [code]: the unified currency code of the conversion trade
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        NclTReqIdr  r   r  r  )r5  privateGetAssetConvertHistoryr  r  rv  rp  r  rj  )rg  rJ   r  rs  r  r  r  r  rk  rm  rl  rn  s               ri  fetch_convert_tradezokx.fetch_convert_trade  s      !!!
 ;;DKKQW<XYY, ~~h3a,))&)<''
;
%==8L#|4J$$V\:FFI 	" Zs"   CC,CCBCCc                 2  K   | j                          d{    i }| j                  d||      \  }}|||d<   |||d<   | j                  | j                  ||             d{   }| j	                  |dg       }| j                  ||dd||      S 7 |7 /w)a  
        fetch the users history of conversion trades

        https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-convert-history

        :param str [code]: the unified currency code
        :param int [since]: the earliest time in ms to fetch conversions for
        :param int [limit]: the maximum number of conversion structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest conversion to fetch
        :returns dict[]: a list of `conversion structures <https://docs.ccxt.com/#/?id=conversion-structure>`
        Nr  r  rS  r  r  r  )r5  r  rv  r  r  parse_conversions)rg  r  r  rS  rs  r  r  rowss           ri  fetch_convert_trade_historyzokx.fetch_convert_trade_history  s      !!!227GVL %GH$GG;;DKKQW<XYY, ~~h3%%dD)ZPUVV= 	" Zs"   BBAB%B&.BB
conversionrl  rn  c                 z   | j                  |dd      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  ||      }||| j                  |      | j	                  |g d      || j                  |dd      || j                  |dd	      | j                  |d
d      d d
S )N	quoteTimer  r  r  )clQReqIdro  r  baseSz
fillBaseSzquoteSzfillQuoteSzcnvtPxrp  )
r  r  r  rJ   rl  
fromAmountrn  toAmountr>  r  )r  rp  r  r  r  r  )	rg  r|  rl  rn  r  fromCoinrd  r  re  s	            ri  rj  zokx.parse_conversion  s    j ''
KF	##J	:**8\Bj*5((Z8"Y/$$Z1ST$,,Z<P **:y-P''
HhG
 	
rj  c                   K   | j                          d{    | j                  |       d{   }i }| j                  |dg       }t        dt	        |            D ]j  }||   }| j                  |d      }| j                  |      }|||dddddddd| j                  |d      | j                  |d      dddddddddd	||<   l |S 7 7 w)
a6  
        fetches all available currencies that can be converted

        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
        Nr  r   r  r  rP  r  )r  r   r  )r  rJ   r  r  ro  rK   r  r  r   r  r  r  r  )r5   privateGetAssetConvertCurrenciesr  r  r  rp  r  r  )	rg  rs  r  r  r  r  r  rJ   r  s	            ri  fetch_convert_currencieszokx.fetch_convert_currencies-  s     !!!>>vFF ~~h3q#d)$ 	AGE!!%/B**2.D  !  $//u=#//u=
  $#!
  $#   5F4L		@ c 	"Fs    CCCCBCChttpCodereasonr   r  rw  rv  c
                    |sy | j                  |d      }
|
dk7  r|
dk7  r| j                  dz   |z   }| j                  |dg       }t        dt	        |            D ]k  }||   }| j                  |d      }| j                  |d      }| j                  | j                  d	   ||       | j                  | j                  d
   ||       m | j                  | j                  d	   |
|       t        |      y )Nr  r  r   r  r   r  sMsgr  r  )	rp  rJ   r  r  r  throw_exactly_matched_exceptionr  throw_broadly_matched_exceptionr,   )rg  r  r  r   r  rw  rv  r  requestHeadersrequestBodyr  feedbackr  r  errorr  messages                    ri  handle_errorszokx.handle_errorsi  s    * &1CKdckww}t+H>>(FB7D1c$i( bQ ,,UG<	**5&944T__W5MyZbc44T__W5MwX`ab 001I4QYZ))rj  c                   K   | j                          d{    | j                  |d      }|t        | j                  dz         |dk(  }|rdnd}|r |rd}nt	        | j                  dz   |z         |d	d
}	| j                  |d      }
| j                  |d      }|||	d<   |||	d<   |
|
|	d<   d}| j                         }|dz
  }|dz
  }|||kD  r*| j                  | j                  |	|             d{   }nG||kD  r*| j                  | j                  |	|             d{   }nt	        | j                  dz         | j                  |d      }| j                  |      }| j                  ||||      S 7 g7 7 Yw)aF  
        fetches the history of margin added or reduced from contract isolated positions

        https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-7-days
        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 int [since]: the earliest time in ms to fetch margin adjustment history for
        :param int [limit]: the maximum number of entries to retrieve
        :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 argumentr  160161162z* cannot fetch margin adjustments for type r  )subTyper  r  r  rS  endTimei $l    X zS fetchMarginAdjustmentHistory() cannot fetch margin adjustments older than 3 monthsr  )r5  r  r1   rJ   r2   r  rq  r  r  r  r  r  parse_margin_modificationsr  )rg  ry  ro  r  rS  rs  r  isAddr  r  r  r  r  
oneWeekAgothreeMonthsAgor  modificationss                    ri  fetch_margin_adjustment_historyz#okx.fetch_margin_adjustment_history  s     !!!~~ff-<#DGG.h$hii %e +W!WZ^!^__!
 !!&'267+#(GK $GG!&GI!9_
z)Muz1!88Wf9UVVH^#!??GU[@\]]HTWW'||}}V ~~h/77=00uUU[ 	"8 W]s5   FE=C"F9F :.F(F)AF FFc                   K   | j                          d{    | j                  |d      }| j                  |d      }| j                  |g d      }|d}d|i}|,t	        |      }|dk(  r| j                  |d         }	|	d	   |d
<   |||d<   |||d<   | j                  | j                  ||             d{   }
| j                  |
d      }| j                  |||      }| j                  |||      S 7 7 >w)u~  
        fetches historical positions

        https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions-history

        :param str [symbols]: unified market symbols
        :param int [since]: timestamp in ms of the earliest position to fetch
        :param int [limit]: the maximum amount of records to fetch, default=100, max=100
        :param dict params: extra parameters specific to the exchange api endpoint
        :param str [params.marginMode]: "cross" or "isolated"

 EXCHANGE SPECIFIC PARAMETERS
        :param str [params.instType]: margin, swap, futures or option
        :param str [params.type]: the type of latest close position 1: close position partially, 2：close all, 3：liquidation, 4：partial liquidation; 5：adl, is it is the latest type if there are several types for the same position
        :param str [params.posId]: position id, there is attribute expiration, the posid will be expired if it is more than 30 days after the last full close position, then position will use new posid
        :param str [params.before]: timestamp in ms of the earliest position to fetch based on the last update time of the position
        :param str [params.after]: timestamp in ms of the latest position to fetch based on the last update time of the position
        :returns dict[]: a list of `position structures <https://docs.ccxt.com/#/?id=position-structure>`
        NrC  rn  )r  rC  rn  r  rS  r   r   rJ   r  r  r  )r5  rp  safe_string_upperrq  r  rl  r!  r  r  parse_positionsfilter_by_since_limit)rg  r]  r  rS  rs  rC  rn  r  symbolsLengthrl  r  r  r&  s                ri  fetch_positions_historyzokx.fetch_positions_history  s&    ( !!!%%fl;
))&*=6#FG=EU
 LM!WQZ0$*4L!!!+GI"*GJ??GU[@\]]D ~~h/((w?	)))UEBBm 	"$ ^s"   C<C8B$C<;C:<=C<:C<r  c                 <  K   | j                          d{    | j                  |      }d|d   i}| j                  |dd      }| j                  |d      }|||d<   |||d<   |||d<   |||d<   | j	                  | j                  ||             d{   }	| j                  |	d	g       }
g }t        d
t        |
            D ];  }|
|   }|j                  | j                  |d
      | j                  |d      d       = | j                  ||      S 7 7 w)a  
        fetches the long short ratio history for a unified market symbol

        https://www.okx.com/docs-v5/en/#trading-statistics-rest-api-get-contract-long-short-ratio

        :param str symbol: unified symbol of the market to fetch the long short ratio for
        :param str [timeframe]: the period for the ratio
        :param int [since]: the earliest time in ms to fetch ratios for
        :param int [limit]: the maximum number of long short ratio structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest ratio to fetch
        :returns dict[]: an array of `long short ratio structures <https://docs.ccxt.com/#/?id=long-short-ratio-structure>`
        Nr  rJ   r  r  r  r  rS  r  r   r   )r  longShortRatio)r5  rl  ra  rq  8publicGetRubikStatContractsLongShortAccountRatioContractr  r  r  r  r  rp  parse_long_short_ratio_history)rg  ry  r  r  rS  rs  rl  r  r  r  r  r  r  r  s                 ri  fetch_long_short_ratio_historyz"okx.fetch_long_short_ratio_history8   sO     !!!V$fTl
 ""67E:67+"GEN  )GH$GG$GGVVW[WbWbcjlrWstt ~~h3q#d)$ 	AGEMM!--eQ7"&"2"25!"< 	 2266BBG 	" us#   DDBDDA?DDc           	          | j                  |d      }d }||d   }|||| j                  |      d | j                  |d      dS )Nr  ry  r  )r  ry  r  r  r  r  )r  r  r  )rg  r  rl  r  ry  s        ri  parse_long_short_ratiozokx.parse_long_short_ratiok   s\    %%dK8	H%F"Y/"..t5EF
 	
rj  )NNNN)N)NN)__name__
__module____qualname__r   re  rf  r   rr  rx  r  r!   r)   r  r  r   r  r+   r   r  r  r  dictr  r  r   r0  r   r8  r#   rX  r\  r"   r$   rf  rj  rl  r&   r  r  r  r  r  r  r  r  r  r'   r  r  r   r  floatr  r  r   r   r   r9  r  r   rG  rX  r\  rb  rh  r_  r   rt  rz  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*  r  r*   r   r^  rd  rl  rp  r  r%   r  r  r  r  r  r  r  boolr  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#  r6  r:  r4  r?  r   rD  rB  rY  r   r\  r   r_  r[  r	   ro  rs  rw  r{  rj  r  intr  r  r  r   r  r  __classcell__)rh  s   @ri  rG   rG   (   s   U# Un( OS[]lp h hV hux h;;
3 ;
zUC U URU Ujm U  zI U )+ 4l ') .S .. +- *g *XD *, V *N4 NF N` 8: 50n -/ |: || @DB 5?S 5? 5?S\ 5?nH4 H H6 HT 68 ,0 ,0F ,0\ 6:" 547 54 54n :< BS B BB :>b 4w 4W 4:X Xv X Xt <@d[] G= G=S G= G=bfglbm G=R
 
4 
4 8<$]ajl ]H ]HC ]HWZ ]Hquvzq{ ]H~ >BPTcgpr @Ys @Y# @Y]` @YD8)2)
T 
6 
EX 
0 ;= -5c -5AT -5^ *, {@ {@z XZ fc f f* Y[ gs g% g* os{} b,3 b,i b,y b,Z_ b,hk b,H mqy{ 9 9I 9Y 9X] 9fi 9v FH /'$|*< /'b FJQU^` J,S J,X fjx|  FH ?3 ? ?9 ?I ?_b ?ru ?B 9=R &/S &/# &/P	 6:" YIs YIv Y[ JGd;N6O JGX BD S :	: 	:D Dv D DL 8<B O/C O/ O/b 59tZ^gi Z=c Z= Z=TW Z=nrsxny Z=x 9=4^bkm m=# m=S m=X[ m=^ 7;\`ik n= n=3 n=VY n=ptuzp{ n=` 37TX\eg BDC BDs BDRU BDH ?CQUdhqs ^3 ^ ^3 ^^a ^, .2SW`b p?s p?# p?S p?gklwgx p?d3 Bt Bx B; BH]
h ]
R` ]
~ JL (0S (0PTUcPd (0T =? / /> /< JNVX 9=3 9= 9= 9=]h 9=v 04$UYbd KM KMC KMs KMimnyiz KMZ 8<B 9c 9 90 37TX\eg CMC CMs CMRU CMlpq|l} CMJ ;?r +2 +2C +2Z+:s +:Z[
T [
X [
Q\ [
z 8: '13 '1h '1R
t 
V 
x 
2 8: H53 H5T 8<B TeW Te4PX> Tel DF <s <\t \V \| ac 9:3 9: 9:C 9:TW 9:gt 9:vJ
t J
x J
= J
X:C :C : 9=R -s -# -M -> 154VZce :O# :OS :OPS :Ojno|j} :Ox &eBSW 1Pf:
6 :
[ :
x? @B 
=3 
=k 
= <> $6s $6+ $6L 9=4^bkm VO# VOS VOX[ VOp ?C2 43 4 4l 7;2 
 
@ CGr d C B DHPR - -S -^ 57 ;K : ?A ,# ,_ ,B
 
(#8 7;\`ik 'K3 'KVY 'KR GKY]fh (HC (H (HSV (HT LN  Rd BG
d G
F G
N` G
R FH Q# Qu QL^ Q CE Ns NE NI[ N EG 4> 4>4P\K] 4>l& &$|J\ &P 7;$]apt} 8Q 8QC 8QWZ 8Qjm 8Q  EI  JX  EY 8Qt
$ 
 
. 
" JL $6c $65 $6L BD *6S *6X
 
. =? &9 &9P HLZ^mqz| >K >KTW >Kgj >K@2F 2hJt J BFb <=w <=|9#v <@daenp 2YS 2Y 2Y[^ 2Yh
"4 46 "H 68 7 7F 7r/
4 /
 /
6 /
b CGr </3 </i </V[ </| 68 ,6 ,6F ,6\ :< -?S -? -?^*
$ *
( *
6 *
]c *
X SW_a 2G# 2Gs 2GC 2Gfp 2Gh ]aik 3GS 3GC 3G 3GVY 3Gpz 3Gj >B" /GC /Gs /GQ[ /Gb =Atbfoq +Wc +W +W\_ +Wvz  |F  wG +WZE
4 E
x E
\d E
pz E
N 57 :: :x#c #3 #S ## #X\ #dg #J CGTXgkz~  HJ \VC \Vc \Vad \Vtw \V  OS  Tf  Og \V| @DRVeirt JCW JCC JC_b JCy}  G  zH JCX BFX\ko  C  LN 1C3 1CRU 1Ceh 1Cx{ 1C  SW  Xf  Sg 1Cf
4 
 
> 
rj  rG   )M 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   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   typingr+   ccxt.base.errorsr,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   ccxt.base.decimal_to_precisionrD   ccxt.base.preciserE   rG    rj  ri  <module>r     s    6 )   Z  Z  Z  Z  Z  Z  Z  Z  Z  Z  * 0 - . - . ' & . 4 . + ) * 0 ) ) + . 1 * ) + * 4 %OA
(K OA
rj  