
    !:h                        d dl mZ d dlm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.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lGmHZH d dlImJZJ  G d  d!ee      ZKy)"    )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    B/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/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_params@  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_typeH  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_marketL  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                    | j                  |      }| 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 )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>`
        dataNr   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    --f5* ~~h3Y
)Qd]
 q#d)$ 	(AGE$$UG4E --eU;F5M ,,UF;F5M	!#0x +%#'x +%#'x *$#'x 	( rj  c                     | j                  |      }| j                  |dg       }| j                  |di       }| j                  |d      S )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
        r  r   ts)publicGetPublicTimer  rv  r  )rg  rs  r  r  firsts        ri  
fetch_timezokx.fetch_time  sM     ++F3 ~~h3tQ+  --rj  c           	         | j                  |      }| j                  |dg       }g }t        dt        |            D ]B  }||   }| j	                  |d      }| j	                  |d      }|j                  ||d|dd       D |S )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
        r  r   uidacctLvN)rJ   ro  currencyr  code)privateGetAccountConfigr  r  r  rp  append)	rg  rs  r  r  resultr  account	accountIdro  s	            ri  fetch_accountszokx.fetch_accounts  s     //7( ~~h3q#d)$ 
	A1gG((%8I##GX6DMM  	
	 rj  c                 B    | j                         | j                  d   z
  S )Nr  )millisecondsr`  )rg  s    ri  noncez	okx.nonce	  s       "T\\2B%CCCrj  c                 d   | j                   d   r| j                          | j                  | j                   dg       }g }g }t        dt	        |            D ]&  }|j                  | j                  ||   |             ( |}t        dt	        |            D ]  }| j                  |||         } |S )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  r   r   )r`  load_time_differencer  r  r  r  fetch_markets_by_type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q#h-( 	<A&&vx{;F	<rj  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           	      t   d| j                  |      i}|dk(  r| j                  | j                  dddg      }g }t        dt	        |            D ]<  }||   }||d<   |j                  | j                  | j                  ||                   > |}g }	t        dt	        |            D ]:  }| j                  ||i       }
| j                  |
dg       }| j                  |	|      }	< | j                  |	      S | j                  | j                  ||            }| j                  |dg       }| j                  |      S )	Nrn  r[   defaultUnderlyingBTC-USDzETH-USDr   r  r  )rx  r  r`  r  r  r  publicGetPublicInstrumentsr  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[@\ ]^_ &NG1c.12 >nn^Q;..fb9++GW=> %%g..224;;w3OPD ~~h;!!,//rj  c                 H   | j                  | j                  dd      }| j                  d      r|ry| j                  |      }| 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 )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  sp    t||]EJ..u5 11&9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 rj  rS  c                    | j                          | 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	                  ||            }n!| j                  | j	                  ||            }| j                  |dg       }| j                  |di       }	| j                  |	d      }
| j                  |	||
      S )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
        r  rJ   Nr   r  publicGetMarketBookspublicGetMarketBooksFulli  r  szi  r  r   r  )
load_marketsrl  handle_option_and_paramsr1  r  r0  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_bookf  s    	V$fTl
 66v?OQY[qr//EMEE!GDM00eck44T[[&5QRH00Wf1MNH, ~~h3tQ+%%eT2	$$UFI>>rj  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  r7  rl  r  r  ry  r:  rI  rW   rR  rQ  r>  r?  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                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  |di       }| j                  ||      S )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>`
        r  rJ   r  r   )r3  rl  publicGetMarketTickerr  r  rv  rV  rg  ry  rs  rl  r  r  r  r  s           ri  fetch_tickerzokx.fetch_ticker  s     	V$fTl
 --dkk'6.JK6 ~~h3tQ+  //rj  symbolsc                    | j                          | 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                  ||            }| j                  |d
g       }	| j                  |	|      S )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  )r3  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!+..t{{7F/KL6 ..626!!'733rj  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d      }| j                  | j                  |d      |      S )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>`
        r  rJ   r  r   )r3  rl  publicGetPublicMarkPricer  r  rV  rv  )rg  ry  rs  rl  r  r  r  s          ri  fetch_mark_pricezokx.fetch_mark_priceL  s{     	V$fTl
 00Wf1MN ~~h/  a!8&AArj  c                    | j                          | 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                  ||            }| j                  |dg       }	| j                  |	|      S )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  )r3  r]  r^  rr  rx  rp  r`  r_  r1   rJ   rf  r  r  ra  rb  s
             ri  fetch_mark_priceszokx.fetch_mark_pricesm  s    	%%g.--g6
!??PVX^`fg
F77
C
 ! $ 0 0?RT] ^++FE:GXYJ!'  3L  )L  M  M!+00Wf1MN..626!!'733rj  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fillSzr2  sideordIdr  feeCcyr  r  execTypeTr  Mr  )r  r  r  ry  rJ   orderro  takerOrMakerrp  r>  r  r  r  )	rp  r  r  r_  rE   
string_negr  
safe_trader  )rg  rj  rl  rJ   r  ry  r  r>  r  rp  orderIdfeeCostStringr  feeCostSignedfeeCurrencyIdfeeCurrencyCoderx  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                 2   | j                          d}| j                  |dd      \  }}|r| j                  d||||dddd	      S | j                  |      }d|d	   i}d}|d
   r"| j	                  | j                  ||            }nm|||d<   d}	| j                  |ddd      \  }	}|	dk(  r"| j                  | j                  ||            }n&|	dk(  r!| j                  | j                  ||            }| j                  |dg       }
| j                  |
|||      S )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>`
        Fr   paginaterl  afterNr  r  rJ   r[   rS  r  publicGetMarketTradespublicGetMarketHistoryTradesr  )
r3  r4  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  sG    	88PZ[&33M65RWY_ajlsuy{~V$fTl
 (77GV8TUH #( F!::6=RZ\stNFF0055dkk'66RS99<<T[[RX=YZF ~~h3  vue<<rj  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           	         | j                          | j                  |      }d}| j                  |dd      \  }}|r| j                  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(  rF|r"| j!                  | j#                  ||            }n| j%                  | j#                  ||            }n|dk(  rQ|d   d   |d<   |r"| j'                  | j#                  ||            }ng| j)                  | j#                  ||            }nE|r"| j+                  | j#                  ||            }n!| j-                  | j#                  ||            }| j/                  |dg       }| j1                  |||||      S )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
        Fr   r     r>  r  r  Nr  r  i`T  rJ   )r  barrS  Candles  i  HistoryCandlesr   r   beforer  untilro  r;  r<  r  
instFamilyr  r  )r3  rl  r4  "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_ohlcvG	  s   * 	V$88zZ&::<QVX]_hjpruvv  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?FFt{{SZ\bGcd??GU[@\]g &v| <GHBB4;;wX^C_`;;DKKQW<XY==dkk'SY>Z[66t{{7F7ST ~~h3  vy%GGrj  c           
         |t        | j                  dz         | j                          d}| j                  |dd      \  }}|r| j	                  d|||d|d      S | j                  |      }d|d   i}|t        |d	z
  d
      |d<   |||d<   | j                  | j                  ||            }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 )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>`
        z5 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   r3  r4  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&::;TV\^cejlprxz}~~V$fTl
  #EAIq 1GH$GG99$++gv:VW. ~~h3q#d)$ 		A7D))$>ILL**4+;+;D(+KL#//nE& LL3 		 e[1009I5RWXXrj  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  rM  	tierBased)r  rf  rE   ry  r_  )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                    | j                          | 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                  ||            }| j                  |dg       }| j                  |di       }| j                  ||      S )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>`
        rn  ro  rW   rJ   r  rY   rZ   r[   r  r|  r  r  zE fetchTradingFee() supports spot, swap, future or option markets onlyr  r   )
r3  rl  rx  r;   rJ   privateGetAccountTradeFeer  r  rv  r  rY  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11$++gv2NO& ~~h3tQ+%%eV44rj  c                 
   | j                          | j                  dd|      \  }}i }d}|dk(  r"| j                  | j                  ||            }n!| j	                  | j                  ||            }| j                  ||      S )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>`
        rv   Nr-  )r3  rr  privateGetAssetBalancesr  privateGetAccountBalancer  )rg  rs  r  queryr  r  s         ri  fetch_balancezokx.fetch_balance]
  s     	 >>~tU[\
E
 "33DKK4OPH44T[[%5PQHN ))*h??rj  r  c                     | j                          | j                  |      }|d   st        | j                  dz         ddd}| j	                  |dd|d| j                  ||            S )	  

        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>`
        rW   z: createMarketBuyOrderWithCost() supports spot markets onlyF	quote_ccyr  tgtCcyrl  buyNr3  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
  sq     	V$f~tww)eeff16!
   5$dkkRUW]F^__rj  c                     | j                          | j                  |      }|d   st        | j                  dz         ddd}| j	                  |dd|d| j                  ||            S )	r  rW   z; createMarketSellOrderWithCost() supports spot markets onlyFr  r  rl  sellNr  r  s         ri  "create_market_sell_order_with_costz&okx.create_market_sell_order_with_cost
  sq     	V$f~tww)ffgg16!
   64t{{SVX^G_``rj  ro  rp  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  rp  ordTyper2  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  r2  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)rn  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_valuer_  r`  r  r  r4  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  rp  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                    | j                          | 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                  |      }n(|	d
k(  r| j                  |      }n| j                  |      }| j                  |dg       }| j                  |di       }| j                  ||      }||d<   ||d<   |S )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>`
        rh   r  r  r&  r%  r(  r'  r)  r*  privatePostTradeOrderAlgoprivatePostTradeOrderz createOrder() self.options["createOrder"] must be either privatePostTradeBatchOrders or privatePostTradeOrder or privatePostTradeOrderAlgoNr  r   ro  rp  )r3  rl  r5  rp  r`  r,   rJ   r8  r7  r  r  rv  parse_order)rg  ry  ro  rp  r  r>  rs  rl  r  r  requestOrdTyper  r  r  rw  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,,11':H2255g>H77@H~~h3tQ+  /ffrj  ordersc           	         | j                          g }t        dt        |            D ]  }||   }| j                  |d      }| j                  |d      }| j                  |d      }| j	                  |d      }	| j	                  |d      }
| j                  |di       }| j                  ||      }| j                  ||||	|
|      }|j                  |        | j                  |      }| j                  |dg       }| j                  |      S )	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>`
        r   ry  ro  rp  r  r>  rs  r  )r3  r  r  rp  r  rv  r  r5  r  r  r  parse_orders)rg  r;  rs  ordersRequestsr  rawOrderr  ro  rp  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 33NC. ~~h3  &&rj  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algoIdrq  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  r_  r  r  rp  r2   rJ   r  r	  rq  r  )rg  rJ   ry  ro  rp  r  r>  rs  rl  r  isAlgoOrderr  r&  rF  r+  r,  rG  r1  r  r  r  r  stopLossTypetakeProfitTypes                           ri  edit_order_requestzokx.edit_order_requestT  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           	         | j                          | 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	                  |	|            }n!| j                  | j	                  |	|            }| j                  |d	g       }| j                  |d
i       }| j                  ||      }||d<   ||d<   |S )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  rp  )	r3  rl  rT  privatePostTradeAmendAlgosr  privatePostTradeAmendOrderr  rv  r9  )rg  rJ   ry  ro  rp  r  r>  rs  rl  r  rQ  r  r  r  rw  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66t{{7F7STH66t{{7F7STH  ~~h3tQ+  /ffrj  c                 >   |t        | j                  dz         | j                  |dd      }| j                  |dd      }|s|r&| j	                  |g||      }| j                  |d      S | j                          | j                  |      }d|d   i}| j                  |d	d
      }	|	|	|d	<   n||d<   | j                  |d	d
g      }
| j                  | j                  ||
            }| j                  |dg       }| j                  |d      }| j                  ||      S )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>`
        z) cancelOrder() requires a symbol argumentstopr&  rK  Fr   r  rJ   r  r  rq  r  )r1   rJ   r  r  cancel_ordersr  r3  rl  r_  rq  privatePostTradeCancelOrderr  rv  r9  )rg  rJ   ry  rs  r&  rK  
orderInnerrl  r  r  r  r  r  rw  s                 ri  cancel_orderzokx.cancel_order  s/    >#DGG.Y$YZZ##FFI>>>&*e<h++RD&&AJ??:q11V$fTl

 **69oN$!.GI!GG		&9o">?33DKK4OPx4tQ'v..rj  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                 &   |t        | j                  dz         | j                          | 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                  |      }n| j                  |      }| j                  |dg       }| j!                  ||dd|      S )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  rF  rZ  r&  rK  FprivatePostTradeCancelAlgosr   rJ   )rF  r  )rq  r  )r  r  r  )r1   rJ   r3  rl  r  r`  rp  rd  r  r  r  r  r  rf  r"  r  r=  )rg  rc  ry  rs  rl  r  r`  defaultMethodr  clientOrderIdsalgoIdsr&  rK  r  r  
ordersDatas                   ri  r[  zokx.cancel_orders  s0    >#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77@H==gFH< ^^Hfb9
  VT4HHrj  c                    | j                          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                  |      }n| j                  |      }| j                  |dg       }| j                  |ddd|      S )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>`
        r`   r  r"  rZ  r&  rK  Frf  r   rJ   r  r  ry  rq  rF  Nr  r  )r3  rv  r`  rp  safe_bool_2r  r  r  r_  rl  r  rf  r"  r  r=  )rg  r;  rs  r  r`  rg  r  r&  rK  isStopOrTrailingr  rw  rJ   r  ry  rl  idKeyrequestItemr  rj  s                       ri  cancel_orders_for_symbolszokx.cancel_orders_for_symbolso  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77@H==gFH< ^^Hfb9
  T4vFFrj  timeoutc                     | j                          d|dkD  r| j                  |dz        ndi}| j                  | j                  ||            }|S )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
        timeOutr   r  )r3  parse_to_intprivatePostTradeCancelAllAfterr  )rg  rq  rs  r  r  s        ri  cancel_all_orders_afterzokx.cancel_all_orders_after  sW     	Wq[t((48q
 66t{{7F7ST rj  r  c                 :    ddddddd}| j                  |||      S )Nr  rI  closed)r  order_failedlivepartially_filledfilled	effectiverp  rg  r  statusess      ri  parse_order_statuszokx.parse_order_status  s2    "& &!
 &&99rj  rw  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0rq  r  rejected)rJ   r  r  r  rF  cTimer  fillTimerp  r  r  TrS  r  r@  r   r?  r  r|  	accFillSzrn  ordPxavgPxr  r  r  r  rn  r  rl  r/  r  r2  rr  rs  r   r  r  r  r  r  Ftruer  rJ   r  r  r  lastTradeTimestamplastUpdateTimestampry  ro  rI  r  r>  rF  rG  rD  r  moveTriggerPxrN  )r  r  r|  	remainingr  r  tradesr  )rp  
safe_orderr_  r  r  r  r  r`  rE   ry  r  rf  r  r  r  safe_number_n)!rg  rw  rl  scoderJ   r  r  r  rp  ro  r  rI  r  ry  r|  r>  rN  r  r|  r  r  r   r  rn  r  r}  r~  r  r  rF  rG  reduceOnlyRawr  s!                                    ri  r9  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                    |t        | j                  dz         | j                          | 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                  ||            }n!| j                  | j                  ||            }| j                  |dg       }| j                  |d      }| j                  ||      S )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   rZ  r&  privateGetTradeOrderAlgorE  rF  rq  )r  r  r  rZ  r&  r  r   )r1   rJ   r3  rl  r_  r  r`  rp  r  rq  r  r  r   rv  r9  )rg  rJ   ry  rs  rl  r  r  r`  rg  r  r&  r  r  r  rw  s                  ri  fetch_orderzokx.fetch_order  sz    >#DGG.X$XYYV$fTl
 **69oN//$,,bA(((<RS!!&(MB##FFI>/F()6&$&!(%2	"#% 		&"[\//44T[[%5PQH00We1LMHB x4tQ'v..rj  c                 <   | j                          d}| j                  |dd      \  }}|r| j                  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                  ||            }n!| j                  | j                  ||            }| j                  |dg       }| j                  ||||      S )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>`
        Fr   r  NrJ   r  rS  r5  r  r!  r  rZ  r&  rK   privateGetTradeOrdersAlgoPendingr(  r  rZ  r&  rK  r  )r3  r4  fetch_paginated_call_dynamicrl  r  r`  rp  r  r  rq  r  r  r!  r  r=  )rg  ry  r  rS  rs  r  r  rl  r`  r5  rg  r  r  r&  rK  r  r  r  s                     ri  fetch_open_orderszokx.fetch_open_orders:  s   $ 	88ART^_&445FPUW\^dee	
 [[(F &tGH$GG//$,,0A2F7GL(((<Z[!!&(MB""695##FFI>>>&*e<w7n#<7F!2GI'/!*GI		&"KL77<<T[[RW=XYH88We9TUH@ ~~h3  vue<<rj  c                 &   | j                          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                  ||            }n!| j                  | j                  ||            }| j!                  |dg       }| j#                  ||||      S )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  rZ  r&  rK  F privateGetTradeOrdersAlgoHistoryr(  rF  z fetchCanceledOrders() requires an "ordType" string parameter, "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"beginr  r  r  r  )r3  rl  rr  rx  r  r`  rp  r  r  rq  r1   rJ   r  r  r  r#  r  r=  )rg  ry  r  rS  rs  r  rl  ro  r  r`  r5  rg  r  r  r&  rK  rF  r  sendr  r  s                        ri  fetch_canceled_orderszokx.fetch_canceled_orders  sd   $ 	

 [[(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<<T[[RV=WXH88Wd9STHH ~~h3  vue<<rj  c                 b   | j                          d}| j                  |dd      \  }}|r| j                  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                  ||            }nH|dk(  r"| j                  | j                  ||            }n!| j!                  | j                  ||            }| j#                  |dg       }| j%                  ||||      S )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>`
        Fr}   r  NrJ   r  rn  rS  r5  r  r#  r  rZ  r&  rK  r  r}  r  r(  r  r  r  r|  r  #privateGetTradeOrdersHistoryArchiver  )r3  r4  r  rl  rr  rx  rv  r`  rp  rl  r  r  rq  r  r  r  r#  r  r=  )rg  ry  r  rS  rs  r  r  rl  ro  r  r`  r5  rg  r  r  r&  rK  r  r  r  r  s                        ri  fetch_closed_orderszokx.fetch_closed_orders  s   * 	88ATV`a&445H&RWY^`fgg

 [[(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<<T[[RV=WXH<<??GUY@Z[H88Wd9STH@ ~~h3  vue<<rj  c                    | j                          d}| j                  |dd      \  }}|r| j                  d||||      S i }d}|| j                  |      }|d   |d<   |||d<   | j	                  d||      \  }}| j                  d||      \  }}	| j                  |      |d	<   ||||d
<   | j                  | j                  ||	            }
| j                  |
dg       }| j                  |||||	      S )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>`
        Fr   r  NrJ   r  r  r  rn  rS  r  )r3  r4  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_trades5  s/    	88R\]&44_feUZ\bcc
 [[(F &tGH$GG225'6J88&RXYe"==dC
EM$GG33DKK4OP4 ~~h3  vueUCCrj  c           	      R    d|i}| j                  |||| j                  ||            S )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>`
        rq  )r  r  )rg  rJ   ry  r  rS  rs  r  s          ri  fetch_order_tradeszokx.fetch_order_tradesy  s4     R
 ##FE5$++gv:VWWrj  r  c                    | j                          d}| j                  |dd      \  }}|r| j                  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                  ||            }nH|dk(  r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j!                  |dg       }| j#                  ||||      S )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>`
        Fr   r  r  NmgnModeprivateGetAssetBillsrn  rS  rJ   r
  r  privateGetAccountBillsArchiver  )r3  r4  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  s   " 	88PZ[&44]D%QVX^__..}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99$++gu:UVH--00We1LMH224;;w3NOHb ~~h3  x>>rj  c                 D    dddddddddddd}| j                  |||      S )Nr   rj  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  rs  r  r|  billIdrq  ro  balChgr  r  )r  rJ   r  r  r  referenceIdreferenceAccountro  r  ry  r  r  r  r  r  )rp  r  r  r  rf  rE   ry  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_addressU  s0   : "">6:  1IJ;__^XrBF""695C%%ne<
%%j(;  9??8Z<}}Xt4oolE:T N"++L:OQ_`K"";	:--gt<7#""
 	
rj  c                 2   | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  |dd      }| j                  ||d   gd      }| j                  |d      S )	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
        r
  rJ   r  selectedTr  Fr  )r3  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>
 55dkk'66RS, ~~h3>>$
D9--h&9I8JER}}VY//rj  c                    | j                          | j                  |d      }| j                  |d      }| j                  |      }| j	                  ||      }| j                  ||      }|7| j                  ||      }|!t        | j                  dz   |z   dz   |z         |S | j	                  ||      }||v r||   S t        |j                               }| j                  |d      }	| j                  ||	      S )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>`
        r  z# fetchDepositAddress() cannot find z deposit address for r   )r3  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;::4H^^Hg6F~$TWW/T%TW^%^ax%x{%  A  AM--dD9("K((HMMO$  q)~~h..rj  r  c                     | j                  ||      \  }}| j                  |       | j                          | 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                         }| j                  | j                  |      | _        | j                  |d   | j                  |      i       }| j                  |d
      }
|
t        | j                   dz         | j                  |
      |d
<   | j                  |d
g      }| j#                  | j%                  ||            }| j'                  |dg       }| j                  |d      }| j)                  ||      S )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>`
        r   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  r3  r  r  r  rp  rv  r`  upperrq  r.  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-;..0J"..t
KDO NN8J+?AXAXY`AacefM""=%8C{'  3U  )U  V  V..s3		&5'*224;;w3NO ~~h3nnT1-%%k8<<rj  c                    | j                          d}| j                  |dd      \  }}|r| j                  d||||      S i }d}|| j                  |      }|d   |d<   |t	        |dz
  d      |d	<   |||d
<   | j                  d||      \  }}| j                  | j                  ||            }| j                  |dg       }	| j                  |	||||      S )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>`
        Fr   r  NrJ   r
  r   r   r  rS  r  r  )
r3  r4  r  r  rP  r  privateGetAssetDepositHistoryr  r  parse_transactions
rg  r  r  rS  rs  r  r  r  r  r  s
             ri  fetch_depositszokx.fetch_deposits7  s    	88R\]&44_dESXZ`aa
 }}T*H%d^GEN #EAIq 1GH$GG227GVL55dkk'66RSN ~~h3&&tXueVLLrj  c                    | j                          d|i}d}|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  |d      }| j                  |di       }| j                  ||      S )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>`
        depIdNrJ   r
  r  r   )r3  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55dkk'66RSx0..q"-%%gx88rj  c                    | j                          d}| j                  |dd      \  }}|r| j                  d||||      S i }d}|| j                  |      }|d   |d<   |t	        |dz
  d      |d	<   |||d
<   | j                  d||      \  }}| j                  | j                  ||            }| j                  |dg       }	| j                  |	||||      S )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>`
        Fr   r  NrJ   r
  r   r   r  rS  r  r  )
r3  r4  r  r  rP  r   privateGetAssetWithdrawalHistoryr  r  r  r  s
             ri  fetch_withdrawalszokx.fetch_withdrawals  s	    	88ASU_`&445GuV[]cdd
 }}T*H%d^GEN #EAIq 1GH$GG227GVL88Wf9UV> ~~h3&&tXueVLLrj  c                    | j                          d|i}d}|| j                  |      }|d   |d<   | j                  | j                  ||            }| j	                  |dg       }| j                  |di       }| j                  |      S )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>`
        wdIdNrJ   r
  r  r   )r3  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88Wf9UV, ~~h3^^D!R0
%%j11rj  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  r_  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                 |   | j                          d}| j                  d|      \  }}|| j                  |dd      }|dk7  r|dk7  rt        | j                  dz         | j                  |      }|d   |d}| j                  | j                  ||            }| j                  |d	g       }| j                  ||      S )
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  )
r3  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!
 55dkk'66RS ~~h3""400rj  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                 `   | j                          | j                  |      }| j                  d||      \  }}d|d   i}|| j                  |      |d<   | j	                  | j                  ||            }| j                  |dg       }| j                  |d      }	|	y| j                  |	|      S )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>`
        r   r  rJ   Nrn  r  r   )	r3  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224;;w3NO^ ~~h3>>$*""8V44rj  c                    | j                          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                  ||            }n!| j                  | j                  ||            }| j                  |d
g       }g }t        dt        |            D ]%  }|j	                  | j                  ||                ' | j                  |d| j                  |      d      S )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   r`  r  r   r  r  !privateGetAccountPositionsHistoryr  ry  F)r3  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$  ss    	

 I1c'l+ /
U+  ./ ")nO"$'HHY$7! $t||=Mr R!!"7C_`88==dkk'SY>Z[H66t{{7F7STH^ NN8VR8	q#i.) 	=AMM$--il;<	=--fh@S@ST[@\^cddrj  c                 (    | j                  |g|      S )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>`
        )r!  rg  ry  rs  s      ri  fetch_positions_for_symbolzokx.fetch_positions_for_symbolz  s     ##VHf55rj  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  rO  notionalUsdr[  r  r  	openAvgPxuplr  r  imrr  r  mmrr   z0.00005liqPxuplRatior  r  r  rJ   posIdr!  rC  liquidationPrice
entryPriceunrealizedPnlrealizedPnlrM  	contractsrS  	lastPrice
closeAvgPxrp  rJ  r  r  )r  r  maintenanceMarginmaintenanceMarginPercentage
collateralinitialMargininitialMarginPercentagerL  marginRatiorF  rG  )rp  r  rE   
string_absr_  rf  r  r  	string_ltr  r  r  r  
string_addr  safe_positionr  )"rg  r  rl  r  ry  r&  contractsAbsrp  rJ  r6  r)  parsedCurrencyr  contractSizeStringmarkPriceStringnotionalStringr!  rC  initialMarginStringentryPriceStringunrealizedPnlStringleverageStringr=  collateralStringmaintenanceMarginStringr9  !maintenanceMarginPercentageStringrounderr:  r2  percentageStringrM  r  r>  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                    | j                          | 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                  |
|            }| j                  |dg       }| j                  |di       }| j                  ||      S )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>`
        r6  rJ   r  )r
  r  ro  r  r  masterr  ro  subAcctr  r+  r  r  r  r   )
r3  r  rv  r`  rp  currency_to_precisionprivatePostAssetTransferr  r  parse_transfer)rg  r  r  rQ  rR  rs  r  r6  fromIdtoIdr  r  r  rawTransfers                 ri  r   zokx.transfer%  sp    	==&6FK!!.+{K	9ED>--dF;

 X!GFO!%GI"..vvsCGFO ,,VT3?GDMX!GFO!'GI"..vvsCGFO ,,VT3?GDM00Wf1MN  ~~h3nnT1b1"";99rj  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  r2  r  )	r  rJ   r  r  r  r  rQ  rR  r  )r_  rp  r  r  rv  r`  r  rf  rE   r?  r  parse_transfer_status)rg  r   r  rJ   r%  r  r  fromAccountIdtoAccountIdr7  r  balanceChanges               ri  rX  zokx.parse_transfer`  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  r^  zokx.parse_transfer_status  s%    t
 &&99rj  c                     | j                          d|i}| j                  | j                  ||            }| j                  |dg       }| j	                  |d      }| j                  |      S )Nr]  r  r   )r3  privateGetAssetTransferStater  r  rv  rX  )rg  rJ   r  rs  r  r  r  r   s           ri  fetch_transferzokx.fetch_transfer  sl    r
 44T[[&5QR* ~~h3>>$*""8,,rj  c                    | j                          d}ddi}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j                  ||            }| j	                  |dg       }| j                  |||||      S )	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  )r3  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55dkk'66RSB NN8VR8	##IxvNNrj  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-TIMESTAMPrk  zapplication/jsonzContent-Typebase64zOK-ACCESS-SIGN)r   r  bodyheaders)ra  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  rq  rp  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  rS  rT  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_rate@  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                 &    | j                  ||      S )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>`
        )fetch_funding_rater#  s      ri  fetch_funding_intervalzokx.fetch_funding_interval  s     &&vv66rj  c                 >   | j                          | j                  |      }|d   st        | j                  dz         d|d   i}| j	                  | j                  ||            }| j                  |dg       }| j                  |di       }| j                  ||      S )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>`
        rY   z2 fetchFundingRate() is only valid for swap marketsr  rJ   r  r   )	r3  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
 224;;w3OP" ~~h3tQ+&&uf55rj  c                 b   | j                          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                  ||            }	| 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 )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>`
        ro  r  NrS  ry  r  rZ  ctTyper  r
  r[  r  r   rY   rn  r  r   r  r  r  r  )r  ry  r  r  r  rJ   r  r  )r3  rb  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55dkk'56QR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Nrj  c                 8   |t        | j                  dz         |dk  s|dkD  rt        | j                  dz         | j                          | 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                  ||            }|S )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   r3  rl  r  rp  privatePostAccountSetLeverager  )	rg  rL  ry  rs  rl  rC  r  r  r  s	            ri  set_leveragezokx.set_leverageP  sE    >#DGG.Y$YZZ qLhnTWW'\\]]V$
!??vV
F))&)WEJ'!
j(@TWW'}}~~!Tl

 ""69e<#& W%7Gu<L +!  A  A!(GI55dkk'66RS rj  c                 |   | j                         }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 )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-"";	://
 	
rj  rJ  c                 b    d}|rd}nd}d|i}| j                  | j                  ||            }|S )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  sF     	)I"Iy
 99$++gv:VW rj  rC  c                    |t        | j                  dz         |j                         }|dk7  r|dk7  rt        | j                  dz         | j	                          | j                  |      }| j                  |dd      }|
|dk  s|dkD  rt        | j                  d	z         | j                  |dg      }|||d
   d}| j                  | j                  ||            }|S )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
        z+ 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   r3  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

 55dkk'66RS rj  c                     | j                          | j                  |      }| j                  |dg       }g }t        dt	        |            D ]%  }|j                  | j                  ||                ' |S )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>`
        r  r   )r3  privateGetAccountInterestRater  r  r  r  parse_borrow_rate)rg  rs  r  r  r  r  s         ri  fetch_cross_borrow_rateszokx.fetch_cross_borrow_rates  ss     	55f= ~~h3q#d)$ 	:ALL//Q89	:rj  c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  |di       }| j                  |      S )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>`
        r
  rJ   r  r   )r3  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>
 55dkk'66RS ~~h3~~dAr*%%d++rj  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_rate4  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_historiesH  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                     | j                          i }|||d<   |||d<   | j                  | j                  ||            }| j                  |dg       }| j	                  ||||      S )a  
        retrieves a history of a multiple currencies borrow interest rate at specific time slots, returns all currencies if no symbols passed, default is None

        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
        r  rS  r  )r3  )publicGetFinanceSavingsLendingRateHistoryr  r  r  )rg  r  r  rS  rs  r  r  r  s           ri  fetch_borrow_rate_historieszokx.fetch_borrow_rate_historiesd  s     	
  %GH$GGAA$++gW]B^_ ~~h3//eUEJJrj  c                     | j                          | j                  |      }d|d   i}|||d<   |||d<   | j                  | j                  ||            }| j	                  |dg       }| j                  ||||      S )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>`
        r
  rJ   r  rS  r  )r3  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AA$++gW]B^_ ~~h3--dD%GGrj  c                    | j                          | j                  |      }| j                  |dd      }| j                  |dg      }|d   |||d}| j	                  | j                  ||            }| j                  |dg       }	| j                  |	di       }
| j                  |d      }| j                  | j                  |
|      d|d	k(  rd
i      S di      S )Nr  r(  rJ   )r  r  ro  r  r  r   r  r  r  r  r  )	r3  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	
 ??GU[@\] ~~h3tQ+$$Xv6	{{499%HyC/dK
  	6>K
  	rj  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  )	r_  rp  rE   r  r?  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                 *    | j                  ||d|      S )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  r  rg  ry  r  rs  s       ri  reduce_marginzokx.reduce_margin!  s     ((6JJrj  c                 *    | j                  ||d|      S )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  r  r  s       ri  
add_marginzokx.add_margin.  s     ((GGrj  c                    | j                          | 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                  ||            }| j                  |dg       }	| j                  |	|      S )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>`
        rW   r0  ro  r  r  z< fetchMarketLeverageTiers() cannot fetch leverage tiers for Nr   r  r  )rn  r  r  rJ   r  r  )r3  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;  s    	V$!&>xt/N/NvV\~/^vf~u5x +i!ilr!rss
!??@Z\bc
F))&(GDJ 

 8 &tGH44T[[&5QR, ~~h3//f==rj  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  maxSzr.  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_tiersq  s    0 q#d)$ 	A7D''h7HLL))$7**8V<"7O#//g>#//g>)-)9)9$)F#//jA	 		 rj  c                    | j                          d}| j                  d|      \  }}|| j                  |dd      }d|i}d}|| j                  |      }	|	d   |d<   ||dz
  |d<   |||d	<   || j	                  |      }|d   |d
<   | j                  | j                  ||            }
| j                  |
dg       }| j                  |      }| j                  ||||      S )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  )
r3  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  s    	
!??@UW]^
F))&)WEJz
 }}T*H%d^GEN %	GH$GG[[(F &tGH88Wf9UV( ~~h3..t4228T5%PPrj  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                 (   | j                          | j                  |      }|d   | j                  ||      dd}| j                  | j	                  ||            }| j                  |dg       }| j                  |di       }| j                  ||      S )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>`
        rJ   borrow)r
  r  rp  r  r   )r3  r  rV  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;

 55dkk'66RS  ~~h3~~dAr*%%dH55rj  c                    | j                          | j                  |dd      }| j                  |d      }|t        | j                  dz         | j                  |      }|d   | j                  ||      d|d}| j                  | j                  ||            }| j                  |dg       }| j                  |di       }	| j                  |	|      S )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>`
        rJ   rq  z, repayCrossMargin() requires an id parameterrepay)r
  r  rp  rq  r  r   )r3  r_  rq  r1   rJ   r  rV  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;	
 55dkk'66RS  ~~h3~~dAr*%%dH55rj  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_loan6  sO     %%dE2
//
HE&&tU3
 	
rj  c                 t   | j                          | j                  |      }|d   st        | j                  dz         | j	                  |d         }| j                  |d   d      }|||d   d}| j                  | j                  ||            }| j                  |dg       }| j                  |d	   |      S )
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:
        r  z3 fetchOpenInterest() supports contract markets onlyro  r  r  rJ   )rn  r  r  r  r   )
r3  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_interestM  s     	V$j!TWW'\\]]..vf~>vf~u5Tl

 33DKK4PQ  ~~h3''Q88rj  r   c                    | j                  | j                  di       }| j                  |di       }| j                  |||      }|dk7  r"|dk7  r|dk7  rt        | j                  dz         | j                          d}d}	|| j                  v s|| j                  v r| j                  |      }	|	d   }n| j                  |      }
|
d	   }||d
}d}d}| j                  d|	|      \  }}|dk(  r"| j                  | j                  ||            }nT|||d<   | j                  |d      }|||d<   | j                  |dg      }| j                  | j                  ||            }| j!                  |dg       }| j#                  |d||      S )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   r3  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_historyu  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FFt{{SZ\bGcdH #( %%fg6E !&6G95II$++V]_eJfgH ~~h300tUEJJrj  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  rQ  rR  openInterestAmountopenInterestValuer  r  r  )
rp  r  r  r`  ra  r  r  safe_open_interestr  r  )rg  r  rl  rJ   timer  rQ  rR  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`  rq  rq  )rg  r  rh  s     ri  r  zokx.set_sandbox_mode  sZ    c4)&1&,]#25DLL./"dll299T\\3HIDL 3rj  r  c                     | j                          i }|%| j                  |      }dj                  |      |d<   | j                  | j	                  ||            }| j                  |d      }| j                  ||      S )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>`
        r`  r
  r  )r3  currency_idsr  r  r  r  parse_deposit_withdraw_fees)rg  r  rs  r  rc  r  r  s          ri  fetch_deposit_withdraw_feeszokx.fetch_deposit_withdraw_fees  s}     	##E*C XXc]GEN11$++gv2NOX ~~h///e<<rj  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  rM  )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_fees/  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                 ,   |t        | j                  dz         | j                          | 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                  ||            }| j                  |dg       }	| j                  |	|      }
| j                  |
d      }| j                  ||d   ||      S )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   r3  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_historyj  s=    >#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>>t{{7TZ?[\& ~~h3,,T6:k;7009I5RWXXrj  c                 v    | j                  |d      }|| j                  ||      | j                  |d      d d dS )NinsIdrn  )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  r3  r  r  r  )
rg  r.  rl  r  r  r  r  r  r(  r2  s
             ri  r-  zokx.parse_settlements  s     q#k*+ 		ANE))%6InnUIr:G1c'l+ !2271:vF
dkk*!* $Y 77  			 rj  c                 J   | j                          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                  ||            }| j                  |d	g       }|d
   S )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   )r3  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
 11$++gv2NO nnXvr:1~rj  c                    | j                          | j                  |      }|d   }|j                  d      }|d   d   |d   d   | j                  |d      d}| j	                  | j                  ||            }| j                  |dg       }t        d	t        |            D ]2  }	||	   }
| j                  |
d
      }||k(  s | j                  |
|      c S  y)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>`
        rJ   r|  r  r  r  r   )r  r  r  r  r   r  N)
r3  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

 11$++gv2NO< ~~h3q#d)$ 	8AGE ,,UH=M(((77		8
 rj  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askPricerS  r7  )underlyingPricer  )r  rp  r  r  r  )rg  r>  rl  r  r  ry  s         ri  r;  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                    | j                          | 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                  ||            }
| j                  |
dg       }| j                  |d      }| j                  ||      S )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>`
        r  r  Nrc   r  rJ   r  r  r  r  r  r  r  r
  r  r   )
r3  rl  rp  r  r  privatePostTradeClosePositionr  r  rv  r9  )rg  ry  rp  rs  rl  r  r  rC  r  r  r  r  rw  s                ri  close_positionzokx.close_positionW  s*   $ 	V$((A/
!??QWY`a
FTl!
 %+	"%,	"%)	"$!.GI}}T*H%d^GEN55dkk'66RS$ ~~h3tQ'v..rj  c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  |di       }| j                  |d|      S )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>`
        r  rJ   r  r   N)r3  rl  rX  r  r  rv  parse_option)rg  ry  rs  rl  r  r  r  r  s           ri  fetch_optionzokx.fetch_option  s     	V$fTl
 --dkk'6.JK6 &"5vq"-  f55rj  c                     | j                          | j                  |      }|d   dz   dd}| j                  | j                  ||            }| j	                  |dg       }| j                  |dd      S )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>`
        r  z-USDr3  )r  rn  r  Nr  )r3  r  r`  r  r  parse_option_chain)rg  r  rs  r  r  r  r  s          ri  fetch_option_chainzokx.fetch_option_chain  s{     	==&F#f, 
 ..t{{7F/KL6 &"5&&vtX>>rj  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openInterestrM  rA  rN  rE  midPricerS  r7  r:  rO  rL  rM  rQ  r:  rR  )rp  r  r  r  r  )rg  r  r  rl  r  r  s         ri  rT  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                    | j                          |j                         |j                         |j                         | j                  |      dd}| j                  | j	                  ||            }| j                  |dg       }| j                  |di       }| j                  |d|      }	| j                  |	      }
| j                  |d|      }| j                  |      }| j                  ||
|      S )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>`
        r  )r  r  rfqSzCcyrfqSzrp  r  r   r  r  )
r3  r  r  $privatePostAssetConvertEstimateQuoter  r  rv  rp  r  parse_conversion)rg  r]  r^  r  rs  r  r  r  r  fromCurrencyIdfromCurrencytoCurrencyId
toCurrencys                ri  fetch_convert_quotezokx.fetch_convert_quote  s     	~~' (**62
 <<T[[RX=YZ0 ~~h3a,))&)XF}}^4''
FC]]<0
$$V\:FFrj  c                    | j                          ||||| j                  |      dd}| j                  | j                  ||            }| j	                  |dg       }| j                  |di       }	| j                  |	d|      }
| j                  |
      }| j                  |	d|      }| j                  |      }| j                  |	||      S )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>`
        r  )r  r  r  szCcyr2  rp  r  r   r  r  )	r3  r  privatePostAssetConvertTrader  r  rv  rp  r  rc  )rg  rJ   r]  r^  r  rs  r  r  r  r  rd  re  rf  rg  s                 ri  create_convert_tradezokx.create_convert_tradeR  s     	''/
 44T[[&5QR. ~~h3a,))&)XF}}^4''
FC]]<0
$$V\:FFrj  c                 z   | j                          d|i}| j                  | j                  ||            }| j                  |dg       }| j	                  |di       }| j                  |d      }| j                  |d      }	d}
d}|| j                  |      }
|	| j                  |	      }| j                  ||
|      S )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>`
        clTReqIdr  r   r  r  N)r3  privateGetAssetConvertHistoryr  r  rv  rp  r  rc  )rg  rJ   r  rs  r  r  r  r  rd  rf  re  rg  s               ri  fetch_convert_tradezokx.fetch_convert_trade  s     	
 55dkk'66RS, ~~h3a,))&)<''
;
%==8L#|4J$$V\:FFrj  c                    | j                          i }| j                  d||      \  }}|||d<   |||d<   | j                  | j                  ||            }| j	                  |dg       }| j                  ||dd||      S )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>`
        r  r  rS  r  r  r  )r3  r  ro  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55dkk'66RS, ~~h3%%dD)ZPUVVrj  
conversionre  rg  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  )clQReqIdrl  r  baseSz
fillBaseSzquoteSzfillQuoteSzcnvtPxrm  )
r  r  r  rJ   re  
fromAmountrg  toAmountr>  r  )r  rp  r  r  r  r  )	rg  ru  re  rg  r  fromCoinr]  r  r^  s	            ri  rc  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                 v   | j                          | j                  |      }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 )
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
        r  r   r
  Nr  rP  r  )r  r   r  )r  rJ   r  r  ro  rK   r  r  r   r  r  r  r  )r3   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     	88@ ~~h3q#d)$ 	AGE!!%/B**2.D  !  $//u=#//u=
  $#!
  $#   5F4L		@ rj  httpCodereasonr   r  rq  rp  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  rq  rp  r  requestHeadersrequestBodyr  feedbackr  r  errorr  messages                    ri  handle_errorszokx.handle_errorsh  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                    | j                          | 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                  |	|            }n?||kD  r"| j                  | j                  |	|            }nt	        | j                  dz         | j                  |d      }| j                  |      }| j                  ||||      S )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>`
        autoNz8 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  )r3  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224;;w3OPH^#99$++gv:VWHTWW'||}}V ~~h/77=00uUUrj  c                    | j                          | j                  |d      }| j                  |d      }| j                  |g d      }|d}d|i}|,t	        |      }|dk(  r| j                  |d         }	|	d   |d	<   |||d
<   |||d<   | j                  | j                  ||            }
| j                  |
d      }| j                  |||      }| j                  |||      S )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>`
        rC  rn  )r  rC  rn  r  rS  r   r   rJ   r  r  r  )r3  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99$++gv:VWD ~~h/((w?	)))UEBBrj  r  c                 
   | j                          | j                  |      }d|d   i}| j                  |dd      }| j                  |d      }|||d<   |||d<   |||d<   |||d<   | j	                  | j                  ||            }	| j                  |	dg       }
g }t        d	t        |
            D ];  }|
|   }|j                  | j                  |d	      | j                  |d
      d       = | j                  ||      S )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>`
        r  rJ   r  r  r  r  rS  r  r   r   )r  longShortRatio)r3  rl  r_  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_history7   s5    	V$fTl
 ""67E:67+"GEN  )GH$GG$GGPPQUQ\Q\]dflQmn ~~h3q#d)$ 	AGEMM!--eQ7"&"2"25!"< 	 2266BBrj  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_ratioj   s\    %%dK8	H%F"Y/"..t5EF
 	
rj  )NNNN)N)NN)__name__
__module____qualname__r   re  rb  r   rr  rx  r  r!   r)   r  r  r   r  r+   r   r  r  r  dictr  r  r   r.  r   r6  r#   rV  rZ  r"   r$   rd  rg  ri  r&   r  r  r  r  r  r  r  r  r  r'   r  r  r   r  floatr  r  r   r   r   r5  r  r   rC  rT  rX  r^  rd  r[  r   rp  rv  r  r   r9  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   rX  r^  rf  rj  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  r/  r3  r-  r8  r   r=  r;  rR  r   rU  r   rX  rT  r	   rh  rl  rp  rt  rc  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 .. %' *4= *XD $& $v, *N4 NF N` 24 50n ') |Z || :>b 5?s 5?3 5?Y 5?nH4 H H6 HT 02 ,03 ,0f ,0\ 04B 54W 547 54n 46 Bs B& BB 48 4 4w 4:X Xv X Xt 6:UW G=3 G=s G=# G=\`af\g G=R
 
4 
4 26DW[df ]H# ]Hc ]HQT ]Hkoptku ]H~ 8<$]ajl @Y @YC @YWZ @YD8)2)
T 
6 
EX 
0 57 -5 -5;N -5^ $& {@( {@z RT ` `5 `* SU a aE a* os{} b,3 b,i b,y b,Z_ b,hk b,H gksu 93 9i 9y 9RW 9`c 9v @B /'D$6 /'b FJQU^` J,S J,X `drv  @B ?S ?# ?Y ?i ?Y\ ?lo ?B 37r &/s &/C &/P	 04B YI YIv SU JG5H0I JGX <> s :	: 	:D Dv D DL 26b O/c O/3 O/b /3TXac Z= Z=3 Z=c Z=hlmrhs Z=x 37TX\eg m=C m=s m=RU m=^ 154VZce n=# n=S n=PS n=jnotju n=` -1tRV_a BDc BD BDC BDH 9=4^bkm XS X# XS XX[ X, (,$TZ\ p? p?C p?s p?aefqar p?d3 Bt Bx B; BH]
h ]
R` ]
~ DF (0s (0$~J^ (0T 79 /# /^ /< DHPR 9=S 9=% 9=# 9=Wb 9=v *.Dt\^ KM3 KMc KM KMcghsct KMZ 26b 9 93 90 -1tRV_a CMc CM CMC CMfjkvfw CMJ 59 +23 +2c +2Z+:s +:Z[
T [
X [
Q\ [
z 24 '1S '1 '1R
t 
V 
x 
2 24 H5S H5T 26b Tew TeT(^ Tel >@ 6 6\t \V \| [] 9:S 9:% 9:c 9:c 9:an 9:vJ
t J
x J
= J
X:C :C : 37r - -C -m -> +/TPT]_ :OC :Os :O# :Odhivdw :Ox &eBSW 1Pf:
6 :
[ :
x? :< 
7S 
7 
7 68 $6 $6K $6L 37TX\eg VOC VOs VORU VOp 9=R 4S 4# 4l 15R 
# 
@ =A  c B >B" -# -s -^ /1 5E : 9; ,C , ,B
 
(#8 154VZce 'KS 'KPS 'KR AESW`b (Hc (H# (HS (HT FH 3 L^ BG
d G
F G
N` G
R @B KC K KFX K =? H He HCU H ?A 4># 4>T,EW 4>l& &$|J\ &P 15DW[jnwy 8Q# 8Qc 8QQT 8Qdg 8Q  C  DR  S 8Qt
$ 
 
. 
" DF $6 $6U $6L <> *6s *6X
 
. 79 &9# &9P BFTXgktv >K# >Kc >Kad >K@2F 2hJt J <@ <= <=|9#v 6:[_hj 2Ys 2Y# 2YUX 2Yh
"4 .0 "H 02 73 7f 7r/
4 /
 /
6 /
b =A </S </	 </PU </| 02 ,63 ,6f ,6\ 46 -?s -?+ -?^*
$ *
( *
6 *
]c *
X MQY[ 2GC 2G 2Gc 2G`j 2Gh W[ce 3Gs 3Gc 3G3 3GPS 3Gjt 3Gj 8<B /Gc /G /G: /Gb 7;\`ik +W +W3 +WVY +Wptu  qA +WZE
4 E
x E
\d E
pz E
N /1 :Z :x#c #3 #S ## #X\ #dg #J =Adaetx  BD \Vc \V \V[^ \Vnq \V  IM  N`  Ia \V| :>D_cln JCw JCc JCY\ JCsw  yA  tB JCX <@RVeix|  FH 1CS 1CC 1C_b 1Cru 1C  MQ  R`  Ma 1Cf
4 
 
> 
rj  rG   )Lccxt.base.exchanger   ccxt.abstract.okxr   ry  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    ( )  Z  Z  Z  Z  Z  Z  Z  Z  Z  Z  * 0 - . - . ' & . 4 . + ) * 0 ) ) + . 1 * ) + * 4 %OA
(K OA
rj  